text:
Q: How to inject BotAuthentication into the controller I am seeking help to use BotAuthentication through injection, so that I can use the secrets from keyvault to pass the MicrosoftAppId and MicrosoftAppPassword.
Thanks.
I am using BotBuilder V3.15.3, which allows me to use BotAuthentication and pass the MicrosoftAppId and MicrosoftAppPassword as the parameters. But since, I have these values fetched from keyvault, I am unable to use the annotation, because I cannot read the keyvault as const. There is another provision by using CredentialProviderType, which takes ICredentialProvider type.
[BotAuthentication(CredentialProviderType = typeof(CustomCredentialProvider))]
But, this type does not take appId as parameter. How do I inject appId and appPassword into it?
///Controller code

[BotAuthentication(CredentialProviderType =typeof(NewStaticCredentialProvider))]

public class MessagesController : ApiController
    {}

///CredentialProvider code

public interface ICredentialProvider

{

        Task<bool> IsValidAppIdAsync(string appId);

        Task<string> GetAppPasswordAsync(string appId);

        Task<bool> IsAuthenticationDisabledAsync();
    }

    public class SimpleCredentialProvider : ICredentialProvider
    {
        public string AppId { get; set; }

        public string Password { get; set; }

        public Task<bool> IsValidAppIdAsync(string appId)
        {
            return Task.FromResult(appId == AppId);
        }

        public Task<string> GetAppPasswordAsync(string appId)
        {
            return Task.FromResult((appId == this.AppId) ? this.Password : null);
        }

        public Task<bool> IsAuthenticationDisabledAsync()
        {
            return Task.FromResult(string.IsNullOrEmpty(AppId));
        }
    }

    public sealed class NewStaticCredentialProvider : SimpleCredentialProvider
    {
        public NewStaticCredentialProvider(string appId, string password)
        {
            this.AppId = Secrets.MicrosoftAppId;
            this.Password = Secrets.MicrosoftAppPassword;
        }
    }

In the annotation, I do not see a way to pass the app id and password.
Am I missing something?

A: I have figured out the solution. The problem was that I had my own interface with same name ICredentialProvider because of which it couldn't resolve the instance. I kept only SimpleCredentialProvider class and changed that to some other name. And bingo!


text:
Q: Can you change a Unity theme? I'm pretty new to Ubuntu, so this might not make sense (?) but I see a lot of GNOME Shell themes online, and they make people's computers look awesome, but I like the look of the Unity environment more, so I don't want to switch to the GNOME desktop... is there a way to either install GNOME shell themes without removing Unity, or is there such thing as a Unity theme? (I haven't been able to find one or an answer to this...)

A: If you go to
System Settings/Appearance/Look
you can select one of the default themes.
Of course, you can search for unity themes online. I have never done it until now. There are some examples on this site:
http://kb.openstudioproject.com/content/ubuntu/best-ubuntu-1404-trusty-themes
It seems that you should install unity-tweak-tool first:
sudo apt-get install unity-tweak-tool

and then look for themes online, and add the repository, install the theme, and then switch to it using unity-tweak-tool.
sudo add-apt-repository ppa:numix/ppa
sudo apt-get update
sudo apt-get install numix-gtk-theme numix-icon-theme

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the point of edits that make source citations more visible? Someone recently edited my question on a SE site and made the source citation more visible.
The editor replaced my

[Source]

with

From the Wikipedia article about Entropy (Source view via The Internet Archive):

What is the point of such edits?
Thoughts
When I write on SE, I usually try to make source citations as unintrusive as possible, in order not to distract from the question or answer. Most readers will probably not be interested in the source citation for a definition.
Readers who are interested in the source citation can still find out what it is by opening it. Also, if on desktop, they can hover over the link with their mouse to see the website in the status bar. If on mobile, they can hold the link and most browsers would show where it leads to without opening it.
I do not see the point of this "correction". I checked the Guidelines for Reviewing for relevant information, but couldn't find any.

A: I support such edits because they provide the reader of the post with more information upon which to decide whether they need to visit the link. Perhaps they followed it on a previous visit to the post or perhaps it is a link they were aware of before visiting the post the first time.

A: (converting comment to an answer)
The information being shown directly rather than just being visible when examining the link has several advantages:

*

*The information in the link but it requires hovering over which might be a problem:

*

*there is also screen readers - reading out the sentence "From the Wikipedia article about Entropy (Source view via The Internet Archive)" is more informative and easier to understand than trying to read out the link

*anecdotal example (but I doubt I'm alone), I sometimes have to zoom in a page to make the text readable. But the hover tooltip remains the same size as before which means it's hard to read for me. The way to do it is to copy the link text, paste it in a text editor then zoom that. It's not very convenient.

*Another problem might be mobile devices where reading the full link text can be hard.

*

*on a smaller screen the link https://web.archive.org/web/20161220075809/https://en.wikipedia.org/wiki/Entropy#Reversible_process takes a lot of space and it's annoying to read.

*anecdotal again, I don't browse often from my phone but in my experience that involves pressing and holding on the link for more than 5 seconds (Brave browser on Android. Not sure if there is a setting for it). Even then, that doesn't show me the full link, just the beginning. Your particular link shows up as web.archive.org/web/20161.... The way to see the full thing is either to open it (also not ideal) or copy it out somewhere (ditto). That's significantly slower and less convenient than just reading what the link is about and where it leads.

Even assuming normally sighted person on a desktop, there is still no downside to providing more information about the link without requiring people to hover over it. The miniscule amount of extra characters doesn't negatively impact the message of the post. It can only enhance it or, at worse, leave it the same.


text:
Q: how to store and send $_FILES via javascript/php I'm trying to set up a form that can upload to both YouTube and Vimeo simultaneously. I would prefer to use Posterous.com for something like this, but since they've been acquired by twitter, their help team has dropped off the face of the earth as my emails are now going unanswered (they've removed a bunch of services)...
So anyways here's how the youtube process is supposed to work:

*

*Set a title and category for the video you want to upload via webform

*submit form, get an access token back from youtube

*another form is generated, allowing you to select the file to upload

*submit form, access token and file are sent and youtube uploads the video

What I'm trying to do is turn this into a single step with a drag and drop uploader:

*

*drag and drop file onto page

*javascript grabs the file information, sets the filename as the video title and uses a default category

*javascript calls php and sends filename & category to youtube, gets access token back and creates form with file input

*after getting the token, send a POST (via PHP) request with file upload stored in a session variable (right now I have to select the file again and click submit)

shouldn't I be able to use the file information from the first step, store it in a session variable and programmatically submit the token and file information via php? I don't know how to send this data like it was sent as a form submission and I'm not always getting response codes back from youtube to fix my code.
this may be the answer I need: sending xml and headers via curl but I don't know how to set the $xmlString or $videoData
EDIT::
I think I need to do this via PHP, not javascript because I'm trying to modify the following code:
/**
 * Create upload form by sending the incoming video meta-data to youtube and
 * retrieving a new entry. Prints form HTML to page.
 *
 * @param string $VideoTitle The title for the video entry.
 * @param string $VideoDescription The description for the video entry.
 * @param string $VideoCategory The category for the video entry.
 * @param string $nextUrl (optional) The URL to redirect back to after form upload has completed.
 * @return void
 */

function createUploadForm($videoTitle, $videoCategory, $nextUrl = null) {
$httpClient = getAuthSubHttpClient();
$youTubeService = new Zend_Gdata_YouTube($httpClient);
$newVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

$newVideoEntry->setVideoTitle($videoTitle);

//make sure first character in category is capitalized
$videoCategory = strtoupper(substr($videoCategory, 0, 1))
    . substr($videoCategory, 1);
$newVideoEntry->setVideoCategory($videoCategory);

// convert videoTags from whitespace separated into comma separated

$tokenHandlerUrl = 'https://gdata.youtube.com/action/GetUploadToken';
try {
    $tokenArray = $youTubeService->getFormUploadToken($newVideoEntry, $tokenHandlerUrl);
    if (loggingEnabled()) {
        logMessage($httpClient->getLastRequest(), 'request');
        logMessage($httpClient->getLastResponse()->getBody(), 'response');
    }
} catch (Zend_Gdata_App_HttpException $httpException) {
    print 'ERROR ' . $httpException->getMessage()
        . ' HTTP details
<textarea cols="100" rows="20">'
        . $httpException->getRawResponseBody()
        . '</textarea>
'
        . ''
        . 'click here to view details of last request
';
    return;
} catch (Zend_Gdata_App_Exception $e) {
    print 'ERROR - Could not retrieve token for syndicated upload. '
        . $e->getMessage()
        . '
'
        . 'click here to view details of last request
';
    return;
}

$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];

// place to redirect user after upload
if (!$nextUrl) {
    $nextUrl = $_SESSION['homeUrl'];
}

//instead of echoing the form below, send $_FILES from previous form submit

print <<< END

    <form id="uploadToYouTubeForm" action="${postUrl}?nexturl=${nextUrl}" method="post" enctype="multipart/form-data">
    <input id="uploadToYouTube" name="file" type="file" />
    <input name="token" type="hidden" value="${tokenValue}"/>
    <input value="Upload Video File" type="submit" />
    </form>

END;
}

A: I think I may have a solution. Below is the form I want to use:

<form id="upload" action="" method="POST" enctype="multipart/form-data" class="form-horizontal">
  <fieldset>
    <legend>
Video File Upload
</legend>
    <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="1000000000" />

Drag and drop a video file from your computer here. Or use the 'File upload' button below.

    Files to upload:
    <input type="file" id="fileselect" name="fileselect[]" />
    <button class="btn" id="submitbutton" type="submit">Upload Files</button>

    Title
    <input type="text" id="video-title" class="span4" placeholder="Video Title"/>
    Category
    <select id="video-category" name="videoCategory" class="span4">
      <option value="Autos">Autos & Vehicles</option>
      <option value="Music">Music</option>
      .......
      <option value="Entertainment" selected>Entertainment</option>
    </select>
    <input id="token" type="text" placeholder="token"/>

</fieldset>
</form>

by leaving the action attribute blank, (and using script I already had in place to respond to user interaction) I can ensure the form is submitted programmatically via javascript:

_js/video_app.js:
/**
* Zend Framework
* @package    Zend_Gdata
....
/**
* provides namespacing for the YouTube Video Application PHP version (ytVideoApp)
**/
var ytVideoApp = {};
/**
* Sends an AJAX request to the server to retrieve a list of videos or
* the video player/metadata.  Sends the request to the specified filePath
* on the same host, passing the specified params, and filling the specified
* resultDivName with the resutls upon success.
* @param {String} filePath The path to which the request should be sent
* @param {String} params The URL encoded POST params
* @param {String} resultDivName The name of the DIV used to hold the results
*/
ytVideoApp.sendRequest = function(filePath, params, resultDivName) {
  if (window.XMLHttpRequest) {
    var xmlhr = new XMLHttpRequest();
  } else {
    var xmlhr = new ActiveXObject('MSXML2.XMLHTTP.3.0');
  }

  xmlhr.open('POST', filePath);
  xmlhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  xmlhr.onreadystatechange = function() {
    var resultDiv = document.getElementById(resultDivName);
    if (xmlhr.readyState == 1) {
      resultDiv.innerHTML = 'Loading...';
    } else if (xmlhr.readyState == 4 && xmlhr.status == 200) {
      if (xmlhr.responseText) {
        resultDiv.innerHTML = xmlhr.responseText;
      }
    } else if (xmlhr.readyState == 4) {
      alert('Invalid response received - Status: ' + xmlhr.status);
    }
  }
  xmlhr.send(params);
}

ytVideoApp.prepareSyndicatedUpload = function(videoTitle, videoCategory, fileContents) {
  var filePath = '_scripts/operations.php';
  var params = 'operation=create_upload_form' +
    '&videoTitle=' + videoTitle +
    '&videoCategory=' + videoCategory;
  ytVideoApp.sendRequest(filePath, params, ytVideoApp.SYNDICATED_UPLOAD_DIV);
}

_scripts/operations.php:
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_YouTube');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_App_Exception');
/*
 * The main controller logic.
 *
 * POST used for all authenticated requests
 * otherwise use GET for retrieve and supplementary values
 */
session_start();
setLogging('on');
generateUrlInformation();

if (!isset($_POST['operation'])) {
  // if a GET variable is set then process the token upgrade
  if (isset($_GET['token'])) {
    updateAuthSubToken($_GET['token']);
  } else {
    if (loggingEnabled()) {
      logMessage('reached operations.php without $_POST or $_GET variables set', 'error');
      header('Location: add-content.php');
    }
  }
}

$operation = $_POST['operation'];

switch ($operation) {
  ....
  case 'create_upload_form':
    createUploadForm($_POST['videoTitle'],
                     $_POST['videoCategory'],
                     $_POST['videoContents']);
  break;
  ....
  default:
    unsupportedOperation($_POST);
  break;
}

function createUploadForm($videoTitle, $videoCategory, $nextUrl = null) {
  $httpClient = getAuthSubHttpClient();
  $youTubeService = new Zend_Gdata_YouTube($httpClient);
  $newVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

  $newVideoEntry->setVideoTitle($videoTitle);

  //make sure first character in category is capitalized
  $videoCategory = strtoupper(substr($videoCategory, 0, 1))
                              . substr($videoCategory, 1);
  $newVideoEntry->setVideoCategory($videoCategory);

  // convert videoTags from whitespace separated into comma separated
  $tokenHandlerUrl = 'https://gdata.youtube.com/action/GetUploadToken';
  try {
    $tokenArray = $youTubeService->getFormUploadToken($newVideoEntry, $tokenHandlerUrl);
    if (loggingEnabled()) {
      logMessage($httpClient->getLastRequest(), 'request');
      logMessage($httpClient->getLastResponse()->getBody(), 'response');
    }
  } catch (Zend_Gdata_App_HttpException $httpException) {
    print 'ERROR ' . $httpException->getMessage()
                   . ' HTTP details
<textarea cols="100" rows="20">'
                   . $httpException->getRawResponseBody()
                   . '</textarea>
'
                   . ''
                   . 'click here to view details of last request
';
    return;
  } catch (Zend_Gdata_App_Exception $e) {
    print 'ERROR - Could not retrieve token for syndicated upload. '
                 . $e->getMessage()
                 . '
'
                 . 'click here to view details of last request
';
    return;
  }
  $tokenValue = $tokenArray['token'];
  $postUrl = $tokenArray['url'];
  // place to redirect user after upload
  if (!$nextUrl) {
    $nextUrl = $_SESSION['homeUrl'];
  }

  //instead of outputting the form below, send variables (json???) to be interpreted by xmlhr in _js/video_app.js
  //print <<< END
  //

  //
url: ${postUrl}?nexturl=${nextUrl}

  //<form id="uploadToYouTubeForm" action="temp.php" method="post" enctype="multipart/form-data">
  //<input id="uploadToYouTube" name="file" type="file" onchange="autoUploadToYouTube();" />

  //token: <input id="token" name="token" type="text" value="${tokenValue}"/>

  //<input value="Manual upload" type="submit" />
  //</form>
  //END;
  //}

So the first javascript listens for the drag & drop (on the div) or change() event for the input type="file". The form is not actually submitted, but data is gathered and and sent via ajax to the php script which returns the token and url needed for upload. The original PHP script then outputs a form to select the file (and a hidden field containing the token). INSTEAD of that, I want to pass the url and token as variables and use the XMLHttpRequest to put those variables in the action attribute of the form as well set the key to a hidden input field's value. Then the field can be submitted via $('#uploadToYouTubeForm').submit();
The only problem that may arise is sending additional information to the youtube app, I'm hoping it will simply ignore it or i may need to programmatically remove the fields that youtube won't accept (title, category, max file size)....


text:
Q: How to know if people ever meet when they are walking two different routes at the same time which intersect. So there are two people, person A and person B, walking their own route at the same time. These routes take an arbitrary amount of time to walk and they start at an arbitrary point along this route. So if we take an intersection point p, I would like to know if they ever meet on that point.
So I thought of the problem like this:
There is a certain intersection time in a round $I_A$ at which person A is at the intersection point. So if $r_A$ is the time it takes for A to finish one route then $I_A \equiv t \mod r_A$ (where $t$ is the time, with $t = 0$ being at the start of the hike).
For B this would be the same, so: $I_B \equiv t \mod r_B$. I have also rewritten this expression to $t = r_B \cdot k + I_B = r_A \cdot l + I_A$ where $k, l \in \mathbb{N}$
However, I couldn't really find any solutions. (Or the infinite set of solutions that should be there or not).

A: In general there does not need to be a solution. Assume that person A walks on the real line between 0 and 1 back and forth with speed 1 and person B walks between 1 and $1+\pi$ back and forth with speed 1. Now depending on the starting point of person A and B they will meet either never or once. Assume that they meet a second time, then person B has walked a distance $2n\pi$ with some $n\in \mathbb{N}\setminus \{0\}$ and person A has traveled a distance $m\in \mathbb{N}\setminus\{0\}$. As both are moving with the same speed the two distances have to be equal, but this implies $\pi=\frac{m}{2n}\in \mathbb{Q}$, which is a contradiction. Hence, they can meet at most once. Meeting once is easy, just let them both start at the intersection point. If on the other hand person A starts at 0 and person B starts at $1+\pi$ then they will never meet (by essentially the same argunent like before that they can meet at most once).
Added: If you want to attack this problem in full generality, you will realise that it is not so easy. If $I_A=I_B$ then you are asking whether $r_A$ and $r_B$ are linearly independent over $\mathbb{Q}$. It is for example not so easy to prove that $\pi$ and $\ln(2)$ are not linearly independent over $\mathbb{Q}$ (check Are $\pi$ and $\ln(2)$ linearly independent over rational numbers?).


text:
Q: How does RAM keep up with the CPU? I am trying to understand how RAM manages to keep up with the CPU. Here is a breakdown of why I'm under the impression it wouldn't:

*

*The clock speeds of modern CPUs are often greater than the clock speeds of RAM modules (e.g. a 2.4GHz laptop processor vs a 2133MHz RAM module)

*Such CPUs often have multiple cores, allowing instructions to be executed at a greater rate than the clock speed

*These CPUs may also employ single-core parallelism techniques to execute more instructions per core than there are clock cycles

*Given this, instructions are executed at a far greater rate than the RAM frequency

*At most, you can fetch the contents of one address from RAM per RAM clock cycle

*With perhaps the exception of the BIOS, instructions must ultimately come from RAM

*The demand for instructions to be fetched from memory, therefore, greatly outweighs RAM's ability to provide it

I found an answer by Peter Cordes on this Stack Overflow question, which explains that this problem is addressed by caching and prefetching, but I don't understand how the CPU even gets the opportunity to prefetch, given that the massive rate at which it needs to fetch instructions is seemingly more than can be provided by RAM. This Wikipedia page lists the Intel Core i7 6950X as being able to execute instructions at a rate of 317900 MIPS; using a RAM frequency of 2133MHz, this seems to work out as roughly 150 instructions per RAM clock cycle.
What am I missing?

I just looked at Sydney Hauke's answer to the previously linked question, which states that instructions that the CPU knows will repeat are not re-fetched from memory. Is this on its own sufficient to make up for the speed difference?


text:
Q: How to select multiple plus Nested classes in javascript I want to select multiple and nested , both classes in javascript. Its quite easy in jquery.
for eg -
HTML :

        <button class="uiButton 1sm">Select this<button>

So i want to Select the "button" Using Multiple plus nested classes using javascript.
Working jquery :
var r = $('.6a.6b .uiButton.1sm .uiButtonText');

In javascript i tried :
var r = document.getElementByClassName('6a 6b uiButton 1sm uiButtonText');

But this dont Work.
Any ideas how should i go with javascript?

A: You can use document.querySelectorAll( selectors )
var r = document.querySelectorAll(".6a.6b .uiButton.1sm .uiButtonText");

A: In javascript use :
document.querySelectorAll(".6a.6b .uiButton.1sm .uiButtonText");

And the rest of the Jquery code inside parenthases Remains same.
Cheers :)


text:
Q: Choose between either condition using if with logical OR in java This might seems bit foolish, but it has really caught me.
I want to throw an error if a charString doesn't contain a word "Hi".
So I wrote
if(!charString.contains("Hi"))
   /// throw error on screen

Now, the requirement changed. I want to also throw an error if a charString does not contain "Hello".

So, the requirement is I should not throw an error if the charString
  contains either Hi or Hello

So I wrote:
if(!charString.contains("Hi") || !charString.contains("Hello"))
   /// throw error on screen

To my horror, I realized I am terribly wrong in writing above code. How can I write it in a single if statement then?
The requirement is:

"If charString contains either Hi or Hello, do not throw error"

A: A very clear way (at the expense of a superfluous block that requires a comment) is to write
if (charString.contains("Hi") || charString.contains("Hello")){
    // do nothing
} else {
    // throw an error
}

This is equivalent to the less eyebrow-raising
if (!(charString.contains("Hi") || charString.contains("Hello"))){
    // throw error
}

or (due to De Morgan's Law https://en.wikipedia.org/wiki/De_Morgan%27s_laws)
if (!charString.contains("Hi") && !charString.contains("Hello"))){
    // throw error
}

A: As I understand, you want to throw error when it doesn't contain Hi AND doesn't contain Hello.
if(!charString.contains("Hi") && !charString.contains("Hello"))

Your previous code was:
if the String doesn't contain "Hi" or the String doesn't contain "Hello" throw error. It means that the luck of at least one of those Strings resulted in throwing the error.
Let's describe your flow in plain English:
IF charString contains "Hi" or "Hello" (so is a way of saying "Welcome")
    proceed
ELSE
    throw the error.

We can also use the negation:
 IF charString doesn't contain one of "Hi" or "Hello" (so is a way of saying "Welcome")
    throw the error
ELSE
    proceed.

In Java they would be:
if (charString.contains("Hi") || charString.contains("Hello")) {
    //it's good
} else {
    //it's bad
}

or the second case:
    NOT(charString contains Hi or charString contains Hello)
if (!(charString.contains("Hi") || charString.contains("Hello"))) {
    //it's bad
} else {
    //it's good
}


text:
Q: .NET naming conventions I am supporting and developing a large application.  This question relates specifically to naming conventions.
The previous developer used Pascal Casing, underscores for variable names and a few other techniques, which seem to be frowned upon these days.
My question is: should I continue using the conventions that he used for consistency or introduce conventions that don't seem to be frowned upon as described here: http://www.dofactory.com/reference/csharp-coding-standards.aspx at the expense of inconsistency for at least some time.
I am trying to refactor the code as I go along so maybe I should introduce new conventions in new areas of the application and continue refactoring the code by replacing frowned upon conventions with modern conventions?
Perhaps I am overthinking this.

A: If the old code is consistent, keep it consistent, different style all over the place makes it even more confusing.
If you are going to change, make it a work item, schedule it and do it all at once.
You can of course find arguments for making a gradually change. If you can convince your self that you will complete the renaming by working in small steps where you need to work on the code anyway, go ahead. But to be honest, how many of those gradually transforming code process get finished before there is an updated style guide line and you start of in a third style before cleaning up the first change.
If your code is already in an inconsistent style there is even more compelling reasons to clean up the mess right now before it gets even worse.


text:
Q: Libreoffice Calc CountIf inconsistent behaviour I'm using LibreOffice 4.2.8 and I'm noticing some inconsistent behaviour while using CountIf. I wonder if I'm missing something. When I have the option to use regular expression (Tool->Options->LibreCalc->Calculate->Enable regular expression in formula) I get 0 when using countif on rows that contain some of the characters that would be control a character in a regular expression. In the table below that would be A1,B1,C1. However those same characters by themselves seem to work just fine. In the table below A,B,C. When I turn of regular expression in formula these discrepancies vanish, but I notice that "=" fails. Is this a bug or am I missing some subtlety much like escaping rules on bash?
With regular expressions turned on
A     |B   |C (formula in B)
------|----|---------------
One   |1   |=COUNTIF(A$3:A3,A3)
Two   |1   |=COUNTIF(A$3:A4,A4)
(     |1   |=COUNTIF(A$3:A5,A5)      <<<<<<<<<<<<< A
]     |1   |=COUNTIF(A$3:A6,A6)
[     |1   |=COUNTIF(A$3:A7,A7)      <<<<<<<<<<<<< B
One   |2   |=COUNTIF(A$3:A8,A8)
Two   |2   |=COUNTIF(A$3:A9,A9)
One ( |0   |=COUNTIF(A$3:A10,A10)    <<<<<<<<<<<<< A1
Two [ |0   |=COUNTIF(A$3:A11,A11)    <<<<<<<<<<<<< B1
One ] |1   |=COUNTIF(A$3:A12,A12)
Two ) |0   |=COUNTIF(A$3:A13,A13)
|     |1   |=COUNTIF(A$3:A14,A14)    <<<<<<<<<<<<< C
One | |0   |=COUNTIF(A$3:A15,A15)    <<<<<<<<<<<<< C1
=     |0   |=COUNTIF(A$3:A16,A16)
One = |1   |=COUNTIF(A$3:A17,A17)
+     |1   |=COUNTIF(A$3:A18,A18)
Two + |0   |=COUNTIF(A$3:A19,A19)
^     |1   |=COUNTIF(A$3:A20,A20)
&     |1   |=COUNTIF(A$3:A21,A21)
*     |1   |=COUNTIF(A$3:A22,A22)
One ^ |0   |=COUNTIF(A$3:A23,A23)
Two & |1   |=COUNTIF(A$3:A24,A24)
One * |2   |=COUNTIF(A$3:A25,A25)

With regular expressions turned off
A     |B     |C  (formula in B)
------|------|----------
One   |1    |=COUNTIF(A$1:A1,A1)
Two   |1    |=COUNTIF(A$1:A2,A2)
(     |1    |=COUNTIF(A$1:A3,A3)
]     |1    |=COUNTIF(A$1:A4,A4)
[     |1    |=COUNTIF(A$1:A5,A5)
One   |2    |=COUNTIF(A$1:A6,A6)
Two   |2    |=COUNTIF(A$1:A7,A7)
One ( |1    |=COUNTIF(A$1:A8,A8)
Two [ |1    |=COUNTIF(A$1:A9,A9)
One ] |1    |=COUNTIF(A$1:A10,A10)
Two ) |1    |=COUNTIF(A$1:A11,A11)
|     |1    |=COUNTIF(A$1:A12,A12)
One | |1    |=COUNTIF(A$1:A13,A13)
=     |0    |=COUNTIF(A$1:A14,A14)     <<<<<<<<
One = |1    |=COUNTIF(A$1:A15,A15)
+     |1    |=COUNTIF(A$1:A16,A16)
Two + |1    |=COUNTIF(A$1:A17,A17)
^     |1    |=COUNTIF(A$1:A18,A18)
&     |1    |=COUNTIF(A$1:A19,A19)
*     |1    |=COUNTIF(A$1:A20,A20)
One ^ |1    |=COUNTIF(A$1:A21,A21)
Two & |1    |=COUNTIF(A$1:A22,A22)
One * |1    |=COUNTIF(A$1:A23,A23)

A: For the problem with the "=" you could simply concatenate a "=" as first character in the criteria of COUNTIF. That means look for equality only:
=COUNTIF(A$3:A3,"="&A3)

This way you can also count empty cells. This COUNTIF does not normally.
For the problem with the regular expressions the only way I know is to SUBSTITUTE all possible dangerous characters with the escaped ones.
=COUNTIF(A$3:A3,"="&SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A3,"+","\+"),"|","\|"),"(","\("),")","\)"),"[","\["))

Above formula is not completely of course. And if completed then it will be very long.


text:
Q: Parallel and Multicore Processing in R This is towards the extreme in R's capabilities I think, but here goes...
I'm doing some heavy processing in R in which I've written a function which does all the leg work from a single call. However, I'd like to thread or utilise more than a single core.
I've looked at the Parallel package, which comes up as deprecated. I'd ideally like to call function as a new thread.
I understand the complexities of parallel computing and that it's not the easiest thing in the world, but I'd appreciate it if anyone knew of some packages that would be useful or anything I've overlooked.
Cheers

A: The multicore package is deprecated: not parallel.  Take a look at the documentation for the mclapply function: it's the easiest way to execute functions in parallel in the parallel package.  It's very similar to lapply but with a few new, optional arguments:
library(parallel)
myfun <- function(i) { Sys.sleep(1); i }
mclapply(1:8, myfun, mc.cores=4)

Note that mclapply uses processes, not threads, and doesn't support parallel execution on Windows.  For Windows, you should take a look at parLapply, which is also in parallel.  It is also similar to lapply, but requires a cluster object as the first argument.  Here's the same example, but this works on essentially any platform:
library(parallel)
cl <- makePSOCKcluster(4)
myfun <- function(i) { Sys.sleep(1); i }
parLapply(cl, 1:8, myfun)
stopCluster(cl)


text:
Q: Shell Script : shortcut add and assignment += : command not found Using Mac Terminal and Shell Script
Trying to do Shortcut of add and assignment operator like
SumVar=1

$(( SumVar += 5 ))

echo $SumVar

Getting error :

Error: line 3: 5: command not found

What is the correct syntax of this ?

A: Your syntax for incrementing the variable is correct, but you are using it in a context where Bash wants a command, and it complains that the result of the increment (4) is not a recognized command.
The let keyword is your friend.
let SumVar+=4

Or better yet just leave out the dollar sign (thanks @chepner);
(( SumVar += 4 ))

A: When you use a substitution like this, bash will try to execute a command of the substituted name/value. You can use this instead:
(( Sumvar += 5 ))

Or if you really insist on using substitution here, you can use it as an argument to the : command:
: $(( Sumvar += 5 ))


text:
Q: How to delete all items in list one by one and printing them simultaneously after deleting I am trying to delete elements of a list one by one, and i want to print each element after deleting in the same for loop.
I've tried to delete them using the following code but it says
'IndexError: list assignment index out of range'

usernames = ['yasir', 'anjum', 'moin', 'admin', 'iqbal']
if usernames:
    for i in range(0, len(usernames)):
        #print (usernames[i]) this is working fine
        del (usernames[i])
else:
    print('The list is already empty')

I'm expecting to print the element after deleting it till I'm done deleting all the elements.

A: Use list.pop method.
>>> usernames = ['yasir', 'anjum', 'moin', 'admin', 'iqbal']
>>>
>>> while usernames:
...     print (usernames.pop())
...
iqbal
admin
moin
anjum
yasir

Reverse the list, if you like to retain order.

A: You're using a fixed loop from 0..N-1 with N only calculated once, i.e. when you first enter the loop. But due to the del() N (== len(username)) decreases with every trip around the loop. At some point you reach i >= N and hence IndexError: list index out of range.
Try this variant instead:
while usernames:
    print(usernames[0])
    del(usernames[0])

A: The del statement causes all the later elements to move to the left in the list.  This is why you're getting the IndexError—by the time your loop gets about halfway through the list, the list isn't long enough anymore!
You can delete each element, one at a time, using
while usernames:
    del usernames[0]

If you need to output each element after you delete it, you'll have to keep it in a variable first.
while usernames:
    name = usernames[0]
    del usernames[0]
    print(name)

Note that deleting from a list is a bit inefficient, because the rest of the elements in the list have to be renumbered.

A: This is using for loop, not as efficient but works.
usernames = ['yasir', 'anjum', 'moin', 'admin', 'iqbal']
for i in range(len(usernames)):
    print(usernames[0])
    del usernames[0]


text:
Q: is there an R function to remove an observation when 2 variables are the same?
I am having tough time with this. I wanted to remove the rows that has the same from and to station names. How can I do that in R? Please help.


text:
Q: Why am I not getting the IDs from innerHTML? I have HTML & javascript code where you can click a button to add a row to an existing table. I want to make sure that each row's dropdowns have the correct IDs in ascending order. The middle rows can get deleted, and I need to adjust the IDs.
function addRow(){
    var table = document.getElementById('myTable');

    //Get the number of rows in the table, and use (+1) value for the IDs later
    var rowCount = table.tBodies[0].rows.length;

    var tbodyRef = table.getElementsByTagName('tbody')[0];
    // Insert a row at the end of table
    var newRow = tbodyRef.insertRow();
    // Insert a cell at the end of the row
    var cell0 = newRow.insertCell(-1);
    cell0.innerHTML = '<select id="firstDropdown' + (rowCount + 1) + '"></select>';
    var cell1 = newRow.insertCell(-1);
    cell1.innerHTML = '<select id="secondDropdown' + (rowCount + 1) + '"></select>';
    var cell2 = newRow.insertCell(-1);
    cell2.innerHTML = '<button onclick=deleteRow()>Delete</button>';

    /*Here, I want to get the list of ID's of the firstDropdown of
    each row (for debugging purposes). But this is not printing anything.
    Why is this code below not printing the first dropdown's ids of each row? */
    console.log("------------------------");
    for(var i=0; i<table.tBodies[0].rows.length; i++){
        console.log(table.tBodies[0].rows[i].cells[0].id);
    }
}

function deleteRow(){
    var td = event.target.parentNode;
    var tr = td.parentNode;
    tr.parentNode.removeChild(tr);
}

My HTML code is below:
<button onclick=addRow()>Add row</button>

    1st dropdown
    2nd dropdown
    Remove

I will need to update dropdowns' IDs later when rows are deleted.
I was hoping to do it the same way: table.tBodies[0].rows[i].cells[0].id = "firstDropdown" + (i+1); but I am not sure if this is even going to work now.


text:
Q: How to show or hide a table when hitting enter or clicking on search button I have two tables in my html code and I would like to hide the table from my html page until I click enter in the search area or click on the search button. Once I click enter or hit enter on the search bar then I want my tables to appear.  Right now I am unable to get it to work from the examples I have seen.

$(document).ready(function() {
  //To hide the table
  $("search-input").click(function() {
    $("table1").hide("fast")
  });
  //To show the table
  $("search-input").click(function() {
    $("table1").show("2000")
  });
  //To hide the table
  $("search-input").click(function() {
    $("table2").hide("fast")
  });
  //To show the table
  $("search-input").click(function() {
    $("table2").show("2000")
  });
});

<input type="text" id="search-input" class="form-control input-text" placeholder="Enter Target Property: Street Address, City/Town, State" aria-label="Recipient's Username" aria-describedby="basic-addon2">

 <button class="btn btn-primary btn-lg" type="button"></button>

!--Report Table Start -->

              Report

               Address:

               Latitude:

               Longitude:

               Rank:

               Description:

               NHDES OneStop Website:

                Generator Sites

                  Distance (Miles)
                  Distance (Feet)
                  Generator Name
                 Generator Address
                  Generator Type(s)

A: Try this (pure JavaScript, no jQuery). You will also need to add an HTML ID to the button (Here it is searchbutton)
document.getElementById("table1").style.display = ''; // Show table
document.getElementById("search-input").onkeydown = function(event){ // Handle Textbox KeyDown Events
if (event.key == 'Enter'){ // If key is Enter.
document.getElementById("table1").style.display = 'none'; // Hide Table
}
}
document.getElementById("searchbutton").onclick = function(){ // On Button Click, show table.
document.getElementById("table1").style.display = 'none'; // Hide Table
}

A: This code hides table1 onload.
When search-input is clicked, the view of table1 and table2 is toggled.
$(document).ready(function() {
    $("#table1" ).hide();
    $("#search-input").click(function ()  {
        $("#table1" ).toggle();
        $("#table2" ).toggle();
    });
});

A: If I understand correctly, that's what you wanted.

function showTables() {
  $("#table1").prop('hidden', false);
  $("#table2").prop('hidden', false);
}

<input type="text" id="search-input" class="form-control input-text" placeholder="Enter Target Property: Street Address, City/Town, State" aria-label="Recipient's Username" aria-describedby="basic-addon2">

 <button class="btn btn-primary btn-lg" type="button" onclick="showTables()"></button>

!--Report Table Start -->

              Report

               Address:

               Latitude:

               Longitude:

               Rank:

               Description:

               NHDES OneStop Website:

                Generator Sites

                  Distance (Miles)
                  Distance (Feet)
                  Generator Name
                 Generator Address
                  Generator Type(s)


text:
Q: Database Migration from Oracle 11G to 12C on Sonarqube Version 5.0.1 Could you please advise me the impact of migrating database from Oracle 11g to Oracle 12c for Sonarqube version 5.0.1.
Is this Sonarqube version 5.0.1 supported and tested on Oracle 12c ?
Please advise.
Any help will be appreciated.
Thanks and Regards,
Anish Sethi.

A: As you can read on the "Requirements" page of the SonarQube 5.1, versions of Oracle that are supported include:

12C with Oracle 12.1.0.2.0 drivers since SonarQube 4.5 LTS (port
  number is mandatory in JDBC URL)

So SonarQube 5.0.1 should run fine on Oracle 12. Still:

*

*This does not necessarily mean that the migration from Oracle 11 to 12 is seamless - only your DBA will tell you this.

*SonarQube 5.0 is a quite old version, so you won't get a lot of help in case of trouble

A: yes, Sonarqube 5.0.1 is compatible with oracle 12C and my driver jdbc is  ojdbc6.jar which will also running fine for 12C . my question is do we need to make any other changes inside Sonar application or sonar properties  if The port number, Oracle SID and services does not changes for this upgrade ??


text:
Q: How polymorphism works in Java Can someone explain me whether same name methods are override when we extend?
ClassA ab = new ClassB?
Which methods does ab sees?
Class A:
public class ClassA {

    public static int count = 0;

    public void print(){
        System.out.println("Print A");
    }

    public static void printNumber() {
        System.out.println("Class A " + (++count));
    }
}

Class B:
In class B which methods will be overrided?
public class ClassB extends ClassA {

    public static int count=0;

    public void print() {
        System.out.println("Class B");
    }

    public static void printNumber() {
        System.out.println("Class B " + (++count));
    }
}

Test Class:
Which method will be called here?
public class ClassTest {

    public static void main(String [] arg) {

        ClassA a = new ClassA();
        ClassB b = new ClassB();
        ClassA ab = new ClassB();

        a.print();
        a.printNumber();

        b.print();
        b.printNumber();

        ab.print();  //Why when we call print() method returns print method of ClassA
        ab.printNumber()    ;// Why when we call printNumber() method return method of ClassB
    }
}

A: Calling a static method depends on the declaring type rather than the instantiated type.
So in this line:
ClassA ab = new ClassB();
  ^               ^
declared type    instantiated type

ab will always use static methods of it's declared type (Class A) -- in the case of printNumber(); your IDE should actually give you a suggestion along the lines of:

Static member ClassA.printNumber() accessed via instance reference

and will probably suggest adjusting the line to:
ClassA.printNumber();

This differs from calling a dynamic method (like print()) which will always attempt to call the overriden method of the instantiated type (in the case of ab the instantiated type is ClassB)


text:
Q: Using NServiceBus in an Amazon EC2 hosted application We're starting a new project that has some messaging and queueing requirements that are pretty basic, but in the future there may be some additional requirements for things such as sagas to process messages that might arrive out of order and need to be resequenced.
We've just recently released a project that's completely hosted on Amazon EC2 which also has a simple messaging system in it. We have a very simplistic little pub/sub mechanism whereby we receive a message and then figure out which handler to use for the message based on its type. In our new project we also have a similar mechanism and may have some slightly more sophisticated requirements, but even if we could do away with having our own code to resolve the message handlers this would be cool too.
We're really keen to use NServiceBus as the pub/sub model is really nice, but up until now we've been using Amazon SQS as the queue provider. Each of our EC2 machines has a worker that's listening to the same SQS queue and pulling messages off of that to process them. Obviously SQS isn't supported as a transport layer (and I know it's because NServiceBus is built around a reliable and low latency queue) in NServiceBus.
I know that NServiceBus has a distributor, and I could imagine hosting that on its own EC2 instance, but the problem with that is that there is a huge single point of failure there, so we're basically screwed if that goes down. From what I gather, people setup windows failover clusters to deal with this problem for internal networks, but I don't know if this is applicable to EC2.
This was one of the only blog posts around that I could find by someone who had actually attempted to use NServiceBus in the cloud based context, and he doesn't seem to recommend it. I'm just wondering if anybody else on here has attempted it and if so would they have any advice to offer? Seems like such a shame that we won't be able to make use of such a great framework just because we're hosted on the cloud.
It looks like there's some progress being made with Azure Queues which is something we might look at, but for now we'd like to keep the infrastructure with Amazon as we have a lot of build automation that we can re-use that's based around that.

A: From experience of queueing in Amazon EC2, we've found SQS to be very sluggish for high performance messaging.
We're not currently using NServiceBus as the queueing interface but just thought I'd mention that we're successfully using RabbitMQ on Ubuntu instances in EC2 as our queue provider.
According to this post Udi Dahan suggests that people have swapped out MSMQ for RabbitMQ with NServiceBus so it might be a worthwhile investigation to use RabbitMQ on EC2.
There is a great guide on RabbitMQ's website describing an easy way of installing RabbitMQ on Amazon EC2 by launching a compatible Ubuntu image.
I'd highly recommend installing the RabbitMQ Management Plugin too which gives you a simple web admin interface on the queues.


text:
Q: CPU Info from top command in shell script This the output of top command:
Mem: 245108K used, 784400K free, 6636K shrd, 15128K buff, 41824K cached
CPU:  12% usr   0% sys   0% nic  87% idle   0% io   0% irq   0% sirq
Load average: 2.62 2.58 2.57 2/90 29509

I need a single line script command to execute and get the "CPU" line.
I can get the Mem line from "cat /proc/meminfo" and Load average from "cat /proc/loadavg".
Is there any way to get the same for CPU.

A: @md.jamal -- Try this, to get top 10 most current utilizing resources process Ids with %CPU and %MEM.
    ps -eo pid,ppid,%cpu,%mem | sort -rnk3 | head

Below is details for above command:

where ps --> reports snapshot of current process
-e --> select all processes
-o --> output format
sort -r --> reverse sort, ie descending order
sort -n --> numeric sort
sort -k3 --> to select column no:3
head --> to display top 10 records


text:
Q: How to export first image link from given text with PHP? I want to export the first image link from given text with PHP. Let's say I have text like this:
Lorem ipsum  dolor sit amet, consectetuer

I need to export lorem.jpg to the variable in PHP. So, for example, finally $variable must be equal to lorem.jpg.
I used regular expressions, stripos and so on functions, but everytime there was some problem.
If you have any idea to solve this, please help.

A: Regular expressions can be good for a large variety of tasks, but it usually fails when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately  extract a tag.
We can use DOM parser such as SimpleHTML
You can use it like :
$html = 'Lorem ipsum  dolor sit amet, consectetuer  ';

$first_image_source = get_first_image($html);
echo $first_image_source;

function get_first_image($html){

  require_once('simple_html_dom.php');

  $post_dom = str_get_html($html);

  $first_img = $post_dom->find('img', 0);

  if($first_img !== null) {
      return $first_img->src;
  }

  return null;
}

You can also get the alt attribute of the image in the same way.
If you want to get source of all images then you can use:
function get_images($html){

     require_once('simple_html_dom.php')

     $post_dom = str_get_html($html);

     $img_tags = $post_dom->find('img');

     $images = array();

     foreach($img_tags as $image) {
        $images[] = $image->src;
     }

     return $images;
  }

Hope this helps :) :)

A: Everyone will tell you that you really need to use html parser rather than regex (which is true) because there are many cases where regex will fail to be able to parse valid html.  That being said if you absolutely are sure that the html will be in this format go for
preg_match('/src="([^"]*)"/i',$html,$matches);
$image = $matches[1];

Use preg_match_all if you need more than the first one. Good luck!

A: There are many resources on the net that will tell you that regular expressions are not recommended for parsing DOM elements.  There are several PHP DOM Libraries that can be used for the exact purpose you're looking to use it for, HTML Parsing.
The Simple HTML DOM Library is but one example of a library that can be used to extract DOM elements from a page.

A: Looks like that I can not post comments on other's answer. This is just an extension to hackartist's reply.
Below is a regex used to find the first source in the image link. Because src="([^"]*)" might match src in the iframe too.
]+)src="([^"]*)"


text:
Q: Setting chart gap width in EPPlus / Office Open Xml How can I set the Gap Width value on a column/bar chart in EPPlus?
I have not found a built-in property for this and am expecting I will need to manipulate the chart's Xml, but I've been unable to find the Office Open Xml syntax for doing this.

A: This is supported in EPPLus.
For example:
var barChart = chart.PlotArea.ChartTypes[0] as ExcelBarChart;
barChart.GapWidth = 0;

A: I found the answer by creating what I wanted in a standard Excel sheet, and then looking at the underlying XML it had crated.
I set the Gap Width on an existing chart using the Excel, saved the workbook, renamed the file extension to .zip, and found the corresponding chart XML file within the Zip.
In this case I found the element <c:gapWidth val="15" /> at the following location in the chart's XML: c:chartSpace/c:chart/c:plotArea/c:barChart
I highly recommend this method for solving similar OOXML syntax queries, as the documentation I've seen so far is very dense and not easy to navigate, whereas learning by example in this way helped me find the answer in seconds.


text:
Q: Issue embedding a javascript code within a div overlay I have a a button that once clicked i show an overlay modal div and within this div i embed an adsense code. The code is the following:
$('
').addClass('lightbox').appendTo('body').show();
    $('
').addClass('video_modal').appendTo('body').
                 css('top', '100px').css('left', $(window).width()/2-200+'px').
                 html('
\
        \

\

\
                 <div class="preloader_text"Searching...
').show();

The question is that preloader and it's text is shown but not the adsense ad. What's wrong in my code? I can not understand what's happening.
Thanks.

A: My experience says that dynamically adding AdSense is...difficult. Perhaps Google doesn't allow it and therefor it's not working. My recommendation is creating a hidden div with the AdSense code and later upon whatever event you're firing, with jQuery, move the contents of the hidden div to wherever you prefer.
In this example I've added an ID to one of your divs called "googleadgoeshere", and the hidden div is called "adsense".

<title>Test</title>

Hello world

<input type="button" value="Show ad" onclick="showAd()" />

It works for me, let me know if you run in to any trouble!


text:
Q: Implementation of the SHA256 algorithm do not return the expected result With the implementation below, based on the pseudo-code available here, I am trying to convert a string generated with the concatenation of the members from this class:
class BlockHeader
{
private:
  int version;
  string hashPrevBlock;
  string hashMerkleRoot;
  int time;
  int bits;
  int nonce;
}

into a SHA256 hash, like what was done with the python code below, available here:
>>> import hashlib
>>> header_hex = ("01000000" +
 "81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000" +
 "e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b" +
 "c7f5d74d" +
 "f2b9441a" +
 "42a14695")
>>> header_bin = header_hex.decode('hex')
>>> hash = hashlib.sha256(hashlib.sha256(header_bin).digest()).digest()
>>> hash.encode('hex_codec')
'1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000'
>>> hash[::-1].encode('hex_codec')
'00000000000000001e8d6829a8a21adc5d38d0a473b144b6765798e61f98bd1d'

I expect that my program would return the same result the program above returned, but instead, when I compile and run this:
int main() {
  BlockHeader header;
  header.setVersion(0x01000000);
  header.setHashPrevBlock("81cd02ab7e569e8bcd9317e2fe99f2de44d49ab2b8851ba4a308000000000000");
  header.setHashMerkleRoot("e320b6c2fffc8d750423db8b1eb942ae710e951ed797f7affc8892b0f1fc122b");
  header.setTime(0xc7f5d74d);
  header.setBits(0xf2b9441a);
  header.setNonce(0x42a14695);

  Sha256 hash1(header.bytes());
  array<BYTE, SHA256_BLOCK_SIZE> h1 = hash1.hash();

  cout << "hash1: ";
  for(int i=0; i<h1.size(); i++)
    printf("%.2x", h1[i]);
  printf("\n");

  Sha256 hash2(h1);
  array<BYTE, SHA256_BLOCK_SIZE> h2 = hash2.hash();

  cout << "hash2: ";
  for(int i=0; i<h2.size(); i++)
    printf("%.2x", h2[i]);
  printf("\n");
}

the result is that:
hash1: e2245204380a75c6bc6ac56f0000000040030901000000001100011000000000
hash2: 68a74f2a36c8906068c6cd6f00000000020000000000000080a7d06f00000000

I am aware the endianess in my program are not the same of the python result, but this I can fix later, when I get the correct result. Looking in the code below, can anyone give a hint of what I am missing here?
#define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b))))
#define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b))))

#define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

#define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22))
#define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25))

#define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3))
#define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10))

Sha256::Sha256(vector<BYTE> data) {
    SIZE64 L = data.size() / 2;
    SIZE64 K = 0;
    while( (L + 1 + K + 8) % 64 != 0)
        K = K + 1;

    for(int i=0; i<L; i++) {
        BYTE c = (data[i] % 32 + 9) % 25 * 16 + (data[i+1] % 32 + 9) % 25;
        source.push_back(c);
    }

    source.push_back(0x80);

    for(int i=0; i<K; i++)
        source.push_back(0x00);

    SIZE64 x = L + 1 + K + 8;
    for(int i=0; i<sizeof(x); i++)
        source.push_back( x >> i*8 );
}

Sha256::Sha256(array<BYTE, SHA256_BLOCK_SIZE> data) {
    SIZE64 L = data.size() / 2;
    SIZE64 K = 0;
    while( (L + 1 + K + 8) % 64 != 0)
        K = K + 1;

    for(int i=0; i<L; i++) {
        BYTE c = (data[i] % 32 + 9) % 25 * 16 + (data[i+1] % 32 + 9) % 25;
        source.push_back(c);
    }

    source.push_back(0x80);

    for(int i=0; i<K; i++)
        source.push_back(0x00);

    SIZE64 x = L + 1 + K + 8;
    for(int i=0; i<sizeof(x); i++)
        source.push_back( x >> i*8 );
}

array<BYTE, SHA256_BLOCK_SIZE> Sha256::hash() {
    array<BYTE, SHA256_BLOCK_SIZE> result;

    WORD32 h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;

    WORD32 k[64] = {0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};

    WORD32 a, b, c, d, e, f, g, h, i, j, t1, t2, m[64];

    for(int chunk=0; chunk<=source.size()/64; chunk++) {
        for (i = 0, j = chunk*64; i < 16; ++i, j += 4)
            m[i] = (source[j] << 24) | (source[j + 1] << 16) | (source[j + 2] << 8) | (source[j + 3]);
        for ( ; i < 64; ++i)
            m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];

        a = h0;
        b = h1;
        c = h2;
        d = h3;
        e = h4;
        f = h5;
        g = h6;
        h = h7;

        for (i = 0; i < 64; ++i) {
            t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i];
            t2 = EP0(a) + MAJ(a,b,c);
            h = g;
            g = f;
            f = e;
            e = d + t1;
            d = c;
            c = b;
            b = a;
            a = t1 + t2;
        }

        h0 += a;
        h1 += b;
        h2 += c;
        h3 += d;
        h4 += e;
        h5 += f;
        h6 += g;
        h7 += h;
    }

    for(int i=0; i<4; i++) result[0] = h0 >> i;
    for(int i=0; i<4; i++) result[1] = h1 >> i;
    for(int i=0; i<4; i++) result[2] = h2 >> i;
    for(int i=0; i<4; i++) result[3] = h3 >> i;
    for(int i=0; i<4; i++) result[4] = h4 >> i;
    for(int i=0; i<4; i++) result[5] = h5 >> i;
    for(int i=0; i<4; i++) result[6] = h6 >> i;
    for(int i=0; i<4; i++) result[7] = h7 >> i;

  return result;
}

A: In the Sha256::hash function, result is a BYTE array, whereas h0 is a WORD32. You might want to split h0 into 4 BYTEs and store into the result array, but the for loop at the end of the function won't achieve your goal.
What you want to do is to concatenate h0 to h7, and then extract the bytes from h0 to h7 by shifting 24, 16, 8, 0 bits:
// concatenate h0 to h7
WORD32 hs[8] = {h0, h1, h2, h3, h4, h5, h6, h7};

// extract bytes from hs to result
for(int i=0; i<8; i++) { // loop from h0 to h7
    result[i*4  ] = hs[i] >> 24; // the most significant byte of h_i
    result[i*4+1] = hs[i] >> 16;
    result[i*4+2] = hs[i] >> 8;
    result[i*4+3] = hs[i];       // the least significant byte of h_i
}

EDIT
After some testing, I found another error:
for(int chunk=0; chunk<=source.size()/64; chunk++) {
                      ^^

should be
for(int chunk=0; chunk<source.size()/64; chunk++) {
                      ^

chuck starts from 0, so you should use < instead of <=.
For example, when source.size() is 64, you only have 1 chunk to process.
EDIT2
I fully tested your code and found two problems in the constructors of the Sha256 class.
Your code implies that you assume the vector<BYTE> passed to the constructor is a hex string. That is OK, but you use the same code for the array<BYTE, SHA256_BLOCK_SIZE> version, which is the return type of hash() function, which returns a BYTE array instead of hex string.
For a BYTE array, you can simply push the byte data[i] into the source. Also, L should be data.size() because every element has size 1 in a byte array.
Besides, you try to append the size of the input(x) to source, but x should not include the appended one and zeros, and it is the bit count of the input, so x should simply be L*8. Also, the size should be a big-endian integer, so you have to push the bigger byte first:
for(int i=0; i<sizeof(x); i++) // WRONG: little endian
for(int i=sizeof(SIZE64)-1; i>=0; i--) // Correct: big endian

I have made it execute correctly and output:
hash1: b9d751533593ac10cdfb7b8e03cad8babc67d8eaeac0a3699b82857dacac9390
hash2: 1dbd981fe6985776b644b173a4d0385ddc1aa2a829688d1e0000000000000000

If you encounter other problems, feel free to ask. You are very close to the correct answer. Hope you can fix all the bugs successfully :)
EDIT3: implementation of other function
struct BlockHeader {
    int version;
    string hashPrevBlock;
    string hashMerkleRoot;
    int time;
    int bits;
    int nonce;
    vector<BYTE> bytes();
};

#define c2x(x) (x>='A' && x<='F' ? (x-'A'+10) : x>='a' && x<='f' ? (x-'a'+10) : x-'0')
vector<BYTE> BlockHeader::bytes() {
    vector<BYTE> bytes;
    for (int i=24; i>=0; i-=8) bytes.push_back(version>>i);
    for (int i=0; i<hashPrevBlock.size(); i+=2)
        bytes.push_back(c2x(hashPrevBlock[i])<<4 | c2x(hashPrevBlock[i+1]));
    for (int i=0; i<hashMerkleRoot.size(); i+=2)
        bytes.push_back(c2x(hashMerkleRoot[i])<<4 | c2x(hashMerkleRoot[i+1]));
    for (int i=24; i>=0; i-=8) bytes.push_back(time>>i);
    for (int i=24; i>=0; i-=8) bytes.push_back(bits>>i);
    for (int i=24; i>=0; i-=8) bytes.push_back(nonce>>i);
    return bytes; // return bytes instead of hex string
}

// exactly the same as the vector<BYTE> version
Sha256::Sha256(array<BYTE, SHA256_BLOCK_SIZE> data) {
    SIZE64 L = data.size(); // <<
    SIZE64 K = 0;
    while( (L + 1 + K + 8) % 64 != 0)
        K = K + 1;
    // can be simplified to: int K = (128-1-8-L%64)%64;

    // ** thanks to "chux - Reinstate Monica" pointing out i should be a SIZE64
    for(SIZE64 i=0; i<L; i++) { // **
        source.push_back(data[i]); // <<
    }

    source.push_back(0x80);

    for(int i=0; i<K; i++)
        source.push_back(0x00);

    SIZE64 x = L*8; // <<
    for(int i=sizeof(SIZE64)-1; i>=0; i--) { // big-endian
        source.push_back(x >> i*8);
    }
}

EDIT4: variable size in for loop
As "chux - Reinstate Monica" pointed out, it may be a problem if the size  of the data is bigger than INT_MAX. All for-loop using a size as the upper limit should use a size_t type counter(instead of int) to prevent this problem.
// in BlockHeader::bytes()
for (size_t i=0; i<hashPrevBlock.size(); i+=2)
// in Sha256::hash()
for (size_t chunk=0; chunk<source.size()/64; chunk++)
// in main()
for (size_t i=0; i<h1.size(); i++)
for (size_t i=0; i<h2.size(); i++)

Notice that size_t is unsigned. The reverse version won't work because i is never less than 0.
for (size_t i=data.size()-1; i>=0; i--) // infinite loop


text:
Q: standard deviation of two samples there are two samples, both with standard deviation 8.5.
If one combines the two samples together, find the relation between the standard deviation and 17.
I figure it cannot be determined. But I am not sure how to argue rigorously. Thank you!


text:
Q: When drive mapped on a windows machine from remotely by using "net use" command, shows unavailable status I am trying to map a share directory on remote windows machine by executing "net use" command with admin credentials, however the directory is getting mapped and showing status as unavailable. Following is the command I am using, net use * \xx.xxx.x.xx\share\Software /USER:Administrator password
Also I tried the work-arounds like creating a DWORD to "EnableLinkedConnections", and rebooted the system, but still facing the same issue.


text:
Q: Searching from different workbook and copying values I have 2 wb to_update_example_1 and purchasing_list
basically what I am trying to do is to a loop row by row on workbook to_update_example_1 if the same name is found to copy the a variable to the purchasing_list workbook.
However it keeps giving me error 91 at the searching portion and I would need an advice how do I write vVal2(which is the Qty) to Purchasing list workbook the column is just beside the found name so I tried to use active cell offset but didn't work too
any advice is appreciated thanks
Sub Macro1()

Application.ScreenUpdating = False

Dim x As Integer
Dim vVal1, vVal2 As String

Numrows = Range("A1", Range("A1").End(xlDown)).Rows.Count ' Set numrows = number of rows of data.
Range("A1").Select  ' Select cell a2.
For x = 1 To Numrows ' Establish "For" loop to loop "numrows" number of times.
    vVal1 = Cells(x, 8)
    vVal2 = Cells(x, 7)

    Windows("Purchasing List.xls").Activate

    ActiveSheet.Cells.Find(What:=vVal1, After:=ActiveCell, LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Row

    ''write to Qty cell beside the found name ActiveCell.Offset(0, -2) = vVal2
    Windows("To_update_example_1.xlsm").Activate

    ''''''''ActiveCell.Offset(1, 0).Select
Next
Application.ScreenUpdating = True

End Sub

A: When using the Find function, it's recommended if you set a Range object to the Find result, and also prepare your code for a scenario that Find didn't find vVal1 in "Purchasing List.xls" workbook. You can achieve it by using the following line If Not FindRng Is Nothing Then.
Note: avoid using Select, Activate and ActiveSheet, instead fully qualify all your Objects - see in my code below (with comments).
Modified Code
Option Explicit

Sub Macro1()

Application.ScreenUpdating = False

Dim x As Long, Numrows As Long
Dim vVal1 As String, vVal2 As String
Dim PurchaseWb As Workbook
Dim ToUpdateWb As Workbook
Dim FindRng As Range

' set workbook object of "Purchasing List" excel workbook
Set PurchaseWb = Workbooks("Purchasing List.xls")

' set workbook object of "To_update_example_1" excel workbook
Set ToUpdateWb = Workbooks("To_update_example_1.xlsm")

With ToUpdateWb.Sheets("Sheet1") ' <-- I think you are trying to loop on "To_update_example_1.xlsm" file , '<-- change "Sheet1" to your sheet's name
    ' Set numrows = number of rows of data.
    Numrows = .Range("A1").End(xlDown).Row

    For x = 1 To Numrows ' Establish "For" loop to loop "numrows" number of times
        vVal1 = .Cells(x, 8)
        vVal2 = .Cells(x, 7)

        ' change "Sheet2" to your sheet's name in "Purchasing List.xls" file where you are looking for vVal1
        Set FindRng = PurchaseWb.Sheets("Sheet2").Cells.Find(What:=vVal1, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns)
        If Not FindRng Is Nothing Then '<-- make sure Find was successful finding vVal1
            ' write to Qty cell beside the found name ActiveCell.Offset(0, -2) = vVal2
            ' Not sure eactly what you want to do now ???

        Else ' raise some kind of notification
            MsgBox "Unable to find " & vVal1, vbInformation
        End If
    Next x
End With

Application.ScreenUpdating = True

End Sub

A: Edited to account for OP's comment about where to search and write values
ShaiRado already told you where the flaw was
here's an alternative code
Option Explicit

Sub Macro1()
    Dim cell As Range, FindRng As Range

    Dim purchListSht As Worksheet
    Set purchListSht = Workbooks("Purchasing List.xls").Worksheets("purchaseData") '(change "purchaseData" to your actual "purchase" sheet name)

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    With Workbooks("to_update_example_1").Sheets("SourceData") ' reference your "source" worksheet in "source" workbook (change "SourceData" to your actual "source" sheet name)
        For Each cell In .Range("H1", .Cells(.Rows.Count, 8).End(xlUp)).SpecialCells(xlCellTypeConstants) ' loop through referenced "source" sheet column "H" not empty cells
            Set FindRng = purchListSht.Columns("G").Find(What:=cell.Value, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns) ' try finding current cell content in "purchase" sheet column "G"
            If Not FindRng Is Nothing Then FindRng.Offset(, -2).Value = cell.Offset(, -1).Value ' if successful, write the value of the cell one column left of the current cell to the cell two columns to the left of found cell
        Next
    End With
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
End Sub


text:
Q: Stuck figuring out the initialization sequence of ASP.NET Core 2.1 This is a problem that has been hard for me to figure out.  I wanted to make a micro-service out of an ASP.NET Core Application.  I've been able to deploy .NET Core with Kestrel as an edge server and behind a proxy like Nginx. This seems semi-inconsequential, so haven't spent forever on it, but I can't figure out how to land on a different url other than root when my application starts up.  In other words, I've changed the default routing, this is an mvc application, and I added a prefix like this into Startup.cs:
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "SqlServer/{controller=Home}/{action=Index}/{id?}");
    });

In production, not a problem, doesn't matter what the default route is, but when I develop in VisualStudio and hit play, I get the blank browser because its pointing to "/" instead of "/SqlServer".  Any idea how to fix this?
Also relevant is Program.cs:
public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
            .UseKestrel(options =>
            {
                options.Limits.MaxConcurrentConnections = 100;
                options.Limits.MaxConcurrentUpgradedConnections = 100;
                options.Limits.MaxRequestBodySize = 10 * 1024;
                options.Limits.MinRequestBodyDataRate = new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
                options.Limits.MinResponseDataRate = new MinDataRate(bytesPerSecond: 100, gracePeriod: TimeSpan.FromSeconds(10));
                options.Listen(IPAddress.Any, 5000);
                options.Listen(IPAddress.Any, 5001, listenOptions =>
                {
                    listenOptions.UseHttps("/Users/ryandines/DevelopmentCode/ExampleProject/testCert.pfx", "notMyPassword");
                });
            }).UseStartup<Startup>();
    }
}

A: There's 2 ways of changing this setting.
Using Visual Studio

*

*Right click on the project, select "Properties"

*Select "Debug" tab

*Next to the "Launch browser" checkbox, enter a URL that you want to start when the app runs.

Edit settings manually
Manually add a launchUrl property to the profile, for example:
{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1234/",
      "sslPort": 0
    }
  },
  "profiles": {
    "<name of profile>": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "http://localhost:1234/cheese",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Local"
      }
    },
    //etc...


text:
Q: Cannot access Advanced Startup Options in Window 10 as it closes / crashes automatically Needed to do get the Advanced Startup options within Windows 10 21H2 and for some reason the window opens and then hangs for a moment and then automatically closes / crashes.
This happens whether I try to invoke it directly from the start menu by searching for 'change advanced startup options' or if I go to Settings -> Update & Security and clicking Recovery.
The only way I can access the menu is to hold shift while selecting Restart from the Power menu.
This used to work fine as recently as a few weeks ago, but I can't figure out what's gone wrong.
I have executed the following and rebooted multiple times:
chkdsk /f /v
sfc /scannow
dism /online /cleanup-image /restorehealth
Any suggestions?
I suppose I could try an in-place upgrade, but I've often had mixed results with in-place upgrades so wanted to check with other users here first.

A: Running DISM and SFC is the basic set of repair steps. Since these have not work, the next repair is a Windows 10 Repair Install.
This is a repair and not necessarily an in-place upgrade.
Go to the Windows Media Creation Link
https://www.microsoft.com/en-us/software-download/windows10
Windows 10/11 is running, so click on the Download button (not Upgrade Button) and select Run.
You can also make a USB Key and run Setup.exe on the USB Key.
This will launch the Repair.  Proceed normally answering the prompts. The default Keep prompt is to Keep Everything.
Try Keep Everything first. Your computer will come back the way you left it.
If Keep Everything does not work, the next steps (Keep Just Data and Keep Nothing) are more aggressive. Keep Nothing is like a fresh install.

A: Not Attempting to answer, but I am not able to Comment.
In order to find out why the crash keeps happening, have you checked the event logs? Just FYI, that shouldn't happen and means that the system is not "stable", which why, I think, @John recommended a fresh install. Just being able to get to those options with a "workaround" still means you have an unstable system. I would backup any info I needed and reinstall Windows just like @John said.

A: This particular issue turned out to be a Microsoft issue and I witnessed it across multiple systems in our business simultaneously.  It has now been resolved in a previous Windows update and should be part of KB5016616


text:
Q: Math aid Needed: Scaling an Arduino analog input to be -1 to 1 The Arduino map() function does not work for this problem, and HAVE scoured the 'net for examples but am still coming up at a loss. My 'math-brain' is ded!!  :-(
I have a pot going into an Arduino analog input produces a range of 170 to 1000.  I'd like to scale that to a range of -1 to 1 to simulate a commercial joystick that is being replaced.
There is an Arduino Micro reading the pots and sending the data by serial to Processing.  This all works - just can't get the -1 to 1 range to send out.
A formula to do this would be a HUGE help!
=Alan R.

A: You can use linear interpolation to do the magic. If x is the input and y is your desired output, the following relation will work out:

(y-1)/(x-1000) = (1-(-1))/(1000-170) = 1/415
So basically, y = 1 + (x-1000)/415


text:
Q: mapStateToProps and properties not coming from the stores Is it a good idea to include properties not coming from the store in mapStateToProps?
e.g.
const fooBar = () => 'foobar!'

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter),
    fooBar
  }
}

A: Yes, this is an acceptable use case - however, we might be able to implement this functionality a bit cleaner. For instance, mapStateToProps in react-redux accepts a second argument, titled ownProps, which are the props passed to the container component in question:
Via https://github.com/reactjs/react-redux/blob/master/docs/api.md

[mapStateToProps(state, [ownProps]): stateProps] (Function):
  ...If ownProps is specified as a second argument, its value will be the
  props passed to your component, and mapStateToProps will be re-invoked
  whenever the component receives new props.

So perhaps rather than instantiating fooBar inside of your container component, why not pass it as a prop to the component itself, and then access it via ownProps?
Some Other Component
 <MyContainer fooBar={() => alert('foobar!')}

MyContainer
const mapStateToProps = (state, ownProps) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter),
    fooBar: ownProps.fooBar
  }
}


text:
Q: How to make a .exe from python script with pyinstaller? I'm trying to package up my python file into an .exe file using pyinstaller.
I managed to install pyinstaller with pip but when trying to use pipinstaller in a command window it wouldn't work. I found online to use python -m PyInstaller instead which then worked. But after using cd to change the directory and then doing python -m PyInstaller filename.py it would always give a list of errors saying 1920, 'LoadLibraryExW', 'The file cannot be accessed by the system.'.
I'm using windows 10, python 3.8.3 and the newest version of pip but I couldn't find a soloution. I ran command prompt as an operator but it still wouldn't help.
Any soloutions?

A: Go to the path you've installed your python
if you don't know where you installed python, in the console type 'where python'
> where python
C:\Users\{username}\AppData\Local\Programs\Python\Python38\python.exe

then go to the path
next, go to 'Scripts' folder
cd Scripts

in the Scripts folder, make sure there is pyinstaller.exe file there
if you find pyinstaller.exe in this folder, you are sure pyinstaller is installed on your system, then
> pyinstaller {path to the main.py}

there is two useful switch for pyinstaller

*

*--onefile         >>  your project packaged into ONE file

*--noconsole       >>  no console appear when your app is running

For eg:

pyinstaller d:\myapp\main.py --onefile

You can find your final dot.exe file in the 'dist' folder in 'Scripts' folder

A: I encounter the same question, so I uninstall python which is installed from windows appstore, and reinstall it from the website, and it works fine now, hope it help

A: I decided to try another one after failing to use pyinstaller. I used py2exe and shortly after trying managed to convert it into an .exe file along with moving my files inside of where my python was stored.


text:
Q: Why is it "could" and not "can" in the famous line: "If a face could launch a thousand ships"? This is from a song lyric

If a picture paints a thousand words,
  Then why can't I paint you?
  The words will never show the you I've come to know.
  If a face could launch a thousand ships,
  Then where am I to go?
  There's no one home but you,
  You're all that's left me too.
  And when my love for life is running dry,
  You come and pour yourself on me.

First the singer says If a picture paints a thousand words.
Followed by, If a face could launch a thousand ships.
Why does the singer sing "If a face could launch a thousand ships"?
Why not, "If a face can launch a thousand ships"?
Why is  can used in the past?

A: To start with, could can be read as a conditional. It could launch a thousand ships if the conditions are right.
Secondly, you can indeed read it as past, because it refers to a (mythological) past event.
It is a reference to the quite famous story of the Trojan War. That war, as legend has it, was waged because the prince of Troy abducted the most beautiful woman in the world (Helen).
Because of that, the Greeks assembled the biggest assembled fleet they could, rumoured to be a thousand ships, to besiege Troy. This is all very nicely described by Homer, a Greek writer.
Helen was said to be so beautiful, that her face launched a thousand ships.

A: Jim just to be clear,
the reason that in that song it uses "If a face could launch a thousand ships"
is because that phrase is a pre-existing well-known phrase.
(The whole point of the song, is that the sonf is an "extension" of that well-known phrase .. does that make sense?)
In answer to your other question, why -- in the original phrase -- do we tend to say "could" rather than "can" .... I have absolutely no idea.
It might be there is "no reason" and you are completely correct: either it would be better to use "can" or "can"/"could" are absolutely equally justified by the English grammar board.


text:
Q: picture formatting for kernel svm I'm having some difficulty to get a series of images into the correct format to feed into sklearn.svm.SVC.
This is my first image recognition project, and so Im suffering a bit.
Ive got a loop which brings in a bunch of base64 RGB images (of different sizes) to a dataframe
imageData = mpimg.imread(io.BytesIO(base64.b64decode(value)),format='JPG')

then I convert the RGB image into gray-scale, and flatten
data_images = rgb2gray(imageData).ravel()

where rgb2gray:
def rgb2gray(rgb):
    r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b
    return gray

If I look at the size differences
df_raw.sample(10)

We can see that the picture pixel lengths are not the same between my samples. Im a little confused here about how to proceed. For lack of a better idea I decided to add a padding based on the picture with the largest size,
df_raw.picLen.max()

Then appending a number of zeros to the end of each 1D picture array.
def padPic(x,numb,maxN):
    N = maxN-len(x)
    out = np.pad(x,(numb,N),'constant')
    return out

calling
df_raw['picNew'] = df_raw.apply(lambda row: padPic(row['pic'],0,df_raw.picLen.max()), axis=1)
df_raw['picNewLen']  = df_raw.apply(lambda row: len(row['picNew']), axis=1)

I now have arrays all of the same size

From here I attempt to fit a model to support vector algorithm using the picture data as X and a set of labels as y.
from sklearn.svm import SVC
X_train, X_test, y_train, y_test = train_test_split(df_raw.picNew, df_raw.name, test_size = 0.2, random_state=42)

check the size:
print('Training data and target sizes: \n{}, {}'.format(X_train.shape,y_train.shape))
print('Test data and target sizes: \n{}, {}'.format(X_test.shape,y_test.shape))

Training data and target sizes:  (198,), (198,) Test data and target
  sizes:  (50,), (50,)

after Ive convinced myself everything is ready, then I try to fit the model
svm = SVC()
svm.fit(X_train, y_train)

this throws an error, and I cant figure out why:

/opt/wakari/anaconda/envs/ulabenv_2018-11-13_10.15.00/lib/python3.5/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
      499
      500     """
  --> 501     return array(a, dtype, copy=False, order=order)
      502
      503
ValueError: setting an array element with a sequence.

I think this must have to do with the array size, but I cant figure it out. :-/
In addition to the error, more generally, I have a question to my approach in general. In particular I think my "padding" is probably incorrect and maybe some resize would be better.
I appreciate any feedback to my methodology. Thanks

A: I am pretty sure this is due to using list in a feature column and strings as target values. For the latter You need to use LabelEncoder class to turn them to normalized class labels, as required by fit().
See description here:
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html
This needs to be done before train/test split to make sure you have all names 'seen' by the LabelEncoder.
For the former, you might want to search for MNIST tutorials, that will provide a plethora of algorightms applied to image classification problems.
Also, Resize before flattening should work better than padding.

A: Ive figured out the problem.
Thank you to Artem for his catching my obvious problem of not encoding the classes, but this was not my issue in the end.
Turns out the way that my picture array was represented was incorrect.
The original array was df_raw['picNew'].shape which evaluates to

(248,)

What I needed was a 2D representation
np.stack(df_raw['picNew'] , axis=1).shape

(830435, 248)

All good now.
I'm still unsure about the most "correct" way to resize the images to be all the same length. Appending 0 to the array lengths seems a bit unsophisticated... So if anyone has an idea :)


text:
Q: Concrete5. Create new thumbnail type I am trying to create new thumbnail type, like this:
use Concrete\Core\File\Image\Thumbnail\Type\Type;

$type = new Type();
$type->setName( 'thumbnails name' );
$type->setHandle( 'block_handle' );
$type->setWidth( 250 );
$type->save();

On Concrete5 v7.5 everything working fine, but on v8.0.0 there is an error:
Call to undefined method Concrete\Core\File\Image\Thumbnail\Type\Type::setName()

Where did I make a mistake?

A: This change is documented here.
Unfortunately  lot of the other documentation hasn't been updated yet.
Just replace
Concrete\Core\File\Image\Thumbnail\Type\Type

with
Concrete\Core\Entity\File\Image\Thumbnail\Type\Type


text:
Q: Theming, Layout & Design Questions I am using Magento 1922 with a custom theme. By default Magento comes with 4 Store Views: English, German, Spanish, Russian). I created a new store view named French/french, it has a language set up. When I switch in frontend the language to French the whole layout gets nuts. In backend all store views have the same options in Web section, all coming from Default Config. French has them too, but something makes it not working as expected. In order to fix this I had to fill in the Layout input box in Default Config.
Question: Why those 4 Store Views are displaying great and getting correctly the layout without being specified (only package, templates and skin are filled in as value) and this new store, which has the same values, is not working without having layout filled in.


text:
Q: Countable and uncountable sets in Riemann integration The Riemann integral over $[a,b]$ of a continuous function $f$ is
$$\int\limits_a^bf(x)dx=\lim\limits_{\delta\rightarrow 0} \sum\limits_{i=0}^{n-1} (x_{i+1}-x_i)f(c_i)$$
where $c_i\in[x_i,x_{i+1}]$ and $\delta=\sup(x_{i+1}-x_i)$. The set $[a,b]$ is uncountable. When $\delta\rightarrow 0$, the number of elements in a set $[x_i,x_{i+1}]$ goes to $1$ and so the number of terms in the sum above is countable. How could a counatble set form a partition of an uncountable set (the sets $]x_i,x_{i+1}[$ form a partition of $]a,b[$).
Now I suspect that there's something wrong in "when $\delta\rightarrow 0$, the number of elements in a set $[x_i,x_{i+1}]$ goes to $1$" but even if I replaced it with "when $\delta\rightarrow 0$, the number of elements in a set $[x_i,x_{i+1}]$ goes to an integer $k$" or "when $\delta\rightarrow 0$, the number of elements in a set $[x_i,x_{i+1}]$ is countable" (I don't know why it isn't $1$) I still have the same problem.

A: The most simple limit sum to think of is $$\sum_{k=1}^n \frac 1n =1$$ as $1/n\to 0^+$. Even being that simple, it will clear up the situation. Staring at it, you might say
Well, in the limit $1/n$ goes to $0$ and there is a countable number of terms in this sum. There is clearly something wrong. How could a countable number of zeros sum up to one?
This question is more fundamental than integrals or Riemann sums, it is a question on the behaviour of limits. The formal definition of a limit will rescue us. To refresh our minds, a quick reminder: we say $\lim\limits_{x\to 0}f(x)=L$ if, and only if, for every $\varepsilon>0$ there is $\Delta >0$ such that $$0<|x|<\Delta\implies |f(x)-L|<\varepsilon.$$
Note that we never mentioned what would happen if $x=0$. It does not concern our definition, and that's the fundamental mistake here. We should not judge the sum in the hypothetical situation $1/n=0$, but only when $0<1/n - 0 <\Delta$ for some finite $\Delta$. The paradox disappears, because at any such interval, $\sum 1/n = 1$.
At any finite $\delta=\sup(x_{i+1}-x_i)$, the cardinality of $[x_i, x_{i+1}]$ is definitely not approaching $1$, even though it is $1$ when $\delta =0$. This illustrates a crucial difference between $\delta\to 0$ and $\delta =0$ that cannot be overestimated, and you will highly benefit from thinking about it. To finish the discussion, you might be interested in rereading some content on continuous functions.

A: I am not a mathematician, but from a scientist's perspective, going from the sum to the integral is going from discrete mathematics, where the variable is only defined over discrete values (such as where the physical quantity is a finite dimensional vector), to continuum mathematics, where the variable is defined over a continuum of values (the physical quantity is a function of a real or complex variable). So, I do sympathize with the question's author that in the discrete case, the sum contains the function evaluated at each point where the variable is defined but in the continuum case, the limit of the sum does not contain the function (integrand) evaluated at each of the continuum of points.
I think the key is to understand that not all sets that are countably infinity in size have the same properties. For instance, for the integers, there is such a thing as "next integer". However, for the rationals, which are also countably infinite, there is no "next rational". I think that the countably infinite ordered set of x values, for which the integrand is evaluated in the limit, are such that there is no "next x" in that ordered set. This allows $\delta$ to approach zero in the limit, without having to evaluate the integrand at each of the non-countably infinite set of values of x that are in the interval of integration.


text:
Q: Instance of 'OneToOneField' has no 'username' member I got the following error when I created Profile model

Instance of 'OneToOneField' has no 'username' member

This is the snippet of the code I created
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default="default.jpg", upload_to="profile_pics")

    def __str__(self):
        return f"{self.user.username} Profile"

previously it was working fine. Now, all of a sudden I am getting this error.I didn't understand the meaning of this error.  How do I solve it?
Thank you

A: In order for pylint to work properly with Django you should install the pylint-django packege:
pip install pylint-django

Then you can run pylint with pylint_django as a plugin:
pylint --load-plugins pylint_django <path_to_django_file>

If you are using VSCode as your IDE, you can add this snippet to your .vscode/settings.json file to load the plugin for your project:
{
    "python.linting.pylintArgs": [
        "--load-plugins",
        "pylint_django"
    ]
}

Or, if you have a .pylintrc file, you can add this line to load the plugin:
[MASTER]
load-plugins=pylint_django

You can find out more on about pylint-django here.

A: In addition to the Pumi's answer, when you pip install pylint-django, you may likely have another error:
"ERROR: Cannot uninstall 'wrapt'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall."
Then you have to type this:
pip install wrapt --upgrade --ignore-installed

And re-try pip install pylint-django
Also inside the .vscode/settings.json, there's an existing {"python.pythonPath": "./anaconda3/bin/python"} if you are using conda interpreter. So you only need to add the list without additional curly brackets as specified  @Pumi. So you will have something like this:
{
"python.pythonPath": "./anaconda3/bin/python",

"python.linting.pylintArgs": [
        "--load-plugins",
        "pylint_django"
    ]
}

Then you're good to go.


text:
Q: Can I run a .vdi file for Windows 8.1. virtual machine in KVM/QEMU or VMM? Can I run a .vdi file for Windows 8.1. virtual machine in KVM/QEMU or VMM? Do I need to convert the file from .vdi to some format familiar to KVM/QEMU? What are the steps, if possible?
I have VirtualBox and a Windows 8.1 virtual machine .vdi file created under VirtualBox in a computer. I have KVM/QEMU and VMM in another computer. Both computers run Lubuntu 18.04 as host OS. I am considering to copy the .vdi file to  the second computer and run it there.
I remember Windows 8.1 in the .vdi file has been activated by a product key. Will I be able to have the two Windows 8.1 virtual machines without problem?
Thanks.

A: QEMU can use a VirtualBox-format disk image directly. You can convert them to a "QEMU-native" format if you prefer, using qemu-img:
qemu-img convert -O qcow2 yourimage.vdi yourimage.qcow2

The fact that QEMU can read such disk images doesn't necessarily mean that the VM itself will work as it would in VirtualBox; for example, the VirtualBox images of Windows which Microsoft provides for browser testing tend not to work all that well in QEMU with the original disk images, but work fine when converted to qcow2 format.

Will I be able to have the two Windows 8.1 virtual machines without problem?

That's a Windows-specific question, to which I don't know the answer; you should ask it on a more appropriate Stack Exchange.


text:
Q: Keeping track of a button status inside a thread (PyQt5) I created this simple GUI that displays a conuter on a text box. I am using workers and threads (this is just a simplified program I have other threads). I want to be able to check the status of the push button inside the label update thread. for example if the user clicked, then the counter will increment by 5 instead of 1 (for this iteration only), basically I want to keep an eye on this button's status all the time.
here is my code for the counter, how do I add the button check functionality to it?
Edit: I've updated the code using signals and slots to print 'hi' as a start, yet I do not get any output when I run it.
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QPoint, QRect, QSize, Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

import sys
import os
import cv2
import numpy as np
import time

############################# Telemtry widgets update ##########################
class DISPLAY(QObject):
acc1_val = pyqtSignal(int)
finished = pyqtSignal()

def run(self):
    global cntr
    cntr = 0
    self.inst = Ui_MainWindow()
    self.inst.flag.connect(self.update)
    print('connected')

    while 1:
        cntr = cntr +1
        time.sleep(1)
        self.acc1_val.emit(cntr)
        if(cntr > 50):
            cntr = 0

    self.finished.emit()
@pyqtSlot()
def update(self,flag):
    print('hi')
    print(flag)

############################ GUI #######################################

class Ui_MainWindow(QObject):

    flag = pyqtSignal(int)

def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(500, 500)
    MainWindow.setFocusPolicy(QtCore.Qt.NoFocus)

    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")

    self.Title = QtWidgets.QLabel(self.centralwidget)
    self.Title.setGeometry(QtCore.QRect(30, 10, 421, 71))
    font = QtGui.QFont()
    font.setPointSize(24)
    font.setBold(True)
    font.setWeight(75)
    self.Title.setFont(font)
    self.Title.setObjectName("Title")

    self.ACC1_X = QtWidgets.QLineEdit(self.centralwidget)
    self.ACC1_X.setGeometry(QtCore.QRect(300, 300, 41, 31))
    self.ACC1_X.setObjectName("ACC1_X")

    self.btn = QtWidgets.QPushButton(self.centralwidget)
    self.btn.setGeometry(QtCore.QRect(100, 100, 101, 41))
    font = QtGui.QFont()
    font.setPointSize(13)
    self.btn.setFont(font)
    self.btn.setObjectName("Release_btn")
    self.btn.clicked.connect(self.release_callback)

    MainWindow.setCentralWidget(self.centralwidget)
    self.menubar = QtWidgets.QMenuBar(MainWindow)
    self.menubar.setGeometry(QtCore.QRect(0, 0, 1920, 22))
    self.menubar.setObjectName("menubar")
    MainWindow.setMenuBar(self.menubar)

    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)

    ###################### Display thread ######################

    self.thread1 = QThread()
    self.worker1 = DISPLAY()
    self.worker1.moveToThread(self.thread1)
    self.thread1.started.connect(self.worker1.run)
    self.worker1.acc1_val.connect(self.Label_update)
    self.thread1.finished.connect(self.worker1.deleteLater)

    self.thread1.start()

def release_callback(self,flag):
    self.x = 1
    print(flag)
    self.flag.emit(True)

def Label_update(self,acc_val):

    self.ACC1_X.setText(str(acc_val))
    #print(str(acc_val))

def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
    self.btn.setText(_translate("MainWindow", "click me"))
    self.Title.setText(_translate("MainWindow", "TEST"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())


text:
Q: Streamlit integration and limitations I am new to streamlit and I have been asked to do a feasibility study for dashboarding solution. I want the help of you all to find out the answers of the below questions. I tried but was not able to get a clarity on these.

*

*Is there any data limit that can be displayed for the streamlit library?

*How long it would take to load data of varied sizes is there any way to find it or is load test the way to go?

*How can I integrate streamlit with AWS S3, Athena and Redshift?

A: *

*yes 50k MB of uploaded data is the limit

*not that long, and you can cache it so it doesn't reload.

*integrations isn't problematic at all from my experience with AWS

You should explore a bit yourself, thats the best solution imo. Also, use streamlit community blog, it is much more active on those questions than stackoverflow.


text:
Q: alternative for range and len functions In the For loop below
def __str__(self):
    output = " "
    for i in range(len(self)):
        output += (self.str_data[i] +" ")
    return  output

How may I rewrite this without using range & len or any other inbuilt function?
PS: str_data was used as instance variable of type list in init earlier.

A: If you're allowed to use join() then you could do:
def __str__(self):
    return " ".join(self.str_data)

This is of course assuming len(self) would result in the same as len(self.str_data).
To result in exactly the same as your loop it would actually have to be:
def __str__(self):
    if self.str_data:
        return " " + " ".join(self.str_data) + " "
    else:
        return " "

A: New Answer: (no builtin functions)
def __str__(self):
    output=""
    for i in self.str_data:
         output+=i+" "
    return output

Old Answer :
asterisk and double asterisk can be used within list, tuple, set and dictionary, * will unpack list/tuple and ** will unpack dictionary.
my_array = [0,1,2,3,4,5]
print(*my_array) # unpacking list

Another method using join:
print(' '.join(map(str,my_array)))

Output
0 1 2 3 4 5

For the given question:
Since return keyword returns only one argument we can't unpack the list and we have to use function
def __str__(self):
    return ' '.join(self.str_data)

A: You mean like this ?
class A(object):

    def __init__(self, str_data):
        self.str_data = str_data

    def __str__(self):
        return " ".join(str(s) for s in self)

    def __iter__(self):
        return iter(self.str_data)

if __name__ == '__main__':
    print(A(["1", "2", "3", "4", "5"]))

A: The previous answer is perfectly fine (if you omit builtins), but here's a closer version to what you did:
output = ""
array = [0,1,2,3,4,5]
for i in array:
   output += "%s " % (i)
output = output[:-1]
return output

Please note that I change the way you set your output, as I think in order to get the result you want. Like you asked it does not use any builtin and it works just fine.

A: import json

def __str__(self):
    output = json.dumps(self.str_data)
    output = output[1:-1].replace(',', ' ')
    return  output

For your consideration.

A: You could use highlevel functions like
" ".join(map(lambda x:x+" ",self.str_data))

map applies the function to add a space to each string in self.str_data and " ".join adds each of those to the starting string.
But of course these are built-in functions, it's just a really clean solution.

A: Alternitive to len() could be for loop - like:
var1 = 0
for var2 in list1:
 var1 += 1