text:
Q: What is the most fashionable way of calculating minimum value? I want to calculate a minimum value among a set of values using a custom comparator. At the moment my code looks approximately like this:
SomeStructure best;
for  (int i = 0; i < 100; ++i)
{
    SomeStructure cur = getValue(i);
    if (isLess(cur, best))
    {
        best = cur;
    }
}

I find this way not very explicit. For example, if I used a standard comparer, I could write this much prettier:
accumulator_set<SomeStructure, stats<tag::min>> min;
for (int i = 0; i < 100; ++i))
{
  min(getValue(i));
}
extract::min(min);

So, the question is: how can I write something like the second example, but using a custom comparator?
My project uses C++14 and boost, so the solution can use their features.
C++17 is interesting, though not very useful.
UPDATE: looks like I was not very precise in this question.

*

*getValue is a complicated function calculating some value given its index, not just retrieving it from a container.

*I could store all the data in the container and then just use std::min_element, but I'm sure there's any explicit method without doing this.

A: You can use std::min if you wants to compare two elements or a set of elements contained in an initializer_list, along with a custom comparator.
See here for further details. There is also a bunch of examples.
Otherwise, you can use std::min_element for a range. Here the documentation.
EDIT
As far as I understand from your question/comments, you don't have a container on which to iterate, instead you would like to compare a set of unrelated values.
It follows an example, that is the one available in the documentation slightly reduced:
std::min( { "foo", "bar", "hello" },
    [](const std::string& s1, const std::string& s2) {
        return s1.size() < s2.size();
    });

Use your variables instead and create the initializer list on-the-fly, no need for a container anymore.
EDIT 2
In regarding of the update of the question, it follows a possible solution.
You can compare two elements at a time while you iterate over the whole set. As an example, put the first element in a variable called min, then for each subsequent element compare min with the currently one you are elaborating and, if the former is greater than the latter, updated the min variable.
When the iteration ends, you have the min properly set with the element you were looking for. In this case, std::min with a custom comparator seems to be the best solution.

A: Simply use std::min, something like (assuming you've defined operator<) :
SomeStructure best;
for  (int i = 0; i < 100; ++i)
    best = std::min(best, getValue(i));


text:
Q: WebRTC. Почему не работает P2P соединение? Решил изучить WebRTC, но у меня не получается сделать соединение peer-to-peer.
Подскажите, что я делаю не так, может что-то ещё нужно подключить.
Доступ к своей камере и микрофону я получаю и вижу / слышу себя.
Привожу свой код, html:
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <script src="script.js"></script>
    <video id="video" autoplay="autoplay"></video>
</body>

</html>

JS (script.js):
window.onload = function () {
    var myPeerConnection = new webkitRTCPeerConnection(null);
    myPeerConnection.createOffer().then(function (offer) {
        return myPeerConnection.setLocalDescription(offer);
    }).then(function () {
        sendToServer({
            name: myUsername,
            target: targetUsername,
            type: "video-offer",
            sdp: myPeerConnection.localDescription
        });
    }).catch(function (reason) {

    });

    var usersMedia = navigator.mediaDevices.getUserMedia({
        audio: true,
        video: true
    });

    usersMedia.then(function (mediaStream) {
        var myVideo = document.querySelector('#video');
        myVideo.srcObject = mediaStream;
    });

    usersMedia.catch(function (err) {
        console.log(err.name);
    });

    var offer = getRemoteOffer();
    navigator.mediaDevices.getUserMedia({
        video: true
    }).then(function () {
        myPeerConnection.onaddstream({ stream: stream });
        myPeerConnection.addStream(stream);

        myPeerConnection.setRemoteDescription(new RTCSessionDescription(offer), function () {
            myPeerConnection.createAnswer(function (answer) {
                myPeerConnection.setLocalDescription(answer, function () {

                }, error);
            }, error);
        }, error);
    });
}

A: Во-первых - для того, чтобы видеть удаленное видео, надо добавить в код html соответствующий тег.
<html>

    <head>
        <meta charset="UTF-8">
    </head>

    <body>
        <script src="script.js"></script>
        <video id="myVideo" autoplay></video><!-- Это для показа локального видео -->
        <video id="otherVideo" autoplay></video><!-- Это для показа удаленного видео -->
    </body>

</html>

Во-вторых - может я невнимательно смотрел, но в вашем скрипте нет привязки удаленного видеопотока к объекту на вашей веб-странице.
В-третьих - даже подключив удаленный видеопоток, вы сможете получить видео только от тех, кто находится в той же сети, что и вы (например, в пределах рабочей сети, или у одного провайдера). Для работы с клиентами в других сетях, нужно включать в ваш скрипт описания STUN и TURN серверов. В интернете находится довольно большой список известных серверов такого рода, для ознакомления более чем достаточно. Можно заглянуть сюда за подробностями.
В-четвертых (это наиболее важно, если вы действительно хотите организовать связь между клиентами в разных сегментах сети) - для хоста, на котором размещен сигнальный сервер, необходим ssl-сертификат. Иначе браузер просто не позволит передавать данные о видеопотоках.
Для ознакомления я бы рекомендовал посетить codelab - обучающий курс от создателей webrtc. Там все описывается достаточно просто, но понятно (язык - английский).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parse date issue with IE 10 and IE 11 I set system datetime format to Swedish (Sweden)
And ran this javascript code in both IE 10 and IE 11, both gave different results. I expect the IE 11 results though.
What and how can be done to correct for IE 10 ?
var d = new Date(1444028400000);
var dLocal = d.toLocaleDateString("en-us");
var fixLocalDate  = dLocal.replace(/[^ -~]/g,'');

IE 10 output
d = Mon Oct 5 00:00:00 PDT 2015
fixLocalDate = den 5 oktober 2015
IE 11 and Chrome output
d = Mon Oct 05 2015 00:00:00 GMT-0700 (Pacific Daylight Time)
fixLocalDate = 10/5/2015

A: When you are passing a locale like this, you are effectively using Intl.DateTimeFormat ojbect - https://msdn.microsoft.com/en-us/library/dn342822(v=vs.94).aspx
Which is unfortunately not supported in IE10 and below. Usual way of handling this is to use polyfill:
https://github.com/andyearnshaw/Intl.js/


text:
Q: Are there conventions for representing hierarchical components on a schematic? Say I'm designing a device with a lot of repeated elements, like an 8-channel audio mixer. Each channel will have functional units that are identical and repeated, for example, an amplifier.
To keep the top-level schematic readable, my schematic capture software allows schematics to be hierarchical, where the top schematic has symbols which represent subcircuits.
An example:

simulate this circuit – Schematic created using CircuitLab
What conventions are there for visually representing this? Are there conventions to give the reader of a schematic a hint that A1, A2, and A3 are not discrete components or ICs, but a circuit defined on another page?
What conventions exist for naming (for printing on the PCB) the discrete components that compose these sub-circuits? Would it make sense to concatenate the name of the symbol and the components, so in the example above I'd end up with A1R1, A1R2, A2R1, A2R2, ...? Is there a conventional prefix for the names of the symbols, A1-A3 in the example, which hints at their nature? (As C1 suggests a capacitor, etc...)

A: Sadly there is no accepted standard. As with most schematics, whatever works to convey the information best for your group is all that matters.
Each tool is also going to implement hierarchical designs in different ways. Altium for example, allows you to add suffixes to reference designators. One way for you to do it would be to have R1_1, R1_2, R1_3 .. U1_1 U1_2 U1_3.
http://techdocs.altium.com/display/ADOH/Multi-Channel+Design+Concepts
It's a handy feature in theory but sacrifices the ability to set reference designators based on PCB placement which is much handier when you need to change out R1_2 but now have no idea where it is without searching your layout.


text:
Q: Помогите решить небольшую задачу Написать программу, которая спрашивает у пользователя число, после этого выводит строку типа: 2 компьютера. В зависимости от введенного числа, программа должна корректно подставлять окончание для слово компьютер.
!Код должен быть на языке python!

A: правило такое:
3 формы - 1) мячик, 2) мячика, 3) мячиков

*

*если последние 2 цифры числа от 11 до 19 - то используется 3 форма

*если последняя цифра 1 - 1 форма

*если последняя цифра от 2 до 4 - 2 форма

*во всех остальных случаях - 3 форма

Получить нужные числа/цифры можно определением остатка от деления числа на 10 и 100. Для этого используем %
Получить число от пользователя можно через input()
Преобразовать его (ибо введена будет строка) в число - через int()
Ну и дальше вам понадобится if elif else конструкция

A: Смотрите
number = int(input("Введите количество компьютеров:"))
print(f'{number} Компьютеров')


text:
Q: Proxies in the get method of requests module dont seem to work I've googled the syntax for proxies and it should be the same as in my code and there is no other way around but anyways, after using proxies, https://api.ipify.org still returns my own external ip address.
import requests
import random

def get_site():
    http = ['85.26.146.169:80', '85.143.70.165:80', '213.135.118.150:3128']
    proxi = {
        'http': 'http://'+random.choice(http)
    }
    # proxi = {
    #     'http': 'http://85.26.146.169:80'
    # }
    print(requests.get('https://api.ipify.org', proxies=proxi).text)

get_site()

both commented and uncommented variants dont work
P.S. after changing protocol from http to https now it is working but I doubt that every single one from 18 proxies doesnt work and also i can easily ping them. they're free though
import requests
import random

def get_site():
    https = ['188.134.65.80:41890', '77.236.243.69:1256', '31.163.192.161:3129', '37.110.6.178:8080',
             '31.131.67.14:8080', '77.238.129.14:55443', '85.235.184.186:3129', '195.133.71.199:8080',
             '95.189.104.181:41890',
             '78.36.198.158:80',
             '188.246.186.142:41890',
             '95.140.31.39:41890',
             '178.74.103.46:8080',
             '212.46.255.78:8080',
             '195.68.187.222:3128',
             '81.24.95.176:41258',
             '89.22.152.32:53726',
             '84.201.254.47:3128']
    for i in range(len(https)):
        proxi = {
            'https': 'https://' + https[i]
        }
        print(requests.get('https://api.ipify.org', proxies=proxi).text)


text:
Q: How to send a tweet with jTwitter on Android? Has anyone ever successfully sent a tweet via jTwitter on Android?
I am stuck with the Authentification. I can successfully redirect the user to twitter, authorize my app and redirect to my app with new OAuthSignpostClient(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL). Then I store the oauth_token and oauth_verifier which are given with the Callback URL and try to use the OAuthSignpostClient again to update a state:
OAuthSignpostClient client = new OAuthSignpostClient(TwitterOAuthActivity.CONSUMER_KEY, TwitterOAuthActivity.CONSUMER_SECRET, accessToken, accessTokenSecret);

// Ready to go!
Twitter twitter = new Twitter(null, client);
CharSequence date = DateFormat.format("dd.MM.yyyy @ hh:mm:ss", new Date());
twitter.updateStatus("Yay. It works! " + date);

Which ends in a TwitterException without a caused by:
05-11 12:24:32.643: E/AndroidRuntime(25897): winterwell.jtwitter.TwitterException$E401: Could not authenticate with OAuth.
05-11 12:24:32.643: E/AndroidRuntime(25897): http://api.twitter.com/1/statuses/update.json (anonymous)
05-11 12:24:32.643: E/AndroidRuntime(25897):    at winterwell.jtwitter.URLConnectionHttpClient.processError(URLConnectionHttpClient.java:425)
05-11 12:24:32.643: E/AndroidRuntime(25897):    at winterwell.jtwitter.OAuthSignpostClient.post2_connect(OAuthSignpostClient.java:345)

Does anyone has an idea where my Problem is?

A: The verifier from the callback url is a temporary key. It let's you unlock the OAuthSignpostClient object that you have. You can't use it to construct a new OAuthSignpostClient.
You need to call:
client.setAuthorizationCode(verifier);
// The client can now be used!
// To use it again, without the oauth dance, store _these_ tokens:
String[] tokens = client.getAccessToken();

You may also want to check out the new AndroidTwitterLogin class which makes things easy:
AndroidTwitterLogin atl = new AndroidTwitterLogin(myApp,
                MY_TWITTER_KEY,MY_TWITTER_SECRET,MY_TWITTER_CALLBACK) {

    protected void onSuccess(Twitter jtwitter, String[] tokens) {
        jtwitter.setStatus("I can now post to Twitter!");
        // Recommended: store tokens in your app for future use
        // with the constructor OAuthSignpostClient(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret)
    }
};
atl.run();


text:
Q: Extract best match from string-distance matrix I am having trouble extract best match from string-distance matrix.
I am using the package stringdist to compute string-distance matrix.
For example, i am generating my matrix using these lines of code.
library(stringdist)
lookup <- c('Dog', 'Cat', 'Bear')
data <- c('Do g', 'Do gg', 'Caat')
d.matrix <- stringdistmatrix(a = lookup, b = data, useNames="strings",method="cosine")

The matrix looks something like this

My approach is to extract the cosine similarity with lowest number being the best match.
For example, "Do g" would match with "Dog"
What i want to generate is a matching pair data-frame with consine similarity value
data  |  matchwith  |  cosine.s

Do g       Dog         0.1338746
Do gg      Dog         0.1271284
Caat       Cat         0.05719096

I have no clue how to get the data to the table format that i want (above).
Any help would be much appreciated.

A: The which.min function is a good solution for this problem.
This a solution using base R:
library(stringdist)
lookup <- c('Dog', 'Cat', 'Bear')
data <- c('Do g', 'Do gg', 'Caat')
d.matrix <- stringdistmatrix(a = lookup, b = data, useNames="strings",method="cosine")

#list of minimun cosine.s
  cosines<-apply(d.matrix, 2, min)

#return list of the row number of the minimum value
  minlist<-apply(d.matrix, 2, which.min)
#return list of matching values
  matchwith<-lookup[minlist]

#final answer
answer<-data.frame(data, matchwith, cosines)

A: It's a bit of a brute force technique but you can also say
n.matrix <- data.frame(data=dimnames(d.matrix)[[2]],
                       matchwith = dimnames(d.matrix)[[1]],
                       cosine.s = c(d.matrix[1,1], d.matrix[2,2], d.matrix[3,3]))

If there are a large number of columns and rows in the real problem you're working a function can be built to create the string of values for cosine.s = c(d.matrix[i,i])


text:
Q: Setting print size preset in AppleScript I've been using Folder Actions to automate printing photos taken from OS X built-in Photo Booth software. The AppleScript I use is as follows:
on adding folder items to this_folder after receiving added_items
    try
        tell application "Canon iP2700 series"
            activate
            print added_items
            quit
        end tell
    end try
end adding folder items to

Is there anyway I can set the print job to use a preset size using AppleScript or maybe change the defaults so that AppleScript prints uses that size by default?
I've noticed that they use the size at:
System Preferences > Printers & Scanners > Default paper size
But I require the printer to print at 75x105mm which is not in any preset.

A: If I say anything that you already know I apologize.
It all starts with your printer capability.
Does the Canon supports that size?
Open a app like TextEdit and use the "Page Setup".
Now select your printer and select the print size if available. If not available use the Manage Custom Size and add new size (+) and the dimensions.
Example:

Set it up:

Now go to Print (in TextEdit) and select the Printer & Scanner preferences and select default size.

size


text:
Q: SQL Server loop in SProc to generate query I need to build a query that takes a list of integers and concatenates a few SELECTs with INTERSECTs using SQL Server 2008 R2. Here's basically the query I need to build, but the number of SELECTS will vary:
SELECT col1
FROM table1
WHERE col2 = 1

INTERSECT

SELECT col1
FROM table1
WHERE col2 = 2

INTERSECT

SELECT col1
FROM table1
WHERE col2 = 3

I have a table-valued function that will take a comma-separated list of IDs and create a table out of them. But I basically need to loop through that table-valued function to build the SQL statement and then execute it.
How do I go about creating that loop? Or is there possibly a better way to do this (I can do it in code if it would be better)?
EDIT:
To clarify the purpose of using an INTERSECT, here is what I'm doing. The structure I'm using is for associating parent products with child products based on selection of attributes (size, color, etc). For each combination of attributes, there is a single matching child product. So each select is selecting all the child products mapped to an individual attribute value. I then have to find the intersection of each of those to find the one child product that matches that combination of attributes. If there's a better way to do the query, I'm open to it. I know inner joins would be the same result but would still require the same iteration.

A: Assuming temporary table is called #temp:
SELECT col1
  FROM table1 t
       INNER JOIN
       #temp v
       ON (t.col2 = v.col2)
GROUP BY
       col1
HAVING COUNT(*) = (SELECT COUNT(*) FROM #temp)


text:
Q: Entity Framework 6 fails with FOREIGN KEY constraint error when calling stored procedure inside dbcontext transaction I have a stored procedure that inserts into a table of invoice details and takes a json string as parameter in order to avoid a loop for each detail insert.
This is the stored procedure code:
CREATE PROCEDURE [dbo].[usp_Vta_ListInvoiceDetailCreate]
    (@jsonDetailList NVARCHAR(MAX))
AS
BEGIN
    SET NOCOUNT ON;
BEGIN
    DECLARE @NUEVOS_DETALLES TABLE(ID BIGINT) --Tabla Variable

    INSERT INTO CmpFacturasDetalle (FT_Id_Factura, PR_Id_Producto, AL_Id_Almacen,
                                    MD_Id_Medida, FD_Cantidad, FD_Precio_Unitario,
                                    FD_AlicuotaGR, FD_AlicuotaAdicional, FT_DescripcionProAmp,
                                    FD_TotalIVAAplicado, FT_TotalDscto,
                                    FD_TotalItem, FT_PorcentajeDscto,
                                    FD_PartidaArancelaria, FD_SKU,
                                    FD_CantXEmpaque, FD_Peso, FD_Nombre_Producto)
    OUTPUT inserted.FD_Id_FacDetalle INTO @NUEVOS_DETALLES
        SELECT
            FT_Id_Factura, PR_Id_Producto, AL_Id_Almacen,
            MD_Id_Medida, FD_Cantidad, FD_Precio_Unitario,
            FD_AlicuotaGR, FD_AlicuotaAdicional, FT_DescripcionProAmp,
            FD_TotalIVAAplicado, FT_TotalDscto,
            FD_TotalItem, FT_PorcentajeDscto,
            FD_PartidaArancelaria, FD_SKU,
            FD_CantXEmpaque, FD_Peso, FD_Nombre_Producto
        FROM
            OPENJSON (@jsonDetailList)
            WITH (
                    FT_Id_Factura BIGINT '$.FT_Id_Factura',
                    PR_Id_Producto BIGINT '$.PR_Id_Producto',
                    AL_Id_Almacen BIGINT '$.AL_Id_Almacen',
                    MD_Id_Medida BIGINT '$.idFaMD_Id_Medidactura',
                    FD_Cantidad DECIMAL(10,2) '$.FD_Cantidad',
                    FD_Precio_Unitario MONEY '$.FD_Precio_Unitario',
                    FD_AlicuotaGR DECIMAL(4,2) '$.FD_AlicuotaGR',
                    FD_AlicuotaAdicional DECIMAL(4,2) '$.FD_AlicuotaAdicional',
                    FT_DescripcionProAmp VARCHAR(3000) '$.FT_DescripcionProAmp',
                    FD_TotalIVAAplicado DECIMAL(18,4) '$.FD_TotalIVAAplicado',
                    FT_TotalDscto MONEY '$.FT_TotalDscto',
                    FD_TotalItem MONEY '$.FD_TotalItem',
                    FT_PorcentajeDscto MONEY '$.FT_PorcentajeDscto',
                    FD_PartidaArancelaria VARCHAR(50) '$.FD_PartidaArancelaria',
                    FD_SKU VARCHAR(50) '$.FD_SKU',
                    FD_CantXEmpaque DECIMAL(18,2) '$.FD_CantXEmpaque',
                    FD_Peso DECIMAL(18,2) '$.FD_Peso',
                    FD_Nombre_Producto VARCHAR(2500) '$.FD_Nombre_Producto'
                 )

        SELECT ID FROM @NUEVOS_DETALLES;
    END
END

When I add the stored procedure inside Entity Framework and try to call it, I get this error:

The INSERT statement conflicted with the FOREIGN KEY constraint "FK_CmpFacturasDetalle_CmpFacturas". The conflict occurred in database "IERP", table "dbo.CmpFacturas", column 'FT_Id_Factura'.

This is how I call it:
// begin new transaction
db.Database.BeginTransaction();

// OutputParameter for invoiceHeader insert stored procedure
ObjectParameter FT_Id_Factura = new ObjectParameter("FT_Id_Factura", typeof(long));

// insert invoice header
var invoice_add = db.usp_Vta_InvoiceCreate(client.Name, Client.ID, FT_Id_Factura);

// Assign the invoice header ID to each detail
DetailList.ForEach(Det => Det.FT_Id_Factura = (long)FT_Id_Factura.Value);
var jsonList = JsonConvert.SerializeObject(factura.DetailList);

// insert invoice details without loop
var optimizedQuery = db.Database.ExecuteSqlCommand(System.Data.Entity.TransactionalBehavior.EnsureTransaction , @"EXEC [Operativo].[usp_Vta_ListInvoiceDetailCreate] @jsonDetailList = {0};", jsonList);

// commit current transaction
db.Database.CurrentTransaction.Commit();

If I manually set the 'FT_Id_Factura' foreign key to an existing invoice header the code works, but not the same with the row that isn't committed yet.
I'm using Visual Studio 2019 and Entity Framework 6.4.4 code-first in C#.
Thanks


text:
Q: On certificates, what type should E-mail addresses be when in subjectAltName Little bit of background:
I'm building a certificate authority using M2Crypto and Django, so please think twice before voting to close this as off topic! :)
My approach is that end-users are identified by e-mail addresses and their self-signed trust-anchors are issued obviously by themselves, but how should I store their 'identity'?
I've seen many certificates out there in the wild where the practice has been to store mail addresses as subjectAltName = rfc822:user@domain.test, but googling suggest that the standard way would be subjectAltName = email:user@domain.test.
Is there any difference between the two, and if so, which one is preferred?

A:
Is there any difference between the two, and if so, which one is preferred?

Not really; and it depends on the PKI profile you are using. PKI and X509 are the wild, wild, west.
If you are running a Private PKI internal to you organization, it does not matter how you do it. Pick something and do it consistently.

On the web its generally PKIX and specified in RFC 5280, Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile. According to 4.1.2.6, Subject:
Conforming implementations generating new certificates with
electronic mail addresses MUST use the rfc822Name in the subject
alternative name extension (Section 4.2.1.6) to describe such
identities.  Simultaneous inclusion of the emailAddress attribute in
the subject distinguished name to support legacy implementations is
deprecated but permitted.

Then Section 4.2.1.6, Subject Alternative Name:
When the subjectAltName extension contains an Internet mail address,
the address MUST be stored in the rfc822Name.  The format of an
rfc822Name is a "Mailbox" as defined in Section 4.1.2 of [RFC2821].
A Mailbox has the form "Local-part@Domain".  Note that a Mailbox has
no phrase (such as a common name) before it, has no comment (text
surrounded in parentheses) after it, and is not surrounded by "<" and
">".

Notice that it does not use either rfc822:user@domain.test or email:user@domain.test. Like I said, its the wild, wild west. You should be prepared for anything.

You also have the CA/Browser Forums and their standards for issuing certificates. The two documents of interest are:

*

*Baseline Certificate Requirements

*Extended Validation Certificate Requirements
But they defer back to RFC 5280.

The rfc822: and email: you are seeing is probably added by software for presentation. For example, to enumerate the SANs using OpenSSL, your function would look similar to:
void print_san_name(X509* const cert)
{
    int success = 0;
    GENERAL_NAMES* names = NULL;
    unsigned char* utf8 = NULL;

    do
    {
        if(!cert) break; /* failed */

        names = X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0 );
        if(!names) break;

        int i = 0, count = sk_GENERAL_NAME_num(names);
        if(!count) break; /* failed */

        for( i = 0; i < count; ++i )
        {
            GENERAL_NAME* entry = sk_GENERAL_NAME_value(names, i);
            if(!entry) continue;

            if(GEN_DNS == entry->type)
            {
                int len1 = 0, len2 = -1;

                len1 = ASN1_STRING_to_UTF8(&utf8, entry->d.dNSName);
                if(utf8) {
                    len2 = (int)strlen((const char*)utf8);
                }

                if(len1 != len2) {
                    fprintf(stderr, "Strlen and ASN1_STRING size do not match (embedded null?):"
                                    " %d vs %d\n", len2, len1);
                    /* Handle error */
                }

                /* Do something with utf8 */

                if(utf8) {
                    OPENSSL_free(utf8), utf8 = NULL;
                }
            }
            else if(GEN_EMAIL == entry->type)
            {
                ...
            }
            ...
        }

    } while (0);

    if(names)
        GENERAL_NAMES_free(names);

    if(utf8)
        OPENSSL_free(utf8);
}

(Sorry I don't have an example that extracts the IA5Strings handy).
In the above, notice the type: GEN_DNS or general DNS name. That's used for names like www.example.com. OpenSSL has a few of those types, and below is from x509v3.h:
#define GEN_OTHERNAME   0
#define GEN_EMAIL       1
#define GEN_DNS         2
#define GEN_X400        3
#define GEN_DIRNAME     4
#define GEN_EDIPARTY    5
#define GEN_URI         6
#define GEN_IPADD       7
#define GEN_RID         8

Your certificate viewer or presentation software is probably displaying rfc822: or email: because it encountered a type GEN_EMAIL.

When you look at OpenSSL's configuration file, you will see, for example:
...
[ v3_ca ]
subjectKeyIdentifier   = hash
authorityKeyIdentifier = keyid:always,issuer:always
subjectAltName         = email:myEmail@email.com
issuerAltName          = issuer:copy

The email: is not copied verbatim into the SAN. Rather, it tells OpenSSL to use the GEN_EMAIL type for the field.

If your certificate viewer or presentation software is not adding the prefix, then its probably parsing a Distinguished Named.
As for what's in a distinguished name, Peter Gutmann told me a long time ago (taking from his email): "Stick anything you want in the DN and present only the bits that are useful". Like I said, its the wild, wild west.

Email addresses might show up under an OID, too. For example, the 1.2.840.113549.1.9.1 arc. That's in addition to the SAN. Its why the image below has that label "Email Address".

Peter Gutmann has an X509 Style Guide. Taken from his description: it describes various X.509 certificate implementation details and pitfalls, provides recommendations on what to do and what not to do, and finishes with a list of known bugs and problems to look out for in existing implementations.

Finally, here's a user certificate issued by Startcom. They offer free certificates and charge you for revocation if needed (because that's where the cost lies). That's diametrically opposed to other CAs who charge for the revocation up front and pocket it if not needed  ;)
The first is the X509 certificate:

And second is the dump of the certificate using Gutmann's dumpasn1 (get dumpasn1.c and dumpasn1.cfg from www.cs.auckland.ac.nz/~pgut001; compile with gcc dumpasn1.c -o dumpasn1; and copy into /usr/local/bin). Notice there is not rfc822: or email: prefix:


text:
Q: Why doesn't udev automatically map my usb device to the usbhid driver on every system I have 3 systems running Ubuntu 19.10.
I have a USB HID device which can be seen by each of those systems.
I am using the exact udev rules file on all 3 of them:
SUBSYSTEM=="usb",ATTRS{idVendor}=="XXXX",ATTRS{idProduct}=="YYYY",MODE="0660",GROUP="timothy",SYMLINK+="mydevice%n"

KERNEL=="hidraw*", SUBSYSTEM=="hidraw", MODE="0664", GROUP="timothy"

On all 3 sytems the device correctly shows up as /dev/mydevice...
If I run lsusb -t I will get the following on one system:
Port 4: Dev 3, If 1, Class=Human Interface Device, Driver=usbhid, 12M

As you can see the usbhid driver is mapped correctly here,
but on the other systems I get the following:
Port 2: Dev 1, If 1, Class=Human Interface Device, Driver= , 12M

On these systems the driver is not automatically mapped. Because of this
my software cannot see nor use the device.
I can manually assign the driver using
echo -n "4-3:1.0" > /sys/bus/usb/drivers/usbhid/bind

At which point lsbusb -t shows the following:
Port 4: Dev 3, If 1, Class=Human Interface Device, Driver=usbhid, 12M

Now my software can see the device but cannot open it.
I really cannot figure out why the device is correctly mapped on one system
but not on the others. I didn't do anything special to make it work on the
working system, just a clean install like the other two.
The only difference being that the working one is a desktop and the other two are laptops.
Update 2:
I verified that the device only works after it has been logically
disconnected and re-connected to the host. Currently I am doing this
by connecting it to the VMWARE guest and then reconnecting it to the host.
Is there another way to logically reconnect a device (as opposed to physically)
Update 3:
I can also verify this issue does not exist on Raspbian (RaspberryPI)
or Ubuntu 18.04. On those systems, when you connect the device the hidusb driver is always bound to it.
Update 4:
The rules file is located at /etc/udev/rules.d/100.mydevice.rules
and every time I connect one of those devices the dev file is created
under /dev for example /dev/mydevice4
(This part works every time on every system, but does not mean
I can actually use the device)
On Ubuntu 20.04 I seem to have a little more luck.
That is to say if it does work it keeps working until I reboot
the entire machine, and if it does not work it definitely wont
until I reboot the machine.
udevadm info*
root@devtop-home:/home/timothy# udevadm info /dev/mydevice10
P: /devices/pci0000:00/0000:00:14.0/usb3/3-10
N: bus/usb/003/014
L: 0
S: mydevice10
E: DEVPATH=/devices/pci0000:00/0000:00:14.0/usb3/3-10
E: DEVNAME=/dev/bus/usb/003/014
E: DEVTYPE=usb_device
E: DRIVER=usb
E: PRODUCT=483/5750/200
E: TYPE=0/0/0
E: BUSNUM=003
E: DEVNUM=014
E: MAJOR=189
E: MINOR=269
E: SUBSYSTEM=usb
E: USEC_INITIALIZED=1354934046
E: ID_VENDOR=Acme
E: ID_VENDOR_ENC=Acme
E: ID_VENDOR_ID=0483
E: ID_MODEL=mydevice_V2
E: ID_MODEL_ENC=mydevice\x20V2
E: ID_MODEL_ID=5750
E: ID_REVISION=0200
E: ID_SERIAL=Acme_mydevice_V2_3100079BDA31
E: ID_SERIAL_SHORT=3100079BDA31
E: ID_BUS=usb
E: ID_USB_INTERFACES=:030000:
E: ID_VENDOR_FROM_DATABASE=STMicroelectronics
E: ID_MODEL_FROM_DATABASE=LED badge -- mini LED display -- 11x44
E: ID_PATH=pci-0000:00:14.0-usb-0:10
E: ID_PATH_TAG=pci-0000_00_14_0-usb-0_10
E: DEVLINKS=/dev/mydevice10

As you can see this is based on an STM32F4 MCU
When the device is powered on it needs some time before
HID is enabled in the firmware.


text:
Q: Expanded widget must be placed inside Flex widget New to flutter. Here is my code. Can someone tell where am I wrong?
Also, I don't want TextField to be hidden when keyboard appears. Is there any other way to do this other than using KeyboardAvoider?
return Scaffold(
        resizetoavoidbottomInsets: true,
    body: SafeArea(
      child: Stack(
        children: <Widget>[
            Container(height: MediaQuery.of(context).size.height),
          Image.asset('images/otp.jpeg'),
          Positioned(
            top: MediaQuery.of(context).size.height * 0.3,
            child: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height * 0.7,

              child: ListView(
                children: <Widget>[

                Text('Welcome),
                  Spacer(
                    flex: 1,
                  ),
                  Container(
                    width: MediaQuery.of(context).size.width * 0.8,
                    height: MediaQuery.of(context).size.height * 0.07,

                    child: Form(

                      key: _formKey,
                      child: TextFormField(),

                    ),
                  ),
                 Spacer()

                ],
              ),
            )
);

A:
I don't want TextField to be hidden when keyboard appears. Is there
  any other way to do this other than using KeyboardAvoider?

set the resizeToAvoidBottomInsets property on the scaffold to true
as for the title:

Expanded widget must be placed inside Flex widget

you are putting a Flex widget inside a Widget that doesn't extent Flex (for example Column and Row extend Flex, so you should either remove the Expanded or wrap it inside a Widget that extends Flex


text:
Q: How to find $\int_0^{\infty}\frac{dx}{(1+x^2)^4}$ How would you compute for the definite integral of
$$\int_0^{\infty}\frac{dx}{(1+x^2)^4}$$
I know that integral of $\displaystyle \frac1{(1+x^2)}$ equals $\tan^{-1}x$. I tried using integration by parts without much luck.  My teacher pointed me to special functions by which I found out about the hypergeometric distribution. Although I don't know how to apply it to this problem.
Anybody know how to use special functions or how to go about this problem?

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\down}{\downarrow}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
{\cal F}\pars{\mu}&\equiv
\int_0^{\infty}{\dd x \over \mu + x^{2}}
=\mu^{-1/2}\int_0^{\infty}{\dd x \over 1 + x^{2}} = \half\,\pi\mu^{-1/2}
\end{align}
\begin{align}
{\cal F}^{'''}\pars{\mu}&\equiv
-3!\int_0^{\infty}{\dd x \over \pars{\mu + x^{2}}^{4}}
=\half\,\pi\,\totald[3]{\mu^{-1/2}}{\mu}
=\half\,\pi\,\pars{-\,\half}\pars{-\,{3 \over 2}}\pars{-\,{5 \over 2}}\mu^{-7/2}
\end{align}
Set $\mu = 1$ in both members:
$$
\color{#00f}{\large\int_0^{\infty}{\dd x \over \pars{1 + x^{2}}^{4}}}
={15\pi/16 \over 6}= \color{#00f}{\large{5 \over 32}\,\pi}
$$

A: Integration by parts does in fact help.
Let $I_n = \int (1+x^2)^{-n}dx$.
Then multiply by 1 and integrate by parts:
$$I_n = x (1+x^2)^{-n} - \int x \cdot (-n)2x (1+x^2)^{-n-1}dx = \dots = x (1+x^2)^{-n} + 2n(I_n - I_{n+1}).$$
(In the "..." step, write $x^2=(x^2+1)-1$ in the numerator and then divide.)
From this you can solve for $I_{n+1}$ in terms of $I_n$, and since you know $I_1 = \arctan x + C$, you can recursively compute $I_2$, $I_3$, $I_4$, etc.
(This is pretty much the same method that Sivaram pointed you to for finding $\int \cos^6 \theta \, d\theta$.)

A: The method given below works in general for any integral of the form $\displaystyle \int_{0}^{\infty} \frac{dx}{(1+x^2)^n}$.
Plug in $x = \tan(\theta)$. The integral becomes
$$\displaystyle \int_{0}^{\infty} \frac{dx}{(1+x^2)^4} = \int_{0}^{\pi/2} \frac{\sec^2(\theta) d \theta}{(1+\tan^2(\theta))^4} = \int_{0}^{\pi/2} \cos^{6}(\theta) d\theta = \frac{5}{6}\frac{3}{4}\frac{1}{2}\frac{\pi}{2} = \frac{5}{32}\pi$$
where the last integral has been done in a previous post here. The integration over there has been done for $\sin^n(\theta)$ but the same method works for $\cos^n(\theta)$.
If you are familiar with complex analysis, you could solve it using complex analysis by extending the function into the complex domain, choose a semicircular contour with the diameter along the real axis. Look for the poles inside the contour, (there are four poles at $z=+i$) and compute the residues. Let the radius of the semicircle tend to infinity and evaluate the integral using Cauchy residue theorem.

A: Ten years later (with Residue Calculus).
If $\gamma^R=\gamma_1^R\cup \gamma_2^R$ is the contour
$$
\gamma_R^1(t)=t, \,\,\,t\in [-R,R], \quad
\gamma_R^2(t)=R\mathrm{e}^{it}, \,\,\,t\in [0,\pi],
$$
then
$$
\int_{\gamma_R}\frac{dz}{(1+z^2)^n}=2\pi i\,
\mathrm{Res}\bigg(\frac{1}{(1+z^2)^n},z=i\bigg).
$$
But
$$
\bigg|\int_{\gamma_R^2}\frac{dz}{(1+z^2)^n}\,\bigg|=
\bigg|\int_0^\pi\frac{iR\mathrm{e}^{it}dt}{(1+\big(R\mathrm{e}^{it})\big)^n}
\bigg|\le \int_0^\pi \frac{Rdt}{(R^2-1)^n}=\frac{\pi R}{R^2-1)^n}\to 0,
$$
as $R\to\infty$, while
$$
\lim_{R\to\infty}\int_{\gamma_R^1}\frac{dz}{(1+z^2)^n}=\int_{-\infty}^\infty\frac{dx}{(1+x^2)^n}.
$$
Hence $\int_{-\infty}^\infty\frac{dx}{(1+x^2)^n}=2\pi i\,
\mathrm{Res}\bigg(\frac{1}{(1+z^2)^n},z=i\bigg).$
We use the following fact.
Fact. If $f$ has a pole of order $m$ at $z=a$, then
$$
\mathrm{Res}(f,a)=\frac{1}{(m-1)!} \left((z-a)^mf(z)\right)^{(m-1)}_{z=a}
$$
This is straightforward since
$$
f(z)=a_{-m}(z-a)^{-m}+\cdots+a_{-1}(z-a)^{-1}+a_0+a_{1}(z-a)^{1}+\cdots
$$
and hence
$$
(z-a)^mf(z)=a_m+a_{-m+1}(z-a)^{1}\cdots+a_{-1}(z-a)^{m-1}+a_0(z-a)^{m}+\cdots
$$
and thus
$$
\big((z-a)^mf(z)\big)^{(m-1)}=(m-1)!a_{-1}+m!a_0(z-a)^1+\cdots
$$
and finally $\,\,\frac{1}{(m-1)!} \big((z-a)^mf(z)\big)^{(m-1)}_{z=a}=a_{-1}$.
In our case $f(z)=\frac{1}{(1+z^2)^n}$ has a pole of order $n$, and hence
$$
\mathrm{Res}\bigg(\frac{1}{(1+z^2)^n},z=i\bigg)=
\frac{1}{(n-1)!}
\left(
(z-i)^n \frac{1}{(1+z^2)^n}
\right)^{(n-1)}_{z=i}=\frac{1}{(n-1)!}
\left(\frac{1}{(z+i)^n}
\right)^{(n-1)}_{z=i} \\
=\frac{1}{(n-1)!}\cdot (-1)^{n-1}\cdot n\cdot(n+1)\cdots(2n-2)\cdot
\left(\frac{1}{(z+i)^{2n-1}}\right)_{z=i}\\
=(-1)^{n-1}\binom{2n-2}{n-1}\cdot\frac{1}{(2i)^{2n-1}}=\frac{-i}{2^{2n-1}}\binom{2n-2}{n-1}
$$
Finally
$$
\int_{-\infty}^\infty\frac{dx}{(1+x^2)^n}=2\pi i\,
\mathrm{Res}\bigg(\frac{1}{(1+z^2)^n},z=i\bigg)=2\pi i\,\frac{-i}{2^{2n-1}}\binom{2n-2}{n-1}=\frac{\pi}{2^{2n-2}}\binom{2n-2}{n-1}.
$$


text:
Q: Attribute reference in Python I have some doubts regarding attribute reference in Python. I used to think attribute reference as in instance.attribute is bottom-up approach.
First that attribute is looked up in instance dictionary. But I was reading some article where it claims that attribute lookup is top-down approach i.e. when an attribute is referenced, Class.__getattribute__ is called as first step. Here instance is the instance of class Class
My question is (considering class may contain a data descriptor or non data descriptor)

*

*Is attribute reference a bottom-up or top down

*Looks like both will give similar results. Am I correct here?

A:
Is attribute reference a bottom-up or top down

I wouldn't classify it as bottom-up or top-down. Pythons __getattribute__ first searches in the class dictionary in order to first find data descriptors if they exist, it then also searches the instance dictionary for instance variables (if no data descriptors have been found).

Looks like both will give similar results

No, if it was strictly bottom-up (instance first) then an instance variable with the same name as a data descriptor would mask it.
If it was top-down then a non-data descriptor with the same name as an instance variable would mask it.


text:
Q: Python - 'float' object not subscriptable (GEOJSON file) I am trying to extract the index of a pair of coordinates within a GeoJSON file.
Code:
coords = []
for school in data_set['features']:
  points = school['geometry']['coordinates']
 p1 = [point[0] for point in points]
coords.append(points)
print(coords)

Error message:

p1 = [point[0] for point in points]TypeError: 'float' object is not subscriptable.

When I run the code without defining p1 & p2 I receive the coordinates as floating points that are a nested list within a list. What do I have to do to make the object subscriptable? Also, what does subscriptable mean?
Thank you

A: strings are subscriptable, integers are not. Please use str() function
newStringForSubscriptable=str(point)

A: Generally, subscriptable means that you can use p1[index] to access something within p1 at index. The error tells you that point[0] is trying to access a float like that - which does not work.
The reason you're getting a nested list of floats is visible in this example that I ran in the python shell: append inserts the whole list, not each item individually.
>>> a = []
>>> b = [1,2,3]
>>> a.append(b)
>>> a
[[1, 2, 3]]

Instead, you probably wanted to use extend, which adds a list's element to the list.
>>> c = []
>>> c.extend(b)
>>> c
[1, 2, 3]

This means that your points is actually a non-nested list. And you could get the first point with points[0]


text:
Q: 404 page not working on Nextjs Static Generated File Im having trouble to show 404 custom page i made when i generate static generated file (next build && next export)
When im navigating to non existing page ("/<any-non-existing"), it always redirects to homepage ("/"). My expectation is that it will automatically redirect to ("/404").
However, if im manually navigating to ("/404") page, the page works perfectly fine.
Deployed to S3 with Cloudfront
Enabled next.config.js { trailingSlash: true }


text:
Q: recently made blogsite i need guidance with user permissions (DJANGO PYTHON MYSQL) i made a blog site sometime ago with python and django and used mysql as a database
the viewers can see all written blogs and comments ,but to write blogs and comments viewers have to login or signup ...thats all good but the problem is that when i want to edit or delete a blog or comment , any logged-in user can edit or delete  any comment or blog , i want to implement user permissions so that only the user who wrote the blog /comment can edit /delete it ,not every one
my views
        from django.shortcuts import render,redirect
        from django.contrib.auth.models import User,auth
        from django.contrib import messages
        from app.models import signup,blog
from app.forms import CommentForm,Blogform
# Create your views here.
def signup1(request):
    if request.method == "POST":
        Realname = request.POST['realname']
        Username = request.POST['username']
        sEmail = request.POST['semail']
        sPassword = request.POST['spassword']

        if User.objects.filter(username=Username).exists():
            messages.info(request, "user exists")
            return redirect("/")
        else:
            user = User.objects.create_user(username=Username, email=sEmail, password=sPassword, first_name=Realname)
            user.save()
            auth.login(request, user)
            print("user made")
            return redirect("/")

    else:
        form1 = signup.objects.all()
        return render(request, 'Signup.html', {'signup': form1})

def login(request):
    if request.method == "POST":
        username =request.POST['lgusername']
        password =request.POST['lgpassword']
        user =auth.authenticate(username=username,password=password)

        if user is not None:
            auth.login(request,user)
            return redirect("/")
        else:
            messages.info(request,"invalid username or password")
            return redirect("/login")
    else:
        return render(request,"login.html")

def logout(request):
    auth.logout(request)
    return redirect("/")

def blog1(request):
    blogs= blog.objects.all()
    return render(request,'blog.html',{'blogs':blogs})
def blogdetail(request ,slug):
    post =blog.objects.get(slug=slug)

    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()

            return redirect('post_detail', slug=post.slug)
    else:
        form = CommentForm()

    return render(request,'blog_detail.html',{'post':post ,'form': form})

def writeblog(request):
    if request.method == "POST":
        form=Blogform(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/')
            except:
                pass
    else:
        form=Blogform()
        return render(request,"write.html",{'form':form})

def edit(request,slug):
    edit =blog.objects.get(slug=slug)
    return render(request,"edit.html",{'edit':edit})

def update(request,slug):
    edit = blog.objects.get(slug=slug)
    form = Blogform(request.POST, instance=edit)
    if form.is_valid():
        form.save()
        return redirect("/")
    return render(request, 'update.html', {"edit" :edit})

def delete(request,slug):
    delete= blog.objects.get(slug=slug)
    delete.delete()
    return redirect('/')

////this is my template
 {% extends "base.html" %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>blog</title>

{%block content%}

        {% for blogs in blogs %}

{{blogs.title}}

            posted at {{blogs.date_added}}

{{blogs.intro}}

            Read more

        {% endfor %}

  Link with href

 Hello This is my offcanvas

        <button type="button" class="btn-close" aria-label="sidebar-lable" data-bs-dismiss="offcanvas" ></button>

            this is the body of the offcanvas that i made just five minutes ago .
            hello again
            bye .

        <form class="form-group ">
        Type your name
        <input placeholder="your name" class="form-control" type="text">

        <input type="submit" class="btn  btn-outline-success">
        </form>

{%endblock%}

my urls
   from django.urls import path
from  . import views
urlpatterns=[
    path('signup',views.signup1,name="signup"),
    path('login',views.login,name="login"),
    path('logout',views.logout,name="logout"),
    path('',views.blog1,name="blog"),
    path('write',views.writeblog,name='write')
]

my models
from django.db import models

# Create your models here.

class signup(models.Model):
    Realname = models.CharField(max_length=100)
    Username = models.CharField(max_length=100)
    sEmail = models.EmailField(max_length=150)
    sPassword = models.CharField(max_length=250)
    class Meta:
        db_table ="Signupusers"
    def __str__(self):
        return self.Realname

class blog(models.Model):
    title =models.CharField(max_length=250)
    slug =models.SlugField()
    intro =models.TextField()
    body= models.TextField()
    writer=models.TextField()
    date_added=models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table="blog1"
        ordering =['-date_added']
    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(blog, related_name='comments', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    email = models.EmailField()
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table="comments"
        ordering = ['date_added']


text:
Q: change TextBox readonly by clicking on ListBoxItem I have a TextBox inside a ListBoxItem which is disabled so I can drag and drop it in the ListBox.
Once I double click it I want it to be Enabled so I can edit the Text and when I'm done I want it do be Disabled again to do drag and drop.
I have the MouseDoubleClick event on the ListBoxItem but it doesn't change the TextBox ReadOnly. Can anybody tell me how to achieve this.
at the moment TextBox returns null. seems like I don't get access to it the way I'm trying.
XAML
<ListBox Name="Locations"  Cursor="Hand" HorizontalAlignment="Left" Height="351" Margin="10,48,0,0" VerticalAlignment="Top" Width="285" ItemsSource="{Binding Locations}" dd:DragDrop.IsDragSource="True"
     dd:DragDrop.IsDropTarget="True" SelectedItem="{Binding SelectedItem}">

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
            </Style>
        </ListBox.ItemContainerStyle>

        <ListBox.ItemTemplate>
                <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBox Name="textBox" Text="{Binding Path=Name}"  IsHitTestVisible="False" Width="270" Background="Transparent" BorderThickness="0" Margin="2"/>
                </StackPanel>
                </DataTemplate>
       </ListBox.ItemTemplate>
</ListBox>

In View
private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
     ListBoxItem item = sender as ListBoxItem;
     textBox.IsReadOnly = false;
}

A: That's because the textbox "doesn't exists" in the visual tree, WPF creates one for each listitem when needed, so you never have a reference to it. It is possible to navigate the visual tree and get the textbox reference but I advise against it, instead, create a property in your item model, something like "EditMode" that when you set it to true, the textbox will enable through the binding of the IsEnabled property.


text:
Q: C++: Converting Julian dates to Gregorian I need to write a function that converts a Julian dates (Year, Day of Year, Hour of Day and Minutes) into a standard form (Year, Month, Day of Month, Hour of Day and Minutes) and express it as a string.  I figure there's got to be someone who's already written a library or component which can do the conversion from Day Of Year to Month and Day of Month.  I've looked at several well-known datetime libraries:

*

*ctime - Specifically using a tm struct and mktime(tm *timeptr) as this generally sets the values of the tm struct to the appropriate places except that "The original values of the members tm_wday and tm_yday  of timeptr are ignored..." which doesn't help.

*Boost::DateTime - Gregorian is constructed date(greg_year, greg_month, greg_day) which doesn't help.  However, they do have a date_from_tm(tm datetm) but "The fields: tm_wday , tm_yday , tm_hour, tm_min, tm_sec, and tm_isdst  are ignored."  Again, no help.

*COleDateTime - This project contains COM so why not? The COleDateTime constructor COleDateTime( int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec ) doesn't help.  And I don't see any other conversion functions to go with it.

As you can see, these all need Month and Day of Month which is exactly what I'm trying to avoid in the first place.  I must be either missing something or haven't looked in the right places (not perfect, as much as I try.)
Anyone can help?  I'd prefer to avoid writing my own as there's almost always bound to be some gotcha I miss.

A: I stumbled across this old question, and thought I might be able to add some new information to it.  The single existing answer as I write this by Thomas Pornin is a good answer, and I've upvoted it.  However I've taken it as a challenge to better it.  What if we could produce the same answer twice as fast?  Maybe even faster?
To test this effort, I've wrapped Thomas' answer up in a function:
#include <tuple>

std::tuple<int, int, int>
ymd_from_ydoy1(int year, int day_of_year)
{
    static const int month_len[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    int leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
    int day_of_month = day_of_year;
    int month;
    for (month = 0; month < 12; month ++) {
        int mlen = month_len[month];
        if (leap && month == 1)
            mlen ++;
        if (day_of_month <= mlen)
            break;
        day_of_month -= mlen;
    }
    return {year, month, day_of_month};
}

And my attempt to better it is based off of:

chrono-compatible Low-Level Date Algorithms

The above article does not address this situation directly.  However it does go into detailed descriptions of the algorithms involved with date manipulations, and even includes a "day of year" concept, though that concept is different than what is specified in this question:
In this question "day of year" is a 1-based count with Jan 01 being the start of the year (Jan 1 == day 1).  chrono-compatible Low-Level Date Algorithms has a similar "day of year" concept in the algorithm civil_from_days but it is days past Mar 01 (Mar 1 == day 0).
My thought is that I could pick bits and pieces from civil_from_days and create a new ymd_from_ydoy which did not need to iterate over the 12 months to find the desired result.  Here is what I came up with:
std::tuple<int, int, int>
ymd_from_ydoy2(int year, int day_of_year)
{
    int leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
    if (day_of_year < 60 + leap)
        return {year, day_of_year/32, day_of_year - (day_of_year/32)*31};
    day_of_year -= 60 + leap;
    int mp = (5*day_of_year + 2)/153;
    int day_of_month = day_of_year - (153*mp+2)/5 + 1;
    return {year, mp + 2, day_of_month};
}

There are still branches, but fewer of them.  To test both the correctness and performance of this alternative I wrote the following:
#include <iostream>
#include <chrono>
#include <cassert>

template <class Int>
constexpr
bool
is_leap(Int y) noexcept
{
    return  y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}

constexpr
unsigned
last_day_of_month_common_year(unsigned m) noexcept
{
    constexpr unsigned char a[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    return a[m-1];
}

template <class Int>
constexpr
unsigned
last_day_of_month(Int y, unsigned m) noexcept
{
    return m != 2 || !is_leap(y) ? last_day_of_month_common_year(m) : 29u;
}
int
main()
{
    using namespace std;
    using namespace std::chrono;
    typedef duration<long long, pico> picoseconds;
    picoseconds ps1{0};
    picoseconds ps2{0};
    int count = 0;
    const int ymax = 1000000;
    for (int y = -ymax; y <= ymax; ++y)
    {
        bool leap = is_leap(y);
        for (int doy = 1; doy <= 365 + leap; ++doy, ++count)
        {
            auto d1 = ymd_from_ydoy1(y, doy);
            auto d2 = ymd_from_ydoy2(y, doy);
            assert(d1 == d2);
        }
    }
    auto t0 = high_resolution_clock::now();
    for (int y = -ymax; y <= ymax; ++y)
    {
        bool leap = is_leap(y);
        for (int doy = 1; doy <= 365 + leap; ++doy)
        {
            auto d1 = ymd_from_ydoy1(y, doy);
            auto d2 = ymd_from_ydoy1(y, doy);
            assert(d1 == d2);
        }
    }
    auto t1 = high_resolution_clock::now();
    for (int y = -ymax; y <= ymax; ++y)
    {
        bool leap = is_leap(y);
        for (int doy = 1; doy <= 365 + leap; ++doy)
        {
            auto d1 = ymd_from_ydoy2(y, doy);
            auto d2 = ymd_from_ydoy2(y, doy);
            assert(d1 == d2);
        }
    }
    auto t2 = high_resolution_clock::now();
    ps1 = picoseconds(t1-t0)/(count*2);
    ps2 = picoseconds(t2-t1)/(count*2);
    cout << ps1.count() << "ps\n";
    cout << ps2.count() << "ps\n";
}

There are three loops in this test:

*

*Test that the two algorithms produce the same results over a range of +/- a million years.

*Time the first algorithm.

*Time the second algorithm.

It turns out that both algorithms are wicked fast ... a handful of nanoseconds on the iMac Core i5 I'm testing on.  And thus the introduction of picoseconds to get a first-order estimate of fractional nanoseconds.
    typedef duration<long long, pico> picoseconds;

I'd like to point out two things:

*

*How cool is it that we are starting to use picoseconds as a unit of measurement?

*How cool is it that std::chrono makes it so easy to interoperate with picoseconds?

For me this test prints out (approximately):
8660ps
2631ps

Indicating that ymd_from_ydoy2 is approximately 3.3 times faster than ymd_from_ydoy1.
Hope this helps.  Important things to get from this answer:

*

*chrono-compatible Low-Level Date Algorithms has useful and efficient algorithms for date manipulation.  They can be useful even if you have to pick the algorithms apart and reassemble them, as in this example.  The explanations of the algorithms are there to enable you to pick them apart and reapply them in examples such as this.

*<chrono> can be very flexible in measuring very fast functions.  Three times faster than very fast is still a good win.

A: It seems easy to compute the month and day of month from the day of year. This should do it:
static const int month_len[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

int leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
int day_of_month = day_of_year;
int month;
for (month = 0; month < 12; month ++) {
    int mlen = month_len[month];
    if (leap && month == 1)
        mlen ++;
    if (day_of_month <= mlen)
        break;
    day_of_month -= mlen;
}

Note that this computes the month starting with zero for January, but assumes that day counts (either day of year or day of month) start at one. If the day of year count is invalid (beyond the end of the year) then the resulting month value is 12 (the "month after December").
"Julian" is a source of confusion, since it also stands for the "Julian calendar" which differs from the Gregorian calendar by a few dozen days, and the computation of leap years. Here I just assumed that you just wanted to convert a "day of year" count into a "month and day of month" within the context of a given, Gregorian year.


text:
Q: Spam Registrations Since the past 3 days, I am seeing that every day a new user registers to my WordPress site. The default role is admin and it's very concerning. Their email ids are workspace@kleverandeverbever.top and kennylittleboy@airmail.cc.
I have started using Wordfence and disabled Anyone Can Register in Settings > General.
Can you suggest me what additional shall I do?
Right now, I am manually deleting registrations.

A: I suspect that there is malware files on your system that is allowing those user registrations. There are lots of googles/bings/ducks on how to clean a hacked system. (I use my own procedure here.)
What I would do is these things:

*

*change all credentials everywhere (hosting, FTP, admin etc)

*create a new admin user with a very secure password, log in as it (to verify it works), then demote the current admin user(s) to lowest level. Especially if your admin user is called 'admin'.

*disable xmlrpc.prg on your site (that can be a hack intrusion point)

*reinstall WP (use the Update on the dashboard).

*reinstall all theme from good sources via FTP. Do the same for all plugins

*Manually look at all files in all folders on your site for 'bad' files. Sorting by date helps, since you updated everything - all updated files should have the same datestamp, so unwanted files will stick out. Don't forget to look at all hidden files, including htaccess.

*look at generated source code of pages to ensure nothing funky in there

The site can be cleaned (I've done it, which is how I developed my procedure). But IMHO there is a strong possibility of malware code on your site allowing those registrations.


text:
Q: Modify all links in html to keep hashtag only In html file I have links like
.
How do I modify them all so after the process it becomes
.
Basically, I need to keep hashtag only.

A: Regex:
(]*>)

Replacement string:
\1\2

DEMO
Example:
<?php
$mystring = "The input string foo  bar";
echo preg_replace('~(]*>)~', '\1\2', $mystring);
?>

Output:
The input string foo  bar

Explanation:

*

*(<a href=") The string ]*>) Again the following characters upto the next > symbol are captured by group 2.

*In the replacement part, we are replacing the matched characters with the characters inside the captured groups.

A:  (.*?")(?:.*?)(#.*)

See demo .
http://regex101.com/r/yM7jY2/1

A: You can use ob_start to capture the output and preg_replace to change the href attribute:
<?php

ob_start(); // Capture the output

?>

Link 1
Link 2
Link 3
Link 4

<?php

$output = ob_get_contents(); // Get the output
ob_end_clean(); // Finish capture

// Remove the letters in href attribute before the hash # maintaining the others attributes
echo preg_replace('//','', $output);

?>

See the regexp: http://regexr.com/39bmb.
See how works the example: SandBox example.


text:
Q: Capybara screenshot_and_open_image save whole page I have issue with screenshot_and_open_image from gem capybara-screenshot
i have large page witch need to be scrolled till the end
i have tried to set resolution for screenshot,doesn't help
How to save whole page not only visible part?


text:
Q: What is the value of $p$-adic $\zeta$-function at positive integer point? $p$-adic zeta function is a $p$-adic interpolation of the Riemann $\zeta$-function for the values $\zeta(1−k)$, $k\ge 1$ (see $p$-adic Numbers, $p$-adic Analysis, and Zeta-Functions by Neal Koblitz) or, more precisely, it's corrected values
$$\zeta_p(1−k):=-(1-p^{k-1})\frac{B_k}{k}.$$
What is known about the values $\zeta_p(k)$ for $k\ge 1$?

A: Let me mention some irrationality results about p-adic zeta values:
In 2005, Frank Calegari arxiv link proved that for $p=2,3$, the p-adic zeta values $\zeta_p(3)$ is irrational (hence nonzero). It can be viewed as the p-adic analogue of Apéry's theorem. Later, Frits Beukers arxiv link gave an alternating proof of Calegari's results (and the irrationality for some other p-adic L-values).
In 2010, Pierre Bel arxiv link obtained some partial results on the irrationality of p-adic Hurwitz zeta values. See also his 2018 paper on $\zeta_p(4,x)$.
Very recently (in 2020), Johannes Sprang arxiv link showed that
$$ \dim_{K}(K+\zeta_p(2)K+\zeta_p(3)K+\cdots+\zeta_p(s)K) \geqslant \frac{(1-o(1))\log s}{2[K:\mathbb{Q}](1+\log 2)}, $$
which is the analogue of Ball-Rivoal theorem for p-adic zeta values.

A: If you use this definition, then $\zeta_p(k)$ is zero at negative even integers $k$, so by a $p$-adic continuity argument, it must also be zero at positive even integers.
What about the odd integers? At $k = 1$ there is a pole, unsurprisingly. At odd $k \ge 3$ the value is extremely mysterious, just as the complex zeta values $\zeta(k)$ are. There is an interpretation of the odd $p$-adic zeta values in terms of a $p$-adic regulator map in $K$-theory (see this question), but this is tough to get explicit information out of.
As an example of how little we understand these numbers, I believe it's an open problem whether the values $\zeta_p(k)$ for odd $k \ge 3$ are always non-zero, although this is certainly expected.

A: I agree nothing much is known, but there are a number of formulas linked to
the values at positive integers of p-adic L-functions: see Section 11.3
of my GTM 240 book (sorry for the self-advertisement).


text:
Q: Find and modify a pattern within the start and end patterns and update file I want to find and modify a pattern within the start and end pattern to update multiple files.
I am breaking down the steps if this can achieved with awk / sed.

*

*Find an occurrence of a string within a 'startpat' and 'endpat' (capture the lines between start and end)

*Modify the strings in the instance, for instance:
update 'sss: ccc' to 'sss: ddd'
update 'brr: mmm' to 'brr: rel/ccc'

*Now create a new set of lines from 'startpat' to 'endpat' with the update strings from step 2.

*Append to the start of the file after '---'.

*Delete the last occurrence set of lines from 'startpat' and 'endpat' if it matches the string 'sss: aaa' and 'brr: rel/aaa'

Note: most importantly would like preserve the indents since I am working with json/yaml files.
Input file format (PS ignore comments lines // while parsing the file):
---
 - startpat:        // Startpat - make this line inclusive
    ...
    sss: ccc        // pattern to be modified
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'      // pattern to be modified
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
    ...

 - startpat:        // Endpat - make this line exclusive

expected output after processing:
---
 - startpat:
    sss: ddd
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'

 - startpat:        // Startpat
    ....
    sss: ccc
    ppp: 'vvv'
    pname: 'vvv'
    brr: 'mmm'
    jdk: jdk8
    jdks:
      - jdk8
      - jdk7
    file:
      - test:
          exec: 'input'
    ...

 - startpat:        // Endpat

A: I think the simplest way is to save every line in an array. To get you started:
$ cat f.awk
BEGIN {
    # build regualr expressions to match "start pattern" and
    # "end pattern" (in the question they are the same)

    ws = "[\\t ]*"            # white-spaces
    sp = "^" ws "- startpat:" # [s]tart [p]attern
    ep = sp                   # [e]nd   [p]attern

    # a regular expression to match "---"
    # possibly suraunded by white-spaces
    op = "^" ws "---" ws "$" # where to start appending
}

{ f[NR] = $0 } # save every line to an array

END {
    n = NR # number of line in the file

    find_blocks() # set `nb` (number of blocks), `ss` `ee`

    for (ib = 1; ib <= nb; ib++)
        process_block(ss[ib], ee[ib]) # pass start and end of each block
                                      # set `nex' (number of extra lines) and `eex'
    write()
}

function find_blocks(   i, l, is, ie) {
    for (i = 1; i <= n; i++) {
        l = f[i]
        if (is > ie && l ~ ep) ee[++ie] = i # end
        if (           l ~ sp) ss[++is] = i # start
    }
    nb = ie
}

function process_block(is, ie,   i, l) {
    for (i = is + 1; i <= ie - 1; i++) {
        l = f[i]
        # modify a line (an example)
        if (l ~ /brr:/) sub(/'mmm'/, "'rel/cc'", l)

        eex[++nex] = l # push the line to another array
    }
}

function write(   i, j, l) {
    i = 1
    while (i <= n) { # print everything before "---"
        print l = f[i++]
        if (l ~ op) break
    }

    for (j = 1; j <= nex; j++) # add an extra part
        print eex[j]

    while (i <= n)            # print the part after "---"
        print f[i++]
}

Input file
$ cat input
---
 - startpat:
    XXXXX
    brr: 'mmm'
 - startpat:
    YYYYY
    brr: 'mmm'
 - startpat:

Usage:
awk -f f.awk input

Output:
---
    XXXXX
    brr: 'rel/cc'
    YYYYY
    brr: 'rel/cc'
 - startpat:
    XXXXX
    brr: 'mmm'
 - startpat:
    YYYYY
    brr: 'mmm'
 - startpat:


text:
Q: Reading Xml from an absolute path I need to access a remote Xml document from a WCF service.  Right now I have:
XmlReader reader = XmlReader.Create("path");

But since the Xml doc is elsewhere on our network I need to give the XmlReader an absolute path, as opposed to having it look deeper in the project folder.  How do I do this?  I've found surprisingly little information about this.  It seems like this should be a simple thing to do.  Any help is appreciated!
Thanks

A: You can use overload that accepts Stream parameters as follows:
using (FileStream fileStream = new FileStream(@"\\computername\shared path"))
using (XmlReader reader = XmlReader.Create(fileStream))
{
    // perform your custom code with XmlReader
}

Please note that you need appropriate permission to open remote stream. In WCF service context you may need to use impersonation.


text:
Q: jacoco simple integration test solution I am following the standard Maven pattern where I use a separate module for integration tests. This module has a wrapper class that executes the major dependent jar project.
While the jar project has its own test cases, I am not interested in executing these. I want to see code coverage in the jar project when executed by the integration tests. Simple, no report aggregation.

A: Let me quote http://www.jacoco.org/jacoco/trunk/doc/report-aggregate-mojo.html even if its name contains a kind of "aggregation":

This also allows to create coverage reports when tests are in separate projects than the code under test, for example in case of integration tests.

Let's try. Given jar/src/main/java/example/Example.java:
package example;
public class Example {
  // to be covered by unit test
  public void a() {
    System.out.println("a");
  }

  // to be covered by integration test
  public void b() {
    System.out.println("b");
  }
}

unit test jar/src/test/java/example/ExampleTest.java:
package example;
public class ExampleTest {
  @org.junit.Test
  public void test() {
    new Example().a();
  }
}

integration test it/src/test/java/example/ExampleITTest.java:
package example;
public class ExampleITTest {
  @org.junit.Test
  public void test() {
    new Example().b();
  }
}

pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>example</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <modules>
    <module>jar</module>
    <module>it</module>
  </modules>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <version>0.7.8</version>
        <executions>
          <execution>
            <goals>
              <goal>prepare-agent</goal>
              <goal>report</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

</project>

jar/pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.example</groupId>
    <artifactId>example</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>jar</artifactId>

</project>

and finally most important part it/pom.xml where happens all the magic:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.example</groupId>
    <artifactId>example</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>it</artifactId>

  <dependencies>
    <dependency>
      <groupId>org.example</groupId>
      <artifactId>jar</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.jacoco</groupId>
        <artifactId>jacoco-maven-plugin</artifactId>
        <executions>
          <!--
          "report" goal can't cross boundaries of modules,
          while "report-aggregate" can, so let's use it, however
          by default it will load "jacoco.exec" from this module and from module "jar",
          so let's also change file name for this module to avoid intersection
          -->
          <execution>
            <configuration>
              <destFile>${project.build.directory}/jacoco-it.exec</destFile>
            </configuration>
          </execution>
          <execution>
            <id>it-report</id>
            <phase>verify</phase>
            <goals>
              <goal>report-aggregate</goal>
            </goals>
            <configuration>
              <dataFileIncludes>**/jacoco-it.exec</dataFileIncludes>
              <outputDirectory>${project.reporting.outputDirectory}/jacoco</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

In such setup mvn clean verify will generate two reports - jar/target/site/jacoco showing that method a() is covered, and it/target/site/jacoco showing that method b() is covered.

A: I have attached a Java agent to the application server's standalone.sh (startup script) by adding the line below:
JAVA_OPTS="$JAVA_OPTS -javaagent:/home/jboss/.m2/repository/org/jacoco/org.jacoco.agent/0.7.6.201602180812/org.jacoco.agent-0.7.6.201602180812 -runtime.jar=destfile=/var/lib/jenkins/workspace/HDAP_JaCoCo/jacocoSoapui.exec,includes=*,append=false,output=file"

I have specified the destination file to be located in the workspace of my Jenkins job which runs JaCoco code coverage for unit tests (in order to get the classes to compare my coverage with).
Then I have specified the path of the two exec files (one from the unit tests, and the one that I have created for integration tests in the record coverage report section of the Jenkins job mentioned above). Then we have the coverage for all tests now.
Note:

*

*The app server needs to be stopped to dump the coverage onto the exec file. Let me know if you have any more questions.

*When you want to get coverage for specific set of tests, make sure that nothing else is running because this will give you coverage for basically any calls being made in to the application.


text:
Q: How to loop through an array of objects and filter out the items that are in the same hour I am having trouble with what I am sure is a simple loop and filter process.
I want to loop through this array and return only the objects that are in the same hour i.e. 8am - 9am or 10am - 11am not 8:30am to 9:30am so that means all the 8ams and 10 ams would be returned in this example.
I have an array of objects like so
let arr = [{
     "action": "Coffee with client",
     "time": "1/12/2018 08:30:15"},
    {"action": "Check Email",
     "time": "1/12/2018 08:32:37"},
    {"action": "Order Breakfast Sandwich",
     "time": "1/12/2018 08:45:43"},
    {"action": "Walk Back To Office",
     "time": "1/12/2018 09:15:58"},
    {"action": "Attend Morning Meeting",
     "time": "1/12/2018 10:15:00"},
    {"action": "Add Meeting Notes To Calendar",
     "time": "1/12/2018 10:45:37"}]

I'm struggling with how to group these date time strings. I have tried converting them and doing something like this where what I want to do is convert the string to a date (number) and compare each item in the array to see if its in the same hour and if it is return those items. I'm lost right now and any help would be appreciated.
const hour = 1000 * 60 * 60;

for(let i = 0; i < arr.length-1; i++) {
   const difference = Date.parse(arr[i+1].time) -
   Date.parse(arr[i].time)

   if(difference < hour) {
      //return all items in the same hour

   }
 }

A: If I understand correctly, you can get the hour from the date and make an object keyed to hour where each value is an array of items.

let arr = [{"action": "Coffee with client", "time": "1/12/2018 08:30:15"},{"action": "Check Email", "time": "1/12/2018 08:32:37"},{"action": "Order Breakfast Sandwich", "time": "1/12/2018 08:45:43"},{"action": "Walk Back To Office", "time": "1/12/2018 09:15:58"},{"action": "Attend Morning Meeting", "time": "1/12/2018 10:15:00"}, {"action": "Add Meeting Notes To Calendar", "time": "1/12/2018 10:45:37"}]

let grouped = arr.reduce((obj, item) => {
  let hour = new Date(item.time).getHours()  // the key for the object
  if (!obj[hour]) obj[hour] = []             // new array if it doesn't exist
  obj[hour].push(item)                       // add item to correct group
  return obj
}, {})

console.log(grouped)

All the 8 appoints will be grouped with grouped[8], etc.
It's not clear if you will have appointments from more that one date and what should happen with those.


text:
Q: how to pack a hosted webapp by cordova I want to pack my webapp by using cordova.
My webapp follows SPA pattern.
So, is there any good solution to pack my webapp to native app refer to my website remote url.
and invoke like this <script type="text/script" src="cordova.js"></script>
then I can use Cordova API


text:
Q: R summarize ignores group by and drops column I am having some problems with summarizing a table that I have grouped by Date. Here is the data:
df <- structure(list(Gerät = c("=Soll_149", "=Soll_149", "=Soll_149",
"=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149",
"=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149",
"=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149",
"=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149",
"=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149", "=Soll_149",
"=Soll_149", "=Soll_149"), Datum = structure(c(18324, 18324,
18324, 18324, 18324, 18324, 18324, 18324, 18324, 18324, 18324,
18324, 18324, 18324, 18325, 18325, 18325, 18325, 18325, 18325,
18325, 18325, 18325, 18325, 18325, 18325, 18325, 18325, 18325,
18325), class = "Date"), Uhrzeit = c("10:00:00", "11:00:00",
"12:00:00", "13:00:00", "14:00:00", "15:00:00", "16:00:00", "17:00:00",
"18:00:00", "19:00:00", "20:00:00", "21:00:00", "22:00:00", "23:00:00",
"0:00:00", "1:00:00", "2:00:00", "3:00:00", "4:00:00", "5:00:00",
"6:00:00", "7:00:00", "8:00:00", "9:00:00", "10:00:00", "11:00:00",
"12:00:00", "13:00:00", "14:00:00", "15:00:00"), Tiefe = c("1.28",
"1.28", "1.28", "1.28", "1.28", "1.28", "1.28", "1.28", "1.28",
"1.28", "1.28", "1.28", "1.28", "1.28", "1.28", "1.28", "1.28",
"1.28", "1.28", "1.28", "1.28", "1.28", "1.28", "1.28", "1.28",
"1.28", "1.28", "1.28", "1.28", "1.28"), Temperatur = c("3.9",
"4.5", "5.3", "6.3", "6.4", "7", "6.5", "6", "5.6", "5.3", "4.9",
"4.5", "4.1", "4", "3.7", "3.3", "3", "2.6", "2.3", "2", "1.8",
"1.6", "1.8", "2.7", "4.4", "5.1", "6", "7.2", "8.1", "7.8"),
    Spannung = c("8.63", "8.6", "8.58", "8.57", "8.53", "8.53",
    "8.5", "8.48", "8.46", "8.44", "8.43", "8.43", "8.41", "8.41",
    "8.39", "8.39", "8.37", "8.37", "8.36", "8.36", "8.36", "8.36",
    "8.36", "8.37", "8.41", "8.41", "8.43", "8.44", "8.44", "8.43"
    ), X = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA)), row.names = c(NA, -30L), class = "data.frame")

Here is the code, I have been using so far.
df %>% mutate(Tiefe = as.numeric(Tiefe),
              Temperatur= as.numeric(Temperatur)) %>%
              group_by(Datum) %>%
              summarize(Tiefe = mean(Tiefe))

However, I get the output
Tiefe
1  1.28

What is going on here? I would like to have 2 values for "Tiefe", for the 2020-03-03 as well as 2020-03-04. What am I missing. My original dataset has more than 400 distinct dates, but when I summarize I just get that one value as above. Also, I would like to preserve the "date" column in the output, so it should be like
date           Tiefe

"2020-03-03"    1.28
"2020-03-04"      x
"2020-03-05"      y

and so forth. I could have sworn I have done this before, but I am stuck now and dont know what to do. Any help is really appreciated! :)
Thanks a lot in advance.
Cheers


text:
Q: Beta iOS app distribution problems I have an app ready and I want to test the beta in some external devices. I am using the correct bundle id and in the iTunes connect page I created a certificate , added the devices and then created an ad-hoc provision profile. I opened it on Xcode and then archive the app and export it. I used Diawi and Ubertesters for the app distribution but in both cases I get "Unable to download app". I am missing something ?

A: Most probably the issue is connected to the device provisioning. Please make sure you've added your device UDID to the provisioning profile and sign your .ipa file with it. Once the newly signed up build is uploaded to Ubertesters, please try to install it on your device.


text:
Q: Не могу прописать пагинацию в парсер Python Вот код, не обессудьте первый день этим занимаюсь. Пагинацию не понимаю как прописать, все примеры через pages, а тут просто даты.  https://primatips.com/tips/2022-11-23

import requests
from bs4 import BeautifulSoup
import csv

HOST = 'https://primatips.com'
URL = 'https://primatips.com/tips/'
CSV = 'games.csv'
HEADERS = {
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
    }

def get_html(url, params=()):
    r = requests.get(url, headers=HEADERS, params=params)
    return r

def get_content(html):
    soup = BeautifulSoup(html, 'html.parser')
    items = soup.find_all('a', class_='game')
    games = []

    for item in items:
           games.append(
            {
                'champ':item.find('span', class_= 'cn').get_text(),
                'team':item.find('span', class_= 'nms').get_text(';'),
                'coef':item.find('span', class_= 'os').get_text(';'),
                'goal':item.find('span', class_= 'res').get_text(';'),
                }
            )
    return games

def save_doc(items, path):
    with open(path, 'a', newline='') as file:
        writer = csv.writer(file, delimiter=';')
        writer.writerow(['1','2','3','4'])
        for item in items:
            writer.writerow( [item ['champ'],item ['team'],item ['coef'],item ['goal']])

def parse():
    while True:
        URL = input('SSSS')
        URL = URL.strip()
        html = get_html(URL)
        if html.status_code == 200:
            games = []
            games = get_content(html.text)
            save_doc(games, CSV)
        else:
            print('ERROR')

parse()

A: Каждая страница у вас соответствует дате. В URL страницы есть "базовая" часть, и окончание, соответствующее дате. Вам нужно за некоторый период дат распарсить страницы. Соответсвенно, организуем цикл, в котором к "базовой" части URL будем добавлять строку-окончание с нужной датой в требуемом формате. Ниже простой пример, вам нужно запустить его в консоли, понять, что он делает, адаптировать к вашему коду:
from datetime import date, datetime, timedelta

current_date = date(2022, 11, 1)
base_url = "http://example.com/"

for i in range(0, 10):  # берём за 10 дней
    URL = base_url + datetime.strftime(current_date, "%Y-%m-%d")
    print(URL)
    current_date = current_date + timedelta(days=1)


text:
Q: Span collapse/margin/padding while creating a subcaption? please see this code here:
http://jsfiddle.net/ap6vK/
span.Title{
    font-size: 100px;
    color:#6495ed;
    border:1px solid black;
}

span.SubTitle{
    font-size: 30px;
    position:relative;
    top:23px;
    right:163px;
    color:#778899;
}

    Caption
    SubCaption

I use two spans to create a subcaption. problem I have is that the outer span doesn't collapse. See the black border which extends too far? I would like to have the border cropped to the caption instead of remaining the size of the caption+subcaption next to each other instead of beneath each other. does any one know how to do this?

A: If I understand you correctly, you mean the right padding is too much.  That's because any position relative with left and top set will be like, the element is as if it was there, but just shifted.  (meaning it occupies the real estate, but then shifted).  So that's why the extra padding at the right for your border.
you can look at:
http://jsfiddle.net/ap6vK/4/
it is using the inner span
position: absolute

and the outer span:
position: relative

This way, the inner span is placed, not by the normal flow and with the real estate not considered.  But to make it work, you have to make the outer span position: relative because the container must have any position that is set to something rather than the default value static so that the children element with position: absolute will be relative to this container.


text:
Q: 'Document' is not convertible to 'StitchTask'. This error pops up after following the instructions on mongo cloud atlas I've been following along with tutorials on how to connect an iOS application written in swift which walks thorough a way to connect mongo to the application. I've set up a cluster on mongoDB Atlas and have initialized a collection to store data. I've also installed cocoapods and updated my podfile.
imports to mongo, stitch, and extended json
database code starts at stichClient
I am fairly new to xcode and mongo and I'm not sure what it means when "'Document' is not convertible to 'StitchTask'.
I've been following the instructions on https://docs.mongodb.com/stitch/getting-started/todo-ios/
and have set Google Cloud Platform. I would at least like to add something into the database and I believe the second image contains code that is close to that. I don't understand how to fix the error.

A: The iOS SDK was recently updated to use PromiseKit, but the example code and the documentation were not updated at the same time.
In addition to the SDK changes, the steps for setting up Google Auth to work with iOS also changed, so you hit a perfect storm.
Both the sample code and the docs have been updated. Hopefully that'll get you up and running.


text:
Q: Can't constrain SymPy variables to real numbers SymPy is giving me complex solutions, even when I constrain my variables to be real, as in this answer.
Here's an example finding the intersection of a unit sphere and the plane X=1. There should be exactly 1 real solution, (1,0,0).
>>> import sympy
>>> x,y,z = sympy.symbols('x,y,z', real=True)
>>> list(sympy.solve([x**2 + y**2 + z**2 - 1, x - 1], [x,y,z]))
[(1, -I*z, z), (1, I*z, z)]

These are correct, but not real.
I can't use solveset(…, domain=S.Reals) because solveset doesn't seem to support systems of equations.

A: This seems to be open issue of sympy and known problem:
https://github.com/sympy/sympy/issues/9973
You could probably hack a function that checks whether there is a real solution using a heuristic - for each complex part, it will solve the equation setting the complex part to 0). This might lead to branching and a lot of work if the solutions are not simple though.


text:
Q: Can I skip the property names in an object declaration? on hapi auth tutorial web page I found following code:
const validate = async (request, username, password) => {
    const user = users[username];
    if (!user) {
        return { credentials: null, isValid: false };
    }

    const isValid = await Bcrypt.compare(password, user.password);
    const credentials = { id: user.id, name: user.name };

    return { isValid, credentials }; // <=== Is this a valid js statement?
};

My question is about the return statement. Is that valid? What does it mean?

A: According to new ES6 shorthand syntax
return { isValid, credentials };

translates to
return { isValid: isValid, credentials:credentials };

which is valid

A: Yes, you can skip the property names, ECMAScript 2015 luckily allows you to simply pass in the variable inside the object and the property will automatically become whatever the variable name is.
So...
var1 = true;
var2 = false;

object = { var1, var2 }; // { var1: true, var2: false }

You are effectively returning an "anonymous" variable (object in this case), which is not part variable at that moment, but instantiated at run-time once returned.
This is also known as shorthand property names.


text:
Q: Downloading file from local folder using vue Few hours ago I noticed that  don't work in vue, just before I wanted to finish my project. I've searched for a solution for almost 4h, but I didn't find anything, that's why I'm here.
I would like to simply download files (pdf, doc, docx) from my local folder docs on the server with vue.
Here is the folder tree:
|--src
    |--app.vue
    |--docs
        |--file.doc
        |--file.pdf
        |--file.docx

So there is the Template part:
<v-row justify="center">
      <v-col
      v-for="(docs, i) in info"
      :key="i"
      cols="10"
      >
        <v-card>
          <v-row>
            <v-col
            cols="10"
            >
              <v-icon large>mdi-file-document-outline</v-icon> {{ docs.name }}
            </v-col>
            <v-col
            cols="2"
            >
              <v-row><v-icon color="green" large>mdi-download</v-icon></v-row>
            </v-col>
          </v-row>
        </v-card>
      </v-col>
    </v-row>

...and the script section:
  import axios from 'axios'
  export default {
    data () {
      return {
        info: null,
      }
    },
    mounted () {
      axios
        .get('http://localhost:8080/Project/Orders/')
        .then(response => {this.info = response.data.data})
        .catch(error => console.log(error))
    },
 }

I'm using axios to get data from database (id, name, file=path) with Django (backend). I'd like to download files from docs folder without Django, but if anyone thinks it would be better idea to use it I'll be greatful too.

A: Use the following instead:
/ ...
const link = document.createElement("a");
link.href = '... path to donwload';
link.setAttribute("download", "file.doc");
link.click();

You need your docs folder on your public directory.


text:
Q: Getting "wrong" URL from $_SERVER['REQUEST_URI'] I get "wrong" url when i use $_SERVER['REQUEST_URI'] on my website, to view what the URL/domain is.
The website have to entry domains www.liceng.dk and www.licenergy.co.uk
But no matter what domain I visit, the $_SERVER['REQUEST_URI'] shows as http://www.liceng.dk/. How come? And can i get the domain that is showing as URL somehow, using PHP?
My goal is to change the logo depending on what domain the visitor is using to watch the website. But i can't do that if i can't differentiate what domain the used to get to the website.

A: The actual HTTP HOST used to request the site will be available in $_SERVER['HTTP_HOST']. Use that value to switch the default logo / language / etc. depending on which site is being accessed.


text:
Q: Bookmarks numbering in Beamer of texlive 2018 version I want to number the each section, subsection and subsubsecton in bookmarks of beamer using texlive 2018 version. This problem seems to have been solved many years ago according to the solutions provided by cybersingularity in question Adjust Bookmarks numbering in Beamer.
I followed it and solved it in texlive 2017 last year, however, I can not compile the code in texlive 2018 on Windows OS:

the bookmark is:

The code is as follows:
\documentclass{beamer}
\documentclass{beamer}
\hypersetup{
  bookmarksnumbered=true
}

\setcounter{tocdepth}{4}

% get numbering in section bookmarks
\usepackage{etoolbox}
\usepackage{bookmark}
\makeatletter

\newcounter{realsection}
\newif\ifrealsection
\long\def\beamer@@ssection*#1{\realsectionfalse\beamer@section[{#1}]{}}
\long\def\beamer@@@section#1{\realsectiontrue\beamer@section[{#1}]{#1}}

\patchcmd{\beamer@section}%
    {\refstepcounter{section}}%
    {\ifrealsection\refstepcounter{realsection}\fi\refstepcounter{section}}%
    {}{\errmessage{failed to patch}}

\patchcmd{\beamer@section}%
    {\Hy@writebookmark{\the\c@section}{\secname}}%
    {\Hy@writebookmark{\the\c@section}{\numberline{\therealsection}\secname}}%
    {}{\errmessage{failed to patch}}
\patchcmd{\beamer@subsection}%
   {\Hy@writebookmark{\the\c@subsection}{#2}}%
    {\Hy@writebookmark{\the\c@subsection}{\numberline{\therealsection.\thesubsection}#2}}%
    {}{\errmessage{failed to patch}}
\patchcmd{\beamer@subsubsection}%
    {\Hy@writebookmark{\the\c@subsubsection}{#2}}%
    {\Hy@writebookmark{\the\c@subsubsection}{\numberline{\therealsection.\thesubsection.\thesubsubsection}#2}}%
    {}{\errmessage{failed to patch}}
\makeatother

\begin{document}

\section*{Intro}

\section{section}

\begin{frame}
\end{frame}

\subsection{subsection}
\begin{frame}
\end{frame}

\subsubsection{subsubsection}
\begin{frame}
\end{frame}

\section{section}
\begin{frame}
\end{frame}

\subsection{subsection}
\begin{frame}
\end{frame}

\subsubsection{subsubsection}
\begin{frame}
\end{frame}

\subsubsection{subsubsection}
\begin{frame}
\end{frame}
\end{document}

So, how do i modify the code above and number the subsection and subsusection?
Many thanks for your help.

A: beamer now uses also for subsection and subsubsection commands \subsecname and \subsubsecname:
\documentclass{beamer}
\hypersetup{
  bookmarksnumbered=true
}

\setcounter{tocdepth}{4}

% get numbering in section bookmarks
\usepackage{etoolbox}
\usepackage{bookmark}
\makeatletter

\newcounter{realsection}
\newif\ifrealsection
\long\def\beamer@@ssection*#1{\realsectionfalse\beamer@section[{#1}]{}}
\long\def\beamer@@@section#1{\realsectiontrue\beamer@section[{#1}]{#1}}

\patchcmd{\beamer@section}%
    {\refstepcounter{section}}%
    {\ifrealsection\refstepcounter{realsection}\fi\refstepcounter{section}}%
    {}{\errmessage{failed to patch}}

\patchcmd{\beamer@section}%
    {\Hy@writebookmark{\the\c@section}{\secname}}%
    {\Hy@writebookmark{\the\c@section}{\numberline{\therealsection}\secname}}%
    {}{\errmessage{failed to patch}}
\patchcmd{\beamer@subsection}%
   {\Hy@writebookmark{\the\c@subsection}{\subsecname}}%
    {\Hy@writebookmark{\the\c@subsection}{\numberline{\therealsection.\thesubsection}\subsecname}}%
    {}{\errmessage{failed to patch}}

\patchcmd{\beamer@subsubsection}%
    {\Hy@writebookmark{\the\c@subsubsection}{\subsubsecname}}%
    {\Hy@writebookmark{\the\c@subsubsection}{\numberline{\therealsection.\thesubsection.\thesubsubsection}\subsubsecname}}%
    {}{\errmessage{failed to patch}}
\makeatother

\begin{document}

\section*{Intro}

\section{section}

\begin{frame}
\end{frame}

\subsection{subsection}
\begin{frame}
\end{frame}

\subsubsection{subsubsection}
\begin{frame}
\end{frame}

\section{section}
\begin{frame}
\end{frame}

\subsection{subsection}
\begin{frame}
\end{frame}

\subsubsection{subsubsection}
\begin{frame}
\end{frame}

\subsubsection{subsubsection}
\begin{frame}
\end{frame}
\end{document}


text:
Q: Grails BuildConfig.groovy, difference between build, compile, and runtime? What's the difference between build, runtime, and compile, in BuildConfig.groovy (1.3.7)
grails.project.dependency.resolution = {

    plugins {
        build "acme:acme-cache:latest.integration"
    }

    dependencies {
        build "com.foo.bar:foobar:1.0.5"
        runtime "org.apache.httpcomponents:httpclient:4.0.3"
        compile("com.thoughtworks.xstream:xstream:1.3.1")
    }
}

A: It seems the 2 previous answers conflict on the distinction between compile and build.  I believe that build is the scope that includes grails compile and grails run-app, while compile is just the former.

A: Starting from Grails 3, dependencies are managed by Gradle. The grails-app/conf/BuildConfig.groovy file has been replaced by the build.gradle file in the project's root.
The Grails user guide explain how to set grails depencies with gradle. See also the related Gradle documentation for further details on managing dependencies using it.

A: *

*build - dependency that is only needed by the build process

*runtime - dependency that is needed to run the application, but not compile it e.g. JDBC implementation for specific database vendor. This would not typically be needed at compile-time because code depends only the JDBC API, rather than a specific implementation thereof

*compile - dependency that is needed at both compile-time and runtime. This is the most common case

There are a couple of other dependency scopes:

*

*test - dependency that is only needed by the tests, e.g. a mocking/testing library

*provided - dependency that is needed at compile-time but should not be packaged with the app (usually because it is provided by the container). An example is the Servlet API

A: A couple grails commands help illustrate the difference. Consider grails run-app and grails compile. grails compile is the compile step and will include compile-time dependencies. grails run-app is the run step and will include runtime dependencies. Build dependencies are anything that you might need to run any of these commands, for example, a custom script that hooks into some build events.
So you would pick the one that best fits when you need to be certain the dependency is included.


text:
Q: Mapping entity id to column in table with different name The column name in database table is:  "aID" , but on my entity class the property name is Id.
I've tried this without success in my mapping class:
public AppMap()
{
   Id(app => app.Id).Column("aID");
}

Exception i get when trying to get all dads from database: Unable to resolve property:  Id
In my entity class:
    private int _id;
    public virtual int Id
    {
        get { return _id; }
        set { _id = value; }
    }

Table in db:

Column aID is auto increment in database.
How can i achieve this?
Thanks!


text:
Q: Garageband—how to change volume of a region (not whole track)? In garageband I have one audio track with many regions. I'd like to adjust the volume for each region. Is there an easy way to do that, or do I have to make a new track each time, and adjust the tracks volume?

A: Finally found the answer, not very intuitive but cool once you know.
There's a button to toggle 'automation'. Once that's on you can select from a dropdown whether you want to change volume, echo, reverb, etc. Then you click on the actual waves on the track and a coloured line will appear. Clicking along the line creates break points, and you can move either points or the line segments between points to shift the volume. It's not based on regions—you can adjust it anywhere.
For more information:
https://www.howtogeek.com/238649/how-to-use-automation-in-garageband/

A: Under "Mix," choose Show Automation. You didn't have to do this before. Now you do.