text:
Q: Azure Policy Evaluation triggers - Issues with On-demand evaluation scan As I'm working on implementating policies (especially on App Services Plan and WebApp), I need to  quickly test new rules for my policies. I tried to launch the on-demand scan on my resources with a REST API POST command using the following URI structures:
POST https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation?api-version=2018-07-01-preview
cf. https://learn.microsoft.com/fr-fr/azure/governance/policy/how-to/get-compliance-data
The call returns a 202 Accepted status (=seems good :) ):

Issue : But when I check the Compliance board in the Azure portal, no scan was done.

*

*I'm wondering if on-demand scanning is only available for certain azure services (such as storage account in the example, see shared link above) and not for others such as WebApp, Service Plan etc)

*I'm also wondering if the on-demand scan will trigger the policy evaluation at the same time (even if the effect is different : Deny effect VS deployIfNotExists effect for example) ?

Has anyone ever encountered this kind of issues with on-demand policies evaluation scan ? :)
Thanks !

A: As Kemley noted, the portal will not reflect until the compliance scan is finished. In my experience, it can take a few minutes for portal to reflect the updates.
This Microsoft Blog here does a good summary on the time it takes for the Policy Evaluation Scans: https://msftplayground.com/2019/06/on-demand-azure-policy-scan/
Below is a snippet from that article.

The evaluation of the policies take place on the following events:
* New policy assignment. ( ~30 minutes).
* Updated assignment of a existing policy. (~ 30 minutes)
* Deployment of a resources. (~15 minutes)
* Every 24 hours
* Update of the resource provider
* On-demand (~3 minutes)

You can also find the scan time estimates burried in the official Microsoft Azure Docs here (but it's not as nicely bullet-pointed as the above link): https://learn.microsoft.com/en-us/azure/governance/policy/how-to/get-compliance-data#evaluation-triggers
For the on-demand evaluation scan calling the REST API, the 202 Accepted status is indicating the Scan was triggered, but doesn't mean it has completed yet.
You will receive an HTTP 200 status code when the scan is complete. When you trigger the scan, the response message will include a URI in the Location field of the response header message. This URI is what you can query to check for the scan status (HTTP 202 you can interpret as scan is still running, and HTTP 200 is scan complete).
My experience is that all the policy effects were evaluated and returned by the time the status scan shows completed but I do not see official documentation on this. Also, my experience is that compliance results to reflect in the Portal will sometimes take up to another additional 3 to 5 minutes for Portal (this I speculate is dependent upon the size of the environment/scope of the scans), but Microsoft does not provide specific SLAs on that at this time either.
Microsoft has recently provided a Azure CLI and Azure PowerShell commands to trigger on-demand policy evaluation scans. Those commands are documented here: https://learn.microsoft.com/en-us/azure/governance/policy/how-to/get-compliance-data#on-demand-evaluation-scan

A: The compliance results are not updated on the portal until the compliance scan is finished so there will a bit of time between launching the scan and seeing the results in Portal.

A: You can trigger the actual state for a subscription with
az policy state trigger-scan.


text:
Q: WPF WriteableBitmap drawing over loaded picture with mouse and save. Strange cursor shift I'm trying to implement some WPF drawing sample to understand how it works. I can solve such task with C++ very quickly but I want to understand WPF means.
During the implementation of a task I faced with some strange problem: coordinates shift of mouse cursor responsible to pixels I can see on canvas.
First of all, my task is: load some picture from file; show it on Image component; allow to draw over image with mouse (like pencil tool); save changes to new file. Task is easy to implement.
Here is my code:
XAML:
<Window x:Class="MyPaint.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:MyPaint"
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
    Background="#FF000000"
    mc:Ignorable="d"
    Title="Strange Paint" Height="503.542" Width="766.281" Icon="icons/paint.png">

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="20"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid Grid.Column="0" Grid.Row="1" Width="Auto">
        <StackPanel HorizontalAlignment="Left" Width="Auto" Background="{x:Null}">
            <Button x:Name="arrowButton" Width="25" Height="25" HorizontalAlignment="Left" Click="ArrowButton_Click">
                <Image Source="icons/arrow.png"/>
            </Button>
            <Button x:Name="selectorButton" Width="25" Height="25" Click="SelectorButton_Click" HorizontalAlignment="Left">
                <Image Source="icons/select_selection_tool-128.png"/>
            </Button>
            <Button x:Name="clearButton" Width="25" Height="25" Click="ClearButton_Click" HorizontalAlignment="Left">
                <Image Source="icons/clear.png"/>
            </Button>
            <Button x:Name="pencilButton" Width="25" Height="25" Click="PencilButton_Click" HorizontalAlignment="Left">
                <Image Source="icons/pencil.png"/>
            </Button>
            <Button x:Name="fillButton" Width="25" Height="25" Click="FillButton_Click" HorizontalAlignment="Left">
                <Image Source="icons/fill.png"/>
            </Button>
            <xctk:ColorPicker Width="50"  Name="ClrPcker_Foreground" SelectedColorChanged="ClrPcker_Foreground_SelectedColorChanged">

            </xctk:ColorPicker>
        </StackPanel>
    </Grid>
    <Grid x:Name="drawingCanvas" Grid.Column="1" Grid.Row="1" MouseMove="paintImageCanvas_MouseMove"  MouseLeave="PaintImageCanvas_MouseLeave" MouseLeftButtonUp="PaintImageCanvas_MouseLeftButtonUp">
        <ScrollViewer Grid.Column="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <Canvas x:Name="scrCanvas" Width="{Binding ActualWidth, ElementName=paintImageCanvas}" Height="{Binding ActualHeight, ElementName=paintImageCanvas}" >
                <Image x:Name="paintImageCanvas" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="UniformToFill" MouseDown="paintImageCanvas_MouseDown" MouseMove="paintImageCanvas_MouseMove">

                </Image>
                <Rectangle x:Name="Rect" Stroke="DarkOrange" Visibility="Collapsed" Fill="#77EEEEEE"></Rectangle>
            </Canvas>
        </ScrollViewer>
    </Grid>

    <StackPanel Grid.Row="0">
        <Menu IsMainMenu="True" DockPanel.Dock="Top" Background="#FF000000">
            <MenuItem Header="_File" Foreground="White"  Background="#FF000000">
                <MenuItem x:Name="newMenuItem" Header="_New"  Background="#FF000000" Click="NewMenuItem_Click"/>
                <MenuItem x:Name="openMenuItem" Header="_Open" Click="openMenuItem_Click"  Background="#FF000000"/>
                <MenuItem Header="_Close"  Background="#FF000000"/>
                <MenuItem Header="_Save"  Background="#FF000000" Click="MenuItem_Click"/>
                <MenuItem x:Name="exitMenuItem" Header="_Exit" Click="exitMenuItem_Click"  Background="#FF000000"/>
            </MenuItem>
        </Menu>
        <StackPanel></StackPanel>
    </StackPanel>

</Grid>

Implementation of window class:
Class members:
Point currentPoint = new Point();

    ToolBoxTypes currentSelectedTool = ToolBoxTypes.Unknown;
    Color foregroundColor = Brushes.Black.Color;

    WriteableBitmap imageWriteableBitmap;

Constructor and initialization (init white canvas 1024x768):
        public MainWindow()
    {
        InitializeComponent();
        ClrPcker_Foreground.SelectedColor = foregroundColor;

        imageWriteableBitmap = BitmapFactory.New(1024, 768);
        paintImageCanvas.Source = imageWriteableBitmap;

        imageWriteableBitmap.Clear(Colors.White);
        int i = 0;

    }

Mouse down event (here I get the first point):
private void paintImageCanvas_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ButtonState == MouseButtonState.Pressed)
        {
            currentPoint = e.GetPosition(paintImageCanvas);
        }
        if (currentSelectedTool == ToolBoxTypes.PencilTool)
        {

        }
    }

Mouse move event (draw on canvas if pressed):
        private void paintImageCanvas_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            if(currentSelectedTool == ToolBoxTypes.PencilTool)
            {
                int x1 = Convert.ToInt32(currentPoint.X);
                int y1 = Convert.ToInt32(currentPoint.Y);

                int x2 = Convert.ToInt32(e.GetPosition(paintImageCanvas).X);
                int y2 = Convert.ToInt32(e.GetPosition(paintImageCanvas).Y);

                Console.WriteLine("Mouse X: " + x2 + " Mouse Y: " + y2);
                imageWriteableBitmap.DrawLine(  x1, y1, x2, y2, foregroundColor );

                currentPoint = e.GetPosition(paintImageCanvas);
            }
        }
    }

Ok. That's easy code.
And now, two usecases:

*

*On start and init I can see white canvas and can draw with mouse without any problem (cursor follows pixels):

usecase 1

*I loaded picture (size is 700x600) and got a problem, cursor has different place (can see a shift):

usecase 2
I think that problem is that canvas (Image) has different side than actual picture's side. I'm not sure.
Could you help me please to understand what is wrong and how to fix that?
Thanks.

A: Thanks to Dmitry (see comments on my question) the reason of the problem has been found: DPI of source picture.
I changed my code of picture loading and it works fine:
private void openMenuItem_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "JPEG files (*.jpg)|*.jpg|PNG files (*.png)|*.png";
        if (openFileDialog.ShowDialog() == true)
        {
            BitmapImage image = new BitmapImage(new Uri(openFileDialog.FileName));
            imageWriteableBitmap = new WriteableBitmap(image);
            double dpi = 96;
            int width = imageWriteableBitmap.PixelWidth;
            int height = imageWriteableBitmap.PixelHeight;

            int stride = width * 4;
            byte[] pixelData = new byte[stride * height];
            imageWriteableBitmap.CopyPixels(pixelData, stride, 0);

            BitmapSource bmpSource = BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, stride);

            imageWriteableBitmap = new WriteableBitmap(
                                        bmpSource.PixelWidth,
                                        bmpSource.PixelHeight,
                                        bmpSource.DpiX, bmpSource.DpiY,
                                        bmpSource.Format, null);
            imageWriteableBitmap.WritePixels(
              new Int32Rect(0, 0, bmpSource.PixelWidth, bmpSource.PixelHeight), pixelData, stride, 0);

            paintImageCanvas.Source = imageWriteableBitmap;

        }
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: MongoDB/ Mongoose - how to extend data storage with with GridFS? How can I use GridFS to store data?
I have stored data content in a document as follows:
Schema:
var mongoose = require("mongoose");
var mongoosePaginate = require('mongoose-paginate');

// Declare schema
var streadatamSchema = new mongoose.Schema({
    user_id: {
        type: String,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    public_key: {
        type: String
    },
    private_key: {
        type: String
    },
    data: {
        type: Object
    },
    entries_number: {
        type: Number,
        default: 0
    },
    last_entry_at: {
        type: Date
    },
    created_at: {
        type: Date,
        default: Date.now,
        index: 1 // Note 1
    },
});

streamSchema.plugin(mongoosePaginate);

// Export schema
// Model.paginate()
mongoose.model("Stream", streamSchema);

Example stream:
{
    "_id" : ObjectId("57cfeabd8d9cc38d6d25fd60"),
    "user_id" : "579f52bc53d9e8cc14f504da",
    "title" : "Stream 3",
    "description" : "bla bla bla",
    "public_key" : "CxM2jlAaOHvhC3v4GB",
    "private_key" : "cHeELOOnr2x0WCqdo",
    "data" : {
        "particles" : [
            "27",
            "3",
            "3",
            "8",
            "29",
            "4",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "2",
            "2",
            "2",
            "1",
            "32",
            "0",
            "7",
            "0",
            "5",
            "0",
            "0",
            "1",
            "0",
            "0",
            "0",
            "0",
            "0",
            "0",
            "1",
            "0",
            "0",
            "0",
            "0",
            "0",
            "32",
            "50",
            "52",
            "27",
            "52",
            "3",
            "3",
            "0",
            "0",
            "1",
            "3",
            "17",
            "2",
            "15",
            "0",
            "0",
            "1",
            "48",
            "21",
            "27",
            "7",
            "6",
            "6",
            "2",
            "4",
            "0",
            "0",
            "0",
            "8",
            "2",
            "0",
            "0",
            "3"
        ],
        "timestamp" : [
            1473244226641.0,
            1473244254890.0,
            1473244283134.0,
            1473244311293.0,
            1473244339536.0,
            1473244420579.0,
            1473246125416.0,
            1473246153736.0,
            1473246182281.0,
            1473246210171.0,
            1473246238506.0,
            1473246266681.0,
            1473246294915.0,
            1473246325204.0,
            1473246351579.0,
            1473246379670.0,
            1473246408000.0,
            1473246436252.0,
            1473246464504.0,
            1473246492743.0,
            1473246520906.0,
            1473246549158.0,
            1473246577414.0,
            1473246605652.0,
            1473246633917.0,
            1473246695549.0,
            1473246723868.0,
            1473246752127.0,
            1473246780382.0,
            1473246808543.0,
            1473246836795.0,
            1473246865028.0,
            1473246893295.0,
            1473246921625.0,
            1473246949790.0,
            1473246978115.0,
            1473247006374.0,
            1473247034712.0,
            1473247062773.0,
            1473247091109.0,
            1473247119278.0,
            1473247147609.0,
            1473247175787.0,
            1473247204099.0,
            1473247232287.0,
            1473247260531.0,
            1473247288785.0,
            1473247346870.0,
            1473247375027.0,
            1473247414220.0,
            1473247442496.0,
            1473247470722.0,
            1473247498963.0,
            1473247527122.0,
            1473247555416.0,
            1473247583645.0,
            1473247611975.0,
            1473247640211.0,
            1473247668447.0,
            1473247696712.0,
            1473247724866.0,
            1473247753121.0,
            1473247781412.0,
            1473247809628.0,
            1473247837876.0,
            1473247866137.0,
            1473247894452.0,
            1473247922612.0,
            1473247950961.0,
            1473247979195.0
        ]
    },
    "created_at" : ISODate("2016-09-07T10:23:57.692Z"),
    "entries_number" : 70,
    "species" : [
        {
            "public_name" : "CO2",
            "code_name" : "particles"
        }
    ],
    "__v" : 0,
    "last_entry_at" : ISODate("2016-09-07T11:32:59.195Z")
}

As you can see that the data inside the data can just keep going forever and eventually exceeding the limit - 16MB.
So, how can I extend the data in data with GridFS? Is this possible?
I am using mongoose to store and read data. There are a couple of GridFS packages work with mongooes, gridfs-stream and mongoose-gridfs, but I just have no idea how to integrate them with my existing code.
This is how I inject data into the data field:
var express = require('express');
var router = express.Router();

// Import dependencies.
var mongoose = require("mongoose");

// Import the User schema and the authentication middleware.
var Stream = mongoose.model("Stream");

// GET or POST request to push data to a stream.
// @format:
// http://127.0.0.1:8080/input/<public_key>?private_key=<private_key>&field1=<value>&field2=<value>
// @example:
// http://127.0.0.1:3000/input/ksdoLOZ99qpdL9?private_key=PSsoE6nXcHN7&particles=1.2
router.get("/", log);
router.get("/:publicKey", log);
router.post("/:publicKey", log);

function log (req, res) {

    // Get values from request arguments
    var publicKey = req.params.publicKey;

    // The private key might come in the header or as a GET var depending on the method used for sending data.
    var privateKey = req.headers['stream-private-key'] ? req.headers['stream-private-key'] : req.query.private_key;

    // Strip out cruft
    delete req.query.private_key;

    var data = {};

    if (req.method === 'GET') {
        data = req.query;
    }

    if (req.method === 'POST') {
        data = req.body;
    }

    // Check for public key
    if (!publicKey) {
        res.set('Content-Type', 'application/json');
        return res.status(404).send('stream not found');
    }

    // Check for private key
    if (!privateKey) {
        res.set('Content-Type', 'application/json');
        return res.status(403).send('forbidden: missing private key');
    }

    // Make sure they sent some data.
    // Check if the array object is empty then don't update the model.
    if (Object.keys(data).length === 0 && data.constructor === Object) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('no data received');
    }

    var updateQuery = {};data

    // Send status code for each case : -1 if error, 0 if no stream found and 1 if update successful
    Stream.findOne({
        public_key:publicKey,
        private_key:privateKey
    }, function(err, stream) {

        if (err) {
            console.log("Error retrieving stream: " + err);
            return res.sendStatus(500);
        }

        if (stream === null) {
            console.log("Either no stream was found for this API key: " + privateKey + " or the stream doesn't have any variables set");
            res.set('Content-Type', 'application/json');
            return res.status(200).send('stream not found');
        }

        // Make sure the stream data (object) has keys in
        if (!Object.keys(stream.data).length > 0) {
            res.set('Content-Type', 'application/json');
            return res.status(200).send('update failed');
        }

        // Build $push query with variables passed in POST request.
        // We check that the variable have already been registered otherwise they"ll be ignored.
        for (var property in stream.data) {
            if (data.hasOwnProperty(property) && stream.data.hasOwnProperty(property)) {
                updateQuery["data." + property] = data[property];
            } else {
                updateQuery["data." + property] = null;
            }
        }

        // Current timestamp.
        var timestamp = Date.now();

        // Insert date data.
        updateQuery["data.timestamp"] = timestamp;

        // Update stream with new values and increment entries_number
        stream.update({
            $push: updateQuery,
            $inc: {entries_number: 1},
            last_entry_at: timestamp
        }, function(err, streamID) {

            if (err) {
                console.log("Error updating stream: " + err);
                return res.sendStatus(-1);
            }

            console.log("New entry for stream with API key: " + privateKey);

            res.set('Content-Type', 'application/json');
            return res.status(200).send('success 1');
        });
    });
};

Any ideas how I can integrate mongoose-gridfs or gridfs-stream with my code above?


text:
Q: Proving a property of tame spectra Let $U$ be a universe. Let $D$ be tame spectra, and let $f:E_1\rightarrow E_2$ be a map of spectra that is a spacewise homotopy equivalence. It is supposed to hold that $f^*: h\mathcal{S}U(D,E_1) \rightarrow  h\mathcal{S}U(D,E_2)$ is a bijection.
I can reduce this claim to proving that $f^*: h\mathcal{P}U(D,E_1) \rightarrow  h\mathcal{P}U(D,E_2)$ is a bijection, where $D$ is now a $\Sigma$-cofibrant prespectrum (i.e. the structure maps are cofibrations), but I have been so far unable to prove that this second map is a bijection.
As the structure maps are cofibrations, it would seem natural to use some lifting diagrams to patch the equivalences together, but against what fibrations?


text:
Q: How to convert a pandas dataframe to matrix format in Python? I have a pandas dataframe df which looks as shown. (df.to_dict() is given at the end):
model   scenario    module
AIM/CGE 2.0 ADVANCE_2020_1.5C-2100  wind_total_share    high    high
SSP1-19 wind_total_share    high    high
SSP2-19 wind_total_share    high    high
AIM/CGE 2.1 CD-LINKS_NPi2020_400    wind_total_share    high    high
TERL_15D_LowCarbonTransportPolicy   wind_total_share    medium  medium
TERL_15D_NoTransportPolicy  wind_total_share    medium  medium
GCAM 4.2    SSP1-19 wind_total_share    medium  medium
IMAGE 3.0.1 IMA15-AGInt wind_total_share    low low
IMA15-Def   wind_total_share    low low
IMA15-Eff   wind_total_share    low low

model, scenario, and module are indices while Infrastructure and Investment are two columns of the dataframe. I'd like to convert these two columns into the matrix format, where Infrastructure is similar to x-axis and Investment in similar to Y-axis. Furthermore, both in Infrastructure and Investment, I need to classify them into Low, Medium and High.
In the cells, I'd like to have the name of model and scenarios that satisfy the given category (low/medium/high) for given variable (Infrastructure of Investment) as shown in the screenshot below. There could also be cases when a scenario is high for Infrastructure, but low or medium for Investment and vice versa.

I also want to have another matrix, which shows the number of scenarios that fall into given cell. The second matrix matrices should look something as shown:

I am not familiar with getting such matrix format by modifying the existing pandas dataframe. Are there any functions, or module available that could be used for this purpose? How can I convert my dataframe to the matrix format as shown in the screenshots using Python?
df.to_dict() looks as follows:
{'Infrastructure': {('AIM/CGE 2.0',
   'ADVANCE_2020_1.5C-2100',
   'wind_total_share'): 'high',
  ('AIM/CGE 2.0', 'SSP1-19', 'wind_total_share'): 'high',
  ('AIM/CGE 2.0', 'SSP2-19', 'wind_total_share'): 'high',
  ('AIM/CGE 2.1', 'CD-LINKS_NPi2020_400', 'wind_total_share'): 'high',
  ('AIM/CGE 2.1',
   'TERL_15D_LowCarbonTransportPolicy',
   'wind_total_share'): 'medium',
  ('AIM/CGE 2.1', 'TERL_15D_NoTransportPolicy', 'wind_total_share'): 'medium',
  ('GCAM 4.2', 'SSP1-19', 'wind_total_share'): 'medium',
  ('IMAGE 3.0.1', 'IMA15-AGInt', 'wind_total_share'): 'low',
  ('IMAGE 3.0.1', 'IMA15-Def', 'wind_total_share'): 'low',
  ('IMAGE 3.0.1', 'IMA15-Eff', 'wind_total_share'): 'low'},
 'Investment': {('AIM/CGE 2.0',
   'ADVANCE_2020_1.5C-2100',
   'wind_total_share'): 'high',
  ('AIM/CGE 2.0', 'SSP1-19', 'wind_total_share'): 'high',
  ('AIM/CGE 2.0', 'SSP2-19', 'wind_total_share'): 'high',
  ('AIM/CGE 2.1', 'CD-LINKS_NPi2020_400', 'wind_total_share'): 'high',
  ('AIM/CGE 2.1',
   'TERL_15D_LowCarbonTransportPolicy',
   'wind_total_share'): 'medium',
  ('AIM/CGE 2.1', 'TERL_15D_NoTransportPolicy', 'wind_total_share'): 'medium',
  ('GCAM 4.2', 'SSP1-19', 'wind_total_share'): 'medium',
  ('IMAGE 3.0.1', 'IMA15-AGInt', 'wind_total_share'): 'low',
  ('IMAGE 3.0.1', 'IMA15-Def', 'wind_total_share'): 'low',
  ('IMAGE 3.0.1', 'IMA15-Eff', 'wind_total_share'): 'low'}}

A: pivot_table could help here.
The 2nd matrix can be directly obtained with:
df.assign(values=1).pivot_table(values='values', index='Infrastructure',
          columns='Investment', aggfunc=sum)

which gives:
Investment      high  low  medium
Infrastructure
high             4.0  NaN     NaN
low              NaN  3.0     NaN
medium           NaN  NaN     3.0

For the first one, you could first reset the index to build the expected values:
temp = df.reset_index(2, drop=True).reset_index()
temp['value'] = temp['level_0'] + ' ' + temp['level_1']
df2 = temp.pivot_table(values = 'value', index='Infrastructure',
                       columns='Investment', aggfunc=list)

In df2 multiple identifiers are grouped in a list. If you want them one per row, you can explode the dataframe:
df2.explode('high').explode('medium').explode('low')

to get
Investment                                    high                      low                                         medium
Infrastructure
high            AIM/CGE 2.0 ADVANCE_2020_1.5C-2100                      NaN                                            NaN
high                           AIM/CGE 2.0 SSP1-19                      NaN                                            NaN
high                           AIM/CGE 2.0 SSP2-19                      NaN                                            NaN
high              AIM/CGE 2.1 CD-LINKS_NPi2020_400                      NaN                                            NaN
low                                            NaN  IMAGE 3.0.1 IMA15-AGInt                                            NaN
low                                            NaN    IMAGE 3.0.1 IMA15-Def                                            NaN
low                                            NaN    IMAGE 3.0.1 IMA15-Eff                                            NaN
medium                                         NaN                      NaN  AIM/CGE 2.1 TERL_15D_LowCarbonTransportPolicy
medium                                         NaN                      NaN         AIM/CGE 2.1 TERL_15D_NoTransportPolicy
medium                                         NaN                      NaN                               GCAM 4.2 SSP1-19

A: I did some brainstorming for a while and came up with the solution myself. It is long, but it looks like this.
First, I made the list of scenarios which are high, medium and low for both Infrastructure and Investment respectively:
infra_high = (df[df["Infrastructure"]=="high"].index.get_level_values(0) + " " + df[df["Infrastructure"]=="high"].index.get_level_values(1)).to_list()
infra_medium = (df[df["Infrastructure"]=="medium"].index.get_level_values(0) + " " + df[df["Infrastructure"]=="medium"].index.get_level_values(1)).to_list()
infra_low = (df[df["Infrastructure"]=="low"].index.get_level_values(0) + " " + df[df["Infrastructure"]=="low"].index.get_level_values(1)).to_list()

invest_high = (df[df["Investment"]=="high"].index.get_level_values(0) + " " + df[df["Investment"]=="high"].index.get_level_values(1)).to_list()
invest_medium = (df[df["Investment"]=="medium"].index.get_level_values(0) + " " + df[df["Investment"]=="medium"].index.get_level_values(1)).to_list()
invest_low = (df[df["Investment"]=="low"].index.get_level_values(0) + " " + df[df["Investment"]=="low"].index.get_level_values(1)).to_list()

Next, I did the intersection of the scenarios which are high, high; high, medium and high, low for Infrastructure and Investment as follows:
i1 = list(set(infra_high).intersection(set(invest_high)))
i2 = list(set(infra_high).intersection(set(invest_medium)))
i3 = list(set(infra_high).intersection(set(invest_low)))

i4 = list(set(infra_medium).intersection(set(invest_high)))
i5 = list(set(infra_medium).intersection(set(invest_medium)))
i6 = list(set(infra_medium).intersection(set(invest_low)))

i7 = list(set(infra_low).intersection(set(invest_high)))
i8 = list(set(infra_low).intersection(set(invest_medium)))
i9 = list(set(infra_low).intersection(set(invest_low)))

Next, using the Excel file, I recreated the matrix I wanted to make:

Then, I assigned the list for each cell of the dataframe as follows:
landing_zone1.loc["High","High"] = i1
landing_zone1.loc["High","Medium"] = i2
landing_zone1.loc["High","Low"] = i3

landing_zone1.loc["Medium","High"] = i4
landing_zone1.loc["Medium","Medium"] = i5
landing_zone1.loc["Medium","Low"] = i6

landing_zone1.loc["Low","High"] = i7
landing_zone1.loc["Low","Medium"] = i8
landing_zone1.loc["Low","Low"] = i9

And I did the same for matrix of number of scenarios using len() of each list.


text:
Q: Condition to display image in Javascript I'm looking for create a small javascript code to display images if their src is valid.
I have to separate the script to the html page for better organisation.
Here is what I did :
HTML

JavaScript
var thumbnail = document.images.thmb;

    if(thumbnail.src)
    {
        if(thumbnail.onerror)
        {
            thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
        }
    }
    else
    {
        thumbnail.style.display = "none";
    }

Bu it doesn't work, when I empty the src code in HTML, the border of the image still in the page. And if I write a wrong URL, we can't see the image set in the JavaScript.
Here is the JSFiddle to experiment it.
http://jsfiddle.net/gUb8X/
I'm a beginner in JavaScript.
Thank you !

A: A neat inline solution would be this
DEMO http://jsfiddle.net/LstNS/25/

jQuery:
You can use an ajax call to check if the image file exists
$.ajax({
    url:'http://yourhost/someimage.ext',
    type:'HEAD',
    error: function()
    {
        //file does not exist
    },
    success: function()
    {
        //file exists do something here
    }
});

DEMO http://jsfiddle.net/LstNS/24/
As you can see in the demo, the second image is not loaded and presented as a broken image as it does not exist.
A non jQuery version would be
var img = document.getElementById("myImg");
img.onerror = function () {
    this.style.display = "none";
}

A: You are too late with the test.
Try this
Live Demo
window.onload=function() {
  var thumbContainer = document.getElementById("thmbDiv");
  var thumbnail = document.createElement("img");
  thumbnail.onload=function() {
    thumbContainer.appendChild(thumbnail);
  }
  thumbnail.src = "http://blog.lefigaro.fr/bd/img-sanctuaire.png";
}

Now replace your image with a div with id thmbDiv
if you put placeholders or hide all images you want to test, you can get the src from a data attribute.
Live Demo
window.onload=function() {
  var imgs = document.images; // or document.getElementsByClassName("testImage");
  for (var i=0, n=imgs.length;i<n;i++) {
    var theImage = imgs[i];
    var src = theImage.getAttribute("data-src");
    if (src) {
      theImage.onerror=function() {
        this.style.display="none"; // or this.parentNode.removeChild(this);
      }
    }
    theImage.src=src;
  }
}

A: Your code now tests for thumbnail.src, which means that you are testing for the existence of an src propery, which always exists for a syntactically valid img element. Then you test for the existence of an onerror event handler, and since there is none, you take a branch that does nothing.
A way that works is to use an onerror attribute in the img element and make it remove the element (or remove it from rendering, but actually removing the element is more logical, and safer):

Unfortunately, you can't do this so with a loop that traverses through all img elements. If you try that, your code will run only after the image loading has been performed, so it would be too late to try to set onerror handlers on them.

A: I just found a little trick to make it possible. That doesn't follow the convention but it works. I just use the "alt" image keyword as the "src" keyword, and the JavaScript gives the src equals to alt attribute found in the html.

Javascript :
var img = document.getElementById("thmb");
img.src= img.alt;

img.onerror = function () {
    img.style.display = "none";
}

http://jsfiddle.net/LstNS/28/
To more, because I have to use a function to return all the final html code, I did this :
display: function (data) {
                            var pid = data.record.project_id;
                            var thb = data.record.Thumbnail;
                            var base_url = "<?php echo base_url('project');?>/";
                            function checkImg(){
                                try
                                {
                                    var thumbnail = document.createElement("img");
                                    thumbnail.src = thb;
                                } catch(err) {
                                    //
                                }
                                if(thumbnail.height > 0){
                                    var result = 'src="' + thb + '"';
                                }
                                else
                                {
                                    var result = 'style="display:none;"';
                                }
                                return result;
                            }
                            return '';
                        }

I have to thank you for all your answers which permit me to find a good way to do it !
If you have comments to do, don't hesitate ! ;)


text:
Q: Homepod touch interface is now causing homepod to speak its commands - how to turn off? My Homepod (original) has started doing this weird thing where it 'says' the thing when you use the touch controls in a robotic (non Siri) voice.  It says 'play' or 'pause' or 'increase volume' or 'decrease volume'.  I thought maybe it was some accessibility feature but I haven't changed anything and can't find a setting about this.

A: Same thing happened to mine after the latest update.
You can fix it by toggling Voiceover on and off under the Homepod settings in the Home app.


text:
Q: Xcode Preprocessed File Troubleshooting Circular Import Loop I am using Xcode 4.6.2 and i believe i am facing circular import issue in my project which i am unable to troubleshoot. Due to which i am not able to access few methods from another class using the class method. See my earlier question here.
Although i am using @class instead of #import in my header files, still i am unable to fine where exactly the problem is. Members of the StackOverflow have suggested me to use Xcode's built in functionality found under Product > Generate Output > Preprocessed File.
I have used this functionality and it generated a file that is too long to follow and i don't know what to do with it.
I have tried searching how to use it to troubleshoot the issue but couldn't find much help. Can anyone help me point out how to use "Preprocessed File" to troubleshoot my issue. Thanks!

A: I also went through your earlier question you have mentioned inside the question. You have said that you are using @class instead of #import in your header files, the methods that you are trying to access are declared in the header files and there are no typos of any kind.
In such cases, usually no body points this issue but i am going to do it anyway because i have faced such issues many times. You have probably created many copies of your project to work on each functionality and also keeping a working project.
When you do this, sometimes Xcode is still using the older copies of few files. That means it is still using the older copy of the TheFeedStore.h when the methods you are trying to access were not declared by you.
How to solve this problem is very simple. Go to the file from which you are trying to access the methods and the files in which these methods are declared.
In the Utilities section on the right hand side, check the location and full path under "Identity and Type" area.
First check the names of the project, if it is different from the project name that you are working on, that means Xcode is still pulling the old copies of the files from the previous revision of your project. See the blue arrows where the project name is 13SampleMoreRequests in my case.

If this name is same as your project name, then my answer does not solve your problem. If its different, you should use the new copies of the file by browsing the new location using the sign that is pointed out by red arrow.
Once you browse and use the new files, your problem will be solved and you will be able to access the methods. If you still can't, copy these files, delete from the project and then add them again and you won't face this problem.
Hope this helps!


text:
Q: Are time series methods only good for forecasting? Many time series methods are oriented solely in terms of forecasting (e.g., ARIMA). However, it seems like a growth curve modeling framework (i.e., random coefficient modeling) can do virtually everything else. For instance instead of performing interrupted time series analysis via segmented regression, one can just use a discontinuous growth model. To account for autocorrelation, AR terms can be included within the level-1 growth curve model as well. Even seasonal models (i.e., harmonic and those with indicator variables) can just as easily be used within the growth curve modeling approach at level-1. It also handles multiple "subjects" much better; rather than having to perform a multivariate time series analysis, the growth curve model naturally accommodates additional sources of observations (e.g., people, economic indices).
So my question is:
Am I missing something, or is time series analysis (for all intents and purposes) just a collection of forecasting methods, with any explanatory modelling handleable by the regular multilevel growth curve model?
It seems to me that this might be the case, as there is no essential difference between time series data and longitudinal in data, other than time series are longer and generally pertain to an in-depth analysis of one "subject" (e.g., GDP; see Difference between longitudinal design and time series).

A: Usually you want to forecast the behaviour of a system to improve your reaction to and interaction with that system. But at the end of the day, forecasting is only a last resort, if it is not feasible to control the system. Moreover, forecasting with nothing but time series is something you usually only do if your system is so complex that you cannot incorporate any useful other knowledge about it into your forecasts.
Time-series analysis gives you a lot of methods to understand the inner workings of a system, which in turn may be the first step to controlling it. For example, it may yield the following information:

*

*What are the internal rhythms of the system and what is their relevance to my observable?

*To what extent is my system noise-dominated and how does that noise look like?

*Is the system stationary or not – the latter being an indicator for long-term changes of external conditions influencing the system.

*If I regard my system as a dynamical system, what are the features of the underlying dynamics: Is it chaotic or regular? How does it react to perturbations? How does its phase space look like?

*For a system with multiple components: Which components interact with each other?

*How do I model my system if I want my model to do more than just reproduce certain features of observed time series, such as yielding an understanding of the system, properly describing situations that are not comparable to anything that has been observed in the past at all, e.g., when I actively manipulate the system or an extreme event happens (such as in a disaster simulation). All of the above points can play into this and moreover, time-series analysis can be used to verify a model by comparing the time series of the original and the model.

Some practical examples:

*

*Climate research employs a lot of time-series analysis but is not only good for forecasting climate but also tries to answers the important question of how we influence our climate.

*If you have a time series related to the illness of an individual female patient and you find a strong frequency component of roughly one month, this is a strong hint to the menstrual cycle being somehow involved. Even if you fail to understand this relation, and can only treat the symptoms by giving some medication at the right time, you can benefit from taking the actual menstrual cycle of that patient into account (this is an example were you forecast with more than just time series).

A: I would say no. Time series methods can reveal something about the structure of the problem in hand, not just about some forecasts done only with series own history.
For example state-space model form can be used to model time varying regression with several varieties. And also structural time series can be casted into state space form.
Zellner and Palm wrote an article about the combining structural and time series modeling.
ftp://ftp.uic.edu/pub/depts/econ/hhstokes/e537/zellner_palm_je74.pdf

A: No. I'll give you one use of time series, which is not related to forecasting: spectral analysis.
FFT is the work horse in spectral analysis, but it works best when your series are essentially infinite, or very long. Analyzing sound waves is a good application for FFT. However, in social sciences the series are usually not very long. Usually we have a few dozen observations at most. So in these cases you can use Yule-Walker equations to obtain a periodogram of the series, e.g. see MATLAB pyulear function.


text:
Q: Can we implement a openID options in a Native iPhone App? Is is possible to implement OpenId authentication in iPhone? I found a framework named janrain. But with free sign up, we can avail only features. Is there any other open source framework  available?
Thanks !!

A: I found a solution that uses a standard UIWebView to handle the authentication.  Since cookies are shared within an app, a successful authentication with a UIWebView (that stores a session or authentication cookie) will carry over to other requests.
I don't have a formal framework, but it works like this:  I issue a REST request.  If the request returns a JSON string, then I'm already authenticated and all is good.  If the request returns a redirect (i.e., 301), then the site is trying to redirect for authentication.  Here I stop the redirect and present a modal UIWebView with the sign in page.  The user can sign in with their OpenID, and once the user is authenticated is redirected to a predetermined success url.
The UIWebView -(void)webViewDidFinishLoad:(UIWebView *)webView delegate method checks each URL after it's loaded, and dismisses the modal once it sees that the success url was requested.
That's basically how I did it and it seems to work.


text:
Q: Predicting a continuous variable with PLS regression (mixOmics) I am doing PLS regression with the mixOmics package but struggle with the prediction part. So, if my model with three compoments is pls.res, predict(pls.res, newdata) gives a list with predict, variates and B.hat. predict is a matrix with dimensions 100x1x3. The documentation says that the latter dimension is the model dimensions. Since my response is a one-dimensional vector only, I guess that the model dimensions correspond to the components. But how can I get the most accurate prediction of Y from the PLS model?
An example; if I want to predict wt from the mtcars dataset using PLS regression:
library("mixOmics")
df <- mtcars
pls.res <- pls(df[,1:5], df$wt, mode = "regression")
pls.pred <- predict(pls.res, df[,1:5])
head(pls.pred)

produces the following (truncuated) output
$predict
, , dim1
                           Y
Mazda RX4           2.857348
Mazda RX4 Wag       2.857348
...

, , dim2
                           Y
Mazda RX4           2.847449
Mazda RX4 Wag       2.847449
...

$variates
                          dim1        dim2
Mazda RX4           -0.8392959 -0.02104679
Mazda RX4 Wag       -0.8392959 -0.02104679
...

$B.hat
, , dim1
              Y
mpg  -0.2161400
cyl   0.1949251
...

, , dim2
                 Y
mpg  -0.4171832787
cyl   0.0002618905
...

$call
predict.mixo_pls(object = pls.res, newdata = df[, 1:5])

and I don't understand the difference between the (in this case) two dimensions of $predict


text:
Q: Convert a Java List of Lists to Scala without O(n) iteration? Answers to this question do a good job of explaining how to use Scala's Java Converters to change a Java List into a Scala List. Unfortunately, I need to convert a List of Lists from Java to Scala types, and that solution doesn't work:
// pseudocode
java.util.List[java.util.List[String]].asScala
  -> scala.collection.immutable.List[java.util.List[String]]

Is there a way to do this conversion without an O(N) iteration over the Java object?

A: You need to convert the nested lists as well, but that would require the up front O(n):
import scala.collection.JavaConverters._

val javaListOfLists = List(List("a", "b", "c").asJava, List("d", "e", "f").asJava).asJava
val scalaListOfLists = javaListOfLists.asScala.toList.map(_.asScala.toList)

Alternatively, you could convert the outer list into a Stream[List[T]], that would only apply the conversion cost as you accessed each item
val scalaStreamOfLists = javaListOfLists.asScala.toStream.map(_.asScala.toList)

If you don't want to pay the conversion cost at all, you could write a wrapper around java.util.List which would give you a scala collection interface. a rought shot at that would be:
def wrap[T](javaIterator: java.util.Iterator[T]): Stream[T] = {
  if (javaIterator.hasNext)
    javaIterator.next #:: wrap(javaIterator)
  else
    empty
}

val outerWrap = wrap(javaListOfLists.iterator).map(inner => wrap(inner.iterator()))

A: alternatively you can use scalaj-collection library i wrote specifically for this purpose
import com.daodecode.scalaj.collection._

val listOfLists: java.util.List[java.util.List[String]] = ...
val s: mutable.Seq[mutable.Seq[String]] = listOfLists.deepAsScala

that's it. It will convert all nested java collections and primitive types to scala versions. You can also convert directly to immutable data structures using deepAsScalaImmutable (with some copying overhead of course)


text:
Q: Run a sh file on machine boot up I am quite new to Linux and want to know what to be done to launch a .sh file on machine startup.
Basically, I have a server machine with Linux OS on it and want to run some jboss application when system restart/crashes
I added S99jBossServers in rc2.d with link to /etc/rc.d/init.d/jBossServers.sh and have given full permission(777) to jBossServers.sh
the content in jBossServers.sh is as follows
#!/bin/sh
#
# chkconfig: 2345 80 30
# description:
#

RETVAL=0

start () {
    /root/batch/startSikkimCA.sh
    /root/batch/startSikkimSp.sh
}

stop () {
    /root/batch/stopSikkimCA.sh
    /root/batch/stopSikkimSp.sh
    RETVAL=$?
}
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        start
        ;;
    *)
        start
;;
        RETVAL=$?
esac
exit $RETVAL

I am not sure whether its correct or not but the 2 paths been refered in

start() and stop()

are correct, but still the application doesn't start on machine's restart.

A: Look at init which is the traditional process starter, and runs scripts under /etc/init.d, /etc/rc1.d, etc. and /etc/rc.local, which is probably the location you want.
Some distributions use upstart instead - if so, look at the docs for that.
In either case the exact paths may vary by distro, but this should be enough to get you started.

A: Try to check whether your scripts are being started (e.g. but putting touch /var/tmp/startup.script into them). Are all commands in your scripts in the search-patch during boot?
Runlevel 2 looks unusual to me. 3 should be normal for a Linux without GUI. What distributution and version are you using?

A: In /etc/inittab look for a line like id:3:initdefault:.  The number will probably be 3 or 5, but might be 2 or 4.  The number in that line is the default runlevel.  Most likely it is not 2, so your scripts in rc2.d will not run.
Put your script in the rcN.d directory that matches the number on the initdefault line.
In principle, rc.local is a better choice, but rc.local varies so much from distro to distro (sometimes it's a directory, sometimes it's a script, sometimes it's not set up at all) that without knowing your distro it's easier to just have you put it in the correct runlevel.  You might try man rc.local and see what that says on your system.  If your system supports rc.local as a directroy, then put your script there and don't worry about the runlevels.
Also, make sure your script is owned by root and has permissions either 755 (if you want anyone to be able to run it) or 744.

A: You can use a cron job for this.  The format is
@reboot myjob.sh

If necessary you can put the cron job in the root crontab, but if possible put it in a user cronjob.

A: You can enable running script in Linux startup by creating symbolic link in /etc/rc<runlevel>.d; <runlevel> is numeric and obtained with this command (runlevel) It means that the run level of your Linux system.
For example:
# runlevel

output:
N 2

To set up customScript with priorty 99:
ln -s /etc/init.d/customScript /etc/rc2.d/S99customScript

*

*S ==> start

*99 ==> priority of startup

A: Adding a startup script
This method works with Red Hat, Fedora, Ubuntu (install package chkconfig and service), Suse.
You should copy your script in /etc/init.d (it's either the proper directory or a link to the proper directory so it will work the same)
sudo cp jBossServers.sh /etc/init.d/
sudo chmod 0755 /etc/init.d/jBossServers.sh

Then you need to add it to the system start-up process. Instead of creating all the required links, use chkconfig (install the package first on Ubuntu)
sudo chkconfig add jBossServers.sh

Now reading your script heading this script has already the information for chkconfig rgarding the runlevels and priority. So you are fine. Next time you reboot JBoos will be started.
But you could try to start right now
sudo service jBossServers.sh start

Note: if your system complains that it does not find chkconfig or service, try to call then with /sbin/ before. Example
sudo /sbin/chkconfig add jBossServers.sh
sudo /sbin/service jBossServers.sh start


text:
Q: SQL Join two tables with same column names, and get sum of each column I know that in the long run... the column names being the same is probably irrelevant.  But here's what I've got:
Master Table:
| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  100 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |   20 |

Supplemental Table
| PersonID |   1972 |   1973 |
|----------|--------|--------|
|        1 |    100 | (null) |
|        2 | (null) | (null) |
|        3 | (null) |    200 |

I'd like to have a table (a view, actually) that will join these two tables, and add the sum of the columns into a column with the same name
Combined Table:
| PersonID | 1970 | 1971 | 1972 | 1973 |
|----------|------|------|------|------|
|        1 |   50 |   50 |  200 |   50 |
|        2 |   30 |   30 |   40 |   40 |
|        3 |   40 |   40 |   40 |  220 |

The resulting table needs to have both tables combined..  The years go all the way to 2017, and are the same name for each table.
SQLfiddle

A: If there is only one matching row per id, then left join does it:
select t1.person_id, t1.[1970], t1.[1971],
       (t1.[1972] + coalesce(t2.[1972], 0)) as [1972],
       (t1.[1973] + coalesce(t2.[1973], 0)) as [1973]
from t1 left join
     t2
     on t1.person_id = t2.person_id

A: Unless you choose to use dynamic SQL (generally best to avoid to prevent SQL injection, bugs, and negative performance impacts), the column names being equivalent doesn't give us any shortcuts here.
The canonical way to do this would be to sum each column explicitly:
SELECT mt.PersonID, COALESCE(mt.[1970], 0) + COALESCE(st.[1970], 0), COALESCE(mt.[1971], 0) + COALESCE(st.[1971], 0), ... COALESCE(mt.[2017], 0) + COALESCE(st.[2017], 0)
FROM MasterTable mt
LEFT JOIN SupplementalTable st
    ON mt.PersonID = st.PersonID;

However, this sucks with 40 columns (and it sounds like possibly more in the future). Dynamic SQL is generally best to avoid, but sometimes it's still the best tool for the job. Here's how you could solve the same problem with dynamic SQL:
DECLARE @dynamicSql NVARCHAR(MAX);
DECLARE @selectList NVARCHAR(MAX);

SELECT @selectList = COALESCE(@selectList + ', ', '') + 'COALESCE(mt.[' + mtColumns.COLUMN_NAME + '], 0)' + COALESCE(' + COALESCE(st.[' + stColumns.COLUMN_NAME + '], 0)', '')
FROM INFORMATION_SCHEMA.COLUMNS mtColumns
LEFT JOIN INFORMATION_SCHEMA.COLUMNS stColumns ON mtColumns.COLUMN_NAME = stColumns.COLUMN_NAME
WHERE mtColumns.TABLE_NAME = 'MasterTable'
      AND stColumns.TABLE_NAME = 'SupplementaryTable';

SET @dynamicSql = 'SELECT ' + @selectList + ' FROM MasterTable mt INNER JOIN SupplementaryTable st ON mt.PersonID = st.PersonID;';

EXECUTE sp_executesql @dynamicSql;

I haven't generated the actual tables to test this, but it should be fairly close. The query should generate a list of SELECT field sums for each field and then run it. It should also skip non-existent fields in SupplementaryTable, and it will only operate for fields that do exist in MasterTable.
Using an ORM (like Hibernate) can do a great deal towards mitigating potential bugs or SQL injection vulnerabilities by validating column names ahead of time.


text:
Q: Diff/compare two files by file descriptor (fd) instead of file name Is there any way in Linux, using c, to generate a diff/patch of two files stored in memory, using a common format (ie: unified diff, like with the command-line diff utility)?
I'm working on a system where I generate two text files in memory, and no external storage is available, or desired. I need to create a line-by-line diff of the two files, and since they are mmap'ed, they don't have file names, preventing me from simply calling system("diff file1.txt file2.txt").
I have file descriptors (fds) available for use, and that's my only entry point to the data. Is there any way to generate a diff/patch by comparing the two open files? If the implementation is MIT/BSD licensed (ie: non-GPL), so much the better.
Thank you.

A: On Linux you can use the /dev/fd/ pseudo filesystem (a symbolic link to /proc/self/fd).  Use snprintf() to construct the path for both file descriptors like snprintf(path1, PATH_MAX, "/dev/fd/%d", fd1); ditto for fd2 and run diff on them.

A: Considering the requirements, the best option would be to implement your own in-memory diff -au. You could perhaps adapt the relevant parts of OpenBSD's diff to your needs.

Here's an outline of one how you can use the /usr/bin/diff command via pipes to obtain the unified diff between two strings stored in memory:

*

*Create three pipes: I1, I2, and O.

*Fork a child process.

*In the child process:

*

*Move the read ends of pipes I1 and I2 to descriptors 3 and 4, and the write end of pipe O to descriptor 1.

*Close the other ends of those pipes in the child process. Open descriptor 0 for reading from /dev/null, and descriptor 2 for writing to /dev/null.

*Execute execl("/usr/bin/diff", "diff", "-au", "/proc/self/fd/3", "/proc/self/fd/4", NULL);
This executes the diff binary in the child process. It will read the inputs from the two pipes, I1 and I2, and output the differences to pipe O.

*The parent process closes the read ends of the I1 and I2 pipes, and the write end of the O pipe.

*The parent process writes the comparison data to the write ends of I1 and I2 pipes, and reads the differences from the read end of the O pipe.
Note that the parent process must use select() or poll() or a similar method (preferably with nonblocking descriptors) to avoid deadlock. (Deadlock occurs if both parent and child try to read at the same time, or write at the same time.) Typically, the parent process must avoid blocking at all costs, because that is likely to lead to a deadlock.
When the input data has been completely written, the parent process must close the respective write end of the pipe, so that the child process detects the end-of-input. (Unless an error occurs, the write ends must be closed before the child process closes its end of the O pipe.)
When the parent process notices that no more data is available in the O pipe (read() returning 0), either it has already closed the write ends of the I1 and I2 pipes, or there was an error. If there is no error, the data transfer is complete, and the child process can be reaped.

*The parent process reaps the child using e.g. waitpid(). Note that if there were any differences, diff returns with exit status 1.
You can use a fourth pipe to receive the standard error stream from the child process; diff does not normally output anything to standard error.
You can use a fifth pipe, write end marked O_CLOEXEC with fcntl() in the child, to detect execl() errors. O_CLOEXEC flag means the descriptor is closed when executing another binary, so the parent process can detect successful starting of the diff command by detecting the end-of-data in the read end (read() returning 0). If the execl() fails, the child can e.g. write the errno value (as a decimal number, or as an int) to this pipe, so that the parent process can read the exact cause for the failure.
In all, the complete method (that both records standard error, and detects exec errors) uses 10 descriptors. This should not be an issue in a normal application, but may be important -- for example, consider an internet-facing server with descriptors used by incoming connections.


text:
Q: Windows bash redirect output has weird encoding I use grep to search for patterns which is working properly. However, when I redirect the output to any file, the output gets corrupted due to the encoding.
Is there a way to make the bash in windows output the file in normal UTF-8 encoding so normal text editors can read it properly?
EDIT:
It looks like this when I redirect output the grep results to any file:
[35m[KFile.txt[m[K[36m[K:[m[K[01;31m

I'm running latest Windows and I have bash installed by using developer mode and enabling the bash.
The output gets messed up in the process. Even Windows version of linux text editors display the weird output. However, if I run cat on the file containing the weird output. It shows the output just fine with no issues.
I'm using Notepad++ to view the results.
Thanks

A: That's not an encoding issue. The program whose output you are capturing is emitting ANSI control codes to set cursor position, foreground colour etc.
When you use cat the control codes are processed by the tty and so don't appear in raw form.


text:
Q: React Native - cannot access data from Array inside Array from json file So I have typical json result from Google maps api
"html_attributions" : [],
   "next_page_token" : "CqQCFgEAAL2fPrvHrkhgi11wNUC40-FEYJ93rH1Bo9FRkqxMfMlvqaEQv6hgiLoJXmeFBFMA6Uw-kcECgRXs_VzE6QVNPMRTrh402Z9Rn1dUVC_2B3WwopG_KNcftFARDQZD0K-a7swHAb_jftghftWtzrTqa8GTKMKuLCHS6ZJooPXOGpndn1h2yYO7bIF4GiPE80HgaLrgZDAJ-bf71LXhWmvmPtPiU0UGZeH1Zp4945yS5PHK1WVCMPoIR2XVqv9d9k08ZKqQPtnNOS1YsvdZOaY1Jy76eFIhCMFr1yhR0GyBmtVs6_wf9yEdi-SXSjqiciD77bk9pKf2p4b8C_9jhY3SJvB9wgLGUbDS0Y3gFG63EHcMKva4FVHFiov-7_abNk3i3RIQGSQOIFfRj3zZaSVngR8PcRoUa9z0FhpaicLUkREG-VRpE_wUZhE",
   "results" : [
      {
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_recreational-71.png",
         "name" : "Park Leśny Zdroje",
         "photos" : [
            {
               "height" : 3024,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/103847965103971799822\"\u003eKSD\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAHvmblqXHuIBST9cZZI3yLtIuay_of90rDBUOoBQ64Luh7U_bVFTK5jhliXE9pFhRWMZjw4yHJXOFbxKQYBmEJwvBLNXkQGZrr5CvjlPT0HBHKququkGzjA8JJvbIdVC4EhCX_9SFH1F88ezn0N9XUaEfGhQpUDqAXZzLaSn0rrIIdMFwjCz6yA",
               "width" : 4032
            }
         ],
      },
]

And i cannot somehow access photo_reference from array photos.
                {parks.results.map((element,index)=>
                    <View key={index} style={AppStyle.mapCard}>
                        <View style={AppStyle.mapCardImg}>
//Tried this
                            <Text>{element.photos.map(item => item.photo_reference)}</Text>
//and this
<Text> {element.photos.photo_reference} </Text>
                        </View>
                        <View style={AppStyle.mapCardDescription}>
                            <Text>{element.name}</Text>
                                <Text>
                                    ({element.rating})
                                </Text>
                            </View>
                        </View>
                    </View>
                )}

I know it's array in array and i need to iterate through it but it doesnt work.
This way: {element.photos.map(item => item.photo_reference)} i have undefined is not an object(evaluating element.photos.map)
This way  {element.photos.photo_reference}  undefined is not an object
Whats the solution in react Native?

A: Google Maps Api is not always returning every property of single Place. Error was that some places doesn't have photos so there's no array in json. The same about rating and others.
Adding conditions to check if variable exists solves problem.
element.photos && element.photos.map(item => item.photo_reference)


text:
Q: Почему selenium не видит тег? Есть сайт https://www.myscore.ru/. Решил распарсить с сайта результаты футбольных матчей с помощью селениума в учебных целях, но никак не могу сделать всё "красиво". Во вкладке "завершенные" получается найти все игры, которые не скрыты. Для того чтобы раскрыть игры какой-либо лиги нужно ткнуть на span, но никак не получается его найти, хоть даже тег обладает собственным классом "expand-league".

Вот часть кода:
driver.get(url)
driver.find_element_by_class_name('li2').click()
ended = driver.find_element_by_class_name('table-main').find_elements_by_class_name('soccer')
for item in ended:
    try:
        league = item.find_element_by_class_name('expand-league')
        league.click()
        print(league.text)
    except NoSuchElementException:
        print('.NoSuchElementException')
    except WebDriverException:
        print('WebDriverException')
    games = item.find_elements_by_class_name('stage-finished')
    for game in games:
        print(game.text)


text:
Q: add input fields dynamically using jquery ajax I'm trying to inserting multiple items connected with quantity and price for each. all of the items will be showing the same invoice number and vendor id.
<form name="order" id="order">

Invoice Number
    <input type="text" name="invoicenumber" value="">

Vendor's ID
<select name="vendorid" >

<?php

    $stmt = $dbcon->prepare("SELECT * FROM customers");
    $stmt->execute();
    while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
        ?>

        <option value=" <?php echo $id; ?> "><?php echo $vendorname; ?></option>

<?php
    } ?>
    </select>

Items sold
    <select name="proid[]" >

<?php

    $stmt = $dbcon->prepare("SELECT * FROM products");
    $stmt->execute();
    while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
        extract($row);
        ?>

        <option value=" <?php echo $pid; ?> "><?php echo $pname; ?></option>

<?php
    } ?>
    </select>

    Quantity
    <input type="text" name="tquantity[]" value="">

    Price
    <input type="text" name="saleprice[]" value="">

    <button name="add" id="add" class="btn btn-success">ADD MORE</button>

    <input type="submit" name="submit" value="submit">
</form>

So I'm trying to add input fields dynamically using jQuery ajax following a tutorial but i can't seem to make it work
When I click add to add fields only the link changes to /admin/addinvoice.php?invoicenumber=&vendorid=+2+&proid[]=+10+&tquantity[]=&saleprice[]=&add=
and it's not adding a field


text:
Q: How to partition the array into exactly K non-empty subarrays such that the sum of values of each subarray is equal? You are given an array A of size N, with all values as non-negative integers. Bodega asked you whether it is possible to partition the array into exactly K non-empty subarrays such that the sum of values of each subarray is equal. If it is possible print "Yes", otherwise print "No".
Note:
Every element of the array should belong to exactly one subarray in the partition.
Sample:
3 0 1 2 0 0 6 0 1 5
Sample Output 2:
Yes
Explanation:
The array can be partitioned as {3, 0, 1, 2, 0, 0}, {6}, {0, 1, 5}.
My code :
listt = [3,0,1,2,0,0,6,0,1,5]
# listt.sort()
# listt = [i for i in listt if i != 0]

def find_next_sum(summ,listt,last_index,counter):
    if last_index == 0: #i.e if we are just starting with our listt
    #start iterating
        for i in range(last_index,len(listt)-1):
            #start journey with first sum as 0:i
            print("reset : last_index:",i+1,"sum:",sum(listt[0:i+1]))
            result = find_next_sum(sum(listt[0:i+1]),listt,i+1,1)
            print(result)
        #if we have completed above loop and still last_index == 0
        #that means its not possible

    else:
        # print('else')
        #else if we already have a sum find next summ that match
        #starting from last index of previous sum
        for j in range(last_index,len(listt)):
            next_summ = sum(listt[last_index:j+1])
            print("current_sum:",summ,"next_sum:",next_summ,"last_index:",last_index,"end_index:",j+1)

            if summ == next_summ:
                if j+1 == len(listt):
                    #if we have reached end of list and sums match
                    # print('Yes')
                    return 'Yes'
                if j+1 < len(listt):
                    # find next next sum
                    # print('find next_sum')
                    find_next_sum(next_summ,listt,j+1,counter+1)

            elif summ != next_summ:
                if next_summ<summ and j+1 < len(listt):
                    # find new next sum
                    # print('continue')
                    continue
                if j+1 == len(listt):
                    #give up
                    # print('No')
                    return 'No'
            # reset or find new first sum (this returns None)
            break

find_next_sum(0,listt,0,0)


text:
Q: G Suite Admin SDK Directory API Example - "Error: Bad Request" I am following the example at Node.js Quickstart and when I run it I get the error

"The API returned an error: Error: Bad Request".

This is generated from listUsers(auth). Since the error is so ambiguous I am not sure how to troubleshoot.
function listUsers(auth) {
    var service = google.admin('directory_v1');
    service.users.list({
        auth: auth,
        customer: 'my_customer',
        maxResults: 10,
        orderBy: 'email'
    }, function(err, response) {
        if (err) {
            console.log('The API returned an error: ' + err);
            return;
        }
        var users = response.users;
        if (users.length == 0) {
            console.log('No users in the domain.');
        } else {
            console.log('Users:');
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                console.log('%s (%s)', user.primaryEmail, user.name.fullName);
            }
        }
    });


text:
Q: Не устанавливается приложение apk на телефон Создал приложение в android studio, компилируется, подключенный телефон принимает его, все работает. Но если передаю apk файл другому телефону, он не устанавливает, так и на моем, удалил приложение, установил его через apk файл, он не устанавливает "приложение не установлено". Что требуется изменить в самой программе или где, чтоб устанавливалось?

A: Вероятнее всего у вас не установлена опция "Установка из неизвестных источников".
Для Android начиная с 8 версии мы можем предоставить разрешение на установку приложений из неизвестных источников только для этого Приложения. Включаем разрешение:

Для более старых девайсов:

A: Вариантов несколько.

*

*Если на телефоне уже стояло это приложение с другой подписью и его пытаются обновить, то ничего не выйдет. Надо удалить старое и ставить новое.

*Запрещена установка из неизвестных источников. Хотя при попытке установки приложения система должна уведомить вас.

*Попробуйте еще в AndroidStudio сделать Build->Build Bundle(s)/APK(s)->Build APK(s). После этого внизу появится сообщение об успешном билде и нажмите в нем locate. Откроется папка с APK файлом. Попробуйте его передать на смарт и запустить. Должно сработать.


text:
Q: log4net filtering on exception message? How can I filter logging based on a logged exception's message?
Code looks like this:
try {
    someService.DoSomeWorkflow();
} catch(Exception e) {
    log.Error("Hey I have an error", e);
}

Config looks like this:
<appender name="EventLogger" type="log4net.Appender.EventLogAppender">
    <applicationName value="foo" />
    <layout type="log4net.Layout.PatternLayout" value="PID:%P{pid}: %message" />
    <filter type="log4net.Filter.StringMatchFilter">
        <stringToMatch value="TextInsideTheException" />
    </filter>
</appender>

I'm finding that I can filter only on the logged message ("Hey I have an error") but it seemingly ignores the exception's message.  Since this is in our production environment I can't make any code changes so I can't change the logged message.  Is there some configuration that would specify to also check the exception's message?

A: By subclassing FilterSkeleton, you can implement a filter that evaluates the exception text. Or exception type for that matter.

A: Here are basic implementations based on Peter's accepted answer
using System;
using log4net.Core;

namespace log4net.Filter
{
    public abstract class ExceptionFilterBase : FilterSkeleton
    {
        public override FilterDecision Decide(LoggingEvent loggingEvent)
        {
            if (loggingEvent == null)
                throw new ArgumentNullException("loggingEvent");

            var str = GetString(loggingEvent);
            if (StringToMatch == null || string.IsNullOrEmpty(str) || !str.Contains(StringToMatch))
                return FilterDecision.Neutral;
            return AcceptOnMatch ? FilterDecision.Accept : FilterDecision.Deny;
        }

        protected abstract string GetString(LoggingEvent loggingEvent);

        public string StringToMatch { get; set; }

        public bool AcceptOnMatch { get; set; }
    }

    public class ExceptionMessageFilter : ExceptionFilterBase
    {
        protected override string GetString(LoggingEvent loggingEvent)
        {
            return loggingEvent.ExceptionObject == null
                ? null : loggingEvent.ExceptionObject.Message;
        }
    }

    public class ExceptionTypeFilter : ExceptionFilterBase
    {
        protected override string GetString(LoggingEvent loggingEvent)
        {
            return loggingEvent.ExceptionObject == null
                ? null : loggingEvent.ExceptionObject.GetType().FullName;
        }
    }

    public class ExceptionStackFilter : ExceptionFilterBase
    {
        protected override string GetString(LoggingEvent loggingEvent)
        {
            return loggingEvent.ExceptionObject == null
                ? null : loggingEvent.ExceptionObject.StackTrace;
        }
    }
}

Configuration file
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="Client.log" />
  <layout type="log4net.Layout.PatternLayout">
   <conversionPattern value="%date{yyyy/MM/dd HH:mm:ss,fff} [%-5level] %logger - %message%newline" />
  </layout>
  <filter type="log4net.Filter.StringMatchFilter">
    <stringToMatch value="Token is not valid." />
    <acceptOnMatch value="false" />
  </filter>
  <filter type="log4net.Filter.ExceptionMessageFilter, YourAssembly">
    <stringToMatch value="Application is not installed." />
    <acceptOnMatch value="false" />
  </filter>
  <filter type="log4net.Filter.ExceptionTypeFilter, YourAssembly">
    <stringToMatch value="System.Deployment.Application.DeploymentException" />
    <acceptOnMatch value="false" />
  </filter>
  <filter type="log4net.Filter.ExceptionStackFilter, YourAssembly">
    <stringToMatch value="at System.Deployment.Application.ComponentStore.GetPropertyString(DefinitionAppId appId, String propName)" />
    <acceptOnMatch value="false" />
  </filter>
</appender>

A: Try this:
log.Error("Hey I have an error: " + e.Message);

Edit: Sorry, didn't see that you cannot change that line...


text:
Q: Rust - return a mutable reference to an element in Vec owned by a struct Here is my struct:
pub(crate) struct Graph {
    outbound: HashMap<isize, Vec<isize>>,
    inbound: HashMap<isize, Vec<isize>>,
    edges: Vec<Edge>,
}

and what I tried:
fn get_edge_mut(&mut self, from_id: isize, to_id: isize) -> Result<&mut Edge, GraphError> {
    let mut edges = self
        .edges
        .iter_mut()
        .filter(|edge| edge.get_from() == from_id && edge.get_to() == to_id)
        .collect::<Vec<_>>();
    match edges.len() {
        0 => Err(GraphError(format!(
            "edge from {} to {} does not exist",
            from_id, to_id
        ))),
        1 => Ok(edges[0]),
        _ => panic!(
            "wrong graph structure - edge from {} to {} exists multiple times",
            from_id, to_id
        ),
    }
}

The problem is here: Ok(edges[0])
It fails with cannot return value referencing local variable "edges"
I understand that edges is owned by the current function and I cannot return a reference to it because it goes out of scope, but what would be a better way to return a mutable reference to an element in the "edges" Vec (of the struct) based on some condition?

A: I would suggest using:
    fn get_edge_mut(&mut self, from_id: isize, to_id: isize) -> Result<&mut Edge, GraphError> {
        self.edges.iter_mut()
            .find(|edge| edge.get_from() == from_id && edge.get_to() == to_id)
            .ok_or(GraphError(format!("edge from {} to {} does not exist", from_id, to_id)))
    }

It skips your "wrong graph structure check", but if it's needed, you could go with
fn get_edge_mut(&mut self, from_id: isize, to_id: isize) -> Result<&mut Edge, GraphError> {
    let mut edges_matching = self.edges.iter_mut()
        .filter(|edge| edge.get_from() == from_id && edge.get_to() == to_id);

    let edge = edges_matching.next()
        .ok_or(GraphError(format!("edge from {} to {} does not exist", from_id, to_id)));

    assert_eq!(edges_matching.count(), 0,
               "wrong graph structure - edge from {} to {} exists multiple times",
               from_id, to_id);

    edge
}

It seems like the issue might stem from edges[0] ultimately calling SliceIndex::index, which basically returns an Option<&&mut Edge>, where that first & is actually a reference to the current function.
trendcl is right, edges.pop() works too.


text:
Q: Panel data sequence adding for a particular value I am really new in r and stackoverflow. Apologies in advance for this novice question.
I have a panel data set like the following table.
 ID  Choice
  1     1
  1     1
  1     2
  1     5
  1     1
  2     1
  2     1
  2     5
  2     1
  2     1
  3     3
  3     1
  3     1
  3     2
  3     4

I want to add another column like the following table when choice is 1. This is basically, sequencing the choice 1 within ID.
 ID  Choice  BUS
  1     1  0  (The first 1 will be considered as 0)
  1     1  1
  1     2  1
  1     5  1
  1     1  2
  2     1  0
  2     1  1
  2     5  1
  2     1  2
  2     1  3
  3     3  0
  3     1  0
  3     1  1
  3     2  1
  3     4  1

A: with(df, ave(Choice == 1, ID, FUN = cumsum))

Almost gives you what you want but as you want to consider first 1 as 0 it needs some modification.
df$BUS <- with(df, ave(Choice == 1, ID, FUN = function(x) {
     inds = cumsum(x)
    ifelse(inds > 0, inds - 1, inds)
}))

df

#   ID Choice BUS
#1   1      1   0
#2   1      1   1
#3   1      2   1
#4   1      5   1
#5   1      1   2
#6   2      1   0
#7   2      1   1
#8   2      5   1
#9   2      1   2
#10  2      1   3
#11  3      3   0
#12  3      1   0
#13  3      1   1
#14  3      2   1
#15  3      4   1

Here we subtract 1 from cumulative sum from the first 1.

Using the same logic in dplyr
library(dplyr)
df %>%
  group_by(ID) %>%
  mutate(inds = cumsum(Choice == 1),
        BUS = ifelse(inds > 0, inds - 1, inds)) %>%
  select(-inds)

A: We can also use data.table
library(data.table)
setDT(df1)[, BUS := pmax(0, cumsum(Choice == 1)-1), ID]
df1
#    ID Choice BUS
# 1:  1      1   0
# 2:  1      1   1
# 3:  1      2   1
# 4:  1      5   1
# 5:  1      1   2
# 6:  2      1   0
# 7:  2      1   1
# 8:  2      5   1
# 9:  2      1   2
#10:  2      1   3
#11:  3      3   0
#12:  3      1   0
#13:  3      1   1
#14:  3      2   1
#15:  3      4   1

data
df1 <- structure(list(ID = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
 3L, 3L, 3L, 3L, 3L), Choice = c(1L, 1L, 2L, 5L, 1L, 1L, 1L, 5L,
 1L, 1L, 3L, 1L, 1L, 2L, 4L)), class = "data.frame", row.names = c(NA,
 -15L))


text:
Q: How to get the first page of uploaded file and create thumbnail of it in react Js? There is a form through which Im uploading a presentation (accepted formats are ppt or pdf). When the user uploads the presentation file I want to convert the first slide into an image and show that in the form of thumbnail (refer to image). How to achieve this on frontend (React Js).
(https://i.stack.imgur.com/Qxk8N.png)
I tried using react pdf-viewer library but it need url of the uploaded file for which first i need to upload the file to the backend and this package only works for pdf files.So im thinking good appraoch will be to access the first page of uploaded file and convert it to an image. But im unable for access the first page of uploaded file and convert it to image in react js. Kindly help.


text:
Q: Convert a router to a switch? I have a couple of modem/routers that came with ISP services that are no longer being used. At the moment I have the current ISP's router running the wireless network and a wired portion to a couple of rooms. In one of those rooms I have a switch to connect all the computers there to the cable coming from the router.
In the other room I have a couple of cables (actually one split into two) but I need at least one additional wired connection there.
Can I convert the existing routers that I have to behave as switches? I don't want these routers to control their own subnet giving IPs to devices connected to it. They should be as transparent to the network as if I just had a few additional wired connections available there.

A: That very much depends on the routers.
If you can disable the DHCP server on the router and the router has a built-in switch then yes, you should be able to use it without problems.
If you can't disable the DHCP server then It'll cause problems on your network, so don't use it.

A: *

*Disabling DHCP is one step

*The next step is not using the typically upstream connected WAN port and using only the LAN ports for upstream (connect to router etc) as well as downstream (clients) will cause the LAN ports to behave as as switch and then it would need to pull DHCP IP from an upstream device such as Consumer/ Internet Router or DHCP Server (on a NAS or Domain Controller).

For E.g., In this Home Media Network below the Router WR1 is a DHCP provider for the Local Subnet while the Router WR2 is connected via LAN ports with WAN disconnected. That way they are all on the same Subnet and all IPs are managed via WR1 (Tomato USB firmware based Router)
If I was to connect WR2 using the WAN port (with its own DHCP enabled) it would create another Subnet of its own.


text:
Q: The question related to a regular surface.
Prove that an equation of the form $f(x,y,z)=c$ determines a regular surface if $f$, defined on some open subset $S$ of $\mathbb{R}^3$, is smooth and $\nabla f\neq 0$ everywhere in $S$.

I know these following definitions:
(1) a smooth surface $S$ is  regular if for any surface patch $\sigma$ of $S$, we have $\vert\vert \sigma_u \times \sigma_v\vert\vert \not=0$
(2) a topological surface $S$ in $\Bbb R^3$ issmooth if all coordinate charts are smooth.
(3) $f:U\to \Bbb R^m$ is smooth if all partial derivatives of $f$ of any order exist on $U$.
Please help me solving the question. Thank you.

A: Hint: use the implicit function theorem.

Added: the implicit function theorem has many (seemingly) different statements, but the gist of it is that the level sets of a regular (i.e., one which admits a full-rank differential) $C^1$ (or $C^\infty$) map are locally graphs of a $C^1$ (or $C^\infty$, respectively) function. This function is precisely the patch (which I assume is a different name for a local coordinate system) you require, and if I may presume, I urge you to verify that you are comfortable with this 'language'.
More precisely, in this context, the implicit function theorem affords us for each $(x_0,y_0,z_0)\in S$ such that $f(x_0,y_0,z_0)=c$ and (w.l.o.g.) $\frac{\partial f}{\partial x}(x_0,y_0,z_0)\neq 0$, a neighborhood $U$ of $(y_0,z_0)$ and $V$ of $x_0$ such that $\frac{\partial f}{\partial x}$ doesn't vanish in $V$, $V\times U\subset S$, and a $C^1$ function $g:U\to V$ such that  for all $(x,y,z)\in V\times U$ one has $f(x,y,z)=c$ if and only if $x=g(y,z)$.
Moreover, we have
$$\frac{\partial g}{\partial y}(y,z) = -\left(\frac{\partial f}{\partial x}(g(y,z),y,z)\right)^{-1}\frac{\partial f}{\partial y}(g(y,z),y,z),$$
and similarly for $z$, which helps us to easily verify that $g$ is also $C^\infty$, whenever $f$ is.
This is precisely what we need to note that $\varphi:U\to S$ defined $\varphi(y,z) = (g(y,z),y,z)$ is a patch for the surface $f=c$ in a neighborhood $V\times U$ of $(x_0,y_0,z_0)$, and that
$$\varphi_y(y,z)\times\varphi_z(y,z) = \left(g_y(y,z),1,0\right)\times\left(g_z(y,z),0,1\right) =\\ = (1,-g_y(y,z),-g_z(y,z)) =\\ = \left(\frac{\partial f}{\partial x}(g(y,z),y,z)\right)^{-1}\nabla f(g(y,z),y,z)\neq \overline{0}$$


text:
Q: Using matlab to calculate and plot a set of elastic data I'm considering using Matlab to plot a graph for some sets of elastic data.
Here is the question:
In the mantle, density varies from 2.0 to 5.0 g/cm^3, the bulk modulus varies from 0.0 to 6.6 x 10^11 N/m^2, and the rigidity modulus varies from 0.0 to 2.9. The propose is to determine the greatest effect on P-wave velocities.
The formula for this is: v = sqrt((K+(4/3)u)/p)
which:
v P-wave velocity
p density
k bulk modulus
u rigidity modulus
So now I wish to represent a graph for all value of v in order to observe the greatest value, but I have no idea how to do that.
Thank you very much in advance.


text:
Q: VB.NET 10 items in a list - if there's a new item notify I tried alot of things but it never worked :/
On my site, there's a list of the "10 newest members". I'm trying to do a new "orange" member notification on my application. There is white, grey and orange new members. For now I found how to get the source code of the newest orange members on my site with this : (RichTextBox1 is where my site sourcecode is)
            Dim list As New List(Of String)
            For Each line In RichTextBox1.Lines
                If line.Contains("255, 153, 51") Then
                    list.add(line)
                End If
            Next

This is giving me all the new members in orange, but now I'm trying to do that whenever there's a NEW name on that list, it will notify us. I tried to put it all the orange names in one string and that whenever the string is different than before, it will notify us but the problem is that it notify us if there's orange name that disappear from the list, and I want to know when there's a NEW member on the list.
I hope you can understand :P
Thanks in advance!

A: The easiest way is to use a HashSet<String> here.  This can record all of the namse you've seen before and hence make it easy to determine when a new one is added.
Class TheClass
  Dim seen As New HashSet(Of String)()

  Sub TheFunction()
    Dim list As New List(Of String)
    For Each line In RichTextBox1.Lines
      If line.Contains("255, 153, 51") AndAlso Not seen.Contains(line) Then
         list.Add(line)
         seen.Add(line)
      End If
    Next
  End SUb
End Class

Now the list type will only contain newly seen values


text:
Q: How to prevent editing of files (renaming,sharing etc) while selecting files from a document picker in ios I have implemented a document picker and want to avoid the editing of files & folder (like the option to rename,copy,share etc ) while I browse through the document picker. Can anyone please help me since there is nothing like allowsEditing for UIDocumentPickerViewController.
func documentPicker(from view: UIView) {

   let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF),
   String(kUTTypeJPEG), String(kUTTypeGIF)], in: .import)

   importMenu.delegate = self
   importMenu.setEditing(false, animated: false)
   importMenu.modalPresentationStyle = .popover

   if let presentation = importMenu.popoverPresentationController {
       presentation.permittedArrowDirections = .any
       presentation.sourceView = view
       presentation.sourceRect = view.bounds
   }

   parentController?.present(importMenu, animated: true, completion: nil)
}


text:
Q: React Native Geolocation watchPosition() documentation The documentation seems rather ambiguous and a tad minimalist on this API by React Native.
So I just want to clarify some things with those who have experience in using React Native's Geolocation API:

*

*What's the use of clearWatch() method if what we need to unsubscribe from watchPosition() is stopObserving()? Do we need both to properly unsubscribe?

*Does watchPosition() run when the app is in background by default or do we need to do background setup explicitly? (I do not need it to run on background just when the app is in use, hence the third question)

*If it does run in the background by default, I know we need to set NSLocationAlwaysUsageDescription for IOS' info.plist, but is there any special setup for Android?
Thanks in advance for any Information on these 3 questions that has been bugging me! :D


text:
Q: Why is an input on a transparent div also being rendered transparent? I have a transparent white div in which I want to place an input. For whatever reason, the input and button are also being rendered transparent.
HTML:

            <input type="text" class="form-control" placeholder="Search for...">

    <button class="btn btn-default" type="button">Go!</button>

CSS:
div.covered{
  background: url(http://i2.cdn.cnn.com/cnnnext/dam/assets/140801145902-irpt-birds-heron-scott-baumann-horizontal-large-gallery.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  height: 80%;
  padding-top:50px
}
.covered-container{
  background-color:white;
  opacity: .7;
  margin-bottom:20px;
}

.infotron-home{
  margin-top:50px;
text-align: center;
font-family: "Roboto Slab";
color:#0c5449;
}

.infotron-home li, .infotron-home p{
  list-style-type: none;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
}

.search-home{
  width:80%;
  opacity: 1;
}

input, select, textarea{
  color: #ffffff !important;
  opacity: 1;
}

JsFiddle: https://jsfiddle.net/49fp9ngk/1/
How can I make the input non-transparent and white like default?

A: try this
.covered-container {
    background-color: rgba(255,255,255,0.7);
    margin-bottom: 20px;
}

A: When a opacity is used on parent element it even effects it's child elements, so I suggest you to use background as rgba and remove opacity from both parent and child div, as below.

div.covered{
  background: url(http://i2.cdn.cnn.com/cnnnext/dam/assets/140801145902-irpt-birds-heron-scott-baumann-horizontal-large-gallery.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  height: 80%;
  padding-top:50px;
}
.covered-container{
  background-color:rgba(255,255,255,0.7); /* Add this */
  margin-bottom:20px;
}

.infotron-home{
margin-top:50px;
text-align: center;
font-family: "Roboto Slab";
color:#0c5449;
}

.infotron-home li, .infotron-home p{
  list-style-type: none;
  font-family:Helvetica, Arial, sans-serif;
  font-size:18px;
}

.search-home{
  width:80%;
  opacity: 1;
}

input, select, textarea{
  background:rgba(255,255,255,1); /* Add this */
}

                <input type="text" class="form-control" placeholder="Search for...">

        <button class="btn btn-default" type="button">Go!</button>


text:
Q: React Lazy Load useEffect I have a problem getting clientWidth from useEffect.
There is a lazyLoad which loads a page with users.
import {Suspense, lazy} from 'react';

const UsersContainer = lazy (() => import ('./ users / users-container'));

const Index = (props) => {
    return (
        <Suspense fallback = {
}>
            <UsersContainer />
        </Suspense>
    )
}

export default Index;

UsersContainer has a child component dataTooltip, which displays the full User name if it does not fit into the block.
import React, {useEffect, useRef} from 'react';

import '../common.scss';

const DataTooltip = ({title, ... props}) => {
    let ref = useRef ();

    useEffect (() => {
        if (ref.current.scrollWidth> ref.current.clientWidth) {
            ref.current.setAttribute ('data-tooltip', title)
        }
    });

    return (

            {
                React.cloneElement (props.children, {ref: ref})
            }

    )
}

export default DataTooltip;

What's the problem?
After the UsersContainer is loaded and rendered in the DOM, it has 'display: none' and at the same moment useEffect in DataTooltip is triggered asynchronously.
As a result, DataTooltip says that clientWidth = 0, due to the fact that the parent has 'display: none'.
How to make useEffect work after lazyLoad removed 'display: none'.
PS: useLayoutEffect works the same, clientWidth = 0

Solved the problem this way:
<Suspense fallback={
}>

   <Acquaintance/>
   <UsersContainer/>
   <RegisterContainer/>
</Suspense>

to
<Suspense fallback={
}>

</Suspense>

<Suspense fallback={
}>
    <Acquaintance/>
</Suspense>

<Suspense fallback={
}>
    <UsersContainer/>
</Suspense>

<Suspense fallback={
}>
    <RegisterContainer/>
</Suspense>

A: I don't know if this solves your issue - but one thing I notice immediately is that you're missing the dependency array from your useEffect hook.
import React, {useEffect, useRef} from 'react';
...

const DataTooltip = ({title, ... props}) => {
    let ref = useRef ();

    useEffect (() => {
        if (ref.current.scrollWidth> ref.current.clientWidth) {
            ref.current.setAttribute ('data-tooltip', title)
        }
    });

    return (...)
}

export default DataTooltip;

should be:
import React, {useEffect, useRef} from 'react';
...

const DataTooltip = ({title, ... props}) => {
    let ref = useRef ();

    useEffect (() => {
        if (ref.current.scrollWidth> ref.current.clientWidth) {
            ref.current.setAttribute ('data-tooltip', title)
        }
    }, [ref]);

    return (...)
}

export default DataTooltip;

Also keep in mind that this will cause the component to re-render whenever ref changes, per the documentation of the useEffect hook you should always declare any variables from the upper scope used in the useEffect hook as part of the dependency array, and if you dont dont use any such variables you should pass an empty array still to prevent running an infinite loop.


text:
Q: WPF control with navigation capability I have something like 15 grids and I want to put them in on one control with some kind of navigation ... something like tabs panel but instead of tabs I would like to have arrow or page number.
Any Idea?

A: Place all the (15) grids in a List<Grid> gridList. Create a ContentControl and put first item of gridList as content of ContentControl. Provide buttons(arrow) for forward and back. On the arrow button click change the content of ContentControl based on which button (forward or backward) has been clicked by selecting appropriate Grid from the gridList.

A: Use Frame with several Page objects - you will get Next and Previous controls, history and more for free.
Creating navigation based applications in WPF.


text:
Q: Linux / Change ulimit -Hn When I do ulimit -Sn, I get 1024.
I change it with: ulimit -n 4096
and It changes to 4096.
How do I do the same process to ulimit -Hn

A: Be root. Normal users can only decrease hard limits. From the bash manpage:

A hard limit cannot be increased by a non-root user once it is set; a soft limit may be increased up to the value of the hard limit.

As root, you can for many distros configure the stack size limit (and other limits) for user sessions in /etc/security/limits.conf. This is used by pam_limits (google term):
#<domain>      <type>  <item>         <value>

*               hard    stack          16384    # for example.

Note that this will only affect new sessions. The user will have to log out and in again.


text:
Q: How do I change the x-axis to display 'State' on matplotlib inline How do I get the state name to show in x-axis instead of the numbers and how can I display the chart with different colors. margin of victory by state:

A: You can use the xticks function to change the x-axis labels. In your case, this would look something like this:
plt.xticks(locs=list(range(37)), labels=[list of state names goes here])

Documentation here.


text:
Q: Boy Girl round table permutation problem My book has the answer to this problem but I do not understand how these answers are obtained .I know the circular permutation formula , but I cannot apply it in this specific case.
Problem: part i:Find the number of ways in which 4 boys and 4 girls can be seated around a circular table if the boys and girls are to have alternate seats.
part ii:Find the number of ways if they sit alternately around a circular table and if one boy and one girl are to sit in adjacent seats.
part iii:Find the number of ways if they sit alternately around a circular table and if one boy and one girl must not sit in adjacent seats .
The answers are
part i:3!4!=144.
part ii:2 3! 3!=72.
part iii:144-72=72.
The answers I got are way off and incorrect unfortunately....

A: (i) Fix one boy. (Using the circular symmetry.) The three boys remained and the four girls can be placed independently in $3!$, respectively $4!$ ways, so all together in $3!\;4!$ ways.
(ii) Fix again the one boy, the one given in (ii). "His" girl has to sit near him, so she has two chances, left or right. The three boys remained and the three girls remained can be placed independently in $3!$, respectively $3!$ ways, so all together in $2\;3!\;3!$ ways.
(iii) Just build the difference, or copy the above and place "his" girl on one of the non-adjacent sits.

Note: (ii) has a symmetric solution obtained by letting the one specific girl first have her seat, then her boy finds/chooses easily his place, but she was checking the make-up as i was typing. (Now she is outdoor, a phone call...)


text:
Q: Unable to determine the serialization information for i => i.Id using interfaces First up, I know there is already questions out there with this error message, but I haven't found any that relate to the use of using interfaces with this type of query.
I'm currently trying to update a MongoDB entity using the C# Driver 2.0. However, I'm getting an error when it's trying to build the query (I'm assuming it's the Builders<T>.Filter.Eq(i => i.Id, entity.Id) bit of code) and I'm getting the following error:

Unable to determine the serialization information for i => i.Id.

I've got the following class that I'm trying to update
public interface IEntity {
    string Id { get; set; }
}

public interface ITrack : IEntity {
    string Name { get; set; }
}

public class TrackDTO : ITrack
{

    [BsonId]
    public string Id { get; set; }

    public string Name { get; set; }

}

I'm then using the interface to save the object into the database using the following method in a generic DAO class to replace the entire document. Note, in the example below T is coded as ITrack (i.e. TrackDao = new Dao<ITrack>) but when the object is passed in at runtime it's a TrackDTO object (which is correct):
public async Task<T> Save(T entity)
{
    // Save the entity to the collection.
    ReplaceOneResult result = await _collection.ReplaceOneAsync(Builders<T>.Filter.Eq(i => i.Id, entity.Id), entity, new UpdateOptions() { IsUpsert = true });

    // return the saved user object.
    return entity;
}

I don't know if the Id property of my IEntity class also requires the [BsonId] attribute, but I'd like to avoid this if possible, as I want to keep my model layer (where IEntity resides) free of any database platform specific references.
I've also tried adding the following class map which has had no effect either:
BsonClassMap.RegisterClassMap<TrackDTO>(cm =>
{
    cm.AutoMap();
    cm.MapMember(c => c.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
    cm.SetIdMember(cm.GetMemberMap(c => c.Id));
});

For the same reason as not having the [BsonId] attributes in the Model layer, I don't want to have the Model classes decorated with [BsonKnownTypes] that reference DTO objects, however I don't mind if this needs to occur as part of a class map.

A: *

*For

"Unable to determine the serialization information for i => i.Id."

Try to use: nameof().
Builders<T>.Filter.Eq(nameof(IEntity.Id), entity.Id)

2.

...but I'd like to avoid this if possible, as I want to keep my model
  layer (where IEntity resides) free of any database platform specific
  references.

My solution for problem like your and similar problems:
public interface IEntity {
    [BsonId]
    string Id { get; set; }

    string IdEntity { get; set; }
}

[BsonIgnoreExtraElements(Inherited = true)]
public abstract class BaseEntity : IEntity
{
    [BsonRepresentation(BsonType.ObjectId)]
    public virtual string Id { get; set; }

    [BsonIgnoreIfNull]
    public string IdEntity { get; set; }
}