text:
Q: Whys is ["text"] == ["text"] false? Why does the expression ["text"] == ["text"] evaluate to false in JavaScript?
I intuitively expected it to be true, since the two arrays are identical. Is the JS engine comparing references to two different objects, and thus returning false, instead of comparing the contents of the arrays?

A: You have created two different arrays and JavaScript is comparing their references, not their content.

const array = [1, 2, 3];

// evaluates to true
console.log(array === array);

// evaluates to false
console.log([1, 2, 3] === [1, 2, 3]);

Here is a very well constructed answer on comparing the contents of arrays: How to compare arrays in JavaScript?


text:
Q: Opposes in one localhost port ,, any Solution i'm using sinatra to work with ruby , when i am run the file in the terminal the normal port for sinatra is "4567" , but for three days ago the terminal print this
     Sinatra/1.4.5 has taken the stage on 4567 for development with backup from WEBrick
     [2014-09-06 00:15:16] INFO  WEBrick::HTTPServer#start: pid=770 port=4567

also the webrick port is "4567"

A: Sinatra Docs:

:run - enable/disable the built-in web server Boolean specifying
  whether the built-in web server is started after the app is fully
  loaded. By default, this setting is enabled only when the :app_file
  matches $0, i.e. when running a Sinatra app file directly with ruby
  myapp.rb. To disable the built-in web server:
set :run, false

:server - handler used for built-in web server. String
  or Array of Rack server handler names. When the :run setting is
  enabled, Sinatra will run through the list and start a server with the
  first available handler. The :server setting is set as follows by
  default:
set :server, %w[thin mongrel webrick]

Sinatra README:

Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort:

# myapp.rb
require 'sinatra'

get '/' do
  'Hello world!'
end
Install the gem:

gem install sinatra
And run with:

ruby myapp.rb
View at: http://localhost:4567

It is recommended to also run gem install thin, which Sinatra will pick up if available.

By default, Sinatra first looks to see if you have the Thin server software installed--if yes, Sinatra uses Thin to respond to requests on port 4567.  If you do not have Thin installed, next Sinatra checks if you have the Mongrel server software installed, and Sinatra uses Mongrel if it is installed, and finally Sinatra uses the always available Webrick server software, which comes with ruby.
The message you are seeing is Sinatra telling you which server software it is using to respond to requests on port 4567.

A: It's difficult to understand the problem you're seeing. Maybe this will help:
If I create a simple test server containing the sample Sinatra code:
require 'sinatra'

get '/hi' do
  "Hello World!"
end

And save that to my Desktop as test.rb, I can run Sinatra using:
ruby test.rb

Sinatra tells me:
== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from Thin
Thin web server (v1.6.2 codename Doc Brown)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop

If I uninstall Thin:
gem uninstall thin
Remove executables:
  thin

in addition to the gem? [Yn]  y
Removing thin
Successfully uninstalled thin-1.6.2

And run the code again:
ruby test.rb
[2014-09-05 14:41:23] INFO  WEBrick 1.3.1
[2014-09-05 14:41:23] INFO  ruby 2.1.2 (2014-05-08) [x86_64-darwin13.0]
== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from WEBrick
[2014-09-05 14:41:23] INFO  WEBrick::HTTPServer#start: pid=26786 port=4567

In either case, the code does what it's supposed to. I can connect using curl and get "Hello World!" back:
curl http://localhost:4567/hi
Hello World!

Sinatra uses Webrick by default, but will pick other servers over it:
gem install puma
Fetching: puma-2.9.1.gem (100%)
Building native extensions.  This could take a while...
Successfully installed puma-2.9.1
Parsing documentation for puma-2.9.1
Installing ri documentation for puma-2.9.1
Done installing documentation for puma after 3 seconds
1 gem installed

ruby test.rb
Puma 2.9.1 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:4567
== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from Puma

gem install thin
Fetching: thin-1.6.2.gem (100%)
Building native extensions.  This could take a while...
Successfully installed thin-1.6.2
Parsing documentation for thin-1.6.2
Installing ri documentation for thin-1.6.2
Done installing documentation for thin after 0 seconds
1 gem installed

ruby test.rb
== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from Thin
Thin web server (v1.6.2 codename Doc Brown)
Maximum connections set to 1024
Listening on localhost:4567, CTRL+C to stop

curl http://localhost:4567/hi
Hello World!

Use -s to control which server Sinatra uses:
ruby test.rb -s puma
Puma 2.9.1 starting...
* Min threads: 0, max threads: 16
* Environment: development
* Listening on tcp://localhost:4567
== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from Puma

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert PowerPoint Slides into Single Infographics Infographics are graphic visual representations of information, data, or knowledge intended to present information quickly and clearly.
I have PowerPoint presentation with about 8-10 slides, this slides are well formatted with pretty good visualizations. I would like to convert them all into a single big Infographic image?

Does anyone know how to do that? I know how to convert individual slides to an image and then I can merge them all together into a single vertical image. But it is kind of tedious.
Is there a way to do it automatically?
Thanks.

A: I cant think of a way to create a big vertical image from all the slides but as a workaround to get the screenshots of all the slides into one slide, you can use the zoom function.
You can go to Insert --> Zoom --> Summary Zoom. Select all the slides and click Insert. This gives you a section with one single slide with the screenshots of all the slides. You can resize them to fit and export this single slide as a png.
This would not would not give you a big image, the image would be the same size as the slide but you can change dimensions of the PowerPoint proportionally and use maximise to proportionally increase without affecting any elements in the slides. You can do this before carrying out the above summary zoom step. This could give you a bigger image.

A: Just saw this today for some reason.
I'll paste a bit of VBA below that will do the job for you. It creates a second presentation the height of your original presentation * number of slides in your original, then pastes a copy of each original slide onto the one slide in the new presentation, one stacked neatly atop the other, in order.
One caveat:  PPT won't create slides of over 56" in either dimension, so make sure your slides won't cause an overflow. I haven't bothered to test for this in the VBA.
Option Explicit

Sub MakeInfoGraphic()

Dim oInfoPres As Presentation
Dim oInfoSlide As Slide
Dim oPres As Presentation
Dim oSl As Slide
Dim lTop As Long

Set oPres = ActivePresentation
Set oInfoPres = Presentations.Add
oInfoPres.PageSetup.SlideHeight = oPres.PageSetup.SlideHeight * oPres.Slides.Count
oInfoPres.Slides.AddSlide 1, oInfoPres.SlideMaster.CustomLayouts(7) ' Blank slide

lTop = 0

For Each oSl In oPres.Slides
    oSl.Copy
    With oInfoPres.Slides(1).Shapes.PasteSpecial(ppPastePNG)
        .Left = 0
        .Width = oInfoPres.PageSetup.SlideWidth
        .Top = lTop
        lTop = lTop + .Height
    End With
Next

End Sub


text:
Q: Nodejs 8—destruction to already declared variables gives error I have a function like that:
const exec = data => {
  let list, file;

  switch (data.action) {
    case A:
      { list } = getList(data);
      break;

    case B:
      { list } = getList(data);
      break;
  }
}

Node tells me:
SyntaxError: Unexpected token =

But as documented here (Section »Assignment separate from declaration«)

A variable can be assigned its value via destructuring separate from the variable's declaration.

So, am I doing something wrong here, or is that a part of the ES6 spec, which node does not implement as documented?


text:
Q: Why do I get an error after writing anything below this line? import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from pandas.io.html import read_html
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup

url = 'https://www.globenewswire.com/Search/NewsSearch?keyword=complete%20response%20letter&icb=4570&subjectCode=Company%20Announcement'

def CRL_Updater():
    options = Options()
    options.headless = False
    driver = webdriver.Chrome('/Users/sajjad/Downloads/chromedriver', options=options)
    driver.get(url)
    driver.find_element_by_xpath('/html/body/div[2]/div/a[1]/i[1]').click()
    time.sleep(0.5)
    search_bar = driver.find_element_by_xpath('//*[@id="quicksearch-textbox"]')
    search_bar.send_keys('complete response letter')
    search_bar.send_keys(Keys.ENTER)
    time.sleep(1)
    industry_box = driver.find_element_by_id('facetfield_Icb_4570').click()
    time.sleep(1)
    subject_box =  driver.find_element_by_id('facetfield_SubjectCode_Company_Announcement').click()

CRL_Updater()

Here is my code. Essentially everytime I write ANYTHING after the subject_box =  driver.find_element_by_id('facetfield_SubjectCode_Company_Announcement').click() line, I get the following error,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element <input type="checkbox" id="facetfield_Icb_4570" name="facetfield_Icb" value="4570"> is not clickable at point (27, 588). Other element would receive the click:
...

  (Session info: chrome=87.0.4280.88)

I've used selenium on other sites before and done similar things but I never had an issue like this. It seems every time I add anything after that statement I get this error and I'm not entirely sure why. When I do add what I want to do next, my code takes me up until the checkbox lines, and stops there claiming it won't click. Why can it click it before I add more code but not after?

A: maybe the element is not ready when you click it.
Try this,
import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from pandas.io.html import read_html
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://www.globenewswire.com/Search/NewsSearch?keyword=complete%20response%20letter&icb=4570&subjectCode=Company%20Announcement'

def CRL_Updater():
    options = Options()
    options.headless = False
    driver = webdriver.Chrome('/Users/sajjad/Downloads/chromedriver', options=options)
    driver.get(url)
    driver.find_element_by_xpath('/html/body/div[2]/div/a[1]/i[1]').click()
    time.sleep(0.5)
    search_bar = driver.find_element_by_xpath('//*[@id="quicksearch-textbox"]')
    search_bar.send_keys('complete response letter')
    search_bar.send_keys(Keys.ENTER)
    time.sleep(1)
    industry_box = driver.find_element_by_id('facetfield_Icb_4570').click()
    time.sleep(1)
    subject_box = WebDriverWait(driver, 20).until(
    EC.element_to_be_clickable((By.ID, "facetfield_SubjectCode_Company_Announcement")))
    subject_box.click()

CRL_Updater()

A: That depends on what happens on the page because the element could be intercepted by another element or not properly loaded; in this case, it is more likely that the element is intercepted but to avoid both cases you can use WebDriverWait and Javascript combined in order to wait for the element to be clickable and to be able to click the element even if it is intercepted:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

subject_box =  WebDriverWait(driver, 10).until(ec.element_to_be_clickable((By.ID, 'facetfield_SubjectCode_Company_Announcement')))
driver.execute_script("arguments[0].click();", subject_box)


text:
Q: How can I get content out of Google Maps MVCArray? I'm working with google.maps.polygons.  The library uses a google.maps.MVCArray element to store the vertices of the polygon where each vertex contains a latitude and longitude variable.  So I'm able to create fancy polygons on the fly using user mouse clicks.
var listener1 = google.maps.event.addListener(map, "click", function(e) {
    var latLng = e.latLng;
    var myMvcArray = new google.maps.MVCArray();
    myMvcArray.push(latLng); // First Point
    var myPolygon = new google.maps.Polygon({
        map: map,
        paths: myMvcArray, // one time registration reqd only
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2,
        fillColor: "#FF0000",
        fillOpacity: 0.10,
        editable: true,
        draggable: false,
        clickable: true
    });
    google.maps.event.removeListener(listener1);

    var listener2 = google.maps.event.addListener(map, 'click', function(e) {
        latLng = e.latLng;
        myMvcArray.push(latLng);
        console.log(myMvcArray.getArray());
    });
});

My problem is, that console log result is incomprehensible. I've spent a couple of hours trying to figure out how to get clean data from myMvcArray.  I need to use the data elsewhere.

A: So it turns out the trick is this:
console.log(myMvcArray.getArray()[0].lat(), myMvcArray.getArray()[0].lng() );

Which returns:  XX.XX2157415679654 -XXX.XX782657623291
A For/Each loop will also work.
myMvcArray.getArray().forEach(function(value, index, array_x) {
    console.log(" index: " + index + "    value: " + value);
})

Which returns:
index: 0    value: (XX.XX2157415679654, -XXX.XX782657623291)
index: 1    value: (XX.XX209255908967, -XXX.XX77514743805)

Info offered in case anybody else has issues here.  Note, too, the code above works pretty well for letting users define a google.maps.polygon on a map easily.

A: You can use JSON.stringify()
So your code would be
console.log(JSON.stringify(myMvcArray.getArray()))
This works because stringify calls the methods on the MVCArray to get the contents whereas log doesn't.


text:
Q: Closedness of the subset [0,1] in $\Bbb{Q}$ I'm working through the definitions given in 2.18 in Baby Rudin, and I was wondering how to prove that $E = [0,1] \cap \Bbb{Q}$ is closed in $\Bbb{Q}$.
Clearly, the set $[0,1] \cap \Bbb{R}$ is closed in $\Bbb{R}$, since for all neighborhoods of a point $p \in [0,1]$, we can always find a $q \neq p$ such that $q \in [0,1]$. Intuitively, this is because for all $p \in [0,1] \cap \Bbb{R}$, we can always find a $q \in [0,1] \cap \Bbb{R}$ such that $p - \epsilon < q < p$ or $p < q < p+\epsilon$ for all $\epsilon >0$.
However, that the set $E = [0,1] \cap \Bbb{Q}$ is closed in $\Bbb{Q}$ is sort of clear, but not intuitive to me, since $\Bbb{Q}$ is not uncountably infinite as $\Bbb{R}$ is. Does one have to use that fact that it is closed in $\Bbb{R}$ and that $\Bbb{Q}$ is dense in $\Bbb{R}$? How would one solve it from first principles? i.e. Something along the lines of: Consider an arbitrary $p \in [0,1] \cap \Bbb{Q}$, we show that it is a limit point by...
Any help would be greatly appreciated!

A: The density of $\mathbb Q$ plays no role here. If $A$ and $B$ are subsets of $\mathbb R$ and $A$ is a closed subset of $\mathbb R$, then $A\cap B$ is a closed subset of $B$. That's so because the complement of $A\cap B$ in $B$ is equal to $A^\complement\cap B$. Now, since $A$ is a closed subset of $\mathbb R$, $A^\complement$ is an open subset of $\mathbb R$ and therefore $A^\complement\cap B$ is an open subset of $B$.

A: I'm sorry to say I couldn't follow your argument that it is intuitive $[0,1]$ is closed in $\mathbb R$ at all.
$[0,1]$ is closed (in $\mathbb R$) because all its limit points are in in $[0,1]$.  That is; If $p \in \mathbb R$ and for every $\epsilon > 0$ it will always be that the interval $(p-\epsilon, p+\epsilon)$ will contain a point $q \in [0,1]$, then we can conclude that $p$, itself, is in $[0,1]$.
Pf:  If $p < 0$ and $\epsilon = 0 - p= |p|$ then $(p-\epsilon, p + \epsilon) = (2p, 0)$ is disjoint from $[0,1]$ and there is no point, $q$, in common with $[0,1]$.  And if $p > 0$ and $\epsilon = p - 1$ then $(p-\epsilon, p+ \epsilon) = (1, 2p - 1)$ and there is no point, $q$, in common with $[0,1]$.
So if $p$ is a limit point (if there are any limit points, there might not be) then it would have to be that $0 \le p \le 1$ so $p \in [0,1]$.
Thus by definition $[0,1]$ is closed.
.....
But notice there is nothing in that proof that pertains to any property of $\mathbb R$ and it would have held true for any subspace of $\mathbb R$ at all.  Everything we said would be true for $\mathbb Q$ or any $B \subset \mathbb R$.
Also, although the proof to show $[0,1]$ was closed was particular to $[0,1]$, there is no proof of any other set being closed that would rely upon  the space.
Claim: If $A$ is closed in space $X$ then $A\cap Y$ is closed in $Y \subset X$.
Pf:  Let $p \in Y$ be a limit point of $A\cap Y$ then every neighborhood, $N$ of $p$ contains a point $q; q \ne p; q \in A\cap Y\subset A$.  But then $N$ is a subset of a neighborhood $N'\subset X$.  $q \in A$ and $q \in N'$.  So $p$ is a limit point of $A$.   And as $A$ is closed in $X$ that means $p \in A$. And as $p \in Y$.  So $p \in A\cup Y$.  So $A\cup Y$ is closed in $Y$.

A: A bit formal :
Baby Rudin: Theorem 2.30.
Suppose $Y \subset X$. $A$ subset $E$ of $Y$ is open relative to $Y$
$\iff$
$E=Y \cap G$ for some open subset $G$ of $X$.
$B= [0,1]$ is closed in $\mathbb{R}$.
$B^c:= \mathbb{R}$\ $[0,1]$ is open in $\mathbb{R}$.
Hence
$(B^c \cap \mathbb{Q})$ is open in $\mathbb{Q}$.
The complement of $(B^c \cap \mathbb{Q})$ in $\mathbb{Q}$ is closed in $\mathbb{Q}$ :
$\mathbb{Q} - (B^c \cap \mathbb{Q})=$
$\mathbb{Q} \cap (B^c \cap \mathbb{Q})^c =$
$\mathbb{Q} \cap (B \cup \mathbb{Q}^c)=$
$(\mathbb{Q} \cap B)\cup (\mathbb{Q} \cap \mathbb{Q}^c)=$
$\mathbb{Q} \cap B$.


text:
Q: Remove background from LaTeX table I am creating a Beamer presentation with the metropolis package and I use the ctable package to include tables. However, the background of the slides is not exactly white, it has a nuance of colour to improve visibility.
After typesetting, you can clearly see that the background of the tables is whiter than the slide background. It is not a huge inconvenient, but I was wondering if there is any way to remove the table background. I have checked the colortbl package, but I couldn't find anything.
This is a working example:
\documentclass[10pt]{beamer}
\usetheme[progressbar=frametitle]{metropolis}

\usepackage{times}
\usepackage[english]{babel}
\usepackage{ctable}

\begin{document}
    \begin{frame}
            \ctable[
                caption = My caption,
                label = theLabel,
                pos = tb
            ]{ccccc}{
            }{\FL
            \textbf{A} & \textbf{B} &   \textbf{C} & \textbf{D} & \textbf{E} \ML
            AAA & - & 0.59 &    1.19    & 6,85 \NN
            ABC  & 11.6 - 19.4\%    & 0.98  & 1.29  & 6.20 \NN
            CDA & 10.8 - 21.2\%  & 1.02 & 1.33  & 6.12 \LL
            }
    \end{frame}
\end{document}

A: Normally, you would use the bgopacity=0 key to make the \ctable background transparent.  However, that feature is disabled when tikz is loaded, which is the case for the beamer document class.
Thus, the alternative is to set the framebg (frame background color) key to the same as the metropolis theme, here guessed as .98 .98 .98.
\documentclass[10pt]{beamer}
\usetheme[progressbar=frametitle]{metropolis}

\usepackage{times}
\usepackage[english]{babel}
\usepackage{ctable}

\begin{document}
    \begin{frame}
            \ctable[
                caption = My caption,
                label = theLabel,
                pos = tb,
                bgopacity=0,% DISABLED
                framebg= .98 .98 .98
            ]{ccccc}{
            }{\FL
            \textbf{A} & \textbf{B} &   \textbf{C} & \textbf{D} & \textbf{E} \ML
            AAA & - & 0.59 &    1.19    & 6,85 \NN
            ABC  & 11.6 - 19.4\%    & 0.98  & 1.29  & 6.20 \NN
            CDA & 10.8 - 21.2\%  & 1.02 & 1.33  & 6.12 \LL
            }
    \end{frame}
\end{document}


text:
Q: How to properly test asynchronous faye server? I am using the private_pub gem to have real-time functionality in my app.
I feel really guilty, but I have dropped testing this app!
In order to make sure everything works manually, I have to have two browsers open communicating with each other. (Imagine a facebook chat.)
I don't know how to have two browsers open at once in selenium, capybara, or cucumber. I am open to any kind of testing framework or utility.
How do I test with two open browsers? Let me know if you need any more information.
Thank you!

A: Using selenium you can open how much browsers that you want
But you need to save each browser instance in different variable (WebDriver object)
Then do whatever you want with each instance
Be aware that writing and maintaining such tests required a lot of effort (errors, false positive, timing issues, and much more)


text:
Q: sorting on the sql array in rails 3 @project_list =  Project.find_by_sql("select p.id, p.name, (select sum(i.estimated_hours) from issues i where  i.project_id = p.id)  as estimated_hours,(select sum(t.hours)  from time_entries t where p.id = t.project_id )  as Spent_Hours,(select u.firstname  from users u  where u.id IN(select user_id from members m where m.project_id = p.id and m.id IN   ( select member_id from member_roles   where role_id IN (select id from roles r where r.name  = 'Project Coordinator') )) limit 1 ) as Coordinator,(select u.firstname  from users u  where u.id IN(select user_id from members m where m.project_id = p.id and m.id IN   ( select member_id from member_roles   where role_id IN (select id from roles r where r.name  = 'Project Manager') )) limit 1) as  Manager   from projects p where p.status IN ('16','14','15','17','18','19','20')   group by p.id")

using above query I can get the records in my view page
 Now i want further sorting or searching i.e. by coordinator,start date ,end date etc
 But I can not apply search method on the resulting array because find_by_sql returns an array.Though the above query seems difficult to write using the rails way So

*

*is there any other way like make the read-only model  or some thing like that or

*can any one helps me to write this query using rails way.

any help or suggestion would be a  great help


text:
Q: Generic return value (java) This works nicely:
// Return all objects with code 'code'.
static List<? extends ICode> getObjects(String code, List<? extends ICode> list)
{
  <ICode> retValue = new ArrayList<ICode>();
  for (ICode item : list)
  {
    if (item.getCode().equals(code))
    {
        retValue.add(item);
    }
  }
  return retValue;
}

The 'singular' version can be:
// Return the first object found with code 'code'.
static ICode getObject(String code, List<? extends ICode> lijst)
{
  for (ICode item : lijst)
{
     if (item.getCode().equals(code)) return item;
}
return null;
}

But instead of return value ICode I would like return value <? extends ICode>.
Can it be done?
See Jon Skeets answer, I now prefer to use the T instead of ? also in the plural version:
// Return all objects with code 'code'.
    public static <T extends ICode> List<T> getObjects(String code, List<T> lijst)
    {
        List<T> retValue = new ArrayList<T>();
        for (T item : lijst)
        {
        if (item.getCode().equals(code))
        {
        retValue.add(item);
        }
      }
      return retValue;
    }

A: I assume you want it to be the same type as the actual list. In that case, this should do it:
static <T extends ICode> T getObject(String code, List<T> list)
{
  for (T item : list)
  {
     if (item.getCode().equals(code)) return item;
  }
  return null;
}

A: If you let the return type be ICode then you can return any type that extends ICode.


text:
Q: Flex div is growing vertically when hovered because of its content but not shrinking back Here is what I did, I extracted the important part: http://jsfiddle.net/P9Ftp/3/
My problem is that if the item contains too much text, it will wrap to the second line. If the space gets too small only if hovered though, it grows in order to show the text properly but does not shrink back down once the mouse leaves the field.
By increasing the left margin but not allowing for more space, the text wraps:

asdf asdfadsf asdfa sdf adsfadsf asdf a

The critical CSS part:
section:hover .content {
    margin-left: 32px;
}

Is this expected behaviour / what can I do to avoid this?
Thanks a lot in advance!
UPDATE: appears to be a Chrome issue. Workaround would be appreciated.

A: A solution could be to add display: block; to section (or whatever other display style, such as inline-block)
This changes slightly the appearance, but maybe you can work on other rules to get the desired result.
In general, I think that adding display: flex; to all elements (body * rule) is too broad, and maybe could lead to undesired results.
Working fiddle on Chrome: http://jsfiddle.net/P9Ftp/4/


text:
Q: How to start with developing JavaScript for dynamics crm? I am familiar with Javascript and would like to start developing for dynamic crm.
I downloadi the MS CRM SDK, but got lost there.

*

*Is the Javascript syntax for MS CRM indentical as regular JS ?

*What is the XRM ?

*I tried to hide existing options from picklist and then show it without a success.

A: XRM is (Any RelationShip Management). The following link gives more details on XRM Programming. XRM is the framework used to access CRM Page Entities and Fields and perform client custom validations and web service integrations.
This link gives basic details of XRM Programming.
https://msdn.microsoft.com/en-us/library/gg328261.aspx
The following book has easy to understand samples
ISBN 978-1-78439-415-8,
Microsoft Dynamics CRM 2015 Application Design
By Mahender Pal


text:
Q: Split comma separated multiple strings in c# I have row which is coming from csv file like
"abc@example.com","seattle,US","9999 00000"

Expected Output:
abc@example.com
seattle,US
9999 00000

Actual output when I do string.Split(','):
"abc@example.com"
"seattle
US"
"9999 00000"

A: If you use " character to qualify a column, you can split by ","
string input = "\"abc@example.com\",\"seattle,US\",\"9999 00000\"";

string[] result = input.Trim('"').Split(new string[] { "\",\"" }, StringSplitOptions.None);


text:
Q: ext js - el.ownerDocument.createRange() errors in IE 8 HI,
I am trying to dynamically add a form to a tab in Ext-js. (the tab has already been rendered). fyi, i am using I am using Ext 2.2.
the error occurs when during the tab.add function:
ie:
function tabactivate(tab)   {
            var newItem= new Ext.FormPanel(.....);
            **tab.add(newItem)**;    //ERRORS HERE
            tab.doLayout();
 }

I get this error on line 247 of ext-all-debug.js
which is
range = el.ownerDocument.createRange();

the error is (Object doesn't support this property or method.)
This works fine in Firefox but breaks in IE8.
Does anyone know a workaround for this ?
Thanks

A: This sounds very similar to an issue I had with ExtJS 2.2 and IE.
It seems like a lot of places in the Ext code that you see code like this:
var td = document.createElement("td");
this.tr.insertBefore(td, this.tr.childNodes[index]);

When in fact that doesn't work on IE because "this.tr.childNodes([0])" does not yet exist.
My workaround was to override the prototype (in my case insertButton() in Ext.Toolbar) to check for the existence of this.tr.childNodes([0]), using a different function or creating it if it didn't exist.
I hope that I'm correct that this is the problem you are running into.

A: So i found an old string that had the solution for me.
http://www.extjs.com/forum/showthread.php?t=7912&highlight=createRange
Essentially, when i was instantiating empty tabs, i had my html property set to this:
html: ' ',
once i either took the property out completely or i changed to
html: ''

it stopped breaking.
Thanks

A: IE (even 8) doesn't support the document.createRange() method.
You can try var supportsDOMRanges = document.implementation.hasFeature("Range", "2.0"); to see whether a browser supports DOM ranges per the standard.


text:
Q: Shot map only displays one shot despite having more So, I tried making a shot map in python using Statsbomb's free data, and when the map is generated, it only displays one shot and the other doesn't appear whilst the desired result is to have all the shots appear in the map.
Here's my code:
pitchLengthX=120
pitchWidthY=8

home_team_required ="Iceland Women's"
away_team_required ="France Women's"

pitch = Pitch()
fig, ax = pitch.draw(figsize=(120, 80))

for i,shott in shots.iterrows():
    pitchLengthX=120
    pitchWidthY=80
    goal=shott['shot_outcome']=='Goal'
    team_name=shott['team']

    circleSize=2

    x=shott['location'][0]
    y=shott['location'][1]

if (team_name==home_team_required):

        if goal:
            shotCircle=plt.Circle((x,pitchWidthY-y),circleSize,color="red")
            plt.text((x+1),pitchWidthY-y+1,shott['player'])

        else:
            shotCircle=plt.Circle((x,pitchWidthY-y),circleSize,color="red")
            shotCircle.set_alpha(.2)

        ax.add_patch(shotCircle)

elif (team_name==away_team_required):

  if goal:
    shotCircle=plt.Circle((x,pitchLengthX-x,y), circleSize,color="blue")
    plt.text((pitchLengthX-x+1),shott['player'])
  else:
    shotCircle=plt.Circle((x,pitchLengthX-x,y), circleSize,color="blue")
    shotCircle.set_alpha(.2)

  ax.add_patch(shotCircle)

plt.text(5,75,away_team_required + ' shots')
plt.text(80,75,home_team_required + ' shots')

fig.set_size_inches(20, 14)

plt.show()

The output is shown on the picture attached
here


text:
Q: Is there a way to ensure an open popup is within the view after doing fitbounds So I have too points:
a = fixed location, with open popup "Destination"
b = user's current location, no popup
I know I can easily call (conceptually)
map.fitbound([latlng of a, latlng of b])
and that will zoom my map to contain the two points, the trouble is that it doesn't account for the open popup.  As I have no idea of the user's location, direction from the fix point, or distance, I don't think that using padding possible.
Any hints on how to solve this?
Here's a fiddle that demonstrates the issue.
I've looked at couple of the posts about centering popups, but the javascript there is slightly about me, and the js2coffee converter doesn't like it.

A:
I don't think that using padding is possible

Yes, yes it is, e.g.:
  map.fitBounds(someLatLngBounds, {padding: [100, 100]});

See a working demo, and don't forget to read the docs.

A: You can explore a solution where popups are always visible without having to move the map.
For example: https://github.com/erictheise/rrose
Here is how I use it: http://franceimage.github.io/map
Move the map to have a marker near an edge, hover or click on it, the popup is always visible.

A: To have the popups appear in the same position every time
I'm using the following CSS solution to fix the popup to always appear in the same place where I want it
<style>
    .leaflet-popup {
        transform: none !important;
        position: absolute;
        top: 600px !important;
        left: 20px !important;
    }
</style>

And then to keep the map from moving every time you click on a marker, set autoPan to false in the popup options (https://leafletjs.com/reference-1.6.0.html#popup-autopan) :
 { autoPan: false }


text:
Q: How to install correctly @vue/cli Command:
npm install -g @vue/cli

What is the problem?
The running environment is iPad.
App is named Code.
node v12.19.0
npm v8.4.1
npm ERR! code ENOTEMPTY
npm ERR! syscall rename
npm ERR! path /private/var/moble/Containers/Shared/AppGroup/0A5F620F-9DE9-49DC-9139-DDF9AA52EA48/lib/lib/node_modules/@vue/cli
npm ERR! dest /private/var/moble/Containers/Shared/AppGroup/0A5F620F-9DE9-49DC-9139-DDF9AA52EA48/lib/lib/node_modules/@vue/.cli-y8nVRrYF
npm ERR! errno -66
npm ERR! ENOTEMPTY: directory not empty, renam '/private/var/moble/Containers/Shared/AppGroup/0A5F620F-9DE9-49DC-9139-DDF9AA52EA48/lib/lib/node_modules/@vue/cli'->'/private/var/moble/Containers/Shared/AppGroup/0A5F620F-9DE9-49DC-9139-DDF9AA52EA48/lib/lib/node_modules/@vue/.cli-y8nVRrYF'


text:
Q: Get unique pairs of elements from an ArrayList in Java I've got an ArrayList which contains a series of integers (represnting indices in another ArrayList).
I need to extract each Unique pair eg...
ArrayList = 1,4,5,7

I need:
1:4
1:5
1:7
4:5
4:7
5:7

What's the simplest method of achieving this?

A: convert list to Set and back to List for unique filtering
for(int i = 0 ; i < list.size(); i ++){
  for(int j = i+1 ; j < list.size(); j ++){
    System.out.println(list.get(i) + "," + .list.get(j))
  }
}

A: Well loop through all possible choices for the first element. For each of those, loop through all possible choices for the second.
I'll leave the finding duplicates part up to you (hint: use a Set).

A: You could have two indices: one for the first part, the other for the second.  Then interate through with the first form the beginning to the one-but-last element, and in an inner loop iterate through with the second from one-past-the first to the end.

A: I wonder if using a graph structure with unidirectional relation would suit this problem.
It is way much work than a simple permutation, but probably more interesting to implement. Specially for a large number of pairs.


text:
Q: How do I make my website work with download managers? My website requires a user to login before downloading files, I wish to add support for download managers such as Orbit and Free Download Manager. I have tried downloading a file using these managers and entering the user name and password inside the managers but they download my login page instead of the file.
My login is typical, built on cakephp and doesnt even have CSRF.
Is there something special I need to do to enable the download managers to successfully login?

A: Download managers don't login. They should honor cookies, however. I beleive the problem of your system is cookie lifetime. You, most probably, set cookies to expire when browser closes. So, download managers send cookie, that already expired.
Check this answer for more details.


text:
Q: What's the AS3 equivalent for MovieClip.CreateEmptyMovieClip? I have some older AS2-style Haxe code which uses flash.Lib.Current.CreateEmptyMovieClip() to create a slideshow of disk-based images. It creates a new clip for holding each image and simply fades each image in and out with alpha levels.
Compiling it with -swf -swf-version 8 creates an SWF file fine and this works in the browser.
However, I'm in the process to converting this over to -swf9 and I find that the MovieClip no longer has that method.
How do you load up a series of images with Haxe (AS3-style)?
The code, for what it's worth, is along these lines:
static function main() {
  mc = flash.Lib.current;
  var clip : MovieClip;

  clip = mc.createEmptyMovieClip ("clip_000", mc.getNextHighestDepth());
  clip.loadMovie ("demo_img000.jpg");

  : : :

A: You can just create a new display object w/o linking it to a clip in the library like this:
var sprite:Sprite = new Sprite() // -- creates a sprite
var clip:MovieClip = new MovieClip() // -- creates a movie clip

You can then add it to another display object by using the addChild() method:
myOtherClip.addChild( sprite )

The above line will add the new clip to the top of the display list, just like using getNextHighestDepth().
If you want to add a clip a depth between two other clips you can use:
myOtherClip.addChildAt( movieClip, 2 ); // -- adds a clip at 2 levels up from 0

As for loading an image, loadMovie does not exist in AS3. You need to use the Loader and URLRequest objects like this:
var loader:Loader = new Loader();
var request:URLRequest = new URLRequest( 'path_to_my_image.jpg' );
loader.addEventListener( Event.COMPLETE, onLoadComplete );
loader.load( request );

function onLoadComplete( event:Event ):void
{
     if( loader.content ){
         clip.addChild( loader.content )
     }
}


text:
Q: Use of the word "state" I wonder if the use of "state" in the sentence below is correct or not. What I want to learn is whether this sentence is grammatically correct or not.

Water vapour is water's state turned into gas form by boiling at 100 degree.

A: I can't easily explain why the sentence is poor, but I would write it is as

Water vapour is its gaseous state formed by boiling at 100 degrees.

This also avoids using the word "water" twice in proximity.
However the sentence is scientifically incorrect. Water vapour is created naturally from water, the process of evaporation - turning from liquid into vapour, such as when a puddle dries out. Boiling it simply makes it impossible for the water to remain in its liquid state.


text:
Q: Read last incomming SMS from phone inbox This is my code of brodcast receiver
 Bundle myBundle = intent.getExtras();
    SmsMessage [] messages = null;
    String strMessage = "";

    if (myBundle != null)
    {
        Object [] pdus = (Object[]) myBundle.get("pdus");
        messages = new SmsMessage[pdus.length];

        for (int i = 0; i < messages.length; i++)
        {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            strMessage += "SMS From: " + messages[i].getOriginatingAddress();
            strMessage += " : ";
            strMessage += messages[i].getMessageBody();
            strMessage += "\n";
        }

        Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
        Intent inten = new Intent(context, MainActivity.class);
        inten.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        inten .putExtra("strMessage", strMessage);
        context.startActivity(inten);

I'm getting values in my main activity like this:-
Intent inten= getIntent();

String strMessage = inten.getStringExtra("strMessage");
Toast.makeText(getApplicationContext(),strMessage,Toast.LENGTH_LONG).show();

but, getting null value,please guide me properly as I'm new for this.

A: You just need to register a BroadcastReceiver with IntentFilter of "android.provider.Telephony.SMS_RECEIVED". Then you can get a received message from the intent like this:
    try {
        Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
        for (Object msg : messages) {
            byte[] bytes = (byte[]) msg;
            SmsMessage message = SmsMessage.createFromPdu(bytes);
            String messageBody = message.getDisplayMessageBody(); // this is your SMS message body
        } catch (Exception e) {
            //catch exception here
        }

You will need to add a <uses-permission android:name="android.permission.RECEIVE_SMS"/> to your AndroidManifest.xml and handle Runtime permissions for API > 23.


text:
Q: How to show toast message using JobScheduler I have been learning jobscheduler in andorid. I have trying to show a toast message in the onstartjob() after every 1minute. But its not showing up. Any help will be grateful.
jobschedul_service .class:
package com.prajwal.jobscheduler;

import android.app.Service;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class jobschedul_service extends JobService {

    @Override
    public boolean onStartJob(JobParameters jobParameters) {

        Toast.makeText(getApplicationContext(), "After 15 minutes", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}

MainActivity.class:
package com.prajwal.jobscheduler;

import androidx.appcompat.app.AppCompatActivity;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_ARTWORK_JOB_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        JobScheduler jobScheduler =
                (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder
                (LOAD_ARTWORK_JOB_ID, new ComponentName(this, jobschedul_service.class))
                .setPeriodic(900000)
                .build());
    }
}

Manifest.xml:
  <service
        android:name=".jobschedul_service"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BIND_JOB_SERVICE"></service>

A: Got the answer!
The reason was the setperiodic(long interval).
As per the ss below:

This function was added in API 21 i.e Lolipop version. Whereas I was running the app on version > Lolipop.
Whereas this new function in the image below:

was added in API 24 i.e. Nougat
Hence, if you are targetting your app below Nougat i.e < Nougat but >= Lolipop then use setPeriodic(long interval) method whereas if u r targetting >= Nougat then use setPeriodic(long interval, long flexinterval).
Solution
 if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        {
            builder.setPeriodic(900000,6000);
        }
        else
        {
            builder.setPeriodic(900000);
        }


text:
Q: Stop OWA redirect over https iis I'm currently running a Windows Server 2016 machine, partnered with Exchange Server 2016 and IIS 10. I'm trying to separate the Exchange owa page and run a web host separate from the same IIS web host such that https://mail.example.com redirects to https://mail.example.com/owa and https://example.com just uses the default root domain. I know this isn't best practice for security reasons however this is the way I have / want to do it.
However with just a normal Exchange and IIS setup all the latest versions to date. I've configured a SSL cert through Let's Encrypt Authority. However with the binding to the SSL certificate the root directory automatically redirects to OWA virtual directory when using https protocol for a secure connection.
Does anyone know how to stop that redirect unless typed as mail.domain.com. I know it's possible as when running server 2008 and exchange 2010 it worked as intended out of the box. I just want a fix as clients aren't seeing my page because of it.
Thanks so much in advance.
Edit: As per conversation in comments I've since tried to create a second site within IIS and bind the hostname to mail.domain.com, however when trying to do the same with https only one ssl cert can be used across all sites with https. So i've used one containing all domains.
However even though setup as such with different sites and hostnames directing to the other sites https://example.com still redirects to https://mail.example.com/owa for some reason.


text:
Q: php-fpm, nginx, and headers Recently I switched a project from standard PHP with Apache, to PHP-FPM with NGINX. I immediately noticed that all JSON requests were returning the text/html content type where previously they returned application/json.
After hours searching google and stack overflow and finding nothing and honestly starting to think I was crazy, I finally realised, purely by accident, that the problem stemmed from setting the Content-Type header twice. Once at the very start of the application's entry point, a default to text/html, and then once again when specifically wanting to send JSON (in the case of an XHR request) by setting application/json.
My question is, why the difference? Why does code that works perfectly fine under Apache and PHP, stop working under NGINX and PHP-FPM? What is it about the combination that makes the second call to header() fail?
And as a follow up, should the code have ever worked under Apache/PHP, or is setting the Content-Type twice inherently bad / frowned upon?

A: Setting the Content-Type header twice is illegal and therefore the behaviour will be undefined.
See RFC7230 section 3.2.2:

A sender MUST NOT generate multiple header fields with the same field name in a message unless either the entire field value for that header field is defined as a comma-separated list [i.e., #(values)] or the header field is a well-known exception (as noted below).

Web servers often sanitise the HTTP headers emitted by applications, such as adding missing headers. One assumes that Apache removes the duplicate header whereas nginx does not.


text:
Q: need to copy an image from a doc to another with Google Script I'm trying to copy an image from a google doc "template" and paste in another doc with script. Already search for some solutions in web but none worked for me. Here's my code, this is getting an invalid image data error.
function creatingLabels(link, document, model, labelTemplate) {
    var headerLabel = labelTemplate.getBody().getImages();

    Logger.log(headerLabel.toString());
    Logger.log(headerLabel);

    var textLabel = labelTemplate.getBody().getText();

    var text = textLabel.replace(' %LOCAL%', model);

    var QrCode = getImageFromURL(link);

    document.getBody().insertImage(1, headerLabel)
    labelTemplate.getBody().setText(text);
    labelTemplate.getBody().insertImage(1, QrCode);
}

function getImageFromURL(link) {
    var url = encodeURI(link)

    return UrlFetchApp.fetch(url, { muteHttpExceptions: true });
}

A: This function copies an image from one document and creates another document and appends the image to the new document. It also displays the image on a dialog. If your looking for the image and can't find it, then look in your root folder.
function copyImage() {
  var doc=DocumentApp.getActiveDocument();
  var body=doc.getBody();
  var images=body.getImages();
  var image=images[0];
  var b64Url='data:' + image.getBlob().getContentType() + ';base64,' + Utilities.base64Encode(image.getBlob().getBytes());
  var html=Utilities.formatString('<img src="%s" width="640" height="480" />',b64Url);
  var userInterface=HtmlService.createHtmlOutput(html).setWidth(700).setHeight(550);
  DocumentApp.getUi().showModelessDialog(userInterface, 'Images');
  var doc1=DocumentApp.create('SO2');
  doc1.getBody().appendImage(image.getBlob());
  var image=doc1.getBody().getImages()[0];
  image.setWidth(640);
  image.setHeight(480);
  doc1.saveAndClose();
}


text:
Q: Import csv file and change the name of certain values Okay so my problem is that I want to import a csv file (that is separeted by commas, so R reads it as a dataframe).
The first column is called "Animals", and below there is "crocodile", "elephant" etc.
Here I want to replace names of the animals to be either "reptile" or "mammal".
How do I do this?
Thank you a lot in advance

A: You need to make a reproducible code. A reproducible example allows someone else to recreate your problem by just copying and pasting R code. Btw if I understand correctly try this:
 library(dplyr)

 your_df = read.csv("the file path", sep = ",") %>%
           mutate(Animals = case_when(Animals == "crocodile" ~ "reptile",
                                      Animals == "elephant" ~ "mammal",
                                      T ~ as.character(Animals)))

Where "the file path" is your csv file path like "D:/Users/YourUser/Desktop/my_file.csv"


text:
Q: Graphometric Signature Android library Are there any libraries about Graphometric Signature for Android platform? I found only Olivetti toolkit, but I would use a free library for my Android App.

A: you can try Namirial S.p.A. solution.
http://www.graphosign.com/
http://www.firmagrafometrica.it/
You can use the Namirial solution with Windows, Android & iOs.
They also provide an sdk for the all platform.
For more information you can send an email to: info@graphosign.com

A: I've got the same task last year. The one which looked best is http://www.signotec.com/internet/page.php?naviID=900000026&site=900000025&typ=2&s_sprache=en but it's not free at all.
Some others:

*

*http://www.xyzmo.com/en/products/Pages/digital-signature-ipad-android.aspx

*http://www.androidpit.de/de/android/market/apps/app/com.xyzmo.signature/SIGNificant-E-Unterschrift

*http://www.binarysolutions.biz/2010/12/signature-capture-for-android.html

*http://www.supersignature.com/default.aspx

*http://www.gocanvas.com/content/blog/post/create-your-own-android-mobile-app-with-signature-capture-in-5-minutes

*https://play.google.com/store/apps/details?id=AB.AN&feature=search_result#?t=W251bGwsMSwyLDEsIkFCLkFOIl0

*https://play.google.com/store/apps/details?id=com.rockalldesign.signaturesaver&feature=also_installed


text:
Q: docker port exposing issue I have a flask application that I'm trying to dockerize but the ports are not getting exposed properly.
DockerFile
FROM tiangolo/uwsgi-nginx-flask:python3.7

LABEL Name=testAPP Version=0.0.1
EXPOSE 5000

ADD . /app
WORKDIR /app

# Using pip:
RUN python3 -m pip install -r requirements.txt

ENTRYPOINT [ "python3" ]
CMD ["application.py" ,"runserver","-h 0.0.0.0"]

Docker Build is successful:
docker build --rm -f "Dockerfile" -t testAPP .

Docker Run is building the image successfully
docker run -device -expose 5000:5000 testAPP

Also tried,
docker run --rm -d -p 443:443/tcp -p 5000:5000/tcp -p 80:80/tcp testAPP

But when I try to access the site it throws an error
site can't be reached error
Flask App(Inside the APP)
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)

On Execution of the command
Docker container ps

CONTAINER ID     IMAGE        COMMAND      CREATED          STATUS    PORTS      NAMES
 8724cdb38e14    testAPP   "/entrypoint.sh pyth…" 15 seconds ago   Up 13 seconds    80/tcp, 443/tcp, 0.0.0.0:5000->5000/tcp  funny_galois

A: Defining a port as exposed doesn't publish the port by itself. Try with the flag -p , like:

-p container_port:local_port

example:
docker run -p 8080:8080 -v ~/Code/PYTHON/ttftt-recipes-manager:/app python_dev

But before running try to check if there is something else that already running on the specified port like:
lsof -i :PORTNUM

and after with something like:
docker logs my_container

A: Make sure you're mapping your localhost port to the container's port
docker run -p 127.0.0.1:8000:8000 your_image
And once you're application is in the container, you want to run your app with the host set to 0.0.0.0


text:
Q: How do I use INTERNET_HANDLE_TYPE_INTERNET to constrain the effects of END_BROWSER_SESSION to the current WebBrowser? We have a WebBrowser that needs to have login information reset.
There is a solution in this question that suggests using INTERNET_HANDLE_TYPE_INTERNET with INTERNET_OPTION_END_BROWSER_SESSION. However, I'm not sure where INTERNET_HANDLE_TYPE_INTERNET should go.
private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
private const int INTERNET_HANDLE_TYPE_INTERNET = 1;

[DllImport("wininet.dll", SetLastError = true)]
private static extern bool InternetSetOption(IntPtr hInternet, int dwOption,
    IntPtr lpBuffer, int lpdwBufferLength);

I call it right before I navigate:
InternetSetOption(IntPtr.Zero, INTERNET_OPTION_END_BROWSER_SESSION, IntPtr.Zero,
    0);
browserCtrl.WebBrowser.Navigate(loginUrl);


text:
Q: What are the default access rights for a process started with ShellExecuteEx? I need to perform certain operations on a process started with ShellExecuteEx - like waiting for it, duplicating handles, querying and setting information etc. Now I am wondering if I can do all these things on the hProcess member which is returned in the SHELLEXECUTEINFO structure I pass to ShellExecuteEx. Does anybody know this?
Does the process that called ShellExecuteEx have rights like PROCESS_DUP_HANDLE, SYNCHRONIZE, PROCESS_SET_INFORMATION, PROCESS_QUERY_INFORMATION (and so on) by default, when using the returned hProcess?

A: Yes. The online time you need to worry about access rights is if you do any task that trigger the uac, then you need to set the requestedExecutionLevel= 'highestAvailable'

A: I would guess that it is the same as what you get from CreateProcess, though even that documentation doesn't say (I would venture PROCESS_ALL_ACCESS).  In any event, you could always do GetProcessId() and OpenProcess() to open it with whatever access you need.


text:
Q: Custom Module ACl not working in Magento <config>
    <menu>
      <report>
            <title>Reports</title>
            <sort_order>80</sort_order>
             <children>
               <customreport>
                 <title>Category base Reports</title>
                 <action>customreports/report_index/customreport</action>
                 <sort_order>10</sort_order>
               </customreport>
             </children>
      </report>
    </menu>
    <acl>
        <resources>
            <all>
                <title>Allow everything</title>
            </all>
            <admin>
                <children>
                    <report>
                        <children>
                            <customreports translate="title" module="customreports">
                                <title>Category base Reports</title>
                                <sort_order>60</sort_order>
                            </customreports>
                        </children>
                    </report>
                </children>
            </admin>
        </resources>
    </acl>
</config>

A: You have to add complete menu in ACL too
<config>
    <menu>
      <report>
            <title>Reports</title>
            <sort_order>80</sort_order>
             <children>
               <customreport>
                 <title>Category base Reports</title>
                 <action>customreports/report_index/customreport</action>
                 <sort_order>10</sort_order>
               </customreport>
             </children>
      </report>
    </menu>
    <acl>
        <resources>
            <all>
                <title>Allow everything</title>
            </all>
            <admin>
                <children>
                    <report>
                     <title>Reports</title>
                     <sort_order>80</sort_order>
                      <children>
                       <customreport>
                        <title>Category base Reports</title>
                        <action>customreports/report_index/customreport</action>
                        <sort_order>10</sort_order>
                      </customreport>
                    </children>
                  </report>
                </children>
            </admin>
        </resources>
    </acl>
</config>

A: <config>
    <menu>
      <report>
            <title>Reports</title>
            <sort_order>80</sort_order>
             <children>
               <customreport>
                 <title>Category base Reports</title>
                 <action>customreports/report_index/customreport</action>
                 <sort_order>10</sort_order>
               </customreport>
             </children>
      </report>
    </menu>
    <acl>
        <resources>
            <all>
                <title>Allow everything</title>
            </all>
            <admin>
                <children>
                    <report>
                     <title>Reports</title>
                     <sort_order>80</sort_order>
                      <children>
                       <customreport>
                        <title>Category base Reports</title>
                        <sort_order>10</sort_order>
                      </customreport>
                    </children>
                  </report>
                </children>
            </admin>
        </resources>
    </acl>
</config>


text:
Q: Como puedo refactorizar exceso de if con polimorfismo en php Supongamos que tengo una clase de nombre User con un metodo post que recibe un parámetro y dependiendo del contenido ejecuta un método.
class User
{
    public static function  post($request)
    {
        if ($request[0] == 'register') {
            return self::register();
        } elseif ($request[0] == 'login') {
            return self::login();
        } elseif ($request[0] == 'change') {
            return self::changePaswd();
        } elseif ($request[0] == 'reset') {
            return self::resetPaswd();
        // Dispara una excepción
        throw new Exception("No existe el metodo");
    }
}

En este momento son pocas opciones posibles pero puede crecer mucho mas por lo tanto creo que lo mejor es refactorizar con polimorfismo, gracias!

A: Para hacer lo que tú quieres es muy fácil con php ya que este permite que el nombre de los métodos se pueda llamar de forma dinámica.
Ejemplo:
<?php
class User
{
  /**
   * @param $method => Nombre del método que quiere llamar
   * @return mixed
   */
  public static function post($method)
  {
      return self::{$method}();
  }

  public static function register() {
      echo 'Método register';
  }

  public static function login() {
      echo 'Método login';
  }
}
User::post('login');

Con esto al llamar al método post simplemente le pasas como parámetro el nombre del método que quieres ejecutar y listo, te evitas de hacer muchos if, puede tener los métodos que quieras y solo necesitas el nombre para ejecutarlo.

A: Entiendo que request siempre va a tener el primer elemento como la acción que quieres realizar:
<?php
class User
{
    public static function post($request)
    {
        $method = $request[0];
        if(!method_exists($this, $method){
            throw new Exception("No existe el metodo");
        }
        return self::{$method}();
    }

    private static function register(){};
    private static function login(){};
    private static function change(){};
    private static function reset(){};
}


text:
Q: Site Creation in a load balanced environment We have some functionality that automatically creates sites.
What we are wondering is if the request goes to one of the servers to create the site, and then there is a request to read the site that goes to the other server. Is there a chance that the site is not available?

A: No, a site and its contents are stored in a Content Database and your load balanced web front end servers operate on the same Content Database. Once it's in the database (when creation completes) it's ready to be served by any of the web front ends.

A: I've only seen this when creating new site collections, not subsites off an existing site collection. There are some instances, especially in sharepoint 2003, where the cache on the other servers wouldn't be expired correctly, and I would get a 404 when trying to access a newly created site collection on another wfe from which it was created.  If you are running into that on SP 2007 make sure your farm is configured properly and the sptimer service is working correctly on all of your wfe's.


text:
Q: Get categories of queried posts I queried posts from an array of IDs:
$args = array(
    'post_type' => 'post',
    'post__in' => $ids,
    'orderby' => 'id',
    'order' => 'DESC'
);

Now I want to display a form with checkboxes for the categories of these queried posts. For example if there are two posts from the category "Drama" I dont want the "Comedy"-Category-Checkbox to be displayed.
The problem: As there is no post__in parameter for get_categories, I have no idea, how I can do this.
$catargs = array(
    'post__in' => $ids,
);

$categories = get_categories(  $catargs  ); ?>

A: You need a:

*

*array of post id ( ok )

*array of category id ( not yet )

*array of category id/name with unique value ( not yet )

using wp_get_posts_categories( $post_id ); returns an array of category id, so you can loop your $ids calling this function to collect all categories id.
with the array of categories id you can set up a brand new one with id/name pair and then with array_unique(); clean up it from duplicated values.
I can't find any other solution, so:
UPDATE
<?php
/*
 *Loop through your $ids and:
 * get all the categories id for your queried posts ( wp_get_post_categories( $id ) )
 * loop through this new array to get single category data ( get_category( $catid ) )
 * set up a new array with term_id/name value pairs ( $categories )
 * clean up your new array from duplicate values ( array_unique( $categories ) )
 */
foreach( $ids as $id ){
$catids = wp_get_post_categories( $id );
  foreach( $catids as $catid ){
    $category = get_category( $catid );
    $categories[$category->term_id] = $category->name;
  }
}

$filtered_categories = array_unique($categories);

?>

I've tested and now works. Hope it helps!


text:
Q: Is it legal to create a recursive background handler in iphone?(processing when app enters the background) If I register an app for background app in did enter background and make a background handler with approximately 10 mins to finish the task, after the time is over the handler will call finishing block and in this block again create the background handler you will get again 10 mins and so on, in this way application will remain in background. I mean is it OK to do that....? or will apple object to this?

A: From the documentation:

Applications running background tasks have a finite amount of time in
  which to run them. (You can find out how much time is available using
  the backgroundTimeRemaining property.) If you do not call
  endBackgroundTask: for each task before time expires, the system kills
  the application.

So, no, you can't indefinitely run in the background.

A: Yeah thats correct, you cannot run infinitely in this way. But i have found one more trick, when applicatuon enters background, start playing an audio with 0 volume :-) Your app will never get killed.

A: There is a VoIP app, Media5, which can receive in background incoming calls using UDP sockets.
Developers said they used a "trick" to mantain the app active forever and I'd exclude the silent audio playing option. So the question is: what's that trick?
Also Bria can receive with UDP in background.

A: From Comment 20 at Issue 515: Background app support for iPhones with multitasking support:

I'm pretty sure that without playing continuously an audio file or
  logging GPS position you cannot keep alive UDP listening sockets in
  iOS 4.3+ (both in the main thread or in a secondary one).  If you play
  an audio play with AVAudioPlayer (after initializing an AudioSession
  before) in a nsrunloop every 5 seconds, the main thread is kept active
  and moreover it's NOT necessary to declare the audio background
  support in info.plist.
I think this is the "trick" used by Media5 and Bria.  I tried also
  creating a infinite TCP stream to the loopback interface declaring it
  as VoIP, just to see if also UDP socket is kept alive. The answer is
  no, only TCP sockets works while in background (and with screen
  locked), UDP is closed in the meanwhile and cannot listen for incoming
  calls anymore.
So the key point is that the main thread must be kept active... using
  a simple nstimer o infinite runloop alone is useless, since the
  watchdog kills the process after few seconds in background (except if
  you work in debug mode with GDB interface attached, it runs forever).


text:
Q: How To: Fill the Font Awesome 4.x Lightbulb Currently, the only way to 'fill' the lightbulb icon from Font Awesome (I'm dealing just with version 4.x here) is to apply the fill color as the background. But then you wind up with an ugly box around the icon.
NOT OPTIMUM! (Also ugly!)
I'm curious if anyone knows a way to fill the bulb - just the bulb, and not the background. And not the outline lines of the bulb. The idea is that I'd like to display lightbulbs of different colors, where the bulb is filled in, as the outline colors are honestly not as readily apparent.
The bulb icon in question:
https://fontawesome.com/v4.7.0/icon/lightbulb-o/

A: Here's a way to do it:
.fa-lightbulb-o {
  position: relative;
}

.fa-lightbulb-o:after {
  content: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxzdmcgdmVyc2lvbj0nMS4xJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHhtbG5zOnhsaW5rPSdodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rJyB4PScwcHgnIHk9JzBweCcgdmlld0JveD0nMCAwIDE3OTIgMTc5Micgc3R5bGU9J2VuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTc5MiAxNzkyOycgeG1sOnNwYWNlPSdwcmVzZXJ2ZSc+PHBhdGggZmlsbD0neWVsbG93JyBkPSdNMTE4MS41LDc5Mi4zYzEzLjctMTQuNywyMy44LTI1LjcsMzAuNS0zM2M0NS4zLTUyLjcsNjgtMTEyLjcsNjgtMTgwYzAtNDgtMTEuNS05Mi43LTM0LjUtMTM0Yy0yMy00MS4zLTUzLTc1LjItOTAtMTAxLjVjLTM3LTI2LjMtNzgtNDctMTIzLTYyYy00NS0xNS05MC41LTIyLjUtMTM2LjUtMjIuNXMtOTEuNSw3LjUtMTM2LjUsMjIuNXMtODYsMzUuNy0xMjMsNjJjLTM3LDI2LjMtNjcsNjAuMi05MCwxMDEuNWMtMjMsNDEuMy0zNC41LDg2LTM0LjUsMTM0YzAsNjcuMywyMi43LDEyNy4zLDY4LDE4MGM2LjcsNy4zLDE2LjgsMTguMywzMC41LDMzczIzLjgsMjUuNywzMC41LDMzYzg1LjMsMTAyLDEzMi4zLDIwMS4zLDE0MSwyOThoMjI4YzguNy05Ni43LDU1LjctMTk2LDE0MS0yOThDMTE1Ny43LDgxNy45LDExNjcuOCw4MDYuOSwxMTgxLjUsNzkyLjN6Jy8+PC9zdmc+');
  position: absolute;
  top: 0;
  left: -.214em;
  margin: 0 auto;
  z-index: -1;
  display: block;
  width: 1em;
}

And here's a way to turn it on/off:

var el = document.querySelector('.fa-lightbulb-o');
el.onclick = function() {
  el.classList.toggle('lit');
}
.fa-lightbulb-o {
  position: relative;
}

.fa-lightbulb-o:after {
  content: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxzdmcgdmVyc2lvbj0nMS4xJyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHhtbG5zOnhsaW5rPSdodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rJyB4PScwcHgnIHk9JzBweCcgdmlld0JveD0nMCAwIDE3OTIgMTc5Micgc3R5bGU9J2VuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTc5MiAxNzkyOycgeG1sOnNwYWNlPSdwcmVzZXJ2ZSc+PHBhdGggZmlsbD0neWVsbG93JyBkPSdNMTE4MS41LDc5Mi4zYzEzLjctMTQuNywyMy44LTI1LjcsMzAuNS0zM2M0NS4zLTUyLjcsNjgtMTEyLjcsNjgtMTgwYzAtNDgtMTEuNS05Mi43LTM0LjUtMTM0Yy0yMy00MS4zLTUzLTc1LjItOTAtMTAxLjVjLTM3LTI2LjMtNzgtNDctMTIzLTYyYy00NS0xNS05MC41LTIyLjUtMTM2LjUtMjIuNXMtOTEuNSw3LjUtMTM2LjUsMjIuNXMtODYsMzUuNy0xMjMsNjJjLTM3LDI2LjMtNjcsNjAuMi05MCwxMDEuNWMtMjMsNDEuMy0zNC41LDg2LTM0LjUsMTM0YzAsNjcuMywyMi43LDEyNy4zLDY4LDE4MGM2LjcsNy4zLDE2LjgsMTguMywzMC41LDMzczIzLjgsMjUuNywzMC41LDMzYzg1LjMsMTAyLDEzMi4zLDIwMS4zLDE0MSwyOThoMjI4YzguNy05Ni43LDU1LjctMTk2LDE0MS0yOThDMTE1Ny43LDgxNy45LDExNjcuOCw4MDYuOSwxMTgxLjUsNzkyLjN6Jy8+PC9zdmc+');
  position: absolute;
  top: 0;
  left: -.214em;
  margin: 0 auto;
  z-index: -1;
  display: block;
  width: 1em;
}

i.fa-lightbulb-o {
  cursor: pointer;
  margin: 0 2rem;
  display: flex;
}

.fa-lightbulb-o:after {
  opacity: 0;
  transition: opacity .42s cubic-bezier(.4, 0, .2, 1);
}

.fa-lightbulb-o:after,
.fa-lightbulb-o:before {
  font-size: 10rem;
}

.lit:after {
  opacity: 1;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 8px);
  margin: 0;
  font-size: 7em;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> » <i class="fa fa-lightbulb-o"></i> «

... and the <svg>, in case you want to change the color. remember it needs base64 encoding to be used inside url() cross-browser.
<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 1792 1792' style='enable-background:new 0 0 1792 1792;' xml:space='preserve'>
    <path fill='yellow' d='M1181.5,792.3c13.7-14.7,23.8-25.7,30.5-33c45.3-52.7,68-112.7,68-180c0-48-11.5-92.7-34.5-134c-23-41.3-53-75.2-90-101.5c-37-26.3-78-47-123-62c-45-15-90.5-22.5-136.5-22.5s-91.5,7.5-136.5,22.5s-86,35.7-123,62c-37,26.3-67,60.2-90,101.5c-23,41.3-34.5,86-34.5,134c0,67.3,22.7,127.3,68,180c6.7,7.3,16.8,18.3,30.5,33s23.8,25.7,30.5,33c85.3,102,132.3,201.3,141,298h228c8.7-96.7,55.7-196,141-298C1157.7,817.9,1167.8,806.9,1181.5,792.3z'/>
</svg>


text:
Q: Is it required to add java to your path for android development I was wondering if it is required to have java added to your path (environmental variables), if you are using the adt bundle and the jdk is installed.
With other words: Does java has to be added to your path to let the Android SDK & adt plugin function correctly.

A: I think if you are using IDE (like Eclipse) then there is no need to do so.


text:
Q: Displaying data pulled from googlesheets in Shiny I'm trying to access data from a Google spreadsheet and display it as a table in a Shiny app. After confirmation that the spreadsheet was accessed, the app continues to run without displaying anything. Printing the data to the console works, however.
server.R
library(shiny)
library(googlesheets)

shinyServer(function(input, output) {
  sheet <- gs_title("Google Sheet")
  data <- gs_read_csv(sheet)

  output$table <- renderTable{
    data
  }
})

ui.R
library(shiny)
shinyUI(pageWithSidebar(
  mainPanel(
    dataTableOutput('table')
  )
))

A: In server.Ruse renderDataTable({}) if you use dataTableOutput()
This code works:
library(shiny)
library(googlesheets)

server <- function(input, output) {
  sheet <- gs_title("Google Sheet")
  data <- gs_read_csv(sheet)

  output$table <- renderDataTable({
    data
  })
}

ui <- fluidPage(sidebarLayout(sidebarPanel("Test"),
                              mainPanel(dataTableOutput('table'))
                              )
                )

shinyApp(ui = ui, server = server)


text:
Q: Using git with untracked files How do you "clean" only the workspace files from a git checkout? I have two branches with:
a) files common to both
b) files unique in each branch
c) untracked files.
I need to get rid of the b) files each time I checkout the other branch, without touching c) the untracked files.
Sorry if it's a simple question. I've see that git clean isn't the answer. Something like
    rm `git ls-files`?

A: Did you look into git stash?
git stash
git checkout branch_2
...
git checkout branch_1
git stash pop

A: As Karl stated in the comments, it should be doing that automatically, but since it's not, you can use git ls-files | xargs rm to remove all files (from the working dir) that are in the index (being tracked).  This is kind of a hack, since ideally you would want to figure out why it's not working.


text:
Q: What is the oscillation frequency of the observed/measured free induction decay signal in MRI? I recognize that many articles attempting to describe the basics of MRI under simplify a lot of technical details. I would like to confirm the following understanding about the free induction decay following an RF pulse...as I think these detail simplifications are interfering with the 'correct', foundational understanding.

Specifically, various sources (even research papers) describe the FID signal as a single cosine (or sine) wave at one frequency (the larmor frequency $\omega_0$) multiplied with a scaled (based on longitudinal magnetization and flip angle) exponentially decaying function. For example, the form:  $\cos(\omega_ot)\cdot M_{\alpha}\cdot e^{\frac{t}{T_2^*}}$. This has led many papers I have read to say something like, "The FID signal oscilates at a frequency of $\omega_0$".
Here is my confusion: the whole premise of the transverse magnetization decay (even in the absence of magnetic inhomogeneities) is that it is caused by fluctuations in the magnetic field which lead to subpopulations of protons experiencing magnetic fields slightly deviating away from the $B_0$ field. This results in these subpopulations of protons having a different precession frequency: let's say $\omega_i'=\omega_0 + b_i$, where $i$ is a given proton subpopulation.
Necessarily, then, there are many different protons precessing at different frequencies.  Because the measured signal at our receive coils is capturing the sum magnetic moment from all of these different subpopulations of protons, our FID signal is clearly comprised of many different frequencies.
I have never taken a raw FID signal and put it through a 1D Fourier transform. I suspect, though, that if I did, and then applied an inverse Fourier Transform, I would not recover the formula: $\cos(\omega_ot)\cdot M_{\alpha}\cdot e^{\frac{t}{T_2^*}}$. Instead I would recover something like:
$$\gamma_1\cos((\omega_o+b_1)t)\cdot M_{\alpha}\cdot e^{\frac{t}{T_2^*}}+\gamma_2\cos((\omega_o+b_2)t)\cdot M_{\alpha}\cdot e^{\frac{t}{T_2^*}}+\gamma_3\cos((\omega_o+b_3)t)\cdot M_{\alpha}\cdot e^{\frac{t}{T_2^*}}+\cdots$$
where $\gamma_i$ are different weights reflecting the fractional contribution that a given proton subpopulation $i$ precessing at a frequency $\omega_0+b_i$ gives to the observed FID.
Is this the correct interpretation?
If so, what is the benefit of consistently describing the FID as a signal oscillating at a single frequency? Is it simply for instructional purposes?

A: A pure single frequency signal must have a constant amplitude.
A signal with non constant amplitude, like $\cos(\omega_0 t)\ M_{\alpha}\  e^{\frac{t}{T_2^*}}$ already contains multiple frequencies as is. There is no need to have the weighted sum you mention.
Furthermore, the shorter the $T_2^*$ the broader the range of frequencies in $\cos(\omega_0 t)\ M_{\alpha}\  e^{\frac{t}{T_2^*}}$, which corresponds to the situation with a broader range of dephasing sources.
Now, it is true that $\cos(\omega_0 t)\  M_{\alpha}\  e^{\frac{t}{T_2^*}}$ is an approximation that does not generally exactly match the data. But it is a good first approximation and it already contains the feature that you are intending to capture with your more complicated formula.


text:
Q: How to dynamically create customized TabSheet runtime I would like to create a TTabsheet which has to be create during run time.  The TTabSheet has several components, but all of these components will be identical on every tab.  Is it possible to create a "type" variable which will create these tabs every time?
Thanks

A: Yes. You could create inherited class from TTabSheet
TCustomTabSheet = class(TTabSheet)
public
  constructor Create(AOwner : TComponent); override;
public
   FTestButton : TButton;
end;

constructor TCustomTabSheet.Create(AOwner : TComponent);
begin
  inherited Create(AOwner);
  FTestButton := TButton.Create(Self);
  FTestButton.Parent := Self;
  FTestButton.Left := 1;
  FTestButton.Top := 1;
  FTestButton.Width := 20;
  FTestButton.Heigth := 10;
  FTestButton.Caption := 'Cool button!';
  FTestButton.Name := 'TestButton';
end;

You could also create a frame (TFrame) with your custom controls in design time and host it instances to all new tabs.

A: Just for the fun of it, here's a snippet of code I use periodically to add a tabsheet to a TPageControl that has a TMemo on it. This would be used, for example, if you've got a form that is used for editing text files. You'd call this to add a new tab with the filename as caption, then load the memo's .Line property from the file's contents.
function TMy_form.add_ts_mmo( ntbk : TPageControl; caption : string ) : TTabSheet;
var mmo : TMemo;
begin
  Result := TTabSheet.Create(self);
  Result.PageControl := ntbk;
  Result.Caption := caption;
  mmo := TMemo.Create(self);
  Result.Tag := Integer(mmo);
  mmo.Parent := Result;
  mmo.Font.Name := 'Courier New';
  mmo.Font.Size := 10;
  mmo.Align := alClient;
  mmo.ScrollBars := ssBoth;
  mmo.WordWrap := true;
end;

You call it by giving it the PageControl you want it to be added to, and a caption that's used in the tab.
var
  ts : TTabSheet;
. . .
  ts := add_ts_mmo( myPageControl, ExtractFileName( text_file_nm ) );

Note that I save the new memo's pointer in ts.Tag so I can easily get to it later on through a cast.
TMemo(ts.Tag).Lines.LoadFromFile( text_file_nm );

No subclassing is required. You can create any other components you might want on the tabsheet as well, after the Result.Caption := caption line. Just be sure to set their .Parent property to Result.
The PageControl can be created either at design time or run-time.


text:
Q: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer I built a crud application using mern stack. Then I tried the search operation for the application but it show me this error:

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

This is my client side code:
Search.js
import React from 'react';

const Search = () => {

    const searchHandle = e => {
        e.preventDefault();

        const userName = e.target.search.value;
        fetch(`http://localhost:5000/user/${userName}`)
        .then(res => res.json())
        .then(data => console.log(data))
        .catch(err => console.log(err));

        console.log(typeof(userName));
    }

    return (

Search User:

            <form onSubmit={searchHandle}>
                <input className='bg-gray-200 rounded p-2 w-3/4' type="search" name="search" id="name" />
                <button className='bg-blue-500 mx-2 py-2 px-4 rounded' type='submit'>Search</button>
            </form>

    );
}

export default Search;

This is my server side code:
const expres = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');

const app = expres();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(expres.json())

const uri = "mongodb+srv://user:#@cluster0.moilkdv.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });

async function run() {
    try {
        const userCollection = client.db('simpleNode').collection('users');

        // get all users
        app.get('/user', async (req, res) => {
            const cursor = userCollection.find({});
            const users = await cursor.toArray();
            res.send(users);
        })

        // get a specific user for update
        app.get('/user/:id', async (req, res) => {
            const updateId = req.params.id;
            const updateQuery = { _id: ObjectId(updateId)}
            const user = await userCollection.findOne(updateQuery);
            res.send(user);
        })

        // updating user
        app.put('/user/:id', async (req, res) => {
            const userId = req.params.id;
            const user = req.body;
            const filter = { _id: ObjectId(userId) };
            const options = { upsert: true };
            const updatedUser = {
                $set: {
                    name: user.name,
                    address: user.address
                }
            }
            const result = await userCollection.updateOne(filter, updatedUser, options);
            res.send(result);
        })

        // creating users
        app.post('/user', async (req, res) => {
            console.log('post api called');
            const Nuser = req.body;
            const result = await userCollection.insertOne(Nuser);
            res.send(result);
        });

        // search query
        app.get('/user/:name', (req, res) => {
            const searchName = req.params.name;
            console.log(searchName);
        })

        // deleting user
        app.delete('/user/:id', async(req, res) => {
            const userId = req.params.id;
            const deleteQuery = { _id: ObjectId(userId)};
            const resut = await userCollection.deleteOne(deleteQuery);
            console.log("Delete complete of: ", userId);
            console.log(resut);
            res.send(resut);
        })
    }
    finally {
    }
}

run().catch(console.dir);

app.get('/', (req, res) => {
    res.send('Server is running');
})

app.listen(port);

Please help to solve this error.

A: That request is sent to app.get('/user/:id') route.
:id or :name is just the name of the parameter.
We have to setup another route for searching, eg: change  app.get('/user/:name') to app.get('/user/search/:name')


text:
Q: Email All Rows in Single Email If Dates Match Today I tried to write a script which email the information about all upcoming arrivals for todays and tomorrows dates in a single email. However, my script send each booking details (i.e., if it does match conditional expression) (both for todays and tomorrows conditional expressions) in a separated email.
I'm a complete beginner in scripting with Goole Apps Script. I tried to search for "email array values google app script" and "all matching array values in email" but it hasn't shed new light on a stuck I'm with now.
Instead of this I want it (1) to check the column whether it matches todays and/or tomorrows date then (2) gather all booking details and afterwards (3) splitting them on today-arrivals and tomorrow-arrivals put it into a single electronic mail message.
Here is my source code:
/* Отправка уведомлений о предстоящих заездах на сегодня и на завтра. */
function NotifyUpcomingArrivals() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 2; // Строка с первым бронированием для начала обработки.
    var numRows = sheet.getLastRow()-1; // Количество строк с бронированиями для обработки.
    var dataRange = sheet.getRange(startRow, 1, numRows, 18); // Охват столбцов для обработки ячеек, в данном случае с 1-го по 18-ый.
    var data = dataRange.getValues(); // Получить значение ячеек в каждой ячейке каждой строке в рамках столбцов, охваченных верхним кодом.
    for (var i = 0; i < data.length; ++i) {
        var row = data[i];
        var bookingNumber = [i+2];
        var todaysDate = new Date(); // Сегодняшняя дата.
        var tomorrowsDate = new Date(todaysDate.getTime()+(1*24*3600*1000)); // Завтрашняя дата.
        var dayAfterTomorrowsDate = new Date(todaysDate.getTime()+(2*24*3600*1000)); // Послезавтрашняя дата.
        var checkInDate = new Date(row[0]);
        var checkOutDate = new Date(row[1]);
        var formattedTodaysDate = Utilities.formatDate(todaysDate, "GMT+0300", "dd.MM.yyyy");
        var formattedTomorrowsDate = Utilities.formatDate(tomorrowsDate, "GMT+0300", "dd.MM.yyyy");
        var formattedDayAfterTomorrowsDate = Utilities.formatDate(dayAfterTomorrowsDate, "GMT+0300", "dd.MM.yyyy");
        var formattedCheckInDate = Utilities.formatDate(checkInDate, "GMT+0300", "dd.MM.yyyy");
        var formattedCheckOutDate = Utilities.formatDate(checkOutDate, "GMT+0300", "dd.MM.yyyy");
        var fullCheckInDate = Utilities.formatDate(checkInDate, "GMT+0300", "dd.MM.yyyy") + " в 14:00";
        var fullCheckOutDate = Utilities.formatDate(checkOutDate, "GMT+0300", "dd.MM.yyyy") + " в 12:00";
        var roomType = "«" + row[2] + "»";
        var numberOfGuests = row[3];
        var costPerNight = row[4] + " руб.";
        var prepaymentCost = row[8] + " руб.";
        var contactFullName = row[5];
        var contactPhone = row[6];
        var contactEmail = row[7];
        var bookingNotes = row[11];
        var reviewDummy = row[13];
        /* Здесь расчёт промежуточных переменных. */
        var differenceBetweenDays = Math.round(Math.abs((checkOutDate.getTime() - checkInDate.getTime())/(24*60*60*1000)));
        var unpaidCost = (costPerNight*differenceBetweenDays)-prepaymentCost + " руб."; // Сумма, которую необходимо оплатить гостю по приезде.
        var bookingsListLink = "link";
        /* Здесь установка параметров отправителя. */
        var recipientEmail = "email1@address.com";
        var senderName = "Робот Руслана Селецкого (Мини-гостиница Бердянская 56)";
        var replyTo = "email2@address.com";
        var subject = "Сводка бронирований на" + " сегодня (" + formattedTodaysDate + ") и на" + " завтра (" + formattedTomorrowsDate + ")";
            /* Сегодняшние заезды. */
            if (formattedCheckInDate == formattedTodaysDate && reviewDummy !== "–") { // Условное выражение, позволяющее отобрать бронирования с заездом на сегодня, но кроме тех, которые уже были отменены гостями.
            var todaysArrivalsMessage = "Бронирования на" + " сегодня (" + formattedTodaysDate + ")" + "\n" + "\n" + contactFullName + " (строка № " + bookingNumber + ")" + "\nНомер: " + roomType + "\nТип размещения: " + numberOfGuests + "\nЦена за ночь: " + costPerNight + "\nВнесённый депозит: " + prepaymentCost + "\nОсталось взять по приезде: " + unpaidCost;
            // MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
            Logger.log("Отправлено уведомление о сегодняшнем предстоящем заезде по бронированию № " + bookingNumber + " (" + contactFullName + ")" + " на " + recipientEmail + ".");
            }
            /* Завтрашние заезды. */
            if (formattedCheckInDate == formattedTomorrowsDate && reviewDummy !== "–") { // Условное выражение, позволяющее отобрать бронирования с заездом на завтра, но кроме тех, которые уже были отменены гостями.
            var tomorrowsArrivalsMessage = "\n" + "\nБронирования на" + " завтра (" + formattedTomorrowsDate + ")" + "\n" + "\n" + contactFullName + " (строка № " + bookingNumber + ")" + "\nНомер: " + roomType + "\nТип размещения: " + numberOfGuests + "\nЦена за ночь: " + costPerNight + "\nВнесённый депозит: " + prepaymentCost + "\nОсталось взять по приезде: " + unpaidCost + "\n" + "\nПожалуйста, предупреди горничную о предстоящих заездах, а также сделай всё возможное, чтобы всё было готово по приезде гостей." + "\n" + "\n* Посмотреть полный список бронирований всегда можно тут: " + bookingsListLink + ".";
            // MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
            Logger.log("Отправлено уведомление о завтрашнем предстоящем заезде по бронированию № " + bookingNumber + " (" + contactFullName + ")" + " на " + recipientEmail + ".");
            }
            var message = todaysArrivalsMessage + tomorrowsArrivalsMessage;
            MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
            SpreadsheetApp.flush(); // Показываем пользователю что изменения вступают в силу.
       }
}

How can I fix it to achieve desired results? Please, provide me with both helpful code examples as well as with useful reading for deeper understanding.
All problem-oriented help is at least strongly appreciated and rewarded by community.
UPD № 1. I did minor changes basing on @Afroman Makgalemela suggestion:
/* Отправка уведомлений о предстоящих заездах на сегодня и на завтра (с поправками чувака на Стаковерфлоу.ком). */
function NotifyUpcomingArrivals() {
    var ui = SpreadsheetApp.getUi();
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = SpreadsheetApp.getActiveSheet();
    var startRow = 2; // Строка с первым бронированием для начала обработки.
    var numRows = sheet.getLastRow()-1; // Количество строк с бронированиями для обработки.
    var dataRange = sheet.getRange(startRow, 1, numRows, 18); // Охват столбцов для обработки ячеек, в данном случае с 1-го по 18-ый.
    var data = dataRange.getValues(); // Получить значение ячеек в каждой ячейке каждой строке в рамках столбцов, охваченных верхним кодом.
    /* Здесь установка параметров отправителя. */
    var message = undefined;
    var subject = undefined;
    var recipientEmail = "natalya@berdyanskaya56.ru";
    var bookingsListLink = "http://bitly.com/b56bookingslist";
    var senderName = "Робот Руслана Селецкого (Мини-гостиница Бердянская 56)";
    var replyTo = "ruslan@berdyanskaya56.ru";
    for (var i = 0; i < data.length; ++i) {
        var row = data[i];
        var bookingNumber = [i+2];
        var todaysDate = new Date(); // Сегодняшняя дата.
        var tomorrowsDate = new Date(todaysDate.getTime()+(1*24*3600*1000)); // Завтрашняя дата.
        var dayAfterTomorrowsDate = new Date(todaysDate.getTime()+(2*24*3600*1000)); // Послезавтрашняя дата.
        var checkInDate = new Date(row[0]);
        var checkOutDate = new Date(row[1]);
        var formattedTodaysDate = Utilities.formatDate(todaysDate, "GMT+0300", "dd.MM.yyyy");
        var formattedTomorrowsDate = Utilities.formatDate(tomorrowsDate, "GMT+0300", "dd.MM.yyyy");
        var formattedDayAfterTomorrowsDate = Utilities.formatDate(dayAfterTomorrowsDate, "GMT+0300", "dd.MM.yyyy");
        var formattedCheckInDate = Utilities.formatDate(checkInDate, "GMT+0300", "dd.MM.yyyy");
        var formattedCheckOutDate = Utilities.formatDate(checkOutDate, "GMT+0300", "dd.MM.yyyy");
        var fullCheckInDate = Utilities.formatDate(checkInDate, "GMT+0300", "dd.MM.yyyy") + " в 14:00";
        var fullCheckOutDate = Utilities.formatDate(checkOutDate, "GMT+0300", "dd.MM.yyyy") + " в 12:00";
        var roomType = "«" + row[2] + "»";
        var numberOfGuests = row[3];
        var costPerNight = row[4];
        var prepaymentCost = row[8];
        var formattedCostPerNight = costPerNight + " руб.";
        var formattedPrepaymentCost = prepaymentCost + " руб.";
        var contactFullName = row[5];
        var contactPhone = row[6];
        var contactEmail = row[7];
        var bookingNotes = row[11];
        var reviewDummy = row[13];
        /* Здесь расчёт промежуточных переменных. */
        var numberOfNights = Math.round(Math.abs((checkOutDate.getTime() - checkInDate.getTime())/(24*60*60*1000)));
        var unpaidCost = (costPerNight*numberOfNights)-prepaymentCost;
        var formattedNumberOfNights = numberOfNights + " шт."; // Количество ночей проживания.
        var formattedUnpaidCost = unpaidCost + " руб."; // Сумма, которую необходимо оплатить гостю по приезде.
            /* Сегодняшние заезды. */
            if (formattedCheckInDate == formattedTodaysDate && reviewDummy !== "–") { // Условное выражение, позволяющее отобрать бронирования с заездом на сегодня, но кроме тех, которые уже были отменены гостями.
            var todaysArrivalsMessage = "Бронирования с заездами" + " сегодня (" + formattedTodaysDate + "):" + "\n" + "\n" + contactFullName + " (см. строку № " + bookingNumber + ")" + "\nНомер: " + roomType + "\nТип размещения: " + numberOfGuests + "\nКоличество ночей: " + formattedNumberOfNights + "\nЦена за ночь: " + formattedCostPerNight + "\nВнесённый депозит: " + formattedPrepaymentCost + "\nОсталось взять по приезде: " + formattedUnpaidCost;
            Logger.log("Отправлено уведомление о сегодняшнем предстоящем заезде по бронированию № " + bookingNumber + " (" + contactFullName + ")" + " на " + recipientEmail + ".");
            }
            /* Завтрашние заезды. */
            if (formattedCheckInDate == formattedTomorrowsDate && reviewDummy !== "–") { // Условное выражение, позволяющее отобрать бронирования с заездом на завтра, но кроме тех, которые уже были отменены гостями.
            var tomorrowsArrivalsMessage = "Бронирования с заездами" + " завтра (" + formattedTomorrowsDate + "):" + "\n" + "\n" + contactFullName + " (см. строку № " + bookingNumber + ")" + "\nНомер: " + roomType + "\nТип размещения: " + numberOfGuests + "\nКоличество ночей: " + formattedNumberOfNights + "\nЦена за ночь: " + formattedCostPerNight + "\nВнесённый депозит: " + formattedPrepaymentCost + "\nОсталось взять по приезде: " + formattedUnpaidCost;
            Logger.log("Отправлено уведомление о завтрашнем предстоящем заезде по бронированию № " + bookingNumber + " (" + contactFullName + ")" + " на " + recipientEmail + ".");
            }
            var subject = "Сводка бронирований на" + " сегодня (" + formattedTodaysDate + ") и на" + " завтра (" + formattedTomorrowsDate + ")";
            var messageBeginning = "Доброе утро,";
            var messageSignature = "Пожалуйста, предупреди горничную о предстоящих заездах, а также сделай всё возможное, чтобы абсолютно всё было готово по приезде гостей." + "\n" + "\n* Посмотреть полный список бронирований всегда можно тут: " + bookingsListLink + ".";
            var message = messageBeginning + "\n" + "\n" + todaysArrivalsMessage + "\n" + "\n" + tomorrowsArrivalsMessage + "\n" + "\n" + messageSignature;
            }
    // MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
    ui.alert("Тестирования механизма формирования уведомлений", "Тема письма:" + "\n" + "\n" + subject + "\n" + "\nТекст письма:" + "\n" + "\n" + message, ui.ButtonSet.OK);
    Logger.log("Отправлено уведомление с предстоящими заездами" + formattedTodaysDate + " и " + formattedTomorrowsDate + " на " + recipientEmail + ".");
    SpreadsheetApp.flush(); // Показываем пользователю что изменения вступают в силу.
}

Now it works perfectly. Thanks.

A: Declare message as a global var outside your for loop, and call the sendEmail also from outside the for loop. this -> data = dataRange.getValues(); groups by date, hence why your results for today and tomorrow are send separately.
 /* Отправка уведомлений о предстоящих заездах на сегодня и на завтра. */
    function NotifyUpcomingArrivals() {
        var ss = SpreadsheetApp.getActiveSpreadsheet();
        var sheet = SpreadsheetApp.getActiveSheet();
        var startRow = 2; // Строка с первым бронированием для начала обработки.
        var numRows = sheet.getLastRow()-1; // Количество строк с бронированиями для обработки.
    var message = undefined, subject =undefined;

    var recipientEmail = "natalya@berdyanskaya56.ru";
 var bookingsListLink = "http://bitly.com/b56bookingslist";
            var senderName = "Робот Руслана Селецкого (Мини-гостиница Бердянская 56)";
            var replyTo = "ruslan@berdyanskaya56.ru";
        var dataRange = sheet.getRange(startRow, 1, numRows, 18); // Охват столбцов для обработки ячеек, в данном случае с 1-го по 18-ый.
        var data = dataRange.getValues(); // Получить значение ячеек в каждой ячейке каждой строке в рамках столбцов, охваченных верхним кодом.
        for (var i = 0; i < data.length; ++i) {
            var row = data[i];
            var bookingNumber = [i+2];
            var todaysDate = new Date(); // Сегодняшняя дата.
            var tomorrowsDate = new Date(todaysDate.getTime()+(1*24*3600*1000)); // Завтрашняя дата.
            var dayAfterTomorrowsDate = new Date(todaysDate.getTime()+(2*24*3600*1000)); // Послезавтрашняя дата.
            var checkInDate = new Date(row[0]);
            var checkOutDate = new Date(row[1]);
            var formattedTodaysDate = Utilities.formatDate(todaysDate, "GMT+0300", "dd.MM.yyyy");
            var formattedTomorrowsDate = Utilities.formatDate(tomorrowsDate, "GMT+0300", "dd.MM.yyyy");
            var formattedDayAfterTomorrowsDate = Utilities.formatDate(dayAfterTomorrowsDate, "GMT+0300", "dd.MM.yyyy");
            var formattedCheckInDate = Utilities.formatDate(checkInDate, "GMT+0300", "dd.MM.yyyy");
            var formattedCheckOutDate = Utilities.formatDate(checkOutDate, "GMT+0300", "dd.MM.yyyy");
            var fullCheckInDate = Utilities.formatDate(checkInDate, "GMT+0300", "dd.MM.yyyy") + " в 14:00";
            var fullCheckOutDate = Utilities.formatDate(checkOutDate, "GMT+0300", "dd.MM.yyyy") + " в 12:00";
            var roomType = "«" + row[2] + "»";
            var numberOfGuests = row[3];
            var costPerNight = row[4] + " руб.";
            var prepaymentCost = row[8] + " руб.";
            var contactFullName = row[5];
            var contactPhone = row[6];
            var contactEmail = row[7];
            var bookingNotes = row[11];
            var reviewDummy = row[13];
            /* Здесь расчёт промежуточных переменных. */
            var differenceBetweenDays = Math.round(Math.abs((checkOutDate.getTime() - checkInDate.getTime())/(24*60*60*1000)));
            var unpaidCost = (costPerNight*differenceBetweenDays)-prepaymentCost + " руб."; // Сумма, которую необходимо оплатить гостю по приезде.

            subject = "Сводка бронирований на" + " сегодня (" + formattedTodaysDate + ") и на" + " завтра (" + formattedTomorrowsDate + ")";
                /* Сегодняшние заезды. */
                if (formattedCheckInDate == formattedTodaysDate && reviewDummy !== "–") { // Условное выражение, позволяющее отобрать бронирования с заездом на сегодня, но кроме тех, которые уже были отменены гостями.
                var todaysArrivalsMessage = "Бронирования на" + " сегодня (" + formattedTodaysDate + ")" + "\n" + "\n" + contactFullName + " (строка № " + bookingNumber + ")" + "\nНомер: " + roomType + "\nТип размещения: " + numberOfGuests + "\nЦена за ночь: " + costPerNight + "\nВнесённый депозит: " + prepaymentCost + "\nОсталось взять по приезде: " + unpaidCost;
                // MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
                Logger.log("Отправлено уведомление о сегодняшнем предстоящем заезде по бронированию № " + bookingNumber + " (" + contactFullName + ")" + " на " + recipientEmail + ".");
                }
                /* Завтрашние заезды. */
                if (formattedCheckInDate == formattedTomorrowsDate && reviewDummy !== "–") { // Условное выражение, позволяющее отобрать бронирования с заездом на завтра, но кроме тех, которые уже были отменены гостями.
                var tomorrowsArrivalsMessage = "\n" + "\nБронирования на" + " завтра (" + formattedTomorrowsDate + ")" + "\n" + "\n" + contactFullName + " (строка № " + bookingNumber + ")" + "\nНомер: " + roomType + "\nТип размещения: " + numberOfGuests + "\nЦена за ночь: " + costPerNight + "\nВнесённый депозит: " + prepaymentCost + "\nОсталось взять по приезде: " + unpaidCost + "\n" + "\nПожалуйста, предупреди горничную о предстоящих заездах, а также сделай всё возможное, чтобы всё было готово по приезде гостей." + "\n" + "\n* Посмотреть полный список бронирований всегда можно тут: " + bookingsListLink + ".";
                // MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
                Logger.log("Отправлено уведомление о завтрашнем предстоящем заезде по бронированию № " + bookingNumber + " (" + contactFullName + ")" + " на " + recipientEmail + ".");
                }
                message += todaysArrivalsMessage + tomorrowsArrivalsMessage;

           }
 MailApp.sendEmail(recipientEmail, subject, message, {name: senderName, replyTo: replyTo});
                SpreadsheetApp.flush(); // Показываем пользователю что изменения вступают в силу.
    }