text:
Q: OPENSSL Blowfish CBC encryption differs from PHP to C++ I am trying to encrypt and decrypt a communication between a C++ library and a PHP server using OPENSSL library in both of them. I want to use the Blowfish CBC algorithm but it seems that the results are different between the C++ code and the PHP code. The C++ code is taken from here:
This is the PHP code:
<?php
function strtohex($x)
{
    $s='';
    foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
    return($s);
}

$encryptedMessage = openssl_encrypt("input", "BF-CBC", "123456", 0, "initvect");

echo $encryptedMessage;
echo "\n";
echo strtohex($encryptedMessage);

The PHP output is this:
x9jDa2WMwvQ=
78396A446132574D7776513D

This is the c++ code:
bool do_encrypt(const char *in, unsigned char *out, int *outlen, unsigned    char *key, unsigned char *iv)
{
    int buflen, tmplen;

    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx, EVP_bf_cbc(), nullptr, key, iv);

    if (!EVP_EncryptUpdate(&ctx, out, &buflen, (unsigned char*)in,     strlen(in)))
    {
        return false;
    }

    if (!EVP_EncryptFinal_ex(&ctx, out + buflen, &tmplen))
    {
        return false;
    }

    buflen += tmplen;
    *outlen = buflen;
    EVP_CIPHER_CTX_cleanup(&ctx);

    return true;
}

unsigned char output[2048] = { 0 };
int outLen;

auto result = do_encrypt("input", output, &outLen, (unsigned char*)"123456", (unsigned char*)"initvect");

BIGNUM *outputStr = BN_new();
BN_bin2bn(output, outLen, outputStr);

cout << base64_encode(output, outLen) << "\n";
cout << BN_bn2hex(outputStr) << "\n";

The C++ output is this:
 EfRhhWqGmSQ=
 11F461856A869924

Can someone please help me understand what I'm doing wrong? Any help will be very much appreciated.
Thanks!
Edit 1:
I managed to fix the C++ code after jww's answer and it worked well. I was missing the EVP_CIPHER_CTX_set_key_length However, I couldn't make the PHP code return the same thing and eventually we decided to move to AES and it now works flawlessly. Thanks!

A: For your OpenSSL code, I believe you need to call EVP_CIPHER_CTX_set_key_length to tell the library the key is only 6 bytes.
Let me throw Crypto++ into the arena below. OpenSSL and Crypto++ will converge on the right answer once you add the missing EVP_CIPHER_CTX_set_key_length OpenSSL call. The right answer is 32CEBA7E046431EB (in hex).
I don't know what's going on with PHP:
x9jDa2WMwvQ=
78396A446132574D7776513D

Considering x is ASCII 0x78, 9 is ASCII 0x39, I'm guessing you hex encoded the Base64 string.

$ cat test.cxx
#include "blowfish.h"
#include "modes.h"
#include "channels.h"
#include "filters.h"
#include "base64.h"
#include "hex.h"
using namespace CryptoPP;

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
  const byte key[] = "123456";   // 6
  const byte  iv[] = "initvect"; // 8
  CBC_Mode<Blowfish>::Encryption encryptor;
  encryptor.SetKeyWithIV(key, 6, iv, 8);

  string r1, r2;
  ChannelSwitch chsw;

  Base64Encoder e1(new StringSink(r1));
  HexEncoder e2(new StringSink(r2));
  chsw.AddDefaultRoute(e1);
  chsw.AddDefaultRoute(e2);

  string msg = "input";
  StringSource ss(msg, true,
    new StreamTransformationFilter(encryptor,
      new Redirector(chsw)));

  cout << r1 << endl;
  cout << r2 << endl;

  return 0;
}

The test program results in:
$ ./test.exe
Ms66fgRkMes=
32CEBA7E046431EB

Here's the OpenSSL portion of things. Notice EVP_EncryptInit_ex is called twice. First, EVP_EncryptInit_ex is called to set the block cipher EVP_bf_cbc. The key length is set with EVP_CIPHER_CTX_set_key_length. Then second, EVP_EncryptInit_ex is called to set the key and iv.
#include <openssl/evp.h>

#include <iostream>
#include <iomanip>
#include <stdexcept>
using namespace std;

typedef unsigned char byte;

int main()
{
  EVP_CIPHER_CTX ctx;
  EVP_CIPHER_CTX_init(&ctx);

  int rc;
  const byte key[] = "123456";   // 6
  const byte  iv[] = "initvect"; // 8

  rc = EVP_EncryptInit_ex(&ctx, EVP_bf_cbc(), NULL, 0, 0);
  if (rc != 1)
    throw runtime_error("EVP_EncryptInit_ex failed");

  rc = EVP_CIPHER_CTX_set_key_length(&ctx, 6);
  if (rc != 1)
    throw runtime_error("EVP_CIPHER_CTX_set_key_length failed");

  rc = EVP_EncryptInit_ex(&ctx, NULL, NULL, key, iv);
  if (rc != 1)
    throw runtime_error("EVP_EncryptInit_ex failed");

  const byte msg[] = "input";
  byte buf[32];
  int len1 = sizeof(buf), len2 = sizeof(buf);

  rc = EVP_EncryptUpdate(&ctx, buf, &len1, msg, 5);
  if (rc != 1)
    throw runtime_error("EVP_EncryptUpdate failed");

  rc = EVP_EncryptFinal_ex(&ctx, buf+len1, &len2);
  if (rc != 1)
    throw runtime_error("EVP_EncryptFinal_ex failed");

  for(unsigned int i=0; i<len1+len2; i++)
      cout << std::hex << setw(2) << setfill('0') << (int)buf[i];
  cout << endl;

  EVP_CIPHER_CTX_cleanup(&ctx);
  return 0;
}


text:
Q: How to target an element's value in a html web page which doesn't have id or class(using in a WPF c# application) i want to get the value(in code:x) of a div element in a local html web page that belongs to a wireless network radio. this div has no id or class or attribute.how can i do that in c# Windows Presentation Foundation?(the value is not fixed).i have searched a lot in the past few days. i know that maybe the best way is to use html agility pack to locate that specific line or to index all the div in the page and find this one by it's index.this is a part of that html page:
Link Capacity

header=[Link Capacity]....

x

i just need to grab x which is a number.
also, class="help" was used many time in the page.
"Link Capacity" or "header=[Link Capacity]" are used in the code once. maybe they are the key on this solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I make IMGs width independent of parent's width? I have an  tag in which I load all images in a directory dynamically using PHP. Below you can see what I mean and what the problem is. Since the  tag has overflow on it set, why can't the image's width go beyond it's parent's width? Why must it squish? I've tried what must now be a million combinations of w-full, h-full, object-cover, object-none, object-contain on the  tag itself, on parent divs, etc. It's driving me insane and my brain is foggy. Obviously I've tried googling and searching stackoverflow but I can't find anything.
Dynamic PHP code inside :
function imgLoad($dirPath, $index){
    $dir = ($dirPath . scandir($dirPath)[$index]);
    $files = scandir($dir);
    foreach($files as $file) {
        if($file !== "." && $file !== ".." && $file !== "info.php") {
            echo "";
        }
    }
}

This is the compiled PHP code:

Parent div:

Which looks like this:

Until:


text:
Q: Local port forwarding automatically configured on boot? I have software which needs to run as a non-root user, but needs to listen on port 80 and 443.
With iptables, this isn't all that difficult:
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8080

Though this is simple, how should I persist it to take effect on boot? I tried iptables-save, but this didn't seem to work.

A: The standard method for restoring iptables rules on boot for Debian-based systems is using a pre-up rule in /etc/network/interfaces.
First you need to save the current rules to a file:
iptables-save > /etc/iptables.rules

In the block for the relevant interface in /etc/network/interfaces add:
pre-up iptables-restore < /etc/iptables.rules

Other methods, such as loading via network-manager can be found on the ubuntu wiki.


text:
Q: How to find which word has max occurance in three fields of a table sql server i have a table which has many fields but i want to get count of every word in any three fields of that table
find all title in a table that exist more than once...so for that i can issue this statement
SELECT title, COUNT(title) AS NumOccurrences FROM users
GROUP BY titleHAVING ( COUNT(title) > 1 )

suppose my table has three fields called title,url,description.
basically i do not know which word has been stored in which 3 fields in that table maximum time.
i want to issue a sql statement which can show me which word found maximum time...like
word-name          occurance
---------          -------
sqlserver           300
jquery              120
ajax                110

please guide me with sample sql for sql server 2000/2005 thanks
Here is my updated full code.....please have look
    IF OBJECT_ID('tempdb..#tempSearch') IS NOT NULL
BEGIN
    DROP TABLE #tempSearch
END

CREATE TABLE #tempSearch(
    ID INT,
    Title nvarchar(4000),
    Description ntext,
    Url nvarchar(4000),
    Type char(1))

INSERT INTO #tempSearch
    SELECT * from vwProductSearch

INSERT INTO #tempSearch
    SELECT * from vwContentSearch

    SELECT  Word,
    COUNT(Word) AS TotalOccurrences,
    COUNT(CASE WHEN Field = 'Title' THEN Word END) AS OccurancesInTitle,
    COUNT(CASE WHEN Field = 'URL' THEN Word END) AS OccurancesInURL,
    COUNT(CASE WHEN Field = 'Description' THEN Word END) AS OccurancesInDescription
    FROM    (   SELECT  CONVERT(NTEXT, Title) AS Word, 'Title' AS Field
        FROM    #tempSearch
        UNION ALL
        SELECT  CONVERT(NTEXT, URL), 'URL' AS Field
        FROM    #tempSearch
        UNION ALL
        SELECT  CONVERT(NTEXT, Description), 'Description' AS Field
        FROM    #tempSearch
    ) As Fields
    GROUP BY Word
    HAVING  COUNT(Word) > 1

   DROP TABLE #tempSearch

A: You need to use UNION to combine your 3 fields into a single column so you can use this to group by. I've also added a few more counts in case you need to drill down as to where the word occurs the most.
SELECT  Word,
        COUNT(Word) AS TotalOccurrences,
        COUNT(CASE WHEN Field = 'Title' THEN Word END) AS OccurancesInTitle,
        COUNT(CASE WHEN Field = 'URL' THEN Word END) AS OccurancesInURL,
        COUNT(CASE WHEN Field = 'Description' THEN Word END) AS OccurancesInDescription
FROM    (   SELECT  Title AS Word, 'Title' AS Field
            FROM    Users
            UNION ALL
            SELECT  URL, 'URL' AS Field
            FROM    Users
            UNION ALL
            SELECT  Description, 'Description' AS Field
            FROM    Users
        ) As Fields
GROUP BY Word
HAVING  COUNT(Word) > 1

EDIT
I know you have asked about SQL_Server 2005 and 2000, but if you were ever to upgrade to 2008 or later there is a much cleaner solution:
SELECT  Word,
        COUNT(Word) AS TotalOccurrences,
        COUNT(CASE WHEN Field = 'Title' THEN Word END) AS OccurancesInTitle,
        COUNT(CASE WHEN Field = 'URL' THEN Word END) AS OccurancesInURL,
        COUNT(CASE WHEN Field = 'Description' THEN Word END) AS OccurancesInDescription
FROM    Users
        CROSS APPLY
        (   VALUES
                (Title, 'Title'),
                (URL, 'URL'),
                (Description, 'Description')
        ) AS T (Word, Field)
GROUP BY Word
HAVING  COUNT(Word) > 1

EDIT 2
If all your columns are different datatypes you will need to explicitly convert them:
SELECT  Word,
        COUNT(Word) AS TotalOccurrences,
        COUNT(CASE WHEN Field = 'Title' THEN Word END) AS OccurancesInTitle,
        COUNT(CASE WHEN Field = 'URL' THEN Word END) AS OccurancesInURL,
        COUNT(CASE WHEN Field = 'Description' THEN Word END) AS OccurancesInDescription
FROM    (   SELECT  CONVERT(NTEXT, Title) AS Word, 'Title' AS Field
            FROM    Users
            UNION ALL
            SELECT  CONVERT(NTEXT, URL), 'URL' AS Field
            FROM    Users
            UNION ALL
            SELECT  CONVERT(NTEXT, Description), 'Description' AS Field
            FROM    Users
        ) As Fields
GROUP BY Word
HAVING  COUNT(Word) > 1

EDIT 3
There is no way around the error you are getting, you cannot group by NTEXT. The best solution I can come up with feels very dirty, and I'm not particularly happy with it...
SELECT  COALESCE(Title, URL, Description) AS Word,
        COALESCE(Title.Occurances, 0) + COALESCE(URL.Occurances, 0) + COALESCE(Description.Occurances, 0) AS TotalOccurances,
        COALESCE(Title.Occurances, 0) AS TitleOccurances,
        COALESCE(URL.Occurances, 0) AS URLOccurances,
        COALESCE(Description.Occurances, 0) AS DescriptionOccurances
FROM    (   SELECT  CONVERT(NTEXT, Title) AS Title, COUNT(*) AS Occurances
            FROM    #tempSearch
            GROUP BY Title
        ) AS Title
        FULL JOIN
        (   SELECT  CONVERT(NTEXT, URL) AS URL, COUNT(*) AS Occurances
            FROM    #tempSearch
            GROUP BY URL
        ) AS URL
            ON URL LIKE Title
        FULL JOIN
        (   SELECT  Description, 1 AS Occurances
            FROM    #tempSearch
        ) AS Description
            ON Description LIKE Title

This works, but like I said, it isn't perfect and probably won't perform very well. Strongly consider upgrading to a later version of SQL-Server!

A: You can count the number of occurrences a word has across three fields using the difference in LEN() to account for the word appearing multiple times in the same field:
SELECT
    a.wordname,
    SUM(
        ((LEN(b.title) - LEN(REPLACE(b.title, a.wordname, ''))) / LEN(a.wordname)) +
        ((LEN(b.url) - LEN(REPLACE(b.url, a.wordname, ''))) / LEN(a.wordname)) +
        ((LEN(b.description) - LEN(REPLACE(b.description, a.wordname, ''))) / LEN(a.wordname))
    ) AS occurrence
FROM
    (
        SELECT 'sqlserver' AS wordname UNION ALL
        SELECT 'jquery' AS wordname UNION ALL
        SELECT 'ajax' AS wordname
    ) a
CROSS JOIN
    users b
GROUP BY
    a.wordname
ORDER BY
    occurrence DESC

If you have a table of wordnames, just put that table name in place of the many SELECT ... UNION ALL statements I have put for the sake of example.


text:
Q: How can I log into a MacBook when I tried a few times and now the account is locked? This is a MacBook Pro M1 with Monterey.  The issue is: I cannot even power it down properly.

*

*Can I still retry log in (typing in the password)

*Or, somehow shut it down gracefully

It doesn't show any log in input fields any more, and there is no Shut Down icon. Only a Cancel button which will cause the computer to nap right away.
The details are:
This happens ONLY when I left the MacBook Pro there, and it ran out of power and therefore hibernated, and then I charge it up to 100% and try to log in. In such case it seems it cannot recognize my password.  See the P.S. below about other people having similar issues.
I might have missed one character or two (capitial letter, symbol, etc) and after a perhaps 8 or 10 times, it now says, "Your Account is locked" on the log in screen.
There is only a "Cancel" button to put the computer to nap right away.
So I cannot log in, try again, or gracefully shut down the computer.
I do not want to press the power button for 10 seconds or press the Shift-Ctrl-Opt-CMD Power button to force it to power down, as that would hurt the OS and the hard drive.  Imagine the OS writing something to the hard drive and you force it down.
Also

*

*moving the mouse to the top screen edge doesn't bring out the macOS task bar.

*right click on the desktop background does not do anything

How can I proceed?  I do have another MacBook Air M1 and iPad and iPhone if they can help. I also can use my iTunes / iCloud password to somehow reset my MacBook...  I think Apple goofed at the UI design because they is no graceful way out when a user happens to forget the password.
P.S. It looks like other people are having the same issue. The second post is even about the "cache" being wrong, what a mess: Big Sur - Logging in after sleep sometimes doesn't work and Macbook Pro stuck after I enter my password

A: Do not try to brute force a password on Apple Silicon Macs. You get ten failed attempts total with long delays to ensure you don't do this unintentionally.
You will not harm the system holding the power off button if it was off and then you started it up as the OS isn't running. Even if the OS is running, the chance of damage is very small when the screen is locked, so power down the Mac. Find another computer to read the process, make a beverage and snack and be careful if you're already at 7 failed attempts (15 minute delay territory).
After 3 to 5 failed attempts I recommend people stop and use another unlock method. Apple has a very clear process for you (and others who will surely get locked out at some point) in this next link on how to reset the password.

*

*https://support.apple.com/en-us/HT202860

If the 10 attempts are exhausted, 10 more attempts are available after booting into recoveryOS. And if those are also exhausted, then
10 additional attempts are available for each FileVault recovery mechanism (iCloud recovery, FileVault recovery key, and institutional key), for a maximum of 30 additional attempts. After those additional attempts are exhausted, the Secure Enclave no longer processes any requests to decrypt the volume or verify the password, and the data on the drive becomes unrecoverable.

*

*https://support.apple.com/guide/security/passcodes-and-passwords-sec20230a10d/web
If you have a backup, erase the Mac and restore from backup if you can't get it unlocked with help from us or Apple support or the first link above.

A: It turned out that it may be better to use my iCloud account to reset my password.
By the way, I am not sure if there was any loophole on the Mac with Monterey and some hacker changed my password, because I was quite sure about the possible password combinations and I tried them all, and it still could not log me in. That actually happened to both my MacBook Pro 16 M1 and my MacBook Pro 14 M1.
So follow this link: https://support.apple.com/en-us/HT212190
and it will guide you to reset your Mac password using your iCloud password.
(Basically, if it is Intel Mac, restart the Mac, and press and hold CMD-r to go into recovery mode, or if M1 Mac, then start up the Mac, and press and hold the power button. Once you are in Recovery mode, open Terminal and run resetpassword.)


text:
Q: htaccess is redirecting my wordpress wp-content folder too by mistake ok, so i'm relatively new to .htaccess and redirects but I've been searching high and low for this solution and it's driving me crazy.
Right now I'm redirecting my old blogger blog to wordpress.
So, I have this code in place:
RedirectMatch 301 /2014/01(.*) /journal/trip1/$1

This redirects:
www.website.com/2014/01/BlogTitle

to:
www.website.com/journal/trip1/BlogTitle

This all works great EXCEPT it's also redirecting my images in the "wp-content/uploads/2014/01" folder because it matches the "2014/01" in the redirect
The image should be here:
http://www.website.com/wp-content/uploads/2014/01/SomeImage.jpg

Instead it redirects to here:
http://www.website.com/journal/trip1/SomeImage.jpg

Like I said, I've searched high and low for solutions and I'm sure it's something ridiculously easy.
Any help greatly appreciated!
Thanks
Todd

A: As mentioned in the comment by @Hobo, you are not checking from the beginning of the URI. This means that anything before /2014/01 will also be matched. As such, you'll need to add ^ before the /2014. It should now look like this:
RedirectMatch 302 ^/2014/01/(.*)$ /journal/trip1/$1

As a rule of thumb, it's also better to end the expression with $.
Alternatively, you can use mod_rewrite to do the redirect. Using the condition and rule below, you can do the redirect whilst ensuring the requested URI does not map to an existing file.
RewriteEngine on

# Make sure the request does not map to an existing file:
RewriteCond %{REQUEST_FILENAME} !-f

# If so, redirect:
RewriteRule ^2014/01/(.*)$ /journal/trip1/$1 [R=302,L]

Also, per @Hobo's comment, you should always do a temporary redirect instead of a permanent one when testing. Once you're happy with either of the above (i.e. they're working as expected) change both 302s to 301s.

A: What if you apply the solution said by @MikeRockett and @Hobo, but, instead denying any found file
RewriteCond %{REQUEST_FILENAME} !-f

deny only the images on your URI
RewriteCond %{REQUEST_URI}  !(\.jpg|\.jpeg|\.png|\.gif)$

Not sure if it's the real solution. I'd say that in a comment, but I've got not enough points yet


text:
Q: loading Instagram into frame how to load instagram page into frame.
The code that I wrote below blocks the page of instagram
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
     <title>Title</title>
 </head>
 <body>
    <iframe src="https://www.instagram.com"></iframe>
    <button> Start </button>
 </body>
</html>

A: Short answer: you can't.
Long answer: instagram uses the HTTP header x-frame-options: SAMEORIGIN, so the web browser will not show the page in a <iframe> tag.


text:
Q: clang and clang++ with ASAN generate different output I'm trying to add ASAN (Google's/Clang's address sanitize) to our project and stuck at this problem.
For example, we have this simple C++ code
#include <iostream>
int main() {
    std::cout << "Started Program\n";
    int* i = new int();
    *i = 42;
    std::cout << "Expected i: " << *i << std::endl;
}

Then, I build it with clang++
clang++-3.8 -o memory-leak++ memory_leak.cpp -fsanitize=address -fno-omit-frame-pointer -g

The program gives this output
Started Program
Expected i: 42

=================================================================
==14891==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 4 byte(s) in 1 object(s) allocated from:
    #0 0x4f2040 in operator new(unsigned long) (memory-leak+++0x4f2040)
    #1 0x4f4f00 in main memory_leak.cpp:4:11
    #2 0x7fae13ce6f44 in __libc_start_main /build/eglibc-SvCtMH/eglibc-2.19/csu/libc-start.c:287

SUMMARY: AddressSanitizer: 4 byte(s) leaked in 1 allocation(s).

Cool, it works and symbolizer gives meaningful information too.
Now, I build this with clang
clang-3.8 -o memory-leak memory_leak.cpp -std=c++11 -fsanitize=address -fno-omit-frame-pointer -g -lstdc++

And the program gives this output
Started Program
Expected i: 42

=================================================================
==14922==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 4 byte(s) in 1 object(s) allocated from:
    #0 0x4c3bc8 in malloc (memory-leak+0x4c3bc8)
    #1 0x7f024a8e4dac in operator new(unsigned long) (/usr/lib/x86_64-linux-gnu/libstdc++.so.6+0x5edac)
    #2 0x7f0249998f44 in __libc_start_main /build/eglibc-SvCtMH/eglibc-2.19/csu/libc-start.c:287

SUMMARY: AddressSanitizer: 4 byte(s) leaked in 1 allocation(s).

Ok, it detects memory leak, but the stack trace looks strange and it doesn't really include the memory_leak.cpp:4:11 line.
I've spent quite a while trying to narrow down this problem in our codebase and eventually, the only difference, is clang vs clang++.
Why it's event a problem, can't we use clang++?
We use bazel, which uses CC compiler instead of CXX for some blah-balh reasons. We cannot blindly force to use it CXX because we have CC dependencies which cannot be build by CXX. So...
Any idea how to get the same ASAN output when used with clang and clang++? Or, how to make Bazel to use clang++ for C++ targets and clang for C targets?

A: This seems to be a bug in Clang, could you file bug report in their tracker? (EDIT: this was [resolved as not-a-bug](Asan developers https://github.com/google/sanitizers/issues/872) so probly needs to be fixed by Bazel developers instead).
Some details: when you use ordinary clang, it decides not to link C++ part of Asan runtime as can be seen in Tools.cpp:
if (SanArgs.linkCXXRuntimes())
  StaticRuntimes.push_back("asan_cxx");

and SanitizerArgs.cpp:
LinkCXXRuntimes =
    Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();

(note the D.CCCIsCXX part, it checks for clang vs. clang++ whereas instead they need to check the file type).
C++ part of the runtime contains interceptor for operator new so this would explain why it's missing when you link with clang instead of clang++. On a positive side, you should be able to work around this by adding -fsanitize-link-c++-runtime to your flags.
As for the borked stack, by default Asan unwinds stack with frame pointer based unwinder which has problems unwinding through code which wasn't built with -fno-omit-frame-pointer (like libstdc++.so in your case). See e.g. this answer for another example of such behavior and available workarounds.


text:
Q: Proving an inequality on commute times of two different weight functions Let $G = (V, E)$ be an undirected, connected graph of $n$ vertices, ordered from 1 to $n$. I have two weight functions $w_1, w_2 : E \to \mathbb{R}$, where $w_1$ is just given by $w_1(e) = 1$, $\forall e \in E$, and $w_2$ is such that
\begin{align}
\sum_{(i, j) \in V \times V} w_2(i, j) \leq 2m,
\end{align}
where $m$ is the number of edges in $G$.
Of course, $w_1(i, j) = w_2(i, j) = 0$ when $(i, j) \notin E$.
Let $C_{xy}$ be the expected commute time between $x$ and $y$ of a random walk, then by interpreting the graph $G$ as an electrical network it is a well known result that
\begin{align}
C_{xy} = R_{xy} \cdot \sum_{(i, j) \in V \times V} w(i, j),
\end{align}
where $R_{xy}$ is the effective resistance between vertices $x$ and $y$.
I wish to prove that $C^2_{1n} \leq C^1_{1n}$ on a particular graph, but I'm having problems bounding the increase in effective resistance between 1 and $n$ when moving from weights $w_1$ to weights $w_2$.
I know that most weights in $w_2$ decrease below 1, while only a handful increase above one, but I don't know how to use this to bound the effective resistance.
There doesn't seem to be much literature on this either, as the only result I've found is that the change in effective resistance on $ij$ when $w(a, b)$ is increased by $\alpha > 0$ is equal to
\begin{align}
\Delta R_{ij}(a, b, \alpha) = \frac{\alpha}{1 + \alpha L(b)^{-1}_{aa}} \left(L(b)^{-1}_{ai} - L(b)^{-1}_{aj} \right)^2,
\end{align}
where $L(b)$ is the laplacian of $G$ with row and column $b$ removed.
But this result is too complex to use, I think. This is probably a long shot, but if anyone has any ideas or can point me in the right direction, I would be very thankful!


text:
Q: SAML Logout Request to ADFS through HTTP-Redirect Binding getting response as requestor not a success -Request initiated from browser the following one is my SAML assertion from ADFS
<samlp:Response ID="_69ecb15f-97ad-4d68-b69e-8eb30a37af8e" Version="2.0" IssueInstant="2021-09-21T16:19:29.472Z" Destination="https://localhost:4200/auth/login" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" InResponseTo="ml101e1a-1d87-18dc-1b33-198e1d2a1459"
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
    <Issuer
        xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://saml.mlads.mi***ic.app/adfs/services/trust
    </Issuer>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
    </samlp:Status>
    <Assertion ID="_acced75d-5742-49ee-ad54-4f72049d3268" IssueInstant="2021-09-21T16:19:29.471Z" Version="2.0"
        xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
        <Issuer>http://saml.mlads.m**ic.app/adfs/services/trust</Issuer>
        <Subject>
            <NameID>Administrator@mlads.m**.app</NameID>
            <SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <SubjectConfirmationData InResponseTo="ml101e1a-1d87-18dc-1b33-198e1d2a1459" NotOnOrAfter="2021-09-21T16:24:29.472Z" Recipient="https://localhost:4200/auth/login" />
            </SubjectConfirmation>
        </Subject>
        <Conditions NotBefore="2021-09-21T16:19:29.468Z" NotOnOrAfter="2021-09-21T17:19:29.468Z">
            <AudienceRestriction>
                <Audience>https://localhost:4200</Audience>
            </AudienceRestriction>
        </Conditions>
        <AuthnStatement AuthnInstant="2021-09-21T16:19:29.404Z" SessionIndex="_acced75d-5742-49ee-ad54-4f72049d3268">
            <AuthnContext>
                <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
            </AuthnContext>
        </AuthnStatement>
    </Assertion>
</samlp:Response>

And my sso logout request
<samlp:LogoutRequest ID="_a78ea30f-b1a7-40fc-9a64-a41196d95582"
                     Version="2.0"
                     IssueInstant="'''+ datetime.now(pytz.utc).strftime('%Y-%m-%dT%H:%M:%SZ')+'''"
                     Destination="https://saml.mlads.mindlogic.app/adfs/ls/"
                     xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
  <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">https://localhost:4200</Issuer>
  <NameID xmlns="urn:oasis:names:tc:SAML:2.0:assertion">Administrator@mlads.m**.app</NameID>
  <samlp:SessionIndex>_12c18cfe-6f98-4322-bdd3-a5685dca9399</samlp:SessionIndex>
</samlp:LogoutRequest>

BUT I AM getting below logout response
<samlp:LogoutResponse ID="_1ff3c824-2e33-4f29-b3d7-a6d52e8d9e41" Version="2.0" IssueInstant="2021-09-21T16:36:28.994Z" Destination="https://localhost:4200/auth/login" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" InResponseTo="_a78ea30f-b1a7-40fc-9a64-a41196d95582" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"><Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://saml.mlads.***.app/adfs/services/trust</Issuer><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Requester" /></samlp:Status></samlp:LogoutResponse>

My following adfs configuration rule
E-mail address -> NameID
but  i am always getting "requestor" response instead of "success"

A: some points to notice

*

*Saml logout request must contain some important parameters like Identity provider(ID), issuer.And this Id in the logout request must match the InResponseTo parameter in the logout response.

*The NameID, including format, must exactly match the NameID of the assertion.

    <samlp:LogoutRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="ONELOGIN_********** "
    Version="2.0" IssueInstant=" "
   Destination="https://*******/adfs/services/trust">
   <saml:Issuer>https://localhost:4200</saml:Issuer>
           //
        //
    </samlp:LogoutRequest>

3.Check if the SAML request deflate (compression)and encoding is properly done.

A: though the session index and nameid are the same as long as we tried to initiate from the browser it's not working but if the same request is working when we triggered from the registered application I don't know why if someone explains it would be good.


text:
Q: Setting DOCTYPE With Server-Side Javascript I have a real quick question. I want to set the DOCTYPE for an HTML Page but I need to do it using Server Side Javascript. Every answer I see on this site says "I don't see why you want to do it" but never answers the question (That I could find... please point me in the direction of a post if I am wrong).
The reason it needs to be done is because this is technically being sent as an HTML email. I am using ExactTarget and they won't allow me to type anything above the starting   tag. If I try to establish the DOCTYPE after it, it gets simply removed.
Now I DO have access to server side javascript before the email renders. I need to set this DOCTYPE because I am trying to set  tags to "display:block" and this will not work with the default DOCTYPE. So basically I need to write some script AFTER the opening  tag that will set the doctype for the page (email).
I wish to use the following DOCTYPE but if this is unwise feel free to advise:
 <!DOCTYPE html >

Also here is the CSS not working with the current Doctype:
 @media screen and (max-width: 660px) {
      td {display:block !important;}
  }

Here is the HTML:

           Top Content

           Bottom Content

When I say server side Javascript here is my syntax:

A: If ExactTarget won't let you output anything prior to the starting  tag, then you can't do this. The doctype has to come before that.


text:
Q: Fail to upload image and video of different format using urlconnection in android  public String uploadFile(String sourceFileUri) {

             fileName = sourceFileUri;
             HttpURLConnection conn = null;
             DataOutputStream dos = null;
             String lineEnd = "\r\n";
             String twoHyphens = "--";
             String boundary = "*****";
             int bytesRead, bytesAvailable, bufferSize;
             byte[] buffer;
             int maxBufferSize = 1 * 1024;
             File sourceFile = new File(sourceFileUri);

             if (!sourceFile.isFile()) {
                  return "";

             }
             else
             {
                  try {

                        // open a URL connection to the Servlet
                      FileInputStream fileInputStream = new FileInputStream(sourceFile);
                      URL urls = new URL(url_upload);
                      conn = (HttpURLConnection) urls.openConnection();
                      conn.setDoInput(true); // Allow Inputs
                      conn.setDoOutput(true); // Allow Outputs
                      conn.setUseCaches(false); // Don't use a Cached Copy
                      conn.setChunkedStreamingMode(1024);

                      conn.setRequestMethod("POST");
                      conn.setRequestProperty("Connection", "Keep-Alive");
                      conn.setRequestProperty("ENCTYPE","multipart/form-data");
                      conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
                      conn.setRequestProperty("fileName", fileName);

                      String cookie=AppController.getInstance().getPrefManger().getCookie();
                      Log.i("hello","cookie"+cookie);

                      conn.setRequestProperty("Cookie", cookie);

                      dos = new DataOutputStream(conn.getOutputStream());
                      dos.writeBytes(twoHyphens + boundary + lineEnd);
                      dos.writeBytes("Content-Disposition: form-data; name=\"albumId\"" + lineEnd);
                      dos.writeBytes(lineEnd);
                      dos.writeBytes(selectedAlbumId); // mobile_no is String variable
                      dos.writeBytes(lineEnd);

                      dos.writeBytes(twoHyphens + boundary + lineEnd);
                      dos.writeBytes("Content-Disposition: form-data; name=\"caption\"" + lineEnd);
                      dos.writeBytes(lineEnd);
                      dos.writeBytes(caption.getText().toString()); // mobile_no is String variable
                      dos.writeBytes(lineEnd);

                      dos.writeBytes(twoHyphens + boundary + lineEnd);
                      dos.writeBytes("Content-Disposition: form-data; name=files;fileName="
                                                + fileName + "" + lineEnd);

                      dos.writeBytes(lineEnd);

                      // create a buffer of  maximum size
                      bytesAvailable = fileInputStream.available();

                      bufferSize = Math.min(bytesAvailable, maxBufferSize);
                      buffer = new byte[bufferSize];

                      // read file and write it into form...
                      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                      while (bytesRead > 0) {

                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                       }

                      // send multipart form data necesssary after file data...
                      dos.writeBytes(lineEnd);
                      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                      // Responses from the server (code and message)
                       serverResponseCode = conn.getResponseCode();
                      String serverResponseMessage = conn.getResponseMessage();

                      Log.i("hello", "HTTP Response is : "
                              + serverResponseMessage + ": " + serverResponseCode);

                      if(serverResponseCode == 200){
                           BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                           String temp;
                           while((temp=in.readLine())!=null)
                           {
                               Log.i("hello", "response is"+temp);

                           }
                      }

                      //close the streams //
                      fileInputStream.close();
                      dos.flush();
                      dos.close();

                 } catch (MalformedURLException ex) {

                     ex.printStackTrace();

                     runOnUiThread(new Runnable() {
                         public void run() {
                         }
                     });

                     Log.e("hello", "error: " + ex.getMessage(), ex);
                 } catch (Exception e) {

                     e.printStackTrace();

                     runOnUiThread(new Runnable() {
                         public void run() {
                         }
                     });
                     Log.e("hello", "Exception : "+ e.getMessage(), e);
                 }
                 return String.valueOf(serverResponseCode);

              } // End else block
            }

This is my code which i am using to upload image or video to url.But when i upload files of different format the it fails to upload and unhandled type exception occurs.Please help How can i upload images and video of all type format


text:
Q: Unsupported Media Type al mandar POST en Flutter Hola muy buenas a todos.
Tengo un problema al hacer una petición HTTP POST en Flutter. Intento mandar un JSON (tal como acepta el backend) para hacer una insercion en BBDD. El problema es el siguiente:
statusCode = 415
reasonPhrase = "Unsupported Media Type"

Estoy trabajando con clases que luego convierto a Map para poder mandarlas pero no funciona. También he vuelvo a convertir a JSON ese Map para hacer la prueba pero sigue fallando.
He intentado varias pruebas sin solucionar este problema. Quizá se me escapa algo.
class Incidencia {
  final String  EntidadCentroDestinoId;
  final String  GestionEnumId;
  final String  DetalleGestionEnumId;
  final String  EntidadAlumnoId;
  final String  Descripcion;

  Incidencia({this.EntidadCentroDestinoId, this.GestionEnumId, this.DetalleGestionEnumId, this.EntidadAlumnoId, this.Descripcion,});

  Map toMap() {
    var map = new Map<String, dynamic>();
    map["EntidadCentroDestinoId"] = EntidadCentroDestinoId;
    map["GestionEnumId"] = GestionEnumId;
    map["DetalleGestionEnumId"] = DetalleGestionEnumId;
    map["EntidadAlumnoId"] = EntidadAlumnoId;
    map["Descripcion"] = Descripcion;

    return map;
  }
}

El botón que hace la petición:
            FlatButton(
                child: Text('Enviar'),
                color: Colors.deepOrange,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.0),
                ),
                onPressed: () => {
                  incidencia  = new Incidencia(
                    Descripcion: myController.text,
                    DetalleGestionEnumId: detalleGestionEnumId,
                    EntidadAlumnoId: entidadAlumnoId,
                    EntidadCentroDestinoId: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
                    GestionEnumId: gestionEnumId,
                  ),

                  iSV.insertarIncidencia(incidencia: incidencia.toMap()).then((res) => {
                      print(res),
                      Navigator.pop(context),
                  }),
                } //aqui ira la llamada al metodo future post para guardar la incidencia
            ),

Y este el Service:
Future insertarIncidencia({Map incidencia}) async {
    String jsonmapaIncidencia = jsonEncode(incidencia);
    var url = Uri.parse('http://unadireccion.com/api/metodo');
    var retu =http.post(
       url,
       body: jsonmapaIncidencia,
    );

    return retu;
}

Gracias de antemano.

A: Correcto @ diegoveloper desde postman tampoco lo mandaba. El problema parece ser que los headers son fuertemente tipados y hay que enviarlo con mayusculas incluidas. Además al convertir en JSON me estaba creando un Mapa (no deberia)... Añadiendo:
headers: {"Content-Type": "application/json", "Accept" : "application/json"}

y asegurandome que mi variable es JSON, lo manda sin problema

A: /metodo para crear un usuariod

hola me disculpan por aca esto este metodo para crear un usuario en dynamoDB AWS al principio me creaba en usuario hasta hace poco dejo de hacerlo... con su respuesta vacia y estado de respusta 200 OK
la peticiones GET PUT funcionan normal
Future createUser(UserModel user) async {
//obtengo tok en del usuario
try {
  crearteUser = true;
  notifyListeners();
  final tem = await userId(); //obtengo id del usuariox-www-form-urlencoded
  final token = await userToken();
  user.id = tem;
  user.email = _credentials!.username;
  print(user.toJson());
  final url = Uri.https(_baseUrl, '/user');
  final response = await http.post(
    url,
    body: user.toJson(),
    headers: {
      'Authorization': token,
      'Content-Type': 'application/json',
      "Accept": "application/json, text/plain, */*"
    },
  );

  if (response.statusCode == 200) {
    print(response.body);
    NotificationsService.showSnackbar(response.body);
    if (response.bodyBytes.isNotEmpty) {
      NotificationsService.showSnackbar(response.body + ' Inicia Sesion');
      final state = AuthState(
          authFlowStatus: AuthFlowStatus
              .session); //prueba de la pantalla de verificacion
      authStateController.add(state);
    }
    crearteUser = false;
    notifyListeners();
  }
  crearteUser = false;
  notifyListeners();
} on Exception catch (e) {
  print('error en post2: ' + e.toString());
  NotificationsService.showSnackbar(e.toString());
  crearteUser = false;
  notifyListeners();
}

}


text:
Q: Template is not working in Backbone.js I just started working in Backbone.js
In that I created a simple example of showing the values in the template using the underscore.js
Now I want to create some advanced example of showing the values of a user in the template using the model thing

Now my model is (EditProfileModel.js):
window.EditProfileModel = Backbone.Model.extend({

constructor : function(attributes, options) {
    Backbone.Model.apply(this, arguments);
},
defaults : {
    id : '',
    firstName : '',
    lastName : '',
},
urlRoot: 'rest/editProfile'
});

EditProfileView.js :
window.EditProfileView = Backbone.View.extend({

template : 'tpl/EditProfileTpl.html',
el: content,

initialize:function () {
    this.render();
},

events: {

},

render:function () {
    var $this = this;

    var editProfileModel = new EditProfileModel({
        id:this.model.get('id')
    });

    //GET editProfile/id
    editProfileModel.fetch({
        success : function(model){
            //console.log("I am fetch " + JSON.stringify(model));

            TemplateManager.get($this.template, function(template){

                console.log($(template).html());
                var html = _.template($(template).html(),{user : model});

                $this.$el.html(html);

                return $this;
            });
        }
    });
},

});

and main.js with router thing is:
.....
routes : {
    "profile/:id" : "editProfile"
},

editProfile : function(id){

    var $this = this;

    $this.model = new EditProfileModel({
        id:id
    });

    $('#content').html(
        new EditProfileView({
            model: $this.model
        })
    );
}

......

TemplateManager is just a javascript code that fetches the template on demand and stores it in the array and send the same template back if requested second time from its memory.(I got its code here)
But its showing like this :

(see the textbox value it should be admin as it is returned from the server)
Please help me, this is really wierd..................
:(
this is the html that is coming from the server (template):::

    <form id="frmEditProfile" class="form-horizontal">

            FirstName

                <input id="firstName" name="firstName" placeholder="firstName" value="<%=model.get('firstName')%>" autofocus="autofocus">

            LastName

                <input type="text" id="lastName" name="lastName" placeholder="lastName">

        <input type="hidden" name="id" value="">

                <button class="btn btn-primary" id="btnSave" type="submit">
                     Save
                </button>

    </form>

A: TemplateManager ? Did you see that in the link you post, Derrick mentions it was a bad idea ?
Anyway: you logged the $template.html(), you just need to log the model, then you should be able to see what is wrong in the console.

A: Try decoding the HTML entities that comes back from your TemplateManager.
var data = model.toJSON();
var tmpl = $("
").html($(template).html()).text();
var html = _.template(tmpl, {firstName: data.firstName});

Also change your template to this:
<input id="firstName" name="firstName" placeholder="firstName"
    value="<%= firstName %>" autofocus="autofocus">...


text:
Q: Value of reputation in real life Sorry for the heavy edit, the community comments made me understand that I asked the wrong question (maybe just in the wrong way).
Some time to think about this made me realize the real question I wanted to ask was slightly different:
Should I invest my reputation (offer a bounty) for someone else's gain?

A: Most users answer questions as a hobby as new questions create more curiosity and research. More research means more knowledge. So ultimately the knowledge you have gained by asking or answering questions should matter in your life, not reputation. Knowledge should be your main reward.
Of course, Reputation is a measure of trust. Reputation is money, You can buy good answers with it. But reputation shouldn't matter as much as knowledge when it comes to your life.
So offering a bounty shouldn't be a bad idea if you are rich (high reputation) and if you wanted to ask a question similar to it.

A: SO rep should never be taken as a measure of knowledge, experience, ability or self-worth.
For example, I have more rep than Bjarne, Randal, and Guido combined but I cower at their programming prowess.
What you can infer for someone with high rep is that he/she has chosen to invest their time in participating in the site and their effort is appreciated by others.

A: Why are you trying to commercialize, Reputation?
I value my reputation points very much. Because that amount shows how much community has believed on me so far.
And I don't think it should be regarded as an asset, or an business deal from which you invest, hoping to gain some profit.
If I offer a bounty on a question, I am giving it to get some good answers not rep points.

A: Reputation has no monetary value outside the StackExchange network. Unless you are able to turn bragging value into hard cash.
Inside the value is explained on this page.


text:
Q: Зачем нужен 13 элемент таблицы ASCII? Насколько я знаю,в таблице ASCII 10 и 13 элементы значат LF ('\n') и CR соответственно. В консоли, если нажать 'Enter', то сработает именно linefeed. Тогда зачем нужен 13 (carriage return) элемент? Где он используется? И как ввести его в консоли с клавиатуры.

A: Есть две школы танцев: одна школа танцев от Микрософт а другая школа танцев от Линукса. В школе танцев от Микрософт окончание строки обозначается парой символов CRLF (именно в таком порядке). В школе танцев от Линукса окончание строки обозначается одним символом LF. Вот так и живем. Судя по вопросу, Вы работаете под Линуксом, поэтому у Вас нет в файлах и в консольном вводе символов CR. Где взять символ CR в Линуксе? Можно взять флешку и перенести *.txt файлы, созданные Windows, в Линукс и открыть эти файлы для просмотра. Можно на Линукс написать свою программу и в этой своей программе открыть файл в бинарном режиме и писать туда строки а в конце строк писать пару символов CRLF. Что получится если файлы с разделителями CRLF просматривать в просмотрщиках от Линукс с я лично не знаю, так как сам работаю под Windows. :-) Думаю, что это зависит от просмотрщика. Вполне возможно, что есть линуксовые просмотрщики, которые понимают что бывают разные окончания строки и учитывают возможность просмотра виндовских файлов на Линуксе.
UPD1:
Да, действительно, чтение консоли винды через cin возвращает только LF. Скорее всего это потому, что поток cin открывается системой в текстовом режиме. Сейчас с ходу у меня не получилось ни считать режим открытия cin, ни считать байты из cin в бинарном режиме. Но если в винде открыть обычный файл (который с системной точки зрения тоже является потоком) по чтению в бинарном режиме, то оттуда будут читаться и CR и LF. Вернее оттуда будут читаться те символы, которые туда записаны. Но если писать в винде в файл в текстовом режиме строки, то в конце строки система добавляет именно пару CRLF. Если же писать в линуксе в текстовом режиме строки, то в конце строки система добавляет только LF. Как-то так.
Чтобы Вам система не пудрила мозги попробуйте поэкспериментировать не с системными потоками cin и cout, а с файлами, открытыми как потоки в бинарном и текстовом режиме. Откройте файл как поток в текстовом режиме и напишите в него десяток строк string ну хотя бы методом <<. А потом посмотрите бинарным редактором, что система поставила в качестве разделителя.
Ну вот, чтобы далеко не ходить этот пример выводит в файл именно пару CRLF. Файл открыт в текстовом режиме. Тестировалось под VS2017.
#include "pch.h"
#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;

int main() {

    string str = "example of line";

    ofstream offf("examplt.txt");

    offf << str.c_str();
    offf << endl;
    offf << str.c_str();
    offf << endl;
    offf << str.c_str();
    offf << endl;
    offf << str.c_str();
    offf << endl;
    offf << str.c_str();
    offf << endl;

    return 0;
}

UPD2:
Теперь проверим посимвольное чтение из файла, открытого в текстовом режиме. Вот пример:
#include "pch.h"
#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;

int main() {

    string str;

    ifstream ifff("examplt.txt");

    for (;;) {

        char ch;

        ch = ifff.get();

        cout << (int)ch << " ";

        if (ifff.eof() == true) break;

    }

    return 0;
}

Если этот пример запустить под виндой, то видно, что он читает только символ LF, хотя в файле находится пара символов CRLF. То есть при чтении текстовых файлов система фильтрует ввод и вместо CRLF возвращает пользователю только LF. Если входной поток cin открыт системой в текстовом режиме (а скорее всего так и есть), то из него тоже будет читаться только символ LF при нажатии клавиши Enter.
Однако, если в винде создавать файл через консоль командой
copy con rr.txt

то создается текстовый файл, в котором разделителями служит также пара символов CRLF. То есть при таком вводе файла с консоли система записывает в файл пару символов CRLF при каждом нажатии клавиши Enter. Напомню, что завершением процесса создания файла с консоли служит сочетание клавиш CTRL-Z.


text:
Q: Installing nvidia-current breaks Unity3D
Possible Duplicate:
No window snapping on fresh install

I've recently downloaded the 11.10 Live CD. During testing I found that dragging windows to the edge of the screen had the window properly positioned and resized.  After installing this feature no longer works.  I found that removing the proprietary drivers (apt-get remove nvidia-current nvidia-settings) restores this functionality.
Should this be reported as a bug in launchpad or is some other approach more appropriate?
--Dave


text:
Q: Alljoyn - Scons - Services overview? Building Alljoyn on my Raspberry Pi B, I used the SCONS_FLAGS
CPU=arm OE_BASE=/usr CROSS_COMPILE=/usr/bin/arm-linux-gnueabihf-
seeing that others additionally use for example:
SERVICES="about,notification,controlpanel,config,onboarding"
I was wondering is there some overview over which services are available. (couldn't find any listing of the possible options)
So would be nice if someone how knows if there is a place to look for those options can help. :)

A: To list the possible options run your normal scons command with the -h flag added.
Here is the main documentation page: https://allseenalliance.org/framework/documentation/learn/base-services
Here is the main wiki page: https://wiki.allseenalliance.org/baseservices/start


text:
Q: ServiceStack minimum configuration to get Redis Pub/Sub working between multiple Web sites/services Let's say for sake of argument I have 3 web service hosts running, and only one of them has registered any handlers (which I think equates to subscribing to the channel/topic) e.g.
var mqService = new RedisMqServer(container.Resolve<IRedisClientsManager>())
{
    DisablePriorityQueues = true
};
container.Register<IMessageService>(mqService);
container.Register(mqService.MessageFactory);

mqService.RegisterHandler<OutboundInitiateCallInfo>(ServiceController.ExecuteMessage);
mqService.RegisterHandler<DirectMailAssignmentInfo>(ServiceController.ExecuteMessage);

mqService.Start();

Now my question is, "Do I need to construct the other app hosts in the same fashion if they only publish??" e.g.
var mqService = new RedisMqServer(container.Resolve<IRedisClientsManager>())
{
    DisablePriorityQueues = true
};
container.Register<IMessageService>(mqService);
container.Register(mqService.MessageFactory);

mqService.Start(); <=== Do I need to start the service, or is the MessageFactory registration enough?

Thank you,
Stephen

A: The minimum code for a publisher is just:
var redisManager = container.Resolve<IRedisClientsManager>();

using (var mqProducer = new RedisMessageProducer(redisManager))
{
    mqProducer.Publish(new Msg { ... });
}

You could also use a MessageFactory:
var msgFactory = new RedisMessageFactory(redisMangager);

using (var mqClient = msgFactory.CreateMessageQueueClient())
{
    mqClient.Publish(new Msg { ... });
}


text:
Q: can I create list of buttons for Android app using listview or do I need to use recyclerview? I was wondering if I want to create a simple list of buttons, a recycler view will be needed or if I can make do with a listview.  Thank you

A: A list of buttons can be achieved in both the ways. But ListView is outdated. So better use RecyclerView

A: The simplest method would be to create the buttons and add them the view. I strongly recommend you to not do it the following example is for demonstratiom purpose:
onCreate...
LinearLayout root = findViewBy...
for (item: dataList) {
    Button btn = newn Button(this);
    btn.setText(item.text);
    root.addView(btn);
}

In this example Im using a linear with vertical orientation, that should be inside a scrollview.
That is bad because every view is in memory at the same time. If you have just 2 or 3 buttons then there is no problem but if the number raise to hundreds then there will be memory usage problems.
This is why ListView got deprecated, because every row was rendered. Large data set made the UI slow. Instead RecyclerView literally recyle the views as the name implies. In memory there is only the view on the screen and a bit extra, so when a view leaves the window is available to be reused by the incoming row.
By the comments I can see you are also confused with views and viewgroups. A TextView is a View it can not have another View inside. If you only need to have a click, then TextViews can use a setOnClickListener, other is the case if you need the appearance of a button. Anyway, when you create an adapter you can add any layout you want.


text:
Q: error LNK2019: unresolved external symbol... referenced in function So I'm working on serialization (I have never done it before so this is a first for me) and what I have done is created a base class called serialisable that all my other classes that can serialize can inherent from:
#include <iostream>

class Serializable{

public:
    Serializable();
    virtual ~Serializable();

    virtual void serialize();
    virtual void deserialize();

};

I then have a class that inherits from it which is my AbstractChunk class:
#pragma once

#include <iostream>
#include <list>
#include <fstream>
#include "AbstractBlock.h"
#include "Serialisable.h"

using namespace std;

#ifndef ABSTRACTCHUNK_H
#define ABSTRACTCHUNK_H
class AbstractChunk: public Serializable{
public:
    AbstractChunk();
    AbstractChunk(int x, int y);
    ~AbstractChunk();
    virtual int getXpos();
    virtual int getYpos();
    virtual bool unload();
    void serialize();
    void deserialize();

private:
    list<AbstractBlock> blocks;
    int xpos;
    int ypos;
};

#endif

and then the .cpp for my AbstractChunk (I edited out all the non important stuff):
#include "AbstractChunk.h"

void AbstractChunk::serialize(){
    ofstream chunkFile;
    chunkFile.open("ChunkData/" + to_string(xpos) + "." + to_string(ypos) + ".chunk");
    if (!chunkFile.good())
        cout << "Problem Opening Chunk File" << xpos << "." << ypos << endl;
    chunkFile << "xpos:" << xpos << "\n";
    chunkFile << "ypos:" << ypos << "\n";
    chunkFile.close();
}

void AbstractChunk::deserialize(){

}

So where is this error coming from? It's a linker error however I didn't mess with the dependencies or the project setup at all, I have a feeling I'm doing something stupid as usual.
EDIT
Here are the actual errors
Error   1   error LNK2019: unresolved external symbol "public: __thiscall Serializable::Serializable(void)" (??0Serializable@@QAE@XZ) referenced in function "public: __thiscall AbstractChunk::AbstractChunk(int,int)" (??0AbstractChunk@@QAE@HH@Z)    C:\Users\Magnus\Documents\Visual Studio 2013\Projects\Top Down Shooter\Top Down Shooter\AbstractChunk.obj   Top Down Shooter

Error   2   error LNK2019: unresolved external symbol "public: virtual __thiscall Serializable::~Serializable(void)" (??1Serializable@@UAE@XZ) referenced in function __unwindfunclet$??0AbstractChunk@@QAE@HH@Z$0  C:\Users\Magnus\Documents\Visual Studio 2013\Projects\Top Down Shooter\Top Down Shooter\AbstractChunk.obj   Top Down Shooter

A: You are not specifying the exact linking error but for sure you are missing some methods, you have declared:
class Serializable {
    ..
    virtual void serialize();
    virtual void deserialize();
}

as non pure virtual methods, and you are not implementing them. You should turn them to pure, since Serializable doesn't implement functionality but it's only an interface:
class Serializable {
    ..
    virtual void serialize() = 0;
    virtual void deserialize() = 0;
}


text:
Q: Displaying profile picture in modal dialog in AngularJS Am working on a modal dialog where in i need to display the profile picture of the user along with other data, the ui should like the image below

However the layout design that i have come up is not spanning the image in multiple rows. Below is the current design of my dialog

As you can see in the above picture, there is a blank space between Field 2 and Field 3 because of the image that is part of the Field 2. If the height of the image is more then the gap between these fields increases further.
But this is not the intended design. I need to make sure there is no gap or empty space between field 2 and 3 because of the image.
Below is my html

        Field 1:

           <input type="text" class="form-control" name="field1" id="field1" ng-model="field1" required>

           <input type="text" class="form-control" name="subfield1" id="subfield1" ng-model="subfield1" required>

        Field 2:

           <input type="text" class="form-control" name="field2" id="field2" ng-model="field2" required>

        Field 3:

           <input type="text" class="form-control" name="field3" id="field3" ng-model="field3" required>

        Field 4:

           <input type="text" class="form-control" name="field4" id="field4" ng-model="field4" required>

Am using angularjs with bootstrap.
Any pointers to resolve this layout issue will be helpful

A: You need change your layout. It must contains two cols wrapper, first col contains your main fields, second col contains subfield and image
Also, you can place image as absolute, but it is not the best way

A: It's a little bit like text wrapping around images. Add float:right style to your image.


text:
Q: MySQL node join group replication failed to due extra transactions after failover I have a 3-node mysql InnoDB cluster deployed on kubernetes(k8s). Each mysql node is a k8s POD. To test the availability, I manually removed the docker container mysql primary node corresponding to(with command 'docker rm xxxx -f). As expected, k8s recreated the container successfully. But, the newly created one failed to join the cluster(more specifically, failed to join the group replication). It complained the member has transaction not in current group. But, the extra transaction is the operation to set SESSION.GTID_NEXT to AUTOMATIC. I don't know why it is in binlog and made the rejoining failed. Would anyone give me some hint or suggestion? Thanks a lot!
MySQL version is mysql-community-server-minimal-5.7.20-1. And it's installed from rpm.
InnodDB cluster is created by adopting an existent replication group. This say I've created replication group first, then created the cluster.
MySQL log is this:

2018-03-12T08:17:21.208124Z 0 [Note] Plugin group_replication reported: 'new state x_run'
  2018-03-12T08:17:21.218361Z 0 [ERROR] Plugin group_replication reported: 'This member has more executed transactions than those present in the group. Local transactions: 925deea1-75db-4e92-86a9-00259c8d8078:1-50 > Group transactions: 925deea1-75db-4e92-86a9-00259c8d8078:1-2'
  2018-03-12T08:17:21.218433Z 0 [ERROR] Plugin group_replication reported: 'The member contains transactions not present in the group. The member will now exit the group.'
  2018-03-12T08:17:21.218444Z 0 [Note] Plugin group_replication reported: 'To force this member into the group you can use the group_replication_allow_local_disjoint_gtids_join option'
  2018-03-12T08:17:21.218493Z 3 [Note] Plugin group_replication reported: 'Going to wait for view modification'
  2018-03-12T08:17:21.218546Z 0 [Note] Plugin group_replication reported: 'A new primary with address t-baj3bsrg4cp000a1sp3g-mysql-0.mysql:3306 was elected, enabling conflict detection until the new primary applies all relay logs.'
  2018-03-12T08:17:21.218597Z 15 [Note] Plugin group_replication reported: 'This server is working as primary member.'
  2018-03-12T08:17:21.218634Z 0 [Note] Plugin group_replication reported: 'Group membership changed to t-baj3bsrg4cp000a1sp3g-mysql-0.mysql:3306, t-baj3bsrg4cp000a1sp3g-mysql-1.mysql:3306,  on view 15208422427926210:3.'
  2018-03-12T08:17:21.218655Z 0 [Note] Plugin group_replication reported: 'The member with address t-baj3bsrg4cp000a1sp3g-mysql-2.mysql:3306 was declared online within the replication group'
  2018-03-12T08:17:21.218825Z 4 [ERROR] Plugin group_replication reported: 'Unable to update certification result on server side, thread_id: 136'
  2018-03-12T08:17:21.218838Z 4 [ERROR] Plugin group_replication reported: 'Error at event handling! Got error: 1'
  2018-03-12T08:17:21.218849Z 4 [ERROR] Plugin group_replication reported: 'Fatal error during execution on the Applier process of Group Replication. The server will now leave the group.'
  2018-03-12T08:17:21.218864Z 4 [Warning] Plugin group_replication reported: 'Skipping leave operation: concurrent attempt to leave the group is on-going.'
  2018-03-12T08:17:21.218996Z 7 [Note] Error reading relay log event for channel 'group_replication_applier': slave SQL thread was killed

Bin log events shown on the failed node are:

+-------------------------------------------+-----+----------------+-----------+-------------+-------------------------------------------+
  | Log_name                                  | Pos | Event_type     | Server_id | End_log_pos | Info                                      |
  +-------------------------------------------+-----+----------------+-----------+-------------+-------------------------------------------+
  | t-baj3bsrg4cp000a1sp3g-mysql-0-bin.000003 |   4 | Format_desc    |       100 |         123 | Server ver: 5.7.20-log, Binlog ver: 4     |
  | t-baj3bsrg4cp000a1sp3g-mysql-0-bin.000003 | 123 | Previous_gtids |       100 |         190 | 925deea1-75db-4e92-86a9-00259c8d8078:1-50 |
  +-------------------------------------------+-----+----------------+-----------+-------------+-------------------------------------------+

Transaction of 925deea1-75db-4e92-86a9-00259c8d8078:1-50 shown in binlog file:

FYI, according to mysql log, setting group_replication_allow_local_disjoint_gtids_join option did work for me. But, refer to latest doc of option group_replication_allow_local_disjoint_gtids_join, it would be removed in mysql 5.7.22. So, I have to figure out the root cause of issue. Thanks!

A: My advice is to recheck your infrastructure, as you see you don't have 1 extra transaction. If you look into the information you pasted
925deea1-75db-4e92-86a9-00259c8d8078:1-50 > 925deea1-75db-4e92-86a9-00259c8d8078:1-2

1-50 vs 1-2 means you have 48 extra transactions.
Also, you are looking at a new binlog file, as you purged the older ones or there was a rotation. In this new file, the only information you see is that the Previous-GTID information is 925deea1-75db-4e92-86a9-00259c8d8078:1-50, meaning the older binlog files contained information about these 50 transactions.
You can use the commands
 SHOW BINARY LOGS;

And then
SHOW BINLOG EVENTS [IN 'log_name']

To get more information about the older events or use the mysqlbinlog utility to check the other files.


text:
Q: System.NullReferenceException или почему UserManager == null Всем доброго времени суток, изучая mvc я наткнулся на проблему создания пользователя в БД, все делалось по примеру, но при вводе данных получал вот такое письмо в браузере:

Ссылка на объект не указывает на экземпляр объекта. Описание:
  Необработанное исключение при выполнении текущего веб-запроса. Изучите
  трассировку стека для получения дополнительных сведений о данной
  ошибке и о вызвавшем ее фрагменте кода.
Сведения об исключении: System.NullReferenceException: Ссылка на
  объект не указывает на экземпляр объекта.
Ошибка источника:

Строка 32:             {
Строка 33:                 ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email};
Строка 34:                 IdentityResult result = await UserManager.CreateAsync(user, model.Password);
Строка 35:                 if (result.Succeeded)
Строка 36:                 {

ошибка в 34 строке. Ниже приведу все что я делал по уроку.
В папке Models создаю класс с именем ApplicationContext:
public class ApplicationContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationContext() : base("HomeBDConnectionString") { }

       // public DbSet<RegisterModel> RegisterModels { get; set; }

        public static ApplicationContext Create()
        {
            return new ApplicationContext();
        }
    }

Затем ApplicationUser:
public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
        {

        }
    }

Затем ApplicationUserManager:
 public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
                : base(store)
        {
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
                                                IOwinContext context)
        {
            ApplicationContext db = context.Get<ApplicationContext>();
            ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>(db));
            return manager;
        }
    }

Далее модель регистрации RegisterModel:
public class RegisterModel
    {
        [Required]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [Compare("Password", ErrorMessage = "Пароли не совпадают")]
        [DataType(DataType.Password)]
        public string PasswordConfirm { get; set; }

    }

Далее в папке App_start создаю класс Startup:
 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // настраиваем контекст и менеджер
            app.CreatePerOwinContext<ApplicationContext>(ApplicationContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
            });
        }
    }

После сам контроллер AccountController:
public class AccountController : Controller
    {
        private ApplicationUserManager UserManager
        {
            get
            {
                return HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
        }
        // GET: Account
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task<ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationUser user = new ApplicationUser { UserName = model.Email, Email = model.Email};
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    return RedirectToAction("Login", "Account");
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return View(model);
        }
    }

и наконец View Register:
@model WebHome.Models.RegisterModel

@{
    ViewBag.Title = "Register";
}

Регистрация

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Регистрация пользователя

        @Html.ValidationSummary(false)

            Электронный адрес

                @Html.EditorFor(model => model.Email)

            Пароль

                @Html.EditorFor(model => model.Password)

            Подтвердить пароль

                @Html.EditorFor(model => model.PasswordConfirm)

                <input type="submit" value="Зарегистрировать" />

}

web.config:
 <connectionStrings>
    <add name="HomeBDConnectionString" connectionString="Data Source=ETHERNETS-ПК\WINCCFLEXEXPRESS;Initial Catalog=HomeBD;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

На скриншоте видно что UserManager == null  как вообще он там может быть, когда явно создается экземпляр ?

A: Решение проблемы найти можно здесь Либо создать обычный MVC проект с типом аутентификации No Authentication. Затем руками добавить нужные сборки для работы: Microsoft.AspNet.Identity.EntityFramework Microsoft.AspNet.Identity.OWIN
Microsoft.Owin.Host.SystemWeb
Вот такие подарки преподносит VS 2015 Enterprise update 3. Всем спасибо за помощь


text:
Q: Creating as many processes you want with Fork() I'm trying to get my head around the system call fork() and I'd like to create as many grandchild processes as I'd like. Basically all I want to achieve is:
1 parent process with -> 2 child processes -> each child -> has two child processes (which are a total of 4 grandchild processes from the parent).
              parent
          /           \
         /             \
    child1             child2
    /    \               /  \
   /      \             /    \
  /        \           /      \
g.child1  g.child2  g.child3  g.child4

So far I can get 3 out of the 4 grandchild but I'm also getting a new child from one of the grandchilds. This is the output I'm getting so far:
Process Pid: 5960 PPid: 5958 (position: 1).
Process Pid: 5959 PPid: 5958 (position: 0).
Process Pid: 5962 PPid: 5959 (position: 0).
Process Pid: 5961 PPid: 5960 (position: 1).
Process Pid: 5963 PPid: 5961 (position: 1).
Process Pid: 5964 PPid: 5960 (position: 1).

Any tips?
Thank you
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>

#define NUM_HIJOS 2

void lanzanieto(int i)
{
    int proceso;

    proceso = fork();
        if (proceso > 0) {
                wait(NULL);
        } else if (proceso == 0) {
            printf("Process Pid: %d PPid: %d (position: %d).\n",getpid(),getppid(), i);
        } else if (proceso == -1) {
            perror("fallo en fork");
            exit(EXIT_FAILURE);
        }
}
int main(void)
{
    int proceso, i;

    for (i=0; i<NUM_HIJOS; i++) {
        proceso = fork();

        if (proceso == 0) {

            switch(i) {
                case 0:
                    printf("Process Pid: %d PPid: %d (position: %d).\n",getpid(),getppid(), i);
                    lanzanieto(i);
                    exit(0);
                case 1:
                    printf("Process Pid: %d PPid: %d (position: %d).\n",getpid(),getppid(), i);
                    lanzanieto(i);
                    lanzanieto(i);
                    exit(0);
            }

        }  else if (proceso == -1) {
            perror("fallo en fork");
            exit(EXIT_FAILURE);
        }

    }
    proceso = wait(NULL);
    while (proceso > 0) {
        proceso = wait(NULL);
    }
    /* ************************************* */
    if (proceso == -1 && errno != ECHILD) {
        perror("fallo en wait");
        exit(EXIT_FAILURE);
    }
}

A: Concept
Firstly, create a fork() will look like this :
id = fork();
if (id < 0) {
    /* error */
    exit(1);
}
else if (i > 0) { /* Parent > 0 */
    /* parent logic */
}
else { /* Child = 0 */
    /* child logic */
}

fork() will create a child process along side the parent process.
Therefore, if you want to match your tree (and based on your existing code), the process diagram will look like :
parent : fork()
           |--> parent : fork()
           |               |--> parent
           |               |--> child_2
           |
           |--> child_1 : fork()
                           |--> child_1
                           |--> sub_child_1

To put it simply, you have to recursively fork() inside the parent and every new child process.
However acknowledge that forking process that way aren't nice looking.
It could be better to have a function, let's say create_child(), which fork only from the parent :
parent : create_fork()
               |--> parent : create_child()
               |        |
               |        |--> parent : create_child()
               |        |      |
               |        |      |--> parent
               |        |      |--> child_3 : do_whatever()
               |        |
               |        |--> child_2 : do_whatever()
               |
               |--> child_1 : do_whatever()

Solution
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

void print_pid(char *proc_name)
{
    printf("%s: %d\n", proc_name, getpid());
}

int create_child(void)
{
    pid_t child_pid = fork();
    if (child_pid == 0)
    {
        print_pid("child");
    }
    else if (child_pid < 0)
    {
        perror("create_child");
    }
    return (child_pid);
}

int make_babies(int babies_number)
{
    /* if no baby */
    if (babies_number <= 0)
        return 0;

    /* if baby(ies) */
    pid_t child_pid = create_child();
    if (child_pid > 0)
    {
        make_babies(babies_number - 1);
        waitpid(child_pid, NULL, 0);
    }
    return child_pid;
}

int main(void)
{
    print_pid("parent");
    make_babies(50);
    return errno;
}

A: You must remember that both the child process and the parent process continue executing the same code. When you call lanzanieto(i) twice in case 1: in main(), both the parent and the child from the first call to lanzanieto(i) (which are the child and grandchild of the original parent) continue on to the second call to lanzanieto(i), so both produce another child.


text:
Q: Where should I ask questions that are too "chatty" for Stack Overflow? The FAQ is pretty clear; all questions should be specific and answerable, not open ended discussions.

If your motivation for asking the question is "I would like to participate in a discussion about ______", then you should not be asking here.

So here I am with a burning question that I'd like a broad range of opinions on but I think it'll violate this (quite sensible) policy.
Where should I ask it instead? Or, put differently, where's the best place to ask broad, software development related questions with no definitive answer, that may well generate some informed discussion?

A: The obvious answer here is to go to a related SO chat room, however, getting a real answer in some rooms (as they are under-trafficked) can be difficult.
If that turns out to be the case, try heading over to a related tag's wiki, and look for other websites specifically for that subject (forums, github project page, etc.), and you may get a better answer.
If all else fails, you could try asking the question in a different way, to minimize the amount of 'chattiness' that would ensue. However, note that many questions like that (e.g. "What is the 'best' way to do x") will get closed fast.


text:
Q: How to replace the tokenize() and pad_sequence() functions from transformers? I got the following imports:
import torch, csv, transformers, random
import torch.nn as nn
from torch.utils.data import Dataset
import torch.optim as optim
import pandas as pd
from transformers import GPT2Tokenizer, GPT2LMHeadModel, tokenize, pad_squences

And I'm getting this error:
ImportError                               Traceback (most recent call last)
<ipython-input-35-e04c63220105> in <module>
      4 import torch.optim as optim
      5 import pandas as pd
----> 6 from transformers import GPT2Tokenizer, GPT2LMHeadModel, tokenize, pad_squences

ImportError: cannot import name 'tokenize' from 'transformers' (/usr/local/lib/python3.8/dist-packages/transformers/__init__.py)

This is how I am using the tokenize() and pad_sequence() functions:
class RephraseDataset(Dataset):
    def __init__(self, data, tokenizer):
        self.data = data
        self.tokenizer = tokenizer

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        query, rephrases = self.data[index]
        tokenized_query = tokenizer.encode(query, add_special_tokens=True)
        # tokenized_query = tokenize(self.tokenizer, query)
        padded_query = tokenized_query + [tokenizer.pad_token_id] * (max_length - len(tokenized_query))
        # padded_query = pad_sequences(self.tokenizer, tokenized_query, max_length=128)
        tokenized_rephrases = [tokenize(self.tokenizer, r) for r in rephrases]
        padded_rephrases = [pad_sequences(self.tokenizer, r, max_length=128) for r in tokenized_rephrases]
        return padded_query, padded_rephrases

# Create the dataset
dataset = RephraseDataset(data, tokenizer)

# Create a dataloader
dataloader = torch.utils.data.DataLoader(
    dataset,
    batch_size=32,
    shuffle=True,
)

How can I fix this problem? I couldn't find anything in the docs. What version should I roll transformers back to?

A: [EDIT]
This happend because transformers version to old for this. Please update transformers with pip install -U transformers


text:
Q: Extract tags from xml using python I'm trying to extract tags from an XML file using RE in Python. I need to extract nodes that start with tag "< PE" and their corresponding Unit IDs which are nodes above each tag "<PE". The file can be seen here
When I use the below code, I don't get the correct tags "<unit IDs", that is, the ones that correspond to each tag "<PE". For example, in my output, the content extracted from tag "<PE" with "<Unit ID=250" is actually "<Unit ID=149" in the original file. Besides, the code skips some tags "<Unit ID". Does anyone see in my code where's the error?
import re

t=open('ALICE.per1_replaced.txt','r')

t=t.read()

unitid=re.findall('<unit.*?"pe">', t, re.DOTALL)
PE=re.findall("<PE.*?</PE>", t, re.DOTALL)

a=zip(unitid,PE)

tp=tuple(a)

w=open('Tags.txt','w')

for x, j in tp:
    a=x + '\n'+j + '\n'

    w.write(a)

w.close()

I've tried this version as well but I had the same problems:
with open('ALICE.per1_replaced.txt','r') as t:
  contents = t.read()

unitid=re.findall('<unit.*?"pe">', contents,  re.DOTALL)
PE=re.findall('<PE.*?</PE>', contents, re.DOTALL)
with open('PEtagsper1.txt','w') as fi:
    for i, p in zip(unitid, PE):
        fi.write( "{}\n{}\n".format(i, p))

my desired output is a file with tags "<Unit ID=" followed by the content within the tag that starts with "<PE" and ends with "" as below:
<unit id="16" status="FINISHED" type="pe">
<PE producer="A1.ALICE_GG"><html>
  <head>

  </head>
  <body>
    Eu vou me atrasar!' (quando ela voltou a pensar sobre isso mais trade,
    ocorreu-lhe que deveria ter achado isso curioso, mas na hora tudo pareceu
    bastante natural); mas quando o Coelho de fato tirou um relógio do bolso
    do colete e olhou-o, e então se apressou, Alice pôs-se de pé, pois lhe
    ocorreu que nunca antes vira um coelho com um colete, ou com um relógio de
    bolso pra tirar, e queimando de curiosidade, ela atravessou o campo atrás
    dele correndo e, felizmente, chegou justo a tempo de vê-lo entrar dentro
    de uma grande toca de coelho sob a cerca.
  </body>
</html></PE>

A: You seem to have multiple  tags under each  tag (eg, for unit 3), thus the zip doesn't work correctly. As @Error_2646 noted in comments, some XML or beautiful soup package would work better for this job.
But if for whatever reason you want to stick to regex, you can fix this by running a regex on the list of strings returned by the first regex. Example code that worked on the small part of the input I downloaded:
units=re.findall('<unit.*?</unit>', t, re.DOTALL)
unitList = []
for unit in units:
    #first get your unit regex
    unitid=re.findall('<unit.*?"pe">', unit, re.DOTALL) # same as the one you use
    #there should only be one within each
    assert (len(unitid) == 1)
    #now find all pes for this unit
    PE=re.findall("<PE.*?</PE>", unit, re.DOTALL) # same as the one you use
    # combine results
    output = unitid[0] + "\n"
    for pe in PE:
        output += pe + "\n"
    unitList.append(output)

for x in unitList:
    print(x)


text:
Q: How can I use linear/logistic regression for inference with colinear variables and a smallish dataset? I have a dataset of around 120 observations, with 30 calculated variables and I am trying to predict a continuous response (result of an experiment) using those 30 variables. Ideally the smallest subset of those 30 variables that best explain the data.
Many of these variables are colinear, as there are some secondary variables which are based on combinations of some of the other variables. I am unsure about the best way to proceed. I can use variance inflation factor, and my own knowledge of the subject, to choose between correlated variables and remove any collinearity before using a regression model. I would rather choose myself which variables to include rather than allowing the model to choose arbitrarily between two collinear variables.
I would prefer to use the lasso approach to produce the most sparse model possible, but I am concerned that I would contaminate the reliability of the model by preselecting variables, rather than allowing the algorithm to select variables from the entire set of 30.
As I only have ~120 observations, I have found that the validation set approach to be too unstable. If I split the data 80%-20% between training and validation sets, I find that the coefficient estimates are highly variable between different validation sets, and I will get a very different estimation of the coefficients, and MSE/$R^2$ based on the random training/validation set selectec. As I am looking for inference, and therefore need a stable estimation of the coeffecients, I am hoping that I can use a leave one out cross validation approach to produce the most robust estimate of the coefficients.
My current approach is

*

*Run VIF to find colinear variables

*Train either a least square or logistic regularisation using leave one cross validation or 10-fold cross validation

*Obtain a robust coefficient estimates for the variables

*Build a new predictive model using these variables and test it on the data, maybe using a holdout set?

My primary interest is inference, I would like to know what coefficients are most important. I would also like to use these coefficients to predict future (continuous) observations.

A: You have 30 total variables, making the possibility of generating all possible linear models nearly intractable:
$$\sum^n_{k=1} \binom{30}{k} = 1.1 * 10^9$$.
Not to mention the addition of interactions,
$$y \sim \beta_0 + \beta_1 a + \beta_2 b + \beta_3 (a*b)$$.
I agree with your idea to try VIF, because multiple co-linear features would increase your likelihood of over fitting.
One possible solution to your feature selection issue would be to use Feature Importance generated from a random forest model. Python's library scikitlearn identifies this technique as tree-based feature selection.
I agree that you have too few observations to ascertain the level of overfitting with 120 observations and 30 features in the model.  However, if you reduce the feature space with feature importance or variance you will be much better off in relying on the CV results.
Lastly, with your stated goal of using a linear model wherein you have 30 variables and some number of outcome variables (not sure if this is a classification or regression problem). A careful inspection of each of the 30 variables might lead to some better insight as to which offer more predictive power in specific scenarios as opposed to others.


text:
Q: How to Get the Base Url of a Server-Side Blazor App I have a server-side blazor app and I need to know it's base url (e.g. https://localhost:1234 or https://my-host.com/appname).
In a traditional ASP.NET web application, I could inspect the Request property of a controller and retrieve the information from it (there's Scheme, Host, and PathBase for that). But since this is a server-side running Blazor app, there is no Request object (at least in my understanding and except maybe when serving the Index.cshtml).
How can I then know, to which URL my app has been deployed to and is running at?
Ideally, I would already have this information at startup time, so that I can configure my services accordingly.

A: Getting it inside a page is easy:
@inject NavigationManager Navigator

<p>@Navigator.BaseUri</p>

But you can't use a NavigationManager in the Startup class.

A: In .Net Core 3.0 onwards IUriHelper has been replaced by NavigationManager
To use inside a Blazor page:
    @inject NavigationManager NavigationManager

   //example usage
   var client = _clientFactory.CreateClient();
   client.BaseAddress = new Uri(NavigationManager.BaseUri);


text:
Q: If $A + \Delta A$ has eigenvalue $\lambda$, show that $A$ has eigenvalue $\lambda + \Delta \lambda$. $A$ is symmetric and can be diagonalised as $A = V\Lambda V^{-1}$, where $\Lambda$ is a diagonal matrix with eigenvalues of $A$ and $V$ is an orthogonal matrix with column vectors equal to eigenvectors of $A$.
If $A + \Delta A$ has eigenvalue $\lambda$,  show that $A$ has eigenvalue $\lambda + \Delta \lambda$ with
$$\Delta \lambda = 0 \qquad\text{or}\qquad |\Delta \lambda| = ||(\lambda I - \Lambda)^{-1}||_2^{-1}.$$
My attempt:
$$A u = (\lambda + \Delta \lambda)u$$
$$A u = \lambda u + \Delta \lambda u$$
$$- \Delta \lambda u = (\lambda I - A)u$$
$$-(\lambda I - A)^{-1} \Delta \lambda u = u$$
$$||u||_2 = ||(\lambda I - A)^{-1} \Delta \lambda u||_2$$
Where do I go from here?

A: The key to this problem, I think, is to realize that $A + \Delta A$ doesn't tell us anything about $A$.

By replacing $A$ with $(A - \lambda I)$, suppose without loss of generality that $\lambda = 0$.
We are given that $A + \Delta A$ has eigenvalue $0$, and we want to show that it must either hold that $A$ has eigenvalue $0$ or $A$ has eigenvalue $\Delta \lambda$ with $|\Delta \lambda| = \|\Lambda^{-1}\|^{-1}$. Equivalently, if $A$ does not have $0$ as an eigenvalue (i.e. $A$ is invertible), then $A$ has an eigenvalue $\Delta \lambda$ with $|\Delta \lambda| = \|\Lambda^{-1}\|^{-1}$.
This is easy to see: suppose that $A$ is invertible. We write
$$
\Lambda = \pmatrix{\lambda_1 \\ & \ddots \\ && \lambda_n},
$$
where each $\lambda_i$ is an eigenvalue of $A$. We note that
$$
\Lambda^{-1} = \pmatrix{\lambda_1^{-1}\\ & \ddots \\ && \lambda_n^{-1}},
$$
from which it follows that
$$
\|\Lambda^{-1}\|_2 = \max_{j=1,\dots,n} |\lambda_j|^{-1} = (\min_{j=1,\dots,n} |\lambda_j|)^{-1}.
$$
Thus, we have $\|\Lambda^{-1}\|_2^{-1} = \min_{j=1,\dots,n}|\lambda_j|$. So, it is indeed the case that $A$ has an eigenvalue $\Delta \lambda = \lambda_j$ for which $|\lambda_j| = \|\Lambda^{-1}\|^{-1}$, which is what we wanted to show.

A less "matrix-dependent" approach: again, suppose WLOG that $\lambda = 0$, and suppose that $A$ is invertible. We note that for $z \in \Bbb C$,
$$
A - zI \text{ is invertible }\iff I - z A^{-1} \text{ is invertible }.
$$
For $z$ with $|z|$ sufficiently small, we see that $I - zA^{-1}$ must be invertible because the inverse can be expressed via the convergent Neumann series
$$
(I - zA^{-1}) = \sum_{k=0}^\infty A^{-k} z^k.
$$
The radius of convergence of this series is equal to $\rho(A^{-1})^{-1}$, which is equal to $\|\Lambda^{-1}\|_2^{-1}$ (since $A$ is real and symmetric, this is in turn equal to $\|A^{-1}\|_2^{-1}$). By the analyticity of holomorphic functions, there exists a $z \in \Bbb C$ with $|z| = \|\Lambda^{-1}\|^{-1}$ at which the function $(I - zA^{-1})^{-1} = A^{-1}(A - zI)^{-1}$ has a singularity, which is to say that $A - zI$ fails to be invertible. In other words, such a $z$ must be an eigenvalue of $A$.


text:
Q: Commutator subgroup is the minimal normal subgroup such that quotient group is abelian I was recently asked this in Abstract Algebra class on group theory:

Let G be a group and G' its commutator subgroup (i.e. its minimal subgroup containing all commutators $ [x,y] = xyx^{-1}y^{-1} $ where $ x,y \in G $ ). Where are asked to show G' is the minimal normal subgroup such that the quotient group $  G/G' $ is Abelian (if $ H \unlhd G $ and G/H is Abelian then we must have $ G' < H $)

To be honest I have tried but could not seem to be able to solve this. I have shown G' is normal and quotient group $ G/G' $ is abelian, but I cannot prove G' is minimal normal subgroup with this property. I really would appreciate the help on this. Thanks all


text:
Q: Git deployment to Azure Websites suddenly taking over 30 minutes I'm deploying to Azure Websites using a git repository. I've been using it for some months now and pushing my ASP.NET MVC 5 application triggers the deployment, which has consistently only ever been one or two minutes.
Today, it is now taking 20-30 minutes to do a deployment. See the log file below. You can see a few multi-minute gaps for no explicable reason.
2015-03-04T20:36:06  Updating branch 'master'.
2015-03-04T20:43:52  Updating submodules.
2015-03-04T20:44:07  Preparing deployment for commit id 'cdd77ccfd7'.
2015-03-04T20:44:39  Generating deployment script.
2015-03-04T20:44:46    Using cached version of deployment script (command: 'azure -y --no-dot-deployment -r "D:\home\site\repository" -o "D:\home\site\deployments\tools" --aspWAP "D:\home\site\repository\Mitigation.Ebb.Web\Mitigation.Ebb.Web.csproj" --solutionFile "D:\home\site\repository\Mitigation.sln"').
2015-03-04T20:44:56  Running deployment command...
2015-03-04T20:44:57    Command: "D:\home\site\deployments\tools\deploy.cmd"
2015-03-04T20:45:00    Handling .NET Web Application deployment.
2015-03-04T20:45:44    All packages listed in packages.config are already installed.
2015-03-04T20:46:19      Restoring NuGet packages...
2015-03-04T20:46:21      To prevent NuGet from downloading packages during build, open the Visual Studio Options dialog, click on the Package Manager node and uncheck 'Allow NuGet to download missing packages'.
2015-03-04T20:46:26      All packages listed in packages.config are already installed.
2015-03-04T20:46:46      Restoring NuGet packages...
2015-03-04T20:46:48      To prevent NuGet from downloading packages during build, open the Visual Studio Options dialog, click on the Package Manager node and uncheck 'Allow NuGet to download missing packages'.
2015-03-04T20:47:14      All packages listed in packages.config are already installed.
2015-03-04T20:47:32      Restoring NuGet packages...
2015-03-04T20:47:34      To prevent NuGet from downloading packages during build, open the Visual Studio Options dialog, click on the Package Manager node and uncheck 'Allow NuGet to download missing packages'.
2015-03-04T20:47:37      All packages listed in packages.config are already installed.
2015-03-04T20:47:40      CEA.Web.Infrastructure -> D:\home\site\repository\Mitigation.Ebb.Infrastructure\bin\Release\CEA.Web.Infrastructure.dll
2015-03-04T20:47:46      CEA.Web.Mvc -> D:\home\site\repository\CEA.Web.Mvc\bin\Release\CEA.Web.Mvc.dll
2015-03-04T20:48:08      Restoring NuGet packages...
2015-03-04T20:48:11      To prevent NuGet from downloading packages during build, open the Visual Studio Options dialog, click on the Package Manager node and uncheck 'Allow NuGet to download missing packages'.
2015-03-04T20:48:16      All packages listed in packages.config are already installed.
2015-03-04T20:49:46      Mitigation.Ebb -> D:\home\site\repository\Mitigation.Ebb\bin\Release\Mitigation.Ebb.dll
2015-03-04T20:53:09      Mitigation.Ebb.Web -> D:\home\site\repository\Mitigation.Ebb.Web\bin\Mitigation.Ebb.Web.dll
2015-03-04T20:53:22      Transformed Web.config using D:\home\site\repository\Mitigation.Ebb.Web\Web.Release.config into obj\Release\TransformWebConfig\transformed\Web.config.
2015-03-04T20:53:24      Copying all files to temporary location below for package/publish:
2015-03-04T20:53:27      D:\local\Temp\1aaba3b6-a9af-4653-991d-87e104112d61.
2015-03-04T21:02:19    KuduSync.NET from: 'D:\local\Temp\1aaba3b6-a9af-4653-991d-87e104112d61' to: 'D:\home\site\wwwroot'
2015-03-04T21:02:21    Copying file: 'Web.config'
2015-03-04T21:02:25    Copying file: 'bin\Mitigation.Ebb.dll'
2015-03-04T21:02:28    Copying file: 'bin\Mitigation.Ebb.Web.dll'
2015-03-04T21:02:31    Copying file: 'Views\Home\Contact.cshtml'
2015-03-04T21:02:35    Copying file: 'Views\Shared\EditorTemplates\StringMultiline.cshtml'
2015-03-04T21:02:38    Copying file: 'Views\Shared\EditorTemplates\ContactUs\ReasonForContact.cshtml'
2015-03-04T21:02:42    Finished successfully.
2015-03-04T21:02:51  Deployment successful.

The only change that occurred today was I tried adding Application Insights to my app. However, the push with that deployed quickly. I've rolled back that change so Application Insights is no longer in the project, but it is still deploying slowly.
Azure status page reports no issues in West US region where I'm running.
UPDATE: My last deployment ran in just a minute, so it's not consistent.


text:
Q: Prevent Xcode from indexing a lot of JSON files and include them separately to make Xcode faster I am working with the iOS library Lottie and my problem is that if I add more than 10 Lottie json animations into Xcode it gets stuck. I have actually more than 100 JSON files which I want to use for animation however Xcode is indexing all those files for index highlighting.
If I click on one of those json files by mistake then Xcode crashes. This happens because those JSON files are being loaded in Xcode as if they were Swift classes. I am forced to download those JSON files from a CDN in order to get it to work but I want them to be saved locally.
However I have noticed that downloading those files take too long and my animations do not work how they should. Sometimes they don't even play due to the latency of downloading.
My question is how and where should I store these JSON files properly in Xcode? What is Apple's recommendation? How can I add a bundle programmatically so those files are not being indexed within Xcode?
Why can't I save json files in a .xcassets asset catalog and load it from Lottie? Lottie does not recognize that those are json files and instead handles them as something really strange. So this seems not to be a solution.
I have had this problem for a few weeks and I really don't have any clue what to do. Can anyone give me an advice?


text:
Q: Python regex to extract a word which has + symbol We have text as
"Google and Bert+Amazon+Alexa'

The expected output is when we pass a search text as Google and Bert then the output should be "Google and Bert" and it should not match when the input search word is Google. Need to match to the complete text which can be either before or in between or after symbol "+"
pattern = r'(?:^|\+)' + 'Amazon' + '(?:$|\+)'
re.search(pattern, "Google and Bert+Amazon+Alexa").group()

Output is: +Amazon+ but the expected output is Amazon

A: You do not need a regex here in fact, just split the string with + and check if the search is in the resulting list:
s = "Google and Bert+Amazon+Alexa"
search = "Google and Bert"
if search in s.split('+'):
    print(search)
else:
    print("NO MATCH!")

See the Python demo.
The result of s.split('+') will be ['Google and Bert', 'Amazon', 'Alexa'] and you will be searching for Google and Bert in this list, and returning/displaying the search phrase.
Regarding the regex approach, you may try something like pattern = r'(?:^|\+)(' + re.escape(search) + ')(?:$|\+)' and then re.search(pattern, "Google and Bert+Amazon+Alexa").group(1), but it does not seem what you really need here.

A: When you call search, Use at least a one capturing group and the captured text is returned like this:
import re
pattern = r'(?:^|\+)(Amazon)(?:$|\+)'
r = re.search(pattern, "Google and Bert+Amazon+Alexa")
print(r.groups())  #  ('Amazon',)
print(r.group(1))  #  'Amazon' not group(0)

In match and search: group() and group(0) will return the entire match, the captured groups are in groups()