text:
Q: Define range/ lastrow in VBA I am trying to export data from excelsheet to excel Invoice template. The VBA code which I have, It considers each row as a different Invoice and hence makes a different workbook for each row. In case I have 1 invoice with 3 products in 3 rows this code considers each of the product (row) as separate Invoice which is not correct. I want to modify it in a way that if the Invoice number (PiNo) is repeated in the next row then it means the next product (row) belongs to the above Invoice only. I am new to VBA hence I have taken code from another site.
Here is the code:-

   Private Sub CommandButton1_Click()
   Dim r As Long
   Dim path As String
   Dim myfilename As String
   lastrow = Sheets("CustomerDetails").Range("H" & Rows.Count).End(xlUp).Row
   r = 2
   For r = 2 To lastrow

   ClientName = Sheets("CustomerDetails").Cells(r, 6).Value
   Address = Sheets("CustomerDetails").Cells(r, 13).Value
   PiNo = Sheets("CustomerDetails").Cells(r, 5).Value
   Qty = Sheets("CustomerDetails").Cells(r, 9).Value
   Description = Sheets("CustomerDetails").Cells(r, 12).Value
   UnitPrice = Sheets("CustomerDetails").Cells(r, 10).Value
   Salesperson = Sheets("CustomerDetails").Cells(r, 1).Value
   PoNo = Sheets("CustomerDetails").Cells(r, 3).Value
   PiDate = Sheets("CustomerDetails").Cells(r, 4).Value
   Paymentterms = Sheets("CustomerDetails").Cells(r, 7).Value
   PartNo = Sheets("CustomerDetails").Cells(r, 8).Value
   Shipdate = Sheets("CustomerDetails").Cells(r, 14).Value
   Dispatchthrough = Sheets("CustomerDetails").Cells(r, 15).Value
   Modeofpayment = Sheets("CustomerDetails").Cells(r, 16).Value
   VAT = Sheets("CustomerDetails").Cells(r, 17).Value

   Workbooks.Open ("C:\Users\admin\Desktop\InvoiceTemplate.xlsx")
   ActiveWorkbook.Sheets("InvoiceTemplate").Activate
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("Z8").Value = PiDate
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("AG8").Value = PiNo
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("AN8").Value = PoNo
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("B16").Value = ClientName
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("B17").Value = Address
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("B21").Value = Shipdate
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("K21").Value = Paymentterms
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("T21").Value = Salesperson
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("AC21").Value = Dispatchthrough
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("AL21").Value = Modeofpayment
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("B25").Value = PartNo
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("J25").Value = Description
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("Y25").Value = Qty
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("AF25").Value = UnitPrice
   ActiveWorkbook.Sheets("InvoiceTemplate").Range("AL39").Value = VAT

   path = "C:\Users\admin\Desktop\Invoices\"
   ActiveWorkbook.SaveAs Filename:=path & PiNo & ".xlsx"
   myfilename = ActiveWorkbook.FullName
   ActiveWorkbook.Close SaveChanges:=True

   Next r

   End Sub

"H" is the Product column and the data starts from Row 2. Row 1 are headers.
Any kind of help is appreciated!
enter image description here

A: Your code is lacking declarations. In view of the multitude of variables your design needs I figured the best way would be to declare Types. That are user defined structured variables, basically arrays with named elements. Since you now want to write the headers and bodies of invoices in separate operations (many body items for each one header) you need different Types for invoice body and invoice items.
Type Invoice
    ClientName As String
    Address As String
    PiNo As String
    PiDate As Date
    Salesperson As String
    PoNo As String
    VAT As Double
    PaymentTerms As String
    PaymentMode As String
    ShipDate As Date
    DispatchThrough As String
End Type

Type Item
    Qty As Double
    PartNo As String
    Description As String
    UnitPrice As Double
End Type

Private Sub CommandButton1_Click()

    Const InvoiceItemRow As Long = 25       ' modify to suit

    Dim WbInv As Workbook
    Dim Path As String
    Dim InvFileName As String
    Dim WsInv As Worksheet
    Dim WsCust As Worksheet                 ' always name your sheet
    Dim PiNo As String, Pi As String
    Dim Inv As Invoice, Itm As Item
    Dim Pos As Integer                      ' invoice item counter (1st item = 0)
    Dim NewInvoice As Boolean
    Dim LastRow As Long
    Dim R As Long

    Path = "C:\Users\admin\Desktop\Invoices\"
    ' you may like to use this syntax instead
    Path = Environ("UserProfile") & "\Desktop\Invoices\"

    ' Spaces are permitted in tab names. You may use "Customer Details"
    Set WsCust = ThisWorkbook.Worksheets("CustomerDetails")
    ' observe the leading period in .Rows.Count. That's why to use the With statement.
    With WsCust
        ' Use the Range object to define a range
        LastRow = .Range("H" & .Rows.Count).End(xlUp).Row
        ' but use the Cells collection to define a cell.
        LastRow = .Cells(.Rows.Count, "H").End(xlUp).Row
        ' delete the line you don't want to keep
    End With

    Application.ScreenUpdating = False          ' avoid flicker
    For R = 2 To LastRow
        Pi = WsCust.Cells(R, 5).Value
        If PiNo <> Pi Then
            NewInvoice = True
            If Not WbInv Is Nothing Then
                ' if there is a started invoice already, close it
               InvFileName = Path & Inv.PiNo & ".xlsx"
               With WbInv
                .SaveAs Filename:=InvFileName, FileFormat:=xlOpenXMLWorkbook
                .Close SaveChanges:=True
               End With
            End If
            Inv = SetInvoice(R, WsCust)
        End If

        Itm = SetItem(R, WsCust)
        If NewInvoice Then
            ' if it's a template, save it with xltx or xltm extension
            ' and, in any case, create a copy with the Add Method
            Set WbInv = Workbooks.Add("C:\Users\admin\Desktop\InvoiceTemplate.xlsx")
            Set WsInv = WbInv.Worksheets("InvoiceTemplate")

            With WsInv
                .Cells(16, "B").Value = .ClientName
                .Cells(17, "B").Value = Inv.Address
                .Cells(8, "AG").Value = Inv.PiNo
                .Cells(8, "Z").Value = Inv.PiDate
                .Cells(21, "T").Value = Inv.Salesperson
                .Cells(8, "AN").Value = Inv.PoNo
                .Cells(39, "AL").Value = Inv.VAT
                .Cells(21, "K").Value = Inv.PaymentTerms
                .Cells(21, "AL").Value = Inv.PaymentMode
                .Cells(21, "B").Value = Inv.ShipDate
                .Cells(21, "AC").Value = Inv.DispatchThrough
            End With
            Pos = 0                             ' reset item counter
            NewInvoice = False
        Else
            Pos = Pos + 1
        End If

        With WsInv.Rows(InvoiceItemRow + Pos)
            ' find out the column number with Debug.Print ? Columns("AF").Column
            .Cells(2).Value = PartNo
            .Cells(10).Value = Description
            .Cells(25).Value = Qty
            .Cells(32).Value = UnitPrice
        End With
        PiNo = Pi
    Next R
    Application.ScreenUpdating = True
End Sub

Private Function SetInvoice(ByVal R As Long, _
                            Ws As Worksheet) As Invoice

    Dim Fun As Invoice

    With Fun
        .ClientName = Ws.Cells(R, 6).Value
        .Address = Ws.Cells(R, 13).Value
        .PiNo = Ws.Cells(R, 5).Value
        .PiDate = Ws.Cells(R, 4).Value
        .Salesperson = Ws.Cells(R, 1).Value
        .PoNo = Ws.Cells(R, 3).Value
        .VAT = Ws.Cells(R, 17).Value
        .PaymentTerms = Ws.Cells(R, 7).Value
        .PaymentMode = Ws.Cells(R, 16).Value
        .DispatchThrough = Ws.Cells(R, 15).Value
        .ShipDate = Ws.Cells(R, 14).Value
    End With
End Function

Private Function SetItem(ByVal R As Long, _
                         Ws As Worksheet) As Item

    Dim Fun As Item

    With Fun
        .Qty = Ws.Cells(R, 9).Value
        .PartNo = Ws.Cells(R, 8).Value
        .Description = Ws.Cells(R, 12).Value
        .UnitPrice = Ws.Cells(R, 10).Value
    End With

    SetItem = Fun
End Function

I have tested this code perfunctorily except for the Save & Close part. If your more thorough testing uncovers errors please bear with me, let me know, and I shall correct them.
Testing the SaveAs procedure  ============== (Edit Apr 7, 2020)
The procedure below is an extract from the above. It uses the same syntax for SaveAs as the above code. Follow these steps.

*

*Create a new workbook from your InvoiceTemplate. Its name should be InvoiceTemplate1 and never saved before. Make it the ActiveWorkbook.

*Modify the procedure to create the InvFilename variable in exactly the same way as your code does.

*Then run the procedure.
Private Sub TestSaveAs()
Dim WbInv As Workbook
Dim InvFilename As String

Set WbInv = ActiveWorkbook
InvFilename = Environ("UserProfile") & "\Desktop\MyWorkbook.xlsx"
With WbInv
 .SaveAs Filename:=InvFilename, FileFormat:=xlOpenXMLWorkbook
 .Close SaveChanges:=True
End With

End Sub


text:
Q: Is a metrizable subspace of a separable space separable? Let $X$ be a (Tychonoff) separable topological space (whose weight does not exceed $2^\omega$) and $M$ be a metrizable subspace of $X$. Is true that $M$ is separable?

A: No. Let $X=[0;1]^{\frak c}$ be a Tychonoff cube. Then $X$ is separable, $w(X)=\frak c$, but it contains a discrete space $M=\{e_\alpha:\alpha<\frak c\}$ (where each $e_\alpha=(e_\alpha)_{\beta, \beta<\frak c}$,  $(e_\alpha)_{\alpha}=1$, and $(e_\alpha)_{\beta}=0$  provided $\beta\ne\alpha$) of size $\frak c$.

A: Let $S$ be the Sorgenfrey line, and let $X=S\times S$, the Sorgenfrey plane. $S$ is separable, since $\Bbb Q$ is dense in $S$, so $X$ is separable. $X$ is first countable and of cardinality $2^\omega$, so its weight is clearly no more than $2^\omega$ (and in fact it is $2^\omega$. However, the set $D=\{\langle x,-x\rangle:x\in S\}$ is a closed, discrete subset of cardinality $2^\omega$. Being discrete, it is metrizable, and it's clearly not separable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postgresql INSERT is asking for primary key value? Running Postgres 9.6.6. I created a table as follows:
create table person (
id serial primary key,
name text,
role integer references role (id),
phonenumber text);

When I try to insert data as follows:
insert into person values ('This Person',2,'+15105551111');

I get this message:
ERROR: invalid input syntax for integer: 'This Person'

which suggests that Postgres is expecting a value for id.  But if id is a serial primary key, shouldn't it be autopopulating and autoincrementing?

A: If you do not specify the column names, the values will be applied to the first n columns in the table. Thus 'This Person' will be applied to id, and thus the error you're getting. You can (should) specify the columns names in order to avoid this problem:
INSERT INTO person
(name, role, phonenumber) -- Here
VALUES ('This Person', 2, '+15105551111');

A: If you look at the table definition, you'll see that the column is actually defined like this:
id integer DEFAULT nextval('person_id_seq'::regclass)

This is because serial is only a shorthand.
That means that the auto-generated value is only used if no value is explicitly inserted. But since your INSERT statement has no column list, you actually insert to all columns, so the first value will be inserted into the first column, which leads to the error.
You can either explicitly list the columns:
INSERT INTO person (name, role, phonenumber)
   VALUES ('This Person', 2, '+15105551111');

or you can use DEFAULT to specify that the default value should be used:
INSERT INTO person
   VALUES (DEFAULT, 'This Person', 2, '+15105551111');

The first solution is better because it is always good to be explicit about the columns (tables can get altered).


text:
Q: How to migrate a database from SQL server to Oracle? I have been assigned a task to migrate a database from SQL server to Oracle.
But I have no idea about how to do it.
Also, is there any need to change the existing data model?

A: There are two very detailled documents here and here. There is a step by step guide (with videos) here. It is no coincidence that two of these documents are from Oracle themselves, it being very much in their interest to get clients to move from SQL Server to their product.
Your question is a bit too vague and general for this forum, but since you're new to dba.stackexchange, I'll let that pass. I obtained these links by simply Googling - you should do this before you ask questions here. Show us that you've done a bit of work - then ask more specific questions.
Take the tour and also check out the "help us to help you" blog (both at the bottom left of the page).
Dba.stackexchange is a great resource and you will get all the more out of it by following the guidelines in the posts above. Finally, welcome to the forum! :-)


text:
Q: Error using partials with HTML Webpack Plugin I'm trying to create a setup with static HTML partials using the HTML Webpack Plugin, but running into some errors. This is my current config:
webpack.config.js
const webpack = require('webpack');
const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssets = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

    let config = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, './public'),
    filename: 'app.js'
  },
  module: {
    loaders: [{
        test: /\.html$/,
        loader: 'html-loader'
    }],
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        use: ['css-hot-loader'].concat(ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader', 'postcss-loader'],
        })),
      },
      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        loaders: ['file-loader?context=src/assets/images/&name=images/[path][name].[ext]', {
          loader: 'image-webpack-loader',
          query: {
            mozjpeg: {
              progressive: true,
            },
            gifsicle: {
              interlaced: false,
            },
            optipng: {
              optimizationLevel: 4,
            },
            pngquant: {
              quality: '75-90',
              speed: 3,
            },
          },
        }],
        exclude: /node_modules/,
        include: __dirname,
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: './src/template.html.ejs'
    }),
    new ExtractTextWebpackPlugin('main.css')
  ],
  devServer: {
    contentBase: path.resolve(__dirname, './public'),
    historyApiFallback: true,
    inline: true,
    open: true
  },
  devtool: 'eval-source-map'
}

module.exports = config;

if (process.env.NODE_ENV === 'production') {
  module.exports.plugins.push(
    new webpack.optimize.UglifyJsPlugin(),
    new OptimizeCSSAssets()
  );
}

template.html.ejs (located under ./src)
<%=require('./header.html')%>

    testing schmesting

  <%=require('./footer.html')%>

(footer.html and header.html are located under ./src)
Edit: Updated the code, still issues:
"ERROR in   Error: Child compilation failed:
  Module parse failed: Unexpected token (1:0)
  You may need an appropriate loader to handle this file type.  SyntaxError: Unexpected token (1:0)
  Module parse failed: Unexpected token (1:2)
  You may need an appropriate loader to handle this file type."

A: EDIT
(EDIT: 2017-12-20 move "loaders" to "rules")
By default, "html-webpack-plugin" parses the template as "underscore" (also called lodash) template, your "template.html" is nothing wrong, the error is caused by webpack failed to resolve 'html-loader' for your "template.html"
<%= require('html-loader!./footer.html') %>, so you need to install "html-loader" for webpack, and configure it:
In command line:
npm install html-loader
And configure it for webpack, edit webpack.config.js:
...
module: {
    rules: [
     // ...
        {
            test: /\.html$/, // tells webpack to use this loader for all ".html" files
            loader: 'html-loader'
        }
    ]
}

By now you can run "webpack" you'll see no error, BUT the generated "index.html" is not you expected, because your template file has ".html" extension, webpack now use "html-loader" to load "template.html" instead of default "lodash loader", to solve this you can rename "template.html" to "template.html.ejs" (or any other extension) to make "html-webpack-plugin" fallback. Besides there is a little bit more change on "template.html", remove "html-loader!" from it:
<%= require('./footer.html') %>
now it should work.

EDIT Post my code for reference :
/src/template.html.ejs
<!DOCTYPE html>

        <title>test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

template

        <%=require('./footer.html')%>

/src/footer.html
this is a footer

/webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

let config = {
    entry: {
        index: './src/js/index'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    module: {
        rules: [
            {
                test: /\.html$/,
                loader: 'html-loader'
            }
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/template.html.ejs'
        })
    ]
}

module.exports = config;

/package.json
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "html-loader": "^0.5.1",
    "html-webpack-plugin": "^2.30.1",
    "webpack": "^3.10.0"
  }
}

/src/js/index.js
console.log("A test page!");

environment:

*

*webpack 3.10.0

*npm 5.6.0

content of "/dist/index.html" after run webpack:
<!DOCTYPE html>

        <title>test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

template

        this is a footer

As you can see content of "footer.html" is correctly inserted.

OLD ANSWER
Approach 1: Using "es6" template

*

*Install "html-loader" by npm install html-loader

*Add "html-loader" to your "webpack.config.js" for loading files with ".html" extension, like:

module: {
        rules: [{
            test: /\.html$/,
            loader: 'html-loader'
        }],
    }

*Add interpolate flag to enable interpolation syntax for ES6 template strings, like so:

plugins: [
        new HtmlWebpackPlugin({
            template: '!!html-loader?interpolate!src/template.html'
        })
    ]

*Modify your template.html to match ES6 template:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>

    template

  ${require('./footer.html')}

*Run webpack, it'll work

Approach 2: Using "underscore" template
Follow "approach 1" step 1 and 2, and then:

*

*Rename "template.html" to "template.html.ejs"

*Change template: './src/template.html' to template: './src/template.html.ejs' in "webpack.config.js"

*Run webpack


text:
Q: SmoothDivScroll's "running ticker" only scrolls once My problem today is that the running ticker only scrolls once. The "makeMeScrollable"  contains the text that should be scrolling infinitely but literally only scrolls until the end of the text. Any idea what might be causing this? Firebug shows no issues
Here's my code:
This is in the head:

This is in the body:

this contains very long text

A: I've figured it out, or more specifically, I did some better reading. It turns out that if the different elements each aren't as long as the scrolling bar, they won't get enough time to swap out and therefore the scroller will stop.
I've just increased each text's length and it works perfectly now.


text:
Q: Font family in pseudo element It seems Internet Explorer 8,9,10 uses here always the same (system) font. In fact Internet Explorer doesn't care about the font-family at all. The important thing is the combination of display:table-cell and :before or :after:
<!DOCTYPE html>

Is this a known bug? Can't find anything about it.

A: http://jsfiddle.net/KnfaW/
It seems to me that display: table-cell causes the problem.

User agents must ignore the following properties with :before and :after pseudo-elements: 'position', 'float', list properties, and table properties.
The :before and :after pseudo-elements elements allow values of the 'display' property as follows:
If the subject of the selector is a block-level element, allowed values are 'none', 'inline', 'block', and 'marker'. If the value of the 'display' has any other value, the pseudo-element will behave as if the value were 'block'.
If the subject of the selector is an inline-level element, allowed values are 'none' and 'inline'. If the value of the 'display' has any other value, the pseudo-element will behave as if the value were 'inline'.

W3C CSS2
So instead of display: table-cell use display: block. It will work as expected. IE's error handling may be buggy in this case as my opinion.


text:
Q: Could a view call a function of the model directly? this is a fundamental question about MVC (in particular using AngularJS) and I've found similar questions here, but not the exact same problem:
Could the view call a function of the model, or should it only call functions of the controller?
Here's the example:
In my Model there's a function to delete items of a collection, like this:
function deleteItems(searchExpression) { ... }

Now my Controller has an instance of my model including that function, like this:
$scope.data = queryModelFactory.getModel();

I now want to call that funciton when the user clicks a certain element in the HTML page:

Remove Items

Is that legit? Or would it be better to implement a function in the controller that is passing through the delete request to my model like I'd do in a classical layer architecture? Like this:
function deleteItems(searchExpression) {
    $scope.data.deleteItems(searchExpression);
}

A: The Model-View-Controller pattern divides the application into three interconnected parts namely the model, the view and the controller.
The central component of MVC, the model, captures the behavior of the application in terms of its problem domain, independent of the user interface. The model directly manages the data, logic and rules of the application. A view can be any output representation of information, such as a chart or a diagram. The third part, the controller, accepts input and converts it to commands for the model or view.
The view should not directly interact with the model but rather delegate the events (e.g. user input) to the controller. In your case, the latter option you presented implements the pattern correctly.


text:
Q: Iterating over fields of the same type Let say you have the following classes:
class Data
{
public:
    int a;
    int b;
};

class DataOther
{
public:
    int a;
    int b;
};

class Line
{
public:
    Data Right;
    Data Left;
};

class LineOther
{
public:
    DataOther Right;
    DataOther Left;
}

I have quite a few classes that are structured this way, and when I want to run code over both "sides" of the data I typically do something like this:
enum class Side { RIGHT, LEFT };
template<typename T>
auto GetBySide(const Side &side, T &data) -> decltype(data.Right) &
{
    return side == Side::Left ? data.Left : data.Right;
}

And then in the code:
Line l;
LineOther lOther;
for(auto &side: {Sides::LEFT, Sides::Right})
{
      auto &d = GetBySide(side, l);
      auto &dOther = GetBySide(side, lOther);

      // Do some stuff with the data
}

Now the down side of this, is that it's run-time so not much optimization can be done, though I suppose a compiler might unroll the loop.
Any other ideas on how to structure the code?

A: If you worry about unrolling, you may replace:
Line l;
LineOther lOther;
for (auto &side: {Sides::LEFT, Sides::Right})
{
      auto &d = GetBySide(side, l);
      auto &dOther = GetBySide(side, lOther);

      // Do some stuff with the data
}

by something like:
template <Side side>
void foo(Line& l, LineOther& lOther) {
      auto &d = GetBySide(side, l);
      auto &dOther = GetBySide(side, lOther);

      // Do some stuff with the data
}

and
Line l;
LineOther lOther;
foo<Sides::LEFT>(l, lOther);
foo<Sides::Right>(l, lOther);

A: "I have quite a few classes that are structured this way" it seems that you can leave only one of them. Or at least utilize inheritance or other technique to avoid duplication:
// Declare base class instead of copypasting fields.
class BaseLine
{
public:
    int Right{};
    int Left{};
};

class Line: public BaseLine
{};

class LineOther: public BaseLine
{};

int main()
{
    Line l;
    l.Right = 45; l.Left = 89;
    LineOther lOther;
    lOther.Right = 74; lOther.Left = 33;
    // Use pointer to member to iterate over fields.
    for(auto p_side: {&BaseLine::Right, &BaseLine::Left})
    {
       ::std::cout << (l.*p_side) << ::std::endl;
       ::std::cout << (lOther.*p_side) << ::std::endl;
    }
}

Online compiler


text:
Q: Async Call in $http request How to wait till the response comes from the $http request, in "angularjs"?
In ajax, a successful method is to set async = false like this,
jQuery.ajax({
     url: '/Something/Index',
     success: function (result) {
         result;
     },
     async: false
});

But Its not working in $http request in angularjs.Is there any method for this?

A: $http.get("url")
    .then(response => {
        // async success callback
    })
    .catch(err => {
      // async error callback
    });

A: You can use the promise returned by $http services in AngularJS and use .then function. This ensures that the first function response is received and then only code inside .then function would execute.
A sample code would be as below:
var app = angular.module("app", []);

app.factory('myService', function ($http) {
    return {
        serverCall: function () {
            return $http.get('/Something/Index').then(function (response) {
                console.log(response);
                return response;
            });
        }
    };
});

app.controller("myController", function ($scope, myService) {

    $scope.GetDataFromServer = function () {

        // make the ajax call
        var myData = myService.serverCall();

        // this executes after that ajax call is completed
        myData.then(function (result) {
            $scope.data = result;
        });

    };
});


text:
Q: django settings.py DATETIME_FORMAT: %M does not correspond to Minutes according to https://docs.djangoproject.com/en/1.5/ref/settings/#datetime-input-formats the following pattern should work if I put it into settings.py and deactivate USE_L1ON
'%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'

When i use it, the '%' symbols are printed too, so i cahnged it to
DATETIME_FORMAT = 'Y-m-d H:M'

This, however, yields: 2013-04-10 09:Apr
So 'M' is translated to 'abbreviated month' instead of minutes. How can I fix this? The Django doc wasn't helpful

A: You were looking for date output formatting and i:
DATETIME_FORMAT = 'Y-m-d H:i'

From the linked documentation:

i - Minutes. - '00' to '59'


text:
Q: How to redirect to from autocomplete (jquery) My products.js.coffee
$ ->
  $('#titles').autocomplete(
    source: gon.titles
    minLength: 2).click ->
    $(this).autocomplete 'search'
    return
  return

My index.html.erb
...
<div class="ui-widget">
    <input id="titles" />
</div>
...

In source I have titles from all products (I used gon gem). I would like to choose the product from autocomplete and redirect to the selected product.
Thanks for your advice!

A: My solution products.js.coffee
doSearch = (term, location) ->
  window.location.href = 'products?utf8=✓&search=' + term + '&commit=Search'
  return

$(document).ready ->
  $('#titles').autocomplete
    minLength: 1
    source: gon.titles
    select: (event, ui) ->
      doSearch ui.item.label, ui.item.city
      return
  return


text:
Q: Present Simple Tense with For Is it grammatically correct or colloquial to use "for" with present simple tense as in the following examples :

I do this business for ten years.
I teach Math for five years.
I run this company for years.

A: No. We almost never use the simple present with "for". We can use future or past (I will be there for an hour; I was there for an hour) but for states or activities that are still continuing, we always use the perfect: usually the perfect continuous (I have been studying French for two years), but for verbs which don't normally take continuous forms, the perfect (I have been here for two years).
Sometimes both continuous and non-continuous forms are acceptable: I've watched him for an hour vs I've been watching him for an hour. The latter draws attention to the continuing nature of the watching.

A: You may not need to say for, but have the word 'have' in second? i.e

I have done this business for ten years.
I have taught Math for five years.
I have run this company for years.

I also am not quite sure you would use simple present tense for this; maybe refer to this from Grammarly.

We use the simple present tense when an action is happening right now, or when it happens regularly (or unceasingly, which is why it's sometimes called present indefinite). Depending on the person, the simple present tense is formed by using the root form or by adding ‑s or ‑es to the end.


text: Q: How can I prevent numbers from being affected by rtl editing? I have a multilingual application. I have an order screen. There are numerical expressions like the date on this screen. How can prevent numbers affected rtl editing in XML(textView) ?


text:
Q: I need help creating Power BI Multi Status graph I want to create a graph with projects in the y axis and project phases in the x-axis.
This is my data

I want to display the phases here and not the percentage

Do you know any way to replace the percentage with text category or assign the category a value ?
Thanks.
I tried to create a status like that :

but it don't work from me because I have multiple projects to monitor.


text:
Q: Get the value with most occurrences in data frame for each row Suppose I have a simple data frame
test_df <- data.frame(c(0,0,1,0,0,1,1,1,1,1),c(1,0,0,0,0,0,0,0,0,0))

I want to get which number (0 or 1) is the maximum for each row.
In my example 1 for the first vector (6 occurrences), 0 for the second one (9 occurrences).
I started with:
> sapply(test_df,table)
  c.0..0..1..0..0..1..1..1..1..1. c.1..0..0..0..0..0..0..0..0..0.
0                               4                               9
1                               6                               1

so far looks fine. Then
> sapply((sapply(test_df,table)),max)
[1] 4 6 9 1

I got lost, did I loose the associations? 1 -> 6 , 0 -> 9
What I want is to have returned a vector with the "winner": 1,0,...
1 for the first vector (6 occurrences)
0 for the second vector (9 occurrences)
...

A: We can use apply with MARGIN=1 to extract the max value from each row of the sapply output.
frqCol <- sapply(test_df, table)
apply(frqCol, 1, max)
# 0 1
# 9 6

or use rowMaxs from matrixStats
library(matrixStats)
rowMaxs(frqCol)
#[1] 9 6

If we need the 'max' value per column
apply(frqCol, 2, max)

and
colMaxs(frqCol)

With the new example
test_df <- data.frame(v1= c(0,0,1,0,0,1,1,1,1,1),
                  v2= c(1,0,0,0,0,0,0,0,0,0),
                  v3= c(1,0,0,0,0,0,0,0,0,1))
frqCol <- sapply(test_df, table)
apply(frqCol, 2, max)
#v1 v2 v3
#6  9  8
colMaxs(frqCol)
#[1] 6 9 8

A: This can be done in one apply statement. Although, it's unclear whether you want the maximum occurrences for each row or column, so here's both (using @akrun 's cleaner data set), returning a vector showing the 'winner' (either 1 or 0) for each row/column.
## Data
test_df <- data.frame(v1= c(0,0,1,0,0,1,1,1,1,1),
                      v2= c(1,0,0,0,0,0,0,0,0,0),
                      v3= c(1,0,0,0,0,0,0,0,0,1))
#    v1 v2 v3
# 1   0  1  1
# 2   0  0  0
# 3   1  0  0
# 4   0  0  0
# 5   0  0  0
# 6   1  0  0
# 7   1  0  0
# 8   1  0  0
# 9   1  0  0
# 10  1  0  1

## Solution - For each row
apply(test_df, 1, function(x) { sum(sum(x == 1) > sum(x == 0)) })

## Result
# [1] 1 0 0 0 0 0 0 0 0 1

## Solution - For each column
apply(test_df, 2, function(x) { sum(sum(x == 1) > sum(x == 0)) })

## Result
# v1 v2 v3
# 1  0  0


text:
Q: Logitech webcam USB C Windows I would like to basically just grab frames from a Logitech USB camera.  How does one go about doing this?  I could send it USB instructions; however, I don't think Logitech has a document with the instructions needed to control the camera.  Is the way to do it using the Direct Show?  The Windows MPD seemed like a good idea, but I Don't think Logitech devices support it.  What is the standard way to communicate with a USB camera?
Thanks.


text:
Q: Why doesn't my iOS app disable dark mode? So ... I've tried to set my app to disable iOS 13 dark mode by forcing light mode according apple documentation, in the emulator all attempts work fine, but when I try on the real device, nothing happens, it's like I've never changed my code
First Attempt
Override the Interface Style for a Window, View, or View Controller
I tried to put this code sample in my viewDidLoad()
Nothing Changed
if #available(iOS 13.0, *) {
   overrideUserInterfaceStyle = .light
} else {
  // Fallback on earlier versions
}

Second Attempt
Opt Out of Dark Mode Entirely
The system automatically opts in any app linked against the iOS 13.0 or later SDK to both light and dark appearances. If you need extra time to work on your app's Dark Mode support, you can temporarily opt out by including the UIUserInterfaceStyle key (with a value of Light) in your app's Info.plist file. Setting this key to Light causes the system to ignore the user's preference and always apply a light appearance to your app.
Nothing changed
Apple Documentation: Choosing a Specific Interface Style for Your iOS App
If anyone knows how I set my app only in light mode... I'll be very grateful :D

A: if #available(iOS 13, *) {
    window.overrideUserInterfaceStyle = .light
}

Should work. Call it in your AppDelegate's didFinishLaunchingWithOptions.

A: Change the window UserInterfaceStyle for iOS 13+ version. Just set
UIApplication.shared.changeStatusBarStyle(.light)

or
UIApplication.shared.changeStatusBarStyle(.dark)

after changing window every time.
extension UIApplication {

        enum StatusColor {

            case dark, light
        }

        func changeStatusBarStyle(_ mode: StatusColor = .light) {

            if #available(iOS 13.0, *) {

                guard let appDelegate = delegate as? AppDelegate else { return }

                var interfaceStyle: UIUserInterfaceStyle

                switch mode {
                case .dark:
                    interfaceStyle = .dark
                default:
                    interfaceStyle = .light
                }

                appDelegate.window?.overrideUserInterfaceStyle = interfaceStyle
            }
        }
    }

If any confusion please let me know.

A: Simply you can add a new key UIUserInterfaceStyle in your app info.plist (Notes: Xcode 12 and above has renamed to Appearance) and set its value to Light or Dark. this will override the app default style to the value you provide.
so you don't need to bother about having it anywhere else

A: Add inside Info.plist
<key>Appearance</key>
<string>Light</string>

A: For SwiftUI you might find the following solution helpful:
extension UIApplication {
    func changeInterfaceStyle(_ mode: UIUserInterfaceStyle = .light) {
        if #available(iOS 13.0, *) {
            var window: UIWindow? {
                guard let scene = connectedScenes.first,
                      let windowSceneDelegate = scene.delegate as? UIWindowSceneDelegate,
                      let window = windowSceneDelegate.window else {
                    return nil
                }
                return window
            }
            window?.overrideUserInterfaceStyle = mode
        }
    }
}

Usage:
    Button("Dark") {
        UIApplication.shared.changeInterfaceStyle(.dark)
    }


text:
Q: Uncaught TypeError: Cannot read property 'width' of undefined in JavaScript I have created a program that can move a rectangular block up, down, right, and left within a canvas using the w, a, s, and d keys. There is an error when setting a variable to represent the width of the canvas. The error comes up for this line of code:
    var cw=canvas.width;

I have been trying to use this code on Chrome. Here is the full code:

                <canvas id="canvas1" width="500" height="500" style="border: 1px solid black;"> </canvas>

A: Here is a working live demo
You should use the window.onload function to make sure the HTML gets loaded before trying to access any DOM objects. This syntactically decouples your JavaScript from the HTML.
  var positionX = 0;
  var positionY = 0;
  var canvas = {};
  var cw = 0;
  var ch = 0;
  var bw = 100;
  var bh = 100;

 // Set up initial values, after the page loads
 window.onload = function(){
     positionX = 0;
     positionY = 0;
     canvas = document.getElementById("canvas");
     cw = canvas.width;
     ch = canvas.height;
     draw();
  };
  // Add keyboard listener
  window.addEventListener("keydown", onKeyPress, true);

  function draw(){
      canvas=document.getElementById("canvas");
      cw=canvas.width;
      ch=canvas.height;
      context=canvas.getContext("2d");

      context.clearRect(0, 0, canvas.width, canvas.height);
      context.fillStyle="green";

      context.fillRect(positionX, positionY, bw, bh);
      context.strokeStyle = 'black';
      context.stroke();
  }

  function onKeyPress(e){
    var dx = 50;
    var dy = 15;
    if (e.keyCode == 87){
        console.log("w(87) up");
        positionY=Math.max(0,positionY-dy);
    }
    else if (e.keyCode == 83){
        console.log("s(83) down");
        positionY = Math.min((positionY+dy), (ch-bh));
    }
    else if (e.keyCode == 68){
        console.log("d(68) right");
        positionX = Math.min((positionX+dx), (cw-bw));
    }
    else if (e.keyCode == 65){
        console.log("a(65) left");
        positionX=Math.max(0,positionX-dx);
    }
    draw();
  }

A: Some problems are here
        var positionY=0;
        var cw=canvas.width;
        var ch=canvas.height;

Here canvas variable is undefined . You trying to access canvas before settings its value.
var canvas=document.getElementById("canvas");
var cw=canvas.width;
var ch=canvas.height;

and
            var canvas=document.getElementById("canvas1");
            var cw=canvas1.width;
            var ch=canvas1.height;

there is no variable canvas1 so this should be
            var canvas1=document.getElementById("canvas1");
            var cw=canvas1.width;
            var ch=canvas1.height;

A: var canvas=document.getElementById("canvas1");
should be:
var canvas1=document.getElementById("canvas1");

A: A quick fix:

        <canvas id="canvas" width="500" height="500" style="border: 1px solid black;"> </canvas>

Your script related to the canvas dom should not run before the canvas rendered.


text:
Q: Use tcl twapi getting "Could not get ITypeInfo for coclass: object does not support IProvideClassInfo and clsid not specified." error ( office365) I am using tcl8.5 and twapi 4.2a1 to control outlook via component object module
as following code
This Code can use in office 2016 outlook but in office365 outlook
I got error "Could not get ITypeInfo for coclass: object does not support IProvideClassInfo and clsid not specified" in "set biid [$::items -bind eventhandler]"
Could someone give me a idea to solve this problem?
or Am I missing something ?
package require twapi_com

proc eventhandler {args} {
    global ns
    set event  [lindex $args 0]
    set handle [lindex $args 1]
    puts $event
    puts $handle
    set s ""
    set sdr2 ""
    #return $s
}

set outlook [::twapi::objcom Outlook.Application -active]
set ns [$outlook GetNamespace "MAPI"]
set contacts [$ns GetDefaultFolder 6]
set ::items [$contacts Items]
set biid [$::items -bind eventhandler]

A: It seems your windows registry keys are corrupted. I'd suggest repairing your Office installation.
Also, you may try to automate Outlook from another programming language to make sure the issue is not related to TCL.
See HRESULT:0x80040154 COM object with CLSID {} is either not valid or not registered for more information about the issue.


text:
Q: generate short caption automatically, if there is a citation at the end I have a lot of figures that I'm referring to and I prefer to give short cites for the list of figures, ie without the source, unfortunately when I have to fix a typo etc. I need to change the short- as well as the full-caption. Is there a good way to name the figure just once? (maybe with a variable that contains the short-caption, in the document or is there maybe a more elegant way?)
\documentclass{article}

\usepackage[backend=biber]{biblatex}
\usepackage{caption}
\usepackage[demo]{graphicx}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
    @article{A01,
        author = {Albert Einstein},
        title = {the true about tree},
        journaltitle = {Annalen der Physik},
        year = {1905},
        volume = {322},
        number = {10},
        pages = {891--921}
    }
\end{filecontents}
\addbibresource{\jobname.bib}

\newtoks\shortcap
\shortcap={foo bar baz}

\begin{document}

\listoffigures

\begin{figure}
\centering
\includegraphics[width=3.0in]{example-image-a}
\shortcap={Some Text}
\caption[\the\shortcap]{\the\shortcap, Source:~\cite{A01}}
\end{figure}

\end{document}

A: I'd go the opposite way; defining a different command allows using the original one for tough cases.
\begin{filecontents}{\jobname.bib}
    @article{A01,
        author = {Albert Einstein},
        title = {the true about tree},
        journaltitle = {Annalen der Physik},
        year = {1905},
        volume = {322},
        number = {10},
        pages = {891--921}
    }
\end{filecontents}

\documentclass{article}

\usepackage[backend=biber]{biblatex}
\usepackage{caption}
\usepackage{graphicx}
\usepackage{xparse}

\addbibresource{\jobname.bib}

\NewDocumentCommand{\Caption}{om}{%
  \IfNoValueTF{#1}
    {\caption{#2}}
    {\caption[#2]{#2. Source:~\cite{#1}}}%
}

\begin{document}

\listoffigures

\begin{figure}[htp]
\centering
\includegraphics[width=3.0in]{example-image-a}
\Caption[A01]{Some text}
\end{figure}

\begin{figure}[htp]
\centering
\includegraphics[width=3.0in]{example-image-b}
\Caption{Some text}
\end{figure}

\end{document}

A different approach, where you add the full final text.
\begin{filecontents}{\jobname.bib}
    @article{A01,
        author = {Albert Einstein},
        title = {the true about tree},
        journaltitle = {Annalen der Physik},
        year = {1905},
        volume = {322},
        number = {10},
        pages = {891--921}
    }
\end{filecontents}

\documentclass{article}

\usepackage[backend=biber]{biblatex}
\usepackage{caption}
\usepackage{graphicx}
\usepackage{xparse}

\addbibresource{\jobname.bib}

\NewDocumentCommand{\sourcecaption}{omm}{%
  \IfNoValueTF{#1}
    {\caption[#2]{#2#3}}
    {\caption[#1]{#2#3}}%
}

\begin{document}

\listoffigures

\begin{figure}[htp]
\centering
\includegraphics[width=3.0in]{example-image-a}
\sourcecaption{Some text}{. Source:~\cite{A01}}
\end{figure}

\begin{figure}[htp]
\centering
\includegraphics[width=3.0in]{example-image-b}
\sourcecaption[Some short text]{Some very long text}{, based on~\cite{A01}}
\end{figure}

\end{document}

A: You could also use a specific cite command which disappears in the lof:
\documentclass{article}

\usepackage[backend=biber]{biblatex}
\usepackage{caption}
\addbibresource{biblatex-examples.bib}

\newbool{showcites}
\DeclareCiteCommand\hiddencite{}{}{}{}
\DeclareRobustCommand\nottoccite[1][Source:~]{\ifbool{showcites}{#1\cite}{\hiddencite}}

\begin{document}

\boolfalse{showcites}
\listoffigures
\booltrue{showcites}

\begin{figure}
\centering
blub
\caption{blalbl
 \nottoccite{shore}%
 \nottoccite[, ][50]{aksin}%
 \nottoccite[, and based on~][Vol][3]{herrmann}}
\end{figure}

\end{document}

But I don't like the fiddling with the commas and the text, so in the long run I would probably simply use a generic command to let text disappear in the lof:
\documentclass{article}

\usepackage[backend=biber]{biblatex}
\usepackage{caption}
\addbibresource{biblatex-examples.bib}

\newbool{show}
\DeclareRobustCommand\notintoc[1]{\ifbool{show}{#1}{}}

\begin{document}

\boolfalse{show}
\listoffigures
\booltrue{show}

\begin{figure}
\centering
blub
\caption{blalbl
\notintoc{Source:~\cite{shore}, \cite[50]{aksin}, and based on \cite[Vol][3]{herrmann}}}
\end{figure}

\end{document}


text:
Q: Using python manage.py migrate --check in kubernetes readinessProbe never succeeds I have a django deployment on kubernetes cluster and in the readinessProbe, I am running python, manage.py, migrate, --check. I can see that the return value of this command is 0 but the pod never becomes ready.
Snippet of my deployment:
      containers:
        - name: myapp
          ...
          imagePullPolicy: Always
          readinessProbe:
            exec:
              command: ["python", "manage.py", "migrate", "--check"]
            initialDelaySeconds: 15
            periodSeconds: 5

When I describe the pod which is not yet ready:
Events:
  Type     Reason     Age                From               Message
  ----     ------     ----               ----               -------
  Normal   Scheduled  66s                default-scheduler  Successfully assigned ...  Normal   Pulled     66s                kubelet            Successfully pulled image ...
  Normal   Created    66s                kubelet            Created container ...
  Normal   Started    66s                kubelet            Started container ...
  Warning  Unhealthy  5s (x10 over 50s)  kubelet            Readiness probe failed:

I can see that migrate --check returns 0 by execing into the container which is still in not ready state and running
python manage.py migrate
echo $?
0

Is there something wrong in my exec command passed as readinessProbe?
The version of kubernetes server that I am using is 1.21.7.
The base image for my deployment is python:3.7-slim.

A: The solution for the issue is to increase timeoutSeconds parameter, which is by default set to 1 second:

*

*timeoutSeconds: Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1.

After increasing the timeoutSeconds parameter, the application is able to pass the readiness probe.
Example snippet of the deployment with timeoutSeconds parameter set to 5:
      containers:
        - name: myapp
          ...
          imagePullPolicy: Always
          readinessProbe:
            exec:
              command: ["python", "manage.py", "migrate", "--check"]
            initialDelaySeconds: 15
            periodSeconds: 5
            timeoutSeconds: 5


text:
Q: import and export data from asp.net Hi I am trying to find a solution to export data from my database but i don't know what is the best approach .
simply, i will upgrade my project in the future and i don't want to lose my data plus maybe, i add some new tables in the future and maybe some columns to the current tables .
so what should i do with that ?
and if there is a solution to do that from asp.net it will be great as the project will be on the cloud.
i have tried to backup and restore database it self but its overriding the data and maybe its avoid to restore the data if i added some new tables
Thanks in advance.

A: If you want to do it in code I think the easiest is to create ALTER statements for your modifications; building up a script that can update your database.
On startup of your website? you can check the version of the database with the necessary version and run the scripts (Starting with a backup...). You will need a place to store the version in your database for this to work.
There are also tools available (commercial) that can do this; but it is not scripted so it will be a manual process.


text:
Q: Understanding formula for Short Term / Long Term Degrees of freedom in minitab Now I'm new to statistics, but the last time I did degrees of freedom, the formula I used was
$df = n-1,$
but I've just been playing with Minitab and reading the help to files, and I noticed it is calculating long-term and short-term degrees of freedom like this:
$df(LT) = \sum_{i=1}^j n_j-1$
$df(ST) = \sum_{i=1}^j (n_j-1)$
I interpret it like this:
Data (1 group): 20, 10 ,10, 23, 25, 20
$df(LT) = (20+10+10+23+25+20) - 1$
$df(LT) = 108$
and
$df(ST) = ((20-1)+(10-1)+(10-1)+(23-1)+(25-1)+(20-1))$
$df(ST) = 102$
I have got this right, or am I way out?
UPDATE:
Looking around other help files, I found that
$n_j$ is the number of obervartions in the jth subgroup.
So with that in mind, and my example with only 1 subgroup, I assume that both LT and ST are the same, which is $n - 1$.

A: You are close, but off the mark. While "long-term" and "short-term" are new to me (indeed, they seem to be specific to this site and might as well come with a trademark!) I can tell you that you seem to be calculating the whole-sample variance degrees of freedom (LT) and the anova denominator degrees of freedom (ST), which could also be described as the mean squared error (MSE) degrees of freedom.
To be clear, the values of $n_i$ are the number of measurements in group $i$, not the actual measurements. The total number of measurements $n$ of data acquired from $J$ groups is $$n=\sum_{i=1}^J n_i.$$ The LT degrees of freedom seems to be $n-1$, which would be the number used in the unbiased estimate of the whole-sample variance $$s^2=\frac{1}{n-1} \sum_{k=1}^n(x_k-\bar{x})^2.$$ Here the $x_k$ does correspond to the actual data, and $\bar{x}$ is the whole-sample mean, sometimes called the grand mean.
The short-term degrees of freedom correspond to $n-J$, which is the total number of points acquired minus the number of groups (or treatments) $J$. This would be the degrees of freedom used in calculating the variance within treatments for the group-wise model.
$$
MSE = \frac{1}{n-J} \sum_{i=1}^J \sum_{k=1}^{n_i} \left( x_k^{(i)}-\bar{x}^{(i)} \right)^2,
$$
where $i$ is the index for $J$ treatments or groups, $x_k^{(i)}$ is the $k$-th data point in group $i$, and $\bar{x}^{(i)}$ is the sample mean of the $i$-th group. This would be the denominator of the F test of equal means of $J% groups, and $n-J$ would be the denominator degrees of freedom.

I see that the Minitab page uses $\mu$ to describe a sample average. Argh! This is highly non-standard notation. Greek letters are (nearly-universally) reserved for population parameters, not sample statistics. The (nearly-universally) recognized notation for a sample statistic is the Roman letter. In this case, the sample average is $\bar{x}.$ Hopefully you are not confused by this nonstandard notation. Population parameters are only ever estimated by sample statistics. They themselves are not statistics, at all.


text:
Q: How to sort by custom field? In my custom post type ("mitarbeiter") there is a custom field called "sort" which only allows numbers as value. Currently my posts are getting ordered by the title. I would like to order them by the value of the custom field "sort" which will be given by the function get_field("sort").
This is how my code looks for now:
// Get the team members
function get_employee() {
    query_posts(array(
        'post_type' => 'mitarbeiter',
        'showposts' => 100,
        'orderby' => 'title',
        'order' => 'ASC'
    ) );
    while (have_posts()) : the_post();
        $content = '

';
                            // Display the image
                            $image = get_field('portraitfoto');
                            if (!empty($image)) :
                                $content .= '
';
                            endif;
                        $content .= '

'. get_the_title() .'

'. get_field("funktion") .'
'.
                             get_field("telefon") . '

                            '. get_field("email") .'

';

    echo $content;
    endwhile;
    wp_reset_query();
}

How can I do this?

A: used meta_key  in query_postsand orderby = 'meta_value_num'
query_posts(array(
        'post_type' => 'mitarbeiter',
        'showposts' => 100,
        'meta_key'          => 'sort',
        'orderby'           => 'meta_value_num',
        'order'             => 'ASC/DESC'// Add ASC OR DESC as per your requirement
) );

A: As Pieter mentioned in a comment, query_posts() isn't the best function to use - see this post on WordPress Stack Exchange for some background on this. Basically, it's inefficient and causes some obscure bugs.
The better way to do this would be using WP_Query, and that documentation shows you how to do this as well as quite a lot more (it's a pretty powerful class).
To rewrite your query, and add your sorting criteria, you'd be looking at something like this:
$my_query = new WP_Query(array(
  'post_type' => 'mitarbeiter',
  'posts_per_page' => 100,
  'meta_key' => 'sort',
  'orderby' => 'meta_value_num',
  'order' => 'ASC',
) );

To make your loop work with your custom WP_Query, you'll need to also change this line:
while (have_posts()) : the_post();

to this:
while ($my_query->have_posts()) : $my_query->the_post();

and change the wp_reset_query(); call at the end of your code to wp_reset_postdata();
You should find this sorts by the sort meta key for you, as well as makes sure your page runs a bit faster.


text:
Q: Why is this AND gate neural network not moving towards optimal weights? I have simple neural network of two inputs and one output with no hidden layers. i.e, [input1][weight1 weight2] = z [input2]
output = sigmoid(z)
The weights don't seem move to an optimal value. I've checked the gradient to the best of my knowledge and I can see the weights go up or down depending on the derivative of cost function, but network doesn't move towards optimal values.
Here's the code:
import numpy as np
import random as r
import sys

def sigmoid(ip, derivate=False):
    if derivate:
        return ip*(1-ip)
    return 1.0/(1+np.exp(-1*ip))

class NeuralNet:
    global sigmoid

    def __init__(self):
        self.inputLayers = 2
        self.outputLayer = 1

    def setup(self):
        self.i = np.array([r.random(), r.random()], dtype=float).reshape(2,)
        self.w = np.array([r.random(), r.random()], dtype=float).reshape(2,)

    def forward_propogate(self):
        self.z = self.w*self.i
        self.o = sigmoid(sum(self.z))

    def optimize_cost(self, desired):
        i=0
        current_cost = pow(desired - self.o, 2)
        for weight in self.w:
            dpdw = -1 * (desired-self.o) * (sigmoid(self.o, derivate=True)) * self.i[i]
            print(dpdw)
            self.w[i] = self.w[i] + 500*dpdw
            i+=1
        self.forward_propogate()

    def train(self, ip, op):
        self.i = np.array(ip).reshape(2,)
        self.forward_propogate()
        print("before:{}".format(self.o))
        self.optimize_cost(op[0])
        # print(self.i,self.w)
n = NeuralNet()
n.setup()
# while sys.stdin.read(1):
while True:
    a = r.random()
    b = r.random()
    if a>0.5 and b>0.5:
        c = 0.9
    else:
        c = 0.1
    print(c)
    n.train([a,b],[c])
    print(n.i, n.w)
    print("after: {}".format(n.o))

A: i have read this https://towardsdatascience.com/emulating-logical-gates-with-a-neural-network-75c229ec4cc9 and there is also said that deeper (with (multiple) hidden layers) networks are required to achieve good training results, the reasons mentioned are :

Training and Learning
Now we have shown that this neural network is possible, now the
  remaining question is, it is possible to train. Can we expect that if
  we simply fed in the data drawn from the graph above after defining
  the layers, number of neurons and activation functions correctly, the
  network will train in this way?
No, not always, and not even often. The problem, like with many neural
  networks is one of optimization. In training this network it will
  often get stuck in a local minimum even though a near-perfect solution
  exists. This is where your optimization algorithm may play a large
  role, and this is something which Tensorflow Playground doesn't allow
  you to change and may be the subject of a future post.
[...]
After you have built this network by manually inputting the weights,
  why not try to train the weights of this this network from scratch
  instead of constructing it in manually. I have managed to do this
  after many trials, but I believe it is quite sensitive to the seeding
  and often ends up in local minimums. If you find a reliable way to
  train this network using these features and this network structure
  please reach out in the comments.
Try to build this network using the only this number of neurons and
  layers. In this article I have shown that it is possible to do it with
  this many neurons only. If you introduce any more nodes then you will
  certainly have some redundant neurons. Although, with more
  neurons/layers, I have had better luck in training a good model more
  consistently.

Possibly the problem is related to the multiplication problem of neural nets. Flat (or non-deep / without hidden layers) neural nets are not able to perform a simple multiplication cf https://stats.stackexchange.com/questions/217703/can-deep-neural-network-approximate-multiplication-function-without-normalizatio
UPDATE (comment)
To be honest i am not sure about the MSE error function because it is not good in classification problems, cf https://towardsdatascience.com/why-using-mean-squared-error-mse-cost-function-for-binary-classification-is-a-bad-idea-933089e90df7 and https://medium.com/autonomous-agents/how-to-teach-logic-to-your-neuralnetworks-116215c71a49 (uses negative log likelihood error function that is also known as multiclass cross-entropy) and also https://machinelearningmastery.com/how-to-choose-loss-functions-when-training-deep-learning-neural-networks/ :

Mean Squared Error Loss
The Mean Squared Error, or MSE, loss is the default loss to use for regression [not classification] problems.

source : https://machinelearningmastery.com/how-to-choose-loss-functions-when-training-deep-learning-neural-networks/
Training two labels or classes (True, False) is a classification problem, not a regression problem.
however i think the main systematical problem is that the network is not deep enough. As said in the article https://towardsdatascience.com/emulating-logical-gates-with-a-neural-network-75c229ec4cc9 you can seed combinations of initial weights to avoid local minima but this also does not solve the basic problems (network not deep enough, wrong error function (MSE)).
In https://towardsdatascience.com/lets-code-a-neural-network-in-plain-numpy-ae7e74410795 is a numpy implementation of a neural network for classification that includes an implementation of binary cross-entropy error function, maybe compare this to your code.

A: Answering my own question. All I needed was a BIAS. Without a BIAS, the sigmoid cannot deviate from 0.
Here's a sigmoid with bias of 2. Now sigmoid(0) = closer to 0.1

After including a BIAS node in the network, I was able to get the results.

Success rate: 99.00000042272556% Network trained, took: 2365601 trials
Network weights:[14.0435016  14.04351048]
Bias: 21.861074330808844

Enter INPUT:0 1
Network output:0.00040243926180320134
Enter INPUT: 1 1
Network output:0.9980264340845117


text:
Q: Modificar cada dígito de una cadena por el siguiente (su sucesor) Tengo un archivo plano en formato UNIX delimitado por ; (Punto y coma) con la siguiente estructura:
2020-01-30;1010;1
2020-01-30;1150;2
2020-02-03;1190;3

Debo reemplazar cada caracter desde la posicion (12,4)
0->1
1->2
2->3
3->4 etc etc...

Quedando:
2020-01-30;2121;1
2020-01-30;2261;2
2020-02-03;2201;3

He intentado con varias estrategias sin resultado positivo:
sed -i 's/0/9/g; s/1/8/g; s/2/7/g; s/3/6/g; s/4/5/g; s/5/4/g; s/6/3/g; s/7/2/g; s/8/1/g; s/9/0/g' data.dat > data1.dat

¿Tienen alguna estrategia?

A: Como no me dejaba dormir la idea de poder hacerlo con sed, al final propongo una respuesta para realizar lo mismo.
Respuesta anterior
Con awk se puede hacer de una manera concisa:
#!/bin/bash

#   Declaramos que el            Declaramos que el
#   delimitador sea el ";"       separador de salida (OFS)
#          |                     sea ";" para ahorrarnos
#          |                     la escritura de caracteres.
#          |                      |
#          |                      |
awk --field-separator=";" -v OFS=";" '{
    split($2, campo2, "") # Creamos el array "campo2"
                          # cuyo contenido son las letras
                          # del segundo campo.
    $2 = "" # Borramos el contenido del segundo campo
    for ( numero in campo2 )
        $2 = sprintf( "%s%s",
                        $2,
                        (campo2[numero] + 1) % 10 )
    print $0 # O simplemente print, porque por defecto
             # imprime a $0
}' numeros.txt

Lo que hago con sprintf es concatenar lo que tiene $2 con el módulo 10 del número mas 1. De esa forma me aseguro que se quede en el conjunto del {0...9}.
Definir el OFS como ; es para que al final, cuando hago print $0, ya no tenga que separarlo por ; y awk lo haga por mi. $0 tiene toda la información del registro, pero como modificamos la variable $2, entonces la información del registro se mantiene intacta salvo el segundo campo $2.
El resultado es el que deseas:
2020-01-30;2121;1
2020-01-30;2261;2
2020-02-03;2201;3

Sin los comentarios el código queda:
awk --field-separator=";" -v OFS=";" '{
    split($2, campo2, "")
    $2 = ""
    for ( numero in campo2 )
        $2 = sprintf( "%s%s", $2, (campo2[numero] + 1) % 10 )
    print
}' archivo.txt

Actualización
Recientemente tomé un curso intensivo de sed de la Universidad del Internet y de la Universidad de Leer el Manual. Y logré obtener lo mismo pero con el mero uso de sed.
Antes de poner el código con la explicación incluida, creo que es necesario aclarar ciertos conceptos fundamentales:

*

*pattern space, es un buffer temporal de sed que recibe todos los caracteres y donde se hacen las modificaciones. Sólo se puede interactuar con lo que hay aquí

*hold space, es otro buffer temporal pero que puede almacenar ciertas cosas del pattern space. No se puede interactuar directamente con este buffer; sólo a través de mandar cosas de un buffer a otro. Lo que se encuentra dentro del hold space, se retiene entre ciclos: no cambia a menos que se le indique.

Para comunicar entre estos buffers se tienen los comandos h,H,g,G,x. Que copian o añaden desde el hold space al pattern space, o viceverss, o sólo intercambian lo que hay en uno por lo que hay en otro.
Esto lo explicaría como si fuese el libro Molloy de Samuel Beckett, donde el vagabundo trata de chupar cada piedra que tiene, ayudándose únicamente de los bolsillos (buffers), de sus sacos.
Una vez diciendo esto, pongo el código que deberá ser guardado en un archivo como sed_file.sed con permisos de ejecución dados por chmod u+x sed_file.sed:
#!/bin/sed -rnf
# -r, para utilizar expresiones regulares extendidas
# -n, para no imprimir el pattern space por defecto
# -f, para indicar que este archivo sea tomado como un script de sed

h  # Copiamos lo que se encuentra en pattern space al hold space

s/([^;]*?;)([[:digit:]]{4})(;.*$)/\2/  #  Lo que se encuentra en el pattern space le dejamos,
                                       #+ únicamente los cuatro números en el segundo campo,
                                       #+ dejándo únicamente lo de la forma 1002, 2032, etc.

y/0123456789/1234567890/;  #  Ya teniendo sólo esos cuatro dígitos en el pattern space,
                           #+ transliteramos número por su sucesor. Es decir, hacemos
                           #+ un desplazamiento en uno: el 0 al 1, el 2 al 3, etc.
#|                     |
#|_____________________|
#           |
#           |_____ ¡Esto sigue estando en el pattern space!
#                  Es decir, tenemos (únicamente) números como "2121"
#                  que provienen de otros como "1010".

G  #  Al pattern space se le añade un salto de línea, seguido de lo que está
   #+ el hold space (la cadena inicial que guardamos con el comando "h").

# Hasta aquí tenemos en el pattern space algo de la forma:
#
#    <numerosaumentados>\n<la cadena inicial>
#
# Donde la cadena inicial es de la forma:
#    <fecha>;<numeros anteriores>;<un dígito>
#
#  Ahora tenemos que operar de tal manera que llevemos los números aumentados
#+ de la parte inicial, a en medio de <fecha> y <un dígito>

s/([[:digit:]]{4})\n([^;]*?;)([[:digit:]]{4})(;.*)/\2\1\4/
# |______________|  |_______||______________||___| |_____|
#         |             |            |         |      |
#         |             |            |         |      |__ Modificamos la salida de la
#         |             |            |         |          forma <fecha><numeros aumentados><un digito>
#         |             |            |         |
#         |             |            |         |__ Atrapamos el dígito en \4
#         |             |            |
#         |             |            |__ Atrapamos los números anteriores en \3
#         |             |
#         |             |
#         |             |__ Atrapamos la fecha en \2
#         |
#         |__ Atrapamos los números aumentados en \1
# Todo esto sucede en el pattern space.

p  # Imprimimos el pattern space

O, sin comentarios:
#!/bin/sed -rnf
h
s/([^;]*?;)([[:digit:]]{4})(;.*$)/\2/
y/0123456789/1234567890/
G
s/([[:digit:]]{4})\n([^;]*?;)([[:digit:]]{4})(;.*)/\2\1\4/
p

Entonces corremos:
$ ./sed_file.sed numeros.txt
2020-01-30;2121;1
2020-01-30;2261;2
2020-02-03;2201;3

A: La respuesta de Cuauhtli está muy bien y resuelve el problema correctamente.
Simplemente como referencia y para utilizar otras potencialidades de GNU Awk, veamos cómo hacerlo de otra manera:
gawk -F '' '{for(i=1;i<NF;i++) printf "%s", (i>=12 && i<=15) ? ($i+1)%10: $i; print $NF}'

En GNU Awk es posible definir el separador de campos como la "nada". Con ello, cada carácter es un campo diferente. Esto se hace indicando -F ''.
De esta manera por ejemplo podemos decir:
$ awk -F '' '{for(i=1;i<=NF;i++) print $i}' <<< "hola"
h
o
l
a

Una vez aprendido esto, ahora es simplemente cuestión de iterar sobre la cadena y modificar los caracteres que hay en la posición 12 a 15, utilizando la lógica de la respuesta de Cuauhtli:
for(i=1;i<NF;i++)
   printf "%s", (i>=12 && i<=15) ? ($i+1)%10: $i
print $NF

Es decir, itera sobre todos los caracteres e imprime el carácter en sí ($i) a menos que esté en la posición 12 a 15, en cuyo caso imprimimos ($i+1)%10. Esta decisión la tomamos mediante el operador ternario condición ? reacción_si_cierto : reacción_si_falso.
Finalmente ponemos print $NF para escribir el último campo y que vaya seguido de un salto de línea, porque printf no los añade automáticamente y print sí.

A: Puedes hacerlo con Perl, que viene por defecto en cualquier distribución linux.
 cat fichero.txt | perl -pne 's/(?:^[^;]+;\K|\G)\d/($&+1)%10/ge';

Al utilizar las opciones n, e, lo que hay a continuación se ejecuta para cada línea de entrada y se asume que está en un bucle, donde la variable por defecto ($_) obtendrá cada línea. Con la opción p se imprime al terminar cada iteración (el contenido de la variable)
Así pues como script lo que realmente hacemos es modiciar el contenido de esta variable, que tiene la línea.
Primero, vamos a "buscar" todos los números que hay en la segunda columna. Pero los iremos capturando de uno en uno, en lugar del bloque completo. Para cada captura, remplazaremos su valor por el "incrementado"
Explicación expresión regular:
(Usaremos el modificador "g" para hacer una búsqueda global)
(?: # Una de estas dos opciones:
      # opción1: Empieza el string,
      #          seguido de uno o más caracteres que no sean ';'
      #          luego un punto y coma ';'
      #          y finalmente "olvidamos" lo capturado hasta ahora con \K
      ^ [^;]+ ; \K
      # opción2: Posición dónde nos quedamos justo después de la última búsqueda
    | \G
)
# Un número, es realmente lo que 'encontramos'. Lo anterior sólo es
# para saber a partir de dónde empezar a buscar.
# El valor estará accesible en $&
\d

Para ver esta expresión regular en acción (sin los remplazos) puedes ir a esta demo.
Finalmente miramos con qué remplazarla.
($&+1)%10

En Perl, el modificador e en una expresión regular (como en s/blabla/codigo/e), permite evaluar código.
Como tenemos el número encontrado en $&, lo que hacemos es sumarle 1 y aplicarle un módulo 10 para de esta manera pasar a 0 cuando tenemos un 10.


text:
Q: Django form errors in loop forms.py
def clean(self):
    for item in self.my_items:
        if item.number == 0:
            raise forms.ValidationError("Error %s" % item.pk)

This code displays error only for first item(after first loop). How can I display errors for all my_items?
html:
{% for error in form.non_field_errors %}
    {{ error }}<br>
{% endfor %}

A: You can use the add_error method.
self.add_error(fieldname, 'My error here')


text:
Q: Why do the components of an equivalent kernel sum to 1? Let $\textbf{x} = (x_1, \dots, x_n)^T \in \mathbb{R}^n$ and $k \in \mathbb{N}$. We define
$$
X :=
\begin{pmatrix}
  1 & x_1 & \cdots & x_1^k \\
  \vdots  & \vdots  &  & \vdots  \\
  1 & x_n & \cdots & x_n^k
\end{pmatrix} \in \mathbb{R}^{n \times (k+1)}
$$
and a function $b:\mathbb{R} \rightarrow \mathbb{R}^{k+1}$ with $b: x_0 \mapsto (1, x_0, \dots, x_0^k)^T$. Then, we can compute the equivalent kernel $$l(x_0) = b(x_0)^T(X^T X)^{-1} X^T$$ for any $x_0 \in \mathbb{R}$. The question is: how can we prove that the sum of the components of $l(x_0)$ is $1$ for all $x_0 \in \mathbb{R}$ and $k \in \mathbb{N}$?

Further notes:
This question arises in the context of local polynomial regression and it is a simplified version of Exercise 6.2 in "Elements of Statistical Learning".
I tried induction over $k$ and used a formula for blockwise inversion with no luck.

A: The sum of the components of $l(x_0)$ can be expressed as $l(x_0) \mathbf{1}_{n}$. After defining $S_k := \sum_{i=1}^n x_i^k$ we can rewrite the sum as follows
\begin{align*}
l(x_0) \mathbf{1}_{n}
  &= b(x_0)^T (X^TX)^{-1} X^T \mathbf{1}_{n} \\
  &= b(x_0)^T (X^TX)^{-1} (S_0, \dots, S_k)^T \\
  &= b(x_0)^T
      \begin{pmatrix}
        S_0 & S_1 & \cdots & S_k \\
        \vdots  & \vdots  & \ddots  & \vdots  \\
        S_k & S_{k+1} & \cdots & S_{2k}
      \end{pmatrix}^{-1}
      \begin{pmatrix}
        S_0 \\
        \vdots \\
        S_k
      \end{pmatrix} \\
  &\overset{(*)}{=} b(x_0)^T e_1 \\
  &= 1 \;.
\end{align*}
At step $(*)$ we used the definition of the inverse of a matrix, i.e. $A^{-1} A = I = (e_1, \dots, e_n)$ for all invertible matrices $A$.


text:
Q: Точка после переменной. Пример: $a.=$b[$i]; - ошибка или нет? Копался в одном скрипте покупном и обнаружил примерно такую картину:
$a.=$b[$i];

Информации про точку после переменной в Google не нашел.
Думаю, это ошибка, но все же хотелось бы узнать мнение программистов.
A: Это точка не после переменной, а перед "равно") И нет, не ошибка, укороченный вариант конкатенации (сложения строк).
$a .= $b; // $a = $a . $b;
$x += $y; // $x = $x + $y;
$i /= 5; // $i = $i / 5;

A: $a  = 1;
$a .= 2;
echo $a;

Так же используется! Часто в велосипедах)
A: Вообще, как известно, в языке php знак "." применяется для конкатенации, то есть соединения двух элементов в один. Получается, что

$a  = 1;
$a .= 2;
echo $a;

Выведет число 12*(т.к "1"."2"="12")*


text:
Q: How can I get individual image_urls from an Instagram album using oembed api call? I have been using the Instagram API to get images and videos, which works just fine. I then noticed the oembed API call, which does not require an access_token, and I decided to give that a try, which also worked just great as the thumbnail_url size is adequate for most uses.
However, I noticed that the images retrieved from an album, all have a thumbnail_url that returns a 5xx Error from Instagram.
My thinking is that:
a) This is exactly how it is supposed to work and if I want images from a gallery/album, I need to use the media API call and access_token like most normal people
b) There is a way to access all images from a gallery/album and I just don't know yet. What if I want to embed the album? If this is the case, how can I check if it is an album or single image before making an API call?
Here is what I have so far:
Instagram permalink for album/gallery: https://www.instagram.com/p/BTHpAmzDHKR/
OEMBED API call: https://api.instagram.com/oembed/?url=https%3A%2F%2Fwww.instagram.com%2Fp%2FBTHpAmzDHKR%2F
thumbnail_url returned: https://scontent-dft4-2.cdninstagram.com/t51.2885-15/s612x612/e35/18012162_1608580785827161_2716056344971968512_n.jpg
media API working url for same image:
https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/18012162_1608580785827161_2716056344971968512_n.jpg

This opens up to a 5xx Server Error
Is it possible or not using oembed call?
NOTE: I am trying this just out of curiosity and not for any real app.

A: Closing this out as my research has shown that oembed is for single media type only, not for carousel/albums. Instagram API call which uses tokens is required.


text:
Q: Microsoft's StreamInsight - Experiences & SQL Server 2008 R2 Microsoft's Complex Event Processing (CEP) offering StreamInsight was released in tandem with SQL Server 2008 R2.
I am wondering:

*

*if StreamInsight is in any way tied
to the SQL Server 2008 R2 database and
if it can be run separately.
(From scanning over the documentation
   it looks like StreamInsight can be
   run separately but clarification would be desirable).

*If you have experience using StreamInsight separate from SQL Server 2008 R2 how has the experience been?
Thanks!

A: "As for your thoughts regarding StreamInsight (SI) and SQL Server 2008 R2; at least at this moment, SI has no dependencies on SQL Server 2008 R2 what so ever. For certain operations you may need a SQL Server Compact (CE) db, which stores metadata – but you can definitely use SI against other databases than SQL if you so wish." Niels of http://www.sqldevelop.com/

A: Responding to Tom's issues ...

Lacks query code reuse options

How so? First, you have Query Templates, which allow for query code reuse right out of the box. Second, you can create an architecture (as we have) that encapsulates related sets of queries in a provider model and then hook them up to various input and output adapters.

Adapters are constrained to pulling rather than pushing

Again, how so? The input adapters push data into the StreamInsight engine. Whether or not the data gets pushed into the input adapter depends on the source. We've created an OPC-DA input adapter that uses subscriptions and has data pushed from OPC. OSISoft's PI adapter works the same way.

No fail-over mechanism, no persistency guaranteed.

That is true.

Window logic is not as straightforward as other engines

That may be your opinion based on what you've used before and what you are familiar with. I've found StreamInsight's model to be relatively straightforward, flexible and powerful. I also find the query language (LINQ) much easier to use and very natural for a C# developer.
On another note, most of the other CEP engines out there are a very "heavy" install and can have a significant impact on an enterprise architecture - this from someone that's seen several installations of TIBCO do very unpleasant things to a network. StreamInsight is very lightweight and has a very small footprint compared to other engines.
Just my $.02 worth.

A: StreamInsight have some limitations in the event types, he accept simple (very simple) variable types. In case of an OPC server it is useless ...

A: my experience with streaminsight has been in a POC we've made here.
this product is not mature enough in my opinion to be a production infrastructure.


text:
Q: Template class arguments as type I have a class
template<typename T, typename U>
class A {
  T i;
}

And i have a class B that should use the same types as class A
template<typename A_Type>
class B
    : public A_Type
{
  T j; // here I need a class member of the same type as the first type of A_Type (T from class A)
}

So I would need something like
template<typename A_Type<T, U>>
class B
    : public A_Type
{
  T j;
}

This notation is obviously not working but is there a notation that would fit my needs?

A: You can provide a member alias in A :
template<typename T, typename U>
class A {
  T i;
  using value_type = T;
};

template<typename A_Type>
class B
    : public A_Type
{
  typename A_Type::value_type;
};

Or use specialization to deduce the type of the argument:
template<typename T, typename U>
class A {
  T i;
  using value_type = T;
};

template<typename A_Type>
class B : public A_Type {};

template <typename T,typename U>
class B<A<T,U>> : A<T,U> {
    T j;
};

As mentioned in comments, try to be careful with terminology. Using the terms right avoids issues. Neither A nor B are classes. They are class templates. And the member alias should be protected (or placed in a seperate trait template <typename A> struct get_T_from_instantiation_of_A;)

A: Can't you just pass that type ?
template<typename A_Type, typename T>
class B
    : public A_Type
{
  T j; // here I need a class member of the same type as the first type of A_Type (T from class A)
}

A: You could create some type traits to help out.
First one to test if a type is really an A type:
#include <type_traits>

template<class T>
struct is_A_type {
    static std::false_type test(...);

    template<template<class...> class U, class... V,
                      std::enable_if_t<std::is_same_v<U<V...>, A<V...>>, int> = 0>
    static std::true_type test(const U<V...>&);

    static constexpr bool value = decltype(test(std::declval<T>()))::value;
};

template<class T>
inline constexpr bool is_A_type_v = is_A_type<T>::value;

Then a trait to get the type of the first template parameter:
template<class T>
struct first_type {
    static void test(...);

    template<template<class...> class U, class F, class... V>
    static auto test(const U<F, V...>&) -> F;

    using type = decltype(test(std::declval<T>()));
};

template<class T>
using first_type_t = typename first_type<T>::type;

These traits could then be used like so:
template<class A_Type>
class B : public A_Type {
    static_assert(is_A_type_v<A_Type>, "A_Type must be an A type");

    using T = first_type_t<A_Type>;

    T j;
};


text:
Q: Cannot render value to the html in angular 2 I am implementing this code in my component that basically fetches data from a database. I can console.log the data and I can actually see the results and I can event alert it. But when I render it in my html, I do not see the value anymore. Please see my code below:
.ts
ngOnInit() {
    this.unitid = this.route.snapshot.paramMap.get('unitid');
    if (this.unitid === null) {
        this.router.navigate(['/main/viewproperties']);
    }
    this.getLessee();
    this.getLessor();
}

getLessor() {
    this.clientService.getUnitOwner(this.unitid)
        .subscribe((data: any) => {
          this.unitLessor = data;
          console.log(data);
          this.fname = this.unitLessor.FirstName;
          alert(this.fname);
        });
}

.html
<div *ngIf="fname">
   {{fname}}
</div>

below is what I get on console.log

I would really appreciate your help.

A: You can use router param to initiate ngOnInit() once again if param value changes and it subscribe the value into HTML when param has value, you can try this way :
unitLessor: any; // declare model/entity here
ngOnInit() {
   this.route.params.forEach((params: Params) => {
      this.unitid = parseInt(params['unitid']);
      if (this.unitid) {
         this.getLessor(this.unitid);
      }else{
          this.router.navigate(['/main/viewproperties']);
      }
      this.getLessee();
   }
 }

 getLessor(id: number) {
     this.clientService.getUnitOwner(id)
       .subscribe((data: any) => {
        this.unitLessor = data;
        console.log(data);
     });
 }

AND Html could be :
   <div *ngIf="unitLessor">
       {{unitLessor.FirstName}}
   </div>
   OR
   <div *ngIf="unitLessor?.FirstName">
       {{unitLessor.FirstName}}
   </div>

A: This is a change detection issue .
import {ChangeDetectorRef} from '@angular/core';

constructor(private _cdr : ChangeDetectorRef){}

getLessor() {
    this.clientService.getUnitOwner(this.unitid)
        .subscribe((data: any) => {
          this.unitLessor = data;
          console.log(data);
          this.fname = this.unitLessor.FirstName;
          alert(this.fname);
          this._cdr.detectChanges();
        });
}


text:
Q: 2D Array assign value for loop I need a bit of help. I have two arrays. Let's say
alpha = np.arange(1,5,1) ==> [1,2,3,4]
beta = np.arange(5,8,1) ==> [5,6,7]

How do I use values alpha and beta, call a function, and assign the function return into an array whose number of rows is the same as the number of elements in beta and whose number of columns is the same as the number of elements in alpha.
matrix_assign = np.zeros_like((alpha, beta), dtype = 'float')

+---+---+---+---+---+
|   | 1 | 2 | 3 | 4 |
+---+---+---+---+---+
| 5 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
| 6 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+
| 7 | 0 | 0 | 0 | 0 |
+---+---+---+---+---+

The function I have is a little bit more complicated so for this purpose, lets make the function do
np.sqrt((alpha-beta)^2)

This is the code I have so far but it doesn't seem to be working. Essentially, i in alpha and j in beta goes into the function, and the value that is returned shall replace the zero in its respective cell.
 for i in range(alpha):
        for j in range(beta):
            matrix_assign[i,j] = fn.sample_function(i,j)

eg when alpha[0] and beta[1] goes into the function, the output 5 is assigned to the cell matrix_assign[1,0]
Thank you
EDIT:
import numpy as np

alpha = np.arange(1,5,1) #==> [1,2,3,4]
beta = np.arange(5,8,1) #==> [5,6,7]

matrix_assign = np.zeros_like((alpha, beta), dtype = 'float')

for i in range(alpha):
    for j in range(beta):
        matrix_assign[i,j] = np.sqrt((alpha-beta)^2)

why doesn't the above code work? I'm getting the error
for i in range(alpha):
    TypeError: only integer scalar arrays can be converted to a scalar index

using range(len(alpha)) also doesn't work. I get the error
matrix_assign[i,j] = np.sqrt((alpha-beta)^2)
    ValueError: operands could not be broadcast together with shapes (4,) (3,)

A: You code should be:
import numpy as np

alpha = np.arange(1,5,1) #==> [1,2,3,4]
beta = np.arange(5,8,1) #==> [5,6,7]

matrix_assign = np.zeros_like((alpha, beta), dtype = 'float')

for i in range(alpha.size):
    for j in range(beta.size):
        matrix_assign[i,j] = fn.sample_function(alpha[i], beta[j])

fn.sample_function needs single values of alpha and beta, not the indices.
This is very slow, though.
If your fn.sample_function is vectorized, you can do this:
A, B = np.meshgrid(alpha, beta)
matrix_assign = fn.sample_function(A, B)

You can also mash any function to be pseudo-vectorized by using np.vectorize.
A, B = np.meshgrid(alpha, beta)
matrix_assign = np.vectorize(fn.sample_function)(A, B)

But this is just a convenience function that doesn't have any time benefit over for loops.

A: In general, this is a ufunc.outer operation.  Unfortunately, it only works with ufuncs.  Subtraction is a ufunc, but not the rest of your op.  You can do it this way:
matrix_assign = np.abs(np.subtract.outer(alpha, beta))

But in a generalized way, you'll need to make sure your fn.sample_function is either made up of, or tuned into (as a custom ufunc or a np.frompyfunc), only ufunc.


text:
Q: Why did Harry and Hermione arrive in the Entrance Hall after having used the Time-Turner in the hospital wing? In The Prisoner of Azkaban, after the events in the Shrieking Shack, Harry, Ron and Hermione are in the hospital wing. Dumbledore suggests they (Hermione & Harry) use the Time Turner to save more than one innocent, and leaves them. Hermione throws the chain around her and Harry's necks, turns the hourglass, and they arrive, three hours earlier... in the entrance hall.
I know there's not much information about how Time-Turners work, but I thought they only made you travel into time, not into space. Why did they arrive in the entrance hall and not where they were standing, in the hospital wing?
Furthermore, if there is in fact a space-travelling part in this, why the entrance hall? Was it Hermione's choice (it's not implied, and next to Hagrid's might have been a better choice)? Was it the Time-Turner's choice? Something else?
The quote is quite long, I just included a part of the beginning of the chapter showing they were in the hospital wing, then the part where they use the Time-Turner:

"For heaven's sake!" said Madam Pomfrey hysterically. "Is this a
  hospital wing or not? Headmaster, I must insist --"
[...]
"Here --"
  She had thrown the chain around his neck too.
  "Ready?" she said breathlessly.
  "What are we doing?" Harry said, completely lost.
  Hermione turned the hourglass over three times.
  The dark ward dissolved. Harry had the sensation that he was flying very
  fast, backward. A blur of colors and shapes rushed past him, his ears
  were pounding, he tried to yell but couldn't hear his own voice --
  And then he felt solid ground beneath his feet, and everything came into
  focus again --
He was standing next to Hermione in the deserted entrance hall and a
  stream of golden sunlight was falling across the paved floor from the
  open front doors.
(Prisoner of Azkaban, Chapter 21, Hermione's secret - emphasis mine)

A: Think of it as a safety mechanism: you're traveling backwards in time, which means that presumably you were in a safe location earlier (since you survived being there before) and would, ostensibly, only choose to travel to a time in which it would be safe for you to materialize. If you remained in the same location you were in when you time traveled, you would have no idea what might be (might have been) going on in that location when you arrived.
The spell also seems to have a provision to move you just slightly away from your initial location, so that you don't appear literally on top of yourself; presumably it has buffers that select a safe (read: unobserved) spot in the immediate vicinity for you to pop-up, rather than actually just appearing out of nowhere (as she does in the movies, alas). Perhaps the Time Turners are tied to a sort of Homenum Revelio Charm that nudges the traveler away from any wix in the immediate area?
At any rate, I think if I were going to time travel, I would prefer doing it by materializing in my previous location (where I would know what was happening) than in the one I was in at the present/future moment where I'd have no idea what was waiting for me!

A: Every indication is that using the Time-Turner moves you in space to wherever you were at the time you've just travelled to.
Arguably, this makes Time-Turners more risky than they need to be since the risk of running into yourself increases astronomically if you appear nearby your younger self. Yet this seems to be what happens. In other words, they work as you suggest in both time and space.
The reason why they end up in the Entrance Hall is given straight after the passage that's quoted in the question.

He was standing next to Hermione in the deserted Entrance Hall and a stream of golden sunlight was falling across the paved floor from the open front doors..."In here!" Hermione seized Harry's arm and dragged him across the hall to the door of a broom cupboard.; she opened it, pushed him inside amongst the buckets and mops; followed him in, then slammed the door behind him..."Shh! Listen! Someone's coming! I think - I think it might be us! Hermione had her ear pressed against the cupboard door. "Footsteps across the hall...yes, I think it's us going down to Hagrid's!"
Prisoner of Azkaban, Chapter 21, Hermione's Secret

The fact that Harry and Hermione walked through the Entrance Hall moments afterwards wasn't a coincidence. It happened to be where they were exactly three hours before they went back in time. Presumably if you went to the other side of the country on, say, the Knight bus and then used the Time-Turner then you'd find yourself back in your original location.
This does rather leave it to chance that the location that you're time-travelling into will be deserted so that others don't see you emerging from thin air. And, as I say, the risk that you run into yourself is pretty high. The book doesn't address how Hermione has avoided startling other people by popping into mid-air when using the Time-Turner throughout the year. It has her disappearing when Harry and Ron were sure she was behind them and it has Hermione emerging from a staircase that Harry and Ron know she couldn't feasibly have come down. Nowhere does it show Hermione actually using the Time-Turner, except in the section that I quoted.

A: Because Harry Potter Time Turners work like Google Maps or the TARDIS from Doctor Who, it's never accurate and either by plot or by pot luck you could end up anywhere.


text:
Q: ParallelForeach activity in workflow designed via visio In sharepoint online and workflow engine V4, there is possibility to create parallel foreach cycle in visual studio.
Since there is option to edit XAML definition of workflow via combination of sharepoint designer and Visio, is there a way how to use parallel foreach in Visio? There is no such diagram element available, but it does not make sence to me why it would not be possible. Maybe some workarround?


text:
Q: How do I implement support for customers' GA4 container and Meta Pixel tags on a web app? I am working on a web application that is served as an iframe to several clients. I am interested in adding both Google Analytics 4 and Facebook/Meta Pixel analytics tags to the page (through Google Tag Manager if possible) so that the customer can receive the data, as customers have been asking for this.
I understand I can add this integration via GTM to the website by creating a GTM account, creating a container for the website, adding the provided GTM script and iframe to the head and body respectively, and adding GA4 and Pixel as tags to my GTM account. However, this will only provide myself with the page usage data. I could alternatively add a customer's GA4 and Pixel tags to the site, but then only that one customer would be receiving the data. I want to be able to dynamically send the GA4 and Pixel data to whichever customer is currently displaying the app to an end user.
I've seen there is a way to grant access to your GTM account or a specific container through GTM, but doing this would provide one customer with all the data associated with the web app, not just their implementation of it. This solution would work if only one customer was using the website, but not when it is served out to anyone who adds the iframe to their website.
The Pixel tag provided by Meta/Facebook to include in the head:
    <!-- Meta Pixel Code -->
        <script th:unless="${pixelID == ''}">
            !function(f,b,e,v,n,t,s)
            {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
                n.callMethod.apply(n,arguments):n.queue.push(arguments)};
                if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
                n.queue=[];t=b.createElement(e);t.async=!0;
                t.src=v;s=b.getElementsByTagName(e)[0];
                s.parentNode.insertBefore(t,s)}(window, document,'script',
                'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', pixelID);
            fbq('track', 'PageView');
        </script>
        <noscript th:unless="${pixelID}">
            <img height="1" width="1" style="display:none"
                 th:src="${'https://www.facebook.com/tr?id=' + pixelID + '&ev=PageView&noscript=1'}"/>
        </noscript>
        <!-- End Meta Pixel Code -->

Is solving this problem as simple as replacing the Pixel ID pixelID (and Google analytics container ID in the case of GA4) with a stored customer ID value?
Please let me know if there is anything I can help to clarify about the situation or my problem
Thanks!
Edit -- For those looking for a solution to this, I have found a great blog post here detailing how to implement the event forwarding discussed in the top comment.

A: You typically don't go GTM. While implementing user GTMs is an option, it's not a good option. It's too much work on the vendor side, but it also breaks tracking logic for the client unnecessarily into multiple containers, making debugging and implementation a lot harder and less obvious. Having an iframed GTM has other issues too. Like potential double tracking of pageviews if you're not careful and so on.
The best support an iframed vendor can do for their parent window clients (and the industry standard for it) is pushing window messages to the parent. All kinds of messages, indicating all actions users are doing in the iframe, indicating all page changes if there are any, indicating conversions and flow abandonment if applicable.
Then, have it documented with examples of window listeners that can catch those events and retranslate them into proper dataLayer pushes. This would be very considerate.
If you want to go further, you could make a git repo with the container export that would have a tag to deploy the listener as well as variables triggers and test tags for pseudo-tracking all the possible iframe interactions.


text:
Q: Adding text annotations to a map I'm using geoplotlib to siplay points on a map and i would like to add names to the points displayed in my map, like text annotations. But can't figure out how after googling it for a while and looking in the github documentation site. Here's the code to create the map:
import pandas as pd

# Dataframe containing the data to plot

locs = pd.DataFrame({'name': ['a','b'],'lat': [-22.951916, -43.210487], 'lon': [-13.163141, -72.544962]})

# import eoplotlib.

import geoplotlib
%matplotlib inline

# Load the data

data = locs[['lat', 'lon']]

# Pass the data to geoplotlib.plot

geoplotlib.dot(data, color='b', point_size= 10)

# Display the map.

geoplotlib.inline()

This is the map generated:

How could i display the names of the column names in the df alongside the blue points in the map??
Thanks a lot in advance

A: The geoplotlib API reference for the geoplotlib.dot() function provides an argument f_tooltip which accepts a function to generate a tooltip string for a point.
In your code, you do not need a separate data dataframe to plot the map and get the annotated tooltip. The locs dataframe already has the name column which will provide the string for the tooltip and can be used directly. Behind the scenes, the dataframe is converted into a dictionary of key-value pairs. In our case, we just need a simple lambda function to retrieve the name key from the dictionary for the corresponding lat and lon.
Note: I've used geoplotlib.show() as inline plots aren't working for me at this time.
import pandas as pd

# Dataframe containing the data to plot
locs = pd.DataFrame({'name': ['a','b'],'lat': [-22.951916, -43.210487], 'lon': [-13.163141, -72.544962]})

#import geoplotlib.
import geoplotlib
# %matplotlib inline

#function to create a dot density map with annotated tooltip
geoplotlib.dot(locs, color='b', point_size= 10,f_tooltip=lambda r:r['name'])

# Display the map.
geoplotlib.show()

The result:


text:
Q: hg equivalent of git notes Is there a command in mercurial, that works like git notes?

A: Not that I know of: I do not think Hg has yet a special kind of object to associate to commit message.
Introduced in July 2007, "git notes" by Johannes Schindelin, notes are:

Commit notes are blobs which are shown together with the commit message.
  These blobs are taken from the notes ref, which you can configure by the config variable core.notesRef, which in turn can be overridden by the environment variable GIT_NOTES_REF.
The notes ref is a branch which contains trees much like the loose object trees in .git/objects/.  In other words, to get at the commit notes for a given SHA-1, take the first two hex characters as directory name, and the remaining 38 hex characters as base name, and look that up in the notes ref.
The rationale for putting this information into a ref is this:
  we want to be able to fetch and possibly union-merge the notes, maybe even look at the date when a note was introduced, and we want to store them efficiently together with the other objects.

"git notes" is still evolving right now (February 2010).


text:
Q: How can I use query in router.php of codeigniter? I have a list of router such as:
$route['mobile'] = 'parrent_list';
$route['tables'] = 'parrent_list';
$route['laptop'] = 'parrent_list';
$route['gamer'] = 'parrent_list';

My router.php have about 100 row. I dont't want set it manual. So i want know how can I use query in router to get my categories in database.
Example:
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->get( 'categories' )->where( 'parrent_id', 0 );
$result = $query->result();
foreach( $result as $row )
{
    $route[ $row->slug ]                 = 'parrent_list;
    $route[ $row->slug.'/:any' ]         = 'parrent_list;

}

I try but it don't work.
Thanks all.


text:
Q: How can i fill a 2d ArrayBuffer in a dynamic way only in one dimension? i want to have (id, ArrayBuffer[ArrayBuffer[Double]]) filled from a Dstream batch. My input data is of the form: "id, counter, value" and each id has more than one values per counter in each RDD.
So what i want is:
       +-------+-----+------+----+
       |      |value1|value2|etc |
       +-------------------------+
 (id,  |count1|0.2   |0.3   |    |)
       |count2|0.1   |      |    |
       |etc   |      |      |    |
       +------+------+------+----+

When i get the RDD input, i know the counter dimension but i don't know how many values i have stored in each counter to fill the next empty cell. I tried to create an Array[Array[Double]] with a findNextEmpty() method but i get ArrayIndexOutOfBoundsException, so i am trying ArrayBuffer after that. Is there any way to fill dynamically only one of the dimensions of a 2d ArrayBuffer?
My code is:
var example = inputRdd.transform(x =>
       x.groupBy(_ (0))
       .mapValues(x => x
       .foldLeft( ArrayBuffer[ArrayBuffer[Double]]) { (a, b) => {
        a(b(1).toInt)(??) += b(2).toDouble //Don't know the second dimension
         }}))