text:
Q: Firebase crashlytics dashboard keeps Loading Firebase crashlytics console displays "loading" after a click on the "Enable Crashlytics" button.

*

*Firebase Console: https://console.firebase.google.com/u/0/

*Select Project

*Select Crashlytics

*Click "Enable Crashlytics"

It displays the spinner. It has been like this for several minutes.

A: First, make sure that you've followed all the instructions here to get the Crashlytics SDK set up. Then, force a crash to test your implementation. This is required to get past the onboarding screen that you're seeing at the moment.
If that doesn't work, try enabling debug logging and going through the build, run, crash, and relaunch process again, and paste any Crashlytics or Firebase-related logs into your original question.


text:
Q: vectorizing the htm2txt function is throwing error: "Error in exists(y, hash, inherits = FALSE) : invalid first argument" I am trying to convert a set of HTML emails to readable text. I am trying to use the htm2txt function from the package with the same name.
The problem is that the function is not vectorized and when I try to vectorize the function I get the error Error in exists(y, hash, inherits = FALSE) : invalid first argument
I have tried using the Vectorize() function to make a vectorized version of the function.
I have tried lapply. I have tried a plain for loop. But I keep getting the same error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Backward compatibility of chrome extension Is there any requirement on the minimum Chrome browser version (e.g. 5 stable releases into the past) that an addon has to support in order to be accepted into the Chrome web store?
I'm asking because I'm developing an addon that relies on a feature to be introduced in Chrome 102 (web assembly in MV3 extensions without special flags) and I'm trying to establish a realistic estimate of when could the addon actually be launched


text:
Q: Parse error: syntax error, unexpected 'for' (T_FOR) in C:\wamp\www\php test 11F\test.php on line 3 The variable $n is readed from a form:
<?php
$nume=$_POST['n']
for($i=1;$i<=n;$i++)
{
    for($j=1;$j<=n;$j++)
    {
      if($i==$j) $a[$i][$j]=0;
      else $a[$i][$j]=$i;
      echo $a[$i][$j]." ";
    }
  echo $a[$i][$j];
}
?>

Parse error: syntax error, unexpected 'for' (T_FOR) in C:\wamp\www\php
  test 11F\test.php on line 3

What's the error, the problem?
It is my first project in php.

A: <?php
$n = 20;
for($i=1;$i<=$n;$i++)
{
    for($j=1;$j<=$n;$j++)
    {
      if($i==$j)
          $a[$i][$j]=0;
      else
        $a[$i][$j]=$i;
          echo $a[$i][$j]." ";
    }
}
?>

I fixed these issues,

*

*n should be - $n

*You are trying access value of $a[$i][$j] form outside the second loop - Then $j value equal to $n+1 - but you can get only 1 to $n
Outside the two loops print the array this way then you can see what are the accessible keys
echo "<pre>";
print_r($a);
echo "</pre>";

A: there is no semicolon after $_POST['n']. check below updated code
<?php
$nume=$_POST['n'];
for($i=1;$i<=$nume;$i++)
{
for($j=1;$j<=$nume;$j++)
{
  if($i==$j) $a[$i][$j]=0;
  else $a[$i][$j]=$i;
  echo $a[$i][$j]." ";
}
echo $a[$i][$j];
}
?>


text:
Q: Creating an XML layout from an already existing View I have a View that up to now I have been creating programmatically. I wish to instead create a template, and then load that template via a LayoutInflater in future. Is it possible to create the template as XML from the programmatically created View, or must I manually create it through XML?

A: You have to manually create an xml file and use it as template. Programmatically it is not possible.

A: There is no way to automatically generate an XML from code. You'll have to do the conversion manually.


text:
Q: JQuery .ajax() function call not working, but success method runs I'm having trouble getting an ajax call to work on a webpage. The WebMethod works just fine.
One potential problem that I might see is that the code that calls the ajax method is located in a UserControl that is embedded in a content page that lives in a master page. This page can only be accessed after .Net authentication is verified. I have no clue if any of this matter, I'm just including this information so there are no hidden aspects of this issue.
Another potential issue may be in the Ajax call itself. I just can't see what the problem is. Most confusing of all, the success method in the ajax call runs.. there is no failure. More confusing, if I change the name of the WebMethod to something else entirely, the success method of the ajax call still runs.
Any idea what may be going wrong here?
var sendingThis = { x: 'abc', y: 'def', z: 'ghi' }

$.ajax(
{
    type: "POST",
    url: "TestPage.aspx/someMethod",
    data: sendingThis,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    cache: false,
    success: function (msg)
    {
         //THIS STUFF GETS CALLED...always
    },//end success

    error: function ()
    {
      //DOESN'T GET CALLED
    }
});

Codebehind method in TestPage.aspx:
[System.Web.Services.WebMethod]
public static void someMethod(string x, string y, string z)
{
    //CODE THAT UPDATES DATABASE; *INDEPENDENTLY CONFIRMED WORKING*
}

The button that calls the code..:
<asp:Button ID="btnSomeMethod" runat="server" OnClientClick="return someMethod(this);" Text="Runit" />

Some additional observations I have that may help or not. I've tried using ResolveURL with the .ajax() call's URL, didn't work. I've also tried EnableSession:true as an attribute for the Web Method. I've tried inserting a ScriptManager into the page with EnablePageMethods="true" and a ScriptReference to the .js file that holds the Ajax() call. No luck whatsoever. What on earth is going on?
Another update: I checked the HTTP stream to see what the Response Header is from the the POST request. First off, it's returning 200 OK as the POST status code. Request seems all good. However, in the response header, I'm getting:
`"status":401,"headers":`

This is related to an authentication error.

A: The answer came down to two forward slashes //.. In RouteConfig.cs, you need to comment out the line:
settings.AutoRedirectMode = RedirectMode.Permanent;

That's it, that's all.


text:
Q: How to count the number of objects in a bottle? I am working on a pet project using arduino where I need to keep track on number of objects in a bottle.It requires counting the number of objects(size of a regular pill and approximately of the same weight). My approach to this was asking the user to drop one object into the bottle and weigh it, then ask the user to drop the remaining objects into the bottle. So I can find the number of objects using the formula (total weight)/(weight of single pill).Whenever the weight of the objects in the bottle changes the formula is used and number of objects still in the bottle are found out, as you can see this is not very user friendly so I was looking if anyone can help me out with a better solution.
EDIT:If not by using weight is there any way to count the number of objects by using IR sensors etc., cause I have seen the load cells to measure small cells are quite expensive.

A: A regular pill weighs less than 1g. The main challenge with your approach is to weigh this exactly. As the weighing range of affordable precision scales is quite limited, it's even more challenging to weigh the pills together with the bottle.
Nick's suggestion may help to calculate the exact weight of one object - but you still have the problem to accurately weigh differences of +-1 object.
I'd say you should either lower your requirements (use heavier objects or allow a tolerance on counting) - or buy a ready-to-use counting precision scale.

A: You could allow the user to drop more than one at a time.
Simply measure the hole time and store the weight differences.
All differences a an integer multiple of the weight of a 'pill' so after a few stored value you should be able to calculate the weight of the GDC (greatest common divisor) of all weight differences which should be after a few values be 1.
Than you have the weight of 1 'pill'
Example:

*

*weight of empty bottle: 100g

*weight after 1st filling: 163g  (unknown number of pills) => known differences: 63

*weight after 2nd filling: 211g  (unknown number of pills) => known differences: 63, 111, 48   GDC( 63, 111, 48) = 3

3g was the number I was searching for.
You night wait a 3rd and 4th filling to ensure that you do not have a multiple of the real weight.


text:
Q: Replacing confirm exit dialogue by custom dialogue in Eclipse RCP 3.x application I want to replace the application exit dialogue by custom dialogue or in other word I want to get a hook on click of exit button on workbench window, so I can show messages in dialogue. Currently I am adding window listener and on window close event I perform some operations, but this event is triggered only after the window gets closed.
Is there any way of adding a hook for this. I am using eclipse 3.x application.
Thanks in advance

A: In your org.eclipse.ui.application.WorkbenchAdvisor you can override preShutdown()
@Override
public boolean preShutdown() {
    return MessageDialog.openConfirm(Display.getDefault().getActiveShell(), "Shutdown?", "Should I shutdown?");
}

Your WorkbenchAdvisor should lay in the plugin where your application is delared APPLICATIONNAMEWorkbenchAdvisor.


text:
Q: Jquery Data function returns undefined value when an element is explicitly named in the paremeters I'm using jquery's "data" function to store some information associated with an HTML element. When this element is explicitly referenced throughout the function, the function returns undefined, however when I bind the element to a variable the function works just fine.
Please check out this example below:
This one works (http://jsfiddle.net/sdbA5/):
  $(function() {

    var div = $("#officerBob");

    jQuery.data( div, {
      arrests: 16
    });

    div.click(function(){
       alert("Bob has " + jQuery.data( div ).arrests + " arrests");
    });

});

and this one doesn't (http://jsfiddle.net/5Y6b8/1/):
  $(function() {

    //var div = $("#officerBob");

    jQuery.data( $("#officerBob"), {
      arrests: 16
    });

    $("#officerBob").click(function(){
       alert("Bob has " + jQuery.data( $("#officerBob") ).arrests + " arrests");
    });

});

A: jQuery.data() is supposed to be working off DOM nodes and not jQuery collections.
Changing your code to use a DOM node and it will start working
$(function() {

    jQuery.data( $("#officerBob")[0], {
      arrests: 16
    });

    $("#officerBob").click(function(){
       alert("Bob has " + jQuery.data( $("#officerBob")[0] ).arrests + " arrests");
       alert("Bob has " + jQuery.data( this ).arrests + " arrests");
    });

});

Now why would the first one work? Because it is working off the same object. In the second one, it is a new jQuery object which is not the same as the first one that was assigned.

A: I'm not exactly sure why this is so, but all of the jQuery documentation shows the jQuery objects written as variables before they are passed as parameters in functions.
See: http://learn.jquery.com/using-jquery-core/jquery-object/
I'm just learning more about JavaScript, but I have a feeling that the jQuery object itself $("#officerBob") is essentially a function. Your code, which utilizes the output of that function, is not expecting a function as an input. It is expecting an object.
So, once you encapsulate the output as an object, (by creating an object whose value is equal to the function's output) your code works.


text:
Q: Confused on computing arc length Confused on computing arc length
Question 1:
Compute the arc length of $r = 1 + \cos(\theta),\; 0 \leq \theta \leq 2 \pi$
ans:
$\int_{0}^{2 \pi} \sqrt{(1+\cos(\theta)^2 + (-\sin (\theta))^2}\, d \theta = 8 $
Question 2:
Determine the length of $y = \ln(\sec(x))$ between $0 \leq x \leq \pi / 4$
Solution:
$\sqrt{1+\left(\frac{dy}{dx}\right)^2} = \sqrt{1+\tan^2(x)} = \sec(x)$
$L = \int_{0}^{\pi/4} \sec(x)\,dx = \ln(\sqrt{2} + 1)$
Why is there two ways to do it, yet yielding different answers? The first way got the derivative and took the magnitude of both of it, whereas the second way used the formula
$\displaystyle\int_{C} \sqrt{1+\left(\frac{dy}{dx}\right)^2}\, dx$
I tried using the above formula for the first one but got a different answer.

A: You are using two different formulas, which apply to two different situations:

*

*In the first situation, you are computing the length of a curve wich is expressed in polar coordinate, $r$ and $\theta$. The formula for that is$$\int_a^b\sqrt{r^2(\theta)+\left(\frac{dr}{d\theta}\right)^2}\,\mathrm d\theta.$$

*In the second situation, you are computing the length of the graph of a function $f$. The formula for that is$$\int_a^b\sqrt{1+\bigl(f'(t)\bigr)^2}\,\mathrm dt.$$
Since you have two different (although similar) situations, it is natural that you apply two different (although similar) formulas.

A: The applicability of formula depends upon being able to express the parametric curve in the form required by the formula.

*

*In second case, since parameter curve is given in cartesian coordinates, corresponding formula for arc length, $ \displaystyle \int_{C} \sqrt{1+\left(\frac{dy}{dx}\right)^2}\, dx $ is used

*In first case, since the curve is expressing in polar coordinates, an equivalent formulation in polar coordinates,
$ \displaystyle \int_C {\sqrt {\left(r^{2}+{\frac {dr}{d\theta }}\right)^{2}}}d\theta $
is used

If parametric curves in Question 1 and Question 2 are expressed in cartesian and polar coordinates respectively, then the alternate formulas would apply as well


text:
Q: Alternative of intersects ?# operator in postgres Is there any way to find if a path is intersecting with a box in postgres without using ?# or using an alternative?
I have this query below and hibernate's EntityManager is throwing an exception related to questionmark (?)
SELECT p.id, p.constraint_id, p.distance, p.height, p.coordinates, p.gtype, p.name
FROM geometry p
WHERE p.gtype='PolylineVolume'
AND path(polygon(box(point(15.740013406952562 - (180/pi()) * (p.distance/(6378137*cos(pi()*15.740013406952562/180))),46.97849625047054 - (180/pi()) * (p.distance/6378137)),point(16.007686681509206 + (180/pi()) * (p.distance/(6378137*cos(pi()*16.007686681509206/180))),47.07276572929793 + (180/pi()) * (p.distance/6378137))))) ?# popen(p.coordinates)

A: The PostgreSQL JDBC documenation says:

In JDBC, the question mark (?) is the placeholder for the positional parameters of a PreparedStatement. There are, however, a number of PostgreSQL operators that contain a question mark. To keep such question marks in a SQL statement from being interpreted as positional parameters, use two question marks (??) as escape sequence.


text:
Q: Nokogiri to_xhtml puts doctype before I'm trying to use Nokogiri to parse and update some xhtml files (fixing image sizes).
The parsing and updating works well but when I save the document with:
doc.to_xhtml(:indent_text => "\t", :indent=>1, :encoding => 'UTF-8')

The first two lines change from (original):
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

to (output):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<?xml version="1.0" encoding="utf-8"??>

which isn't a valid xml document (and there's also a double ? at the end of the xml tag).
Am I doing some wrong?
Edit: I've got nokogiri (1.6.0) installed, which seems to be the latest version.

A: This problem is an open (though very old) Nokogiri issue on Github, though it may in fact be a libxml issue. I was able to replicate your output.
The quick fix is to parse your document with Nokogiri::XML rather than Nokogiri::HTML, which is probably better practice anyway when dealing with XHTML files:
doc = Nokogiri::XML(open 'wherever')
doc.to_xhtml(:indent_text => "\t", :indent=>1, :encoding => 'UTF-8')

Note that this won't preserve your XML processing instruction. If you need it, use to_xml.


text:
Q: override background color from a div without class with nth-child? I would like to change the background color from all the div under the div with class=hamburger-react.
I don't have access to this piece of html, so I need to target the good div and !important override.
I tried with :

 div.close-overlay-btn:nth-child(2)  {
    background: rgba(0, 100, 172, 0.411) !important;
    }

But didnt work.
Any tips ? since these div have no class it's a little bit more complicated than expected

A: Your reference in your selectors is invalid. Try this:
.close-overlay-btn>.hamburger-react>div {}

There is no :nth-child(2) to .close-overlay-btn.
.close-overlay-btn is the grandparent, .hamburger-react is the parent, and all of the other divs nested in .hamburger-react are the children to the parent.

.close-overlay-btn>.hamburger-react>div {
  background: rgba(0, 100, 172, 0.411) !important;
}

A: If you really can't access/change the HTML, then the easy way is really using !important (which I do not advise in general) Solution 1
Other - better - solution, is remove the inline styles with JavaScript - and implement the same CSS but without !important Solution 2

You are using your selector the wrong way, try this:
.hamburger-react div

This will affect every div child of .hamburger-react
Solution 1

.hamburger-react div {
  background: rgba(0, 100, 172, 0.411) !important;
}

Solution 2

document.querySelectorAll('.hamburger-react div').forEach(el => el.style.removeProperty('background'))
.hamburger-react div {
  background: rgba(0, 100, 172, 0.411);
}


text:
Q: Normalizing time series measurements I have read the following sentence:

Figure 3 depicts how the pressure develops during a touch event. It
  shows the mean over all button touches from all users. To account for
  the different hold times of the touch events, the time axis has been
  normalized before averaging the pressure values.

They have measured the touch pressure over touch events and made a plot. I think normalizing the time axis means to scale the time axis to 1s, for example. But how can this be made? Let's say for example I have a measurement which spans 3.34 seconds (1000 timestamps and 1000 measurements). How can I normalize this measurement?

A: If you want to normalize you data you can do as you suggest and simply calculate:
z_i=\frac{x_i-min(x)}{max(x)-min(x)}

(Sorry but i cannot post images yet but you can visit this )
where zi is your i-th normalized time data, and xi is your absolute data.
An example using numpy:
import numpy

x = numpy.random.rand(10) # generate 10 random values
normalized = (x-min(x))/(max(x)-min(x))

print(x,normalized)


text:
Q: Random.Next() working only for restricted time/number of invokes? I've been using a code that runs "forever" with a static random in one of classes. All works fine, numbers are random and there's no problem... for a restricted time (or number of invokes, not sure). After some time it starts to generate the same number all the time.
And here's the question: do you know of any time limitations over random class? Have you ever had such a problem?
I've changed the code and I'll now in like a week or two if that helped (each x minutes I create new object), but I'd like to know what's behind that and what should I be more careful about in future.
OK... little update:
No, it's not about multithreading, it works fine for a long time (like a week or so) after that time it returns one number only all the time.
private static Random random = new Random();

public static string GetRandomString(int length)
{
    const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    return new string(Enumerable.Repeat(chars, length)
        .Select(s => s[random.Next(s.Length)]).ToArray());
}

After "a time" (not sure how long) it starts to return the same string all over. as mentioned above: it's not a matter of multithreading as it continues to return the same value "forever".

A: OK,
lets sum it up

*

*yes, multithread access was used to access that random. That didn't seem to be a problem though, as random text was returned and even if a few double texts were returned that was not a problem (should not happen)

*the problem with random and multithreading is not what people use to say: "don't do that because it can return same values", the reason is (mentioned by Evk in chat) the internal state of random resulting in losing "randomness" of random and even breaking the object causing the mentioned malfunction (returning 0 all the time)

*If you still don't believe or just want to know "How does it really work..." (just like me wanted) and you have some time to read... here you go:
inside Random class there is an array
private int[] SeedArray = new int[56];
when using any Next method there is InternalSample method called always and it looks like that:
 private int InternalSample()
    {
      int inext = this.inext;
      int inextp = this.inextp;
      int index1;
      if ((index1 = inext + 1) >= 56)
        index1 = 1;
      int index2;
      if ((index2 = inextp + 1) >= 56)
        index2 = 1;
      int num = this.SeedArray[index1] - this.SeedArray[index2];
      if (num == int.MaxValue)
        --num;
      if (num < 0)
        num += int.MaxValue;
      this.SeedArray[index1] = num;
      this.inext = index1;
      this.inextp = index2;
      return num;
    }

if you access that method by 2 threads at the same time there is a hazard that might cause inext to be incremented and inextp not to be incremented (usually both get +1) if this situation happens 21 times (initial difference between inext and inextp is 21) then this line:
int num = this.SeedArray[index1] - this.SeedArray[index2];

will start causing the seed array to be filled with 0s and after a short while random object will be completely broken returning 0s all the time.
Hazard explenation:
intext = 0; inextp = 21
thread 1 (t1) and thread 2 (t2) access Random object. T1 is near to be finished and is at the line
this.inext = index1; //now this.inext = 1 and still this.inextp = 21

t2 starts to work now and does
    int inext = this.inext; //1
    int inextp = this.inextp; //21!

t1 finishes with
this.inextp = index2; //22

after a while t2 finishes it's work and saves incremented local index1 and index2
        this.inext = index1; //2
        this.inextp = index2; //22!

as mentioned initial difference between this.inext and this.inextp was 21 - now it's only 20, do that 20 more times and random will start returning 0s all the time

*solution1: always lock random when there is possibility that it'll be used by multiple threads.
solution2: that might be an interesting trick to copy disassembled random and write your own with internal lock object used at InternalSample() method (yeah, that will cause Random to work much slower but if you want to use the same object for multiple threads for any reason that would save problems with locking it every time externally).

PS i was pretty sure that multiple threads access to my random is very rare, but it wasn't, i've spotted a bug in code causing it to be accessed much to often by some clients. Thanks to that random error i could spot it and decrease load significantly. at least that was a minor reward.


text:
Q: Confusion about the past progressive and present progressive tense
They were fighting Nazis for three days.
  They fought Nazis for three days.

The first sentence is said to be the correct usage of past progressive tense. But why can't we use it in the same manner in present progressive tense?
It would be wrong to say:

We are fighting Nazis for three days?

The correct form is:

We have been fighting Nazis for three days.

Why do they differ in past progressive and present progressive?

A: English present tense, especially progressive present, can be used to describe planned activities in the future, especially when qualified with a time specification.

I'm buying groceries later today.

So this sounds like it's describing something that is being planned.

We are fighting Nazis for three days = We will be fighting Nazis for three days.

To describe a continuous activity that started in the past and is still continuing now, have been X is the right construction.

We have been fighting Nazis for three days (impiles we still are fighting Nazis).

If you are no longer fighting Nazis, simple past or had been X can be used.

We fought Nazis for three days.
We had fought Nazis for three days.


text:
Q: Implementing ls in c, infinite loop I'm trying to implement ls command in c, when I try to recursively list files and folders, I get infinite loop. I need to handle this options -l, -R, -a, -r and -t, How can I recursively list files?
static int  is_directory(const char *path)
{
   struct stat statbuf;

   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}

void        read_dir(char *dir_name, char *option)
{
    DIR *dir;
    struct dirent *entry;

    dir = opendir(dir_name);
    if (!dir)
    {
        my_putstr("ft_ls: cannot access ");
        perror(dir_name);
        return;
    }
    while ((entry = readdir(dir)) != NULL)
    {
        if (is_directory(entry->d_name) && options('R', option))
            read_dir(entry->d_name, option);
        my_putstr(entry->d_name);
        my_putchar('\n');
    }
    closedir(dir);
}

int         main(int ac, char **av)
{
    (void)ac;
    read_dir(av[1], av[2]);
    return 0;
}

when I run the program with ./ls . -R I get infinite loop.
Allowed functions

A: I have decided to use two while loops, first listing everything in the current folder, then read again this time checking for folders, and recursively calling read_dir function.
#include <dirent.h>
#include "libft.h"
#include <stdio.h>
#include <sys/stat.h>

static int  is_directory(const char *path)
{
    struct stat statbuf;

   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}

void        read_dir(char *dir_name, char *option)
{
    DIR *dir;
    struct dirent *entry;

    dir = opendir(dir_name);
    if (!dir)
    {
        my_putstr("ft_ls: cannot access ");
        perror(dir_name);
        return;
    }
    while ((entry = readdir(dir)) != NULL)
    {
        my_putstr(entry->d_name);
        my_putchar('\n');
    }
    closedir(dir);
    dir = opendir(dir_name);
    if (!dir)
    {
        my_putstr("ft_ls: cannot access ");
        perror(dir_name);
        return;
    }
    while ((entry = readdir(dir)) != NULL && options('R', option))
    {
        if (is_directory(entry->d_name) && (!(my_strncmp(entry->d_name, ".", 1) == 0)))
            read_dir(entry->d_name, option);
    }
    closedir(dir);
}

int         main(int ac, char **av)
{
    if (ac == 3)
        read_dir(av[1], av[2]);
    else if (ac == 2 || ac > 3)
        //call --help function
    else
        read_dir(".", "");
return 0;
}


text:
Q: What is the Cantor Set? How do I write it mathematically? I would like some clarification about the Cantor Set:

*

*What are the elements in the Cantor Set?

*How do I write the Cantor Set in mathematical terms (i.e in a summation)? I have seen online a formula but I do not understand how they got it so would be grateful if you could explain why it is this formula too.

EDIT: The formula I have seen online is:
$$\sum_{i=0}^\infty (a(i)/3^i) $$ where a(i) is either 0 or 2.

A: The Cantor Set $\mathcal C$ can be defined by the following recursive sequence of sets:
$$\mathcal C_0 = [0, 1]$$
$$\mathcal C_{n+1}= \frac{\mathcal C_n}3\cup\left(\frac23+\frac{C_n}3\right)$$
$$\mathcal C := \bigcap^\infty_{n=0}\mathcal C_n$$
This definition should reflect the intuitive notion of what the Cantor Set is and how it can be constructed.

To explain this further, I will explain the math in laymen's terms.
Start with the closed unit interval, $[0, 1]$.
The next iteration is the previous one divided by three and the previous one divided by three with its origin shifted to be at $\frac23$. This yields $[0, \frac13]\cup[\frac23, 1]$, then $[0, \frac19]\cup[\frac29, \frac13]\cup[\frac23, \frac79]\cup[\frac89, 1]$, etc.
The set itself is the set of points that are present in every iteration of this process.

In case you were wondering how the definition you gave ties into mine (which I find much more intuitive), Here is an explanation:
Observe that as $\mathcal C_n$ is iterated, the edges of each interval ($0, \frac13, \frac23, \frac19, $ etc) remain in the set.
All of these numbers can be expressed by the sum $$\sum^\infty_{n=1}\frac{a_n}{3^n}$$ where the sequence $a$ is all $0$s and $2$s.
For example, $\frac13$ is the sum when $a_n = \langle 0, 2, 2, 2, 2, \cdots\rangle$, or $\frac29+\frac2{27}+\frac2{81}+\cdots$
I'll leave it to you to find the reason for this connection, but a hint is that it has to do with the $\frac23$ being added.

A: The elements of the Cantor set are real numbers between $0,1$.  The set is formed by iteratively and infinitely cutting all intervals in thirds and removing the middle third.

*

*$E_0 = [0,1]$

*$E_1 = [0, \frac 13] \cup [\frac 23, 1]$

*$E_2 = [0, \frac 19]\cup [\frac 29, \frac 13]\cup[\frac 23,\frac 79]\cup [\frac 89, 1]$

*.....

The Cantor set is what remains when you do this an "infinite number of times".  If I can abuse notation $CantorSet = E_{\infty}$ or $\lim_{n\rightarrow \infty} E_n$ except... well, that's an abuse of notation.  The proper description would be $\cap_{i=0}^{\infty} E_i$ (but that can be intuitively confusing).
Thus all intervals of the form $(\frac {3k+1}{3^m}, \frac{3k+2}{3^m})$ are removed (and no intervals are left.)
S0 the set is $[0,1] \setminus \{(\frac {3k+1}{3^m}, \frac{3k+2}{3^m})|k,m\in \mathbb Z^+\}$
Or ... $\{\sum_{i=0}^\infty (a(i)/3^i)|\{a_i\} \in \{0,2\}^{\infty}\}$  (where $\{0,2\}^{\infty}$ is the set of all infinite sequences containing $0$ or $2$).
If we use decimal base three notation it would be all numbers between $0$ and $1$ that have only $0$ and $2$ in their base three decimal expansion.  (But as and infinite number of $2$ is the same as a terminating $1$ this can be restated as all real number between $0$ and $1$ who either have no decimal $1$ or only have a single occurrence of $1$ in its terminating position.)
I think (someone will correct me if I am mistaken) the Cantor-ish set of all the real numbers with only $0$ and $5$ in their base $10$ decimal expansion is topologically equivalent to the Cantor set.  This is the set you get by

*

*$G_1 = [0,1]$

*$G_2 = [0,.1]\cup [.5,1]$

*$G_3 = [0,0.01]\cup [.05,.1]\cup[.5,.51]\cup [.55, 1]$

*....

Is the same process, just with a nice base 10 result.

A: Let us define the Cantor representation of a real number to be the ternary expansion of that number where we don't allow a suffix of $1000\cdots$ or $12222\cdots$. So we wouldn't write $1$ as $1.0000\cdots$, we would write it as $0.2222\cdots$. Likewise, $2/3$ is $0.2000\cdots$ not $0.1222\cdots$.
The Cantor set consists of all real numbers in $[0,1]$ whose Cantor representation does not contain any $1$s. We can build the Cantor set by defining the sets $C_n$ of all real numbers in $[0,1]$ whose Cantor representation does not contain a $1$ in the first $n$ digits after the decimal point. The intersection $\bigcap C_n$ will be the Cantor set.
The set $C_0$ is the entire interval, $[0,1]$.
The set $C_1$ consists of all the numbers

*

*between $0 = 0.0000\cdots$ and $1/3 = 0.0222\cdots$ and

*between $2/3 = 0.2000\cdots$ and $1 = 0.2222\cdots$.

Thus $C_1 = [0,\frac13] \cup [\frac23, 1]$.
The set $C_2$ consists of the numbers

*

*between $0 = 0.0000\cdots$ and $1/9 = 0.00222\cdots$ and

*between $2/9 = 0.02000\cdots$ and $1/3 = 0.02222\cdots$ and

*between $2/3 = 0.20000\cdots$ and $7/9 = 0.20222\cdots$ and

*between $8/9 = 0.22000\cdots$ and $1 = 0.22222\cdots$.

So $C_2 = [0,\frac19] \cup [\frac29, \frac13] \cup [\frac23, \frac79] \cup [\frac89, 1]$.
In general, $C_n$ is obtained from $C_{n-1}$ by removing the middle third of each interval in $C_{n - 1}$.

A: That formula isn't all that helpful. The most useful property is $\mathcal C= \frac{\mathcal C}3\cup\left(\frac23+\frac{\mathcal C}3\right)$, i.e. the Cantor set is the union of two subsets obtained by shrinking/shifting of the Cantor set. That's called self-similarity.


text:
Q: Fast way to format doctests Say I write the following function:
def my_marvellous_list(my_list):
    return 'What a marvellous list!'

and would like to add a doctest, to verify that
my_marvellous_list([4, 5, 10, 7, 3, 8, 50, 3, 1, 8, 40, 87, 4, 2, 756756, 20, 10, 5, 30, 5, 543, 7, 8])

returns 'What a marvellous list!'.
Then I would need to modify my function as follows:
def my_marvellous_list(my_list):
    """
    >>> my_marvellous_list([4, 5, 10, 7, 3, 8, 50, 3, 1, 8, 40, 87, 4, 2,
    ...      756756, 20, 10, 5, 30, 5, 543, 7, 8])
    'What a marvellous list!'
    """

    return 'What a marvellous list!'

In order to insert the test into the docstring, I had to add >>> at the beginning of each command, and ... at the beginning of each hanging indent.
This can get tedious to do by hand - does there exist an automated way of converting pure Python to doctest format?

A: IPython has a %doctest_mode magic command that will change its prompts to the standard doctest format.
In [1]: def my_marvellous_list(my_list):
   ...:     return 'What a marvellous list!'
   ...:

In [2]: %doctest_mode
Exception reporting mode: Plain
Doctest mode is: ON
>>> my_marvellous_list([4, 5, 10, 7, 3, 8, 50, 3, 1, 8, 40, 87, 4, 2,
...     756756, 20, 10, 5, 30, 5, 543, 7, 8])
'What a marvellous list!'
>>>


text:
Q: Dell XPS 13 Sputnik3 (Ubuntu 14.04) cannot find display-port Here is the story. I've used the mini-display port from my XPS13 for about a year with an ASUS 2560x1440 res external display, via a mini-DP to DP connector. This has worked fine for 1 year.
This afternoon, I tried to connect my mini-display port to a projector via a mini-DP to HDMI, and nothing happened. I had heard that sometimes there were issues with projectors and XPS Ubuntu DisplayPort, so I unplugged and didn't worry about it.
When I came back to my desk and plugged in my usual external monitor, my XPS 13 was unable to find the monitor. Usually when that happens, I try and manually add a mode with xrandr, like:
xrandr --addmode DP1 2560x1440
xrandr --output DP1 --mode 2560x1440 --right-of LVDS1

When I went to do that, the DP1 output didn't even show as disconnected...this caused (and still is causing) me quite a fright.
Output from xrandr -q:
calvin@silversputnik:~$ xrandr -q
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 32767 x 32767
eDP1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis) 293mm x 165mm
   1920x1080      60.0*+   59.9     48.0
   1680x1050      60.0     59.9
   1600x1024      60.2
   1400x1050      60.0
   1280x1024      60.0
   1440x900       59.9
   1280x960       60.0
   1360x768       59.8     60.0
   1152x864       60.0
   1024x768       60.0
   800x600        60.3     56.2
   640x480        59.9
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

Any help would be appreciated, do I need to reset xrandr? or reload a kernel?
Kind Regards

Update
I installed intel-linux-graphics-installer_1.0.7-0intel1_amd64.deb fresh from Intel HD graphics.
Now I am seeing the DP1 when plugged in, and I see this in xrandr -q:
Screen 0: minimum 320 x 200, current 2560 x 1440, maximum 32767 x 32767
DP1 connected primary 2560x1440+0+0 (normal left inverted right x axis y axis) 597mm x 336mm
   2560x1440      60.0*+
   1920x1080      60.0 +   60.0     50.0     59.9
   1920x1080i     60.1     50.0     60.0
   1680x1050      59.9
   1280x1024      75.0     60.0
   1440x900       59.9
   1280x960       60.0
   1280x800       59.9
   1152x864       75.0
   1280x720       60.0     50.0     59.9
   1440x576       50.0
   1024x768       75.1     70.1     60.0
   1440x480       60.0     59.9
   832x624        74.6
   800x600        72.2     75.0     60.3     56.2
   720x576        50.0
   720x480        60.0     59.9
   640x480        75.0     66.7     60.0     59.9
   720x400        70.1
HDMI1 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

MY eDP1 (native display is gone).


text:
Q: ARC error when deploying to 10.6 I have my app running and tested on 10.7 but later realized that I needed it to work on earlier versions as well. And unfortunately, I started this project with ARC on from the very beginning.
Now my build setup is debug base sdk: 10.7, and release base sdk: 10.6. And when I try to archive my app, I got the following error:
Undefined symbols for architecture x86_64:
"_objc_retain", referenced from:
  +[__ARCLite__ load] in libarclite_macosx.a(arclite.o)
  -[AppDelegate applicationDidFinishLaunching:] in AppDelegate.o
  -[AppDelegate managedObjectModel] in AppDelegate.o
  -[AppDelegate persistentStoreCoordinator] in AppDelegate.o
  -[AppDelegate managedObjectContext] in AppDelegate.o
  -[AppDelegate windowWillReturnUndoManager:] in AppDelegate.o
  -[AppDelegate saveAction:] in AppDelegate.o
  ...
 (maybe you meant: _objc_retainedObject)
"_objc_release", referenced from:
  -[AppDelegate applicationDidFinishLaunching:] in AppDelegate.o
  -[AppDelegate applicationFilesDirectory] in AppDelegate.o
  -[AppDelegate managedObjectModel] in AppDelegate.o
  -[AppDelegate persistentStoreCoordinator] in AppDelegate.o
  -[AppDelegate managedObjectContext] in AppDelegate.o
  -[AppDelegate windowWillReturnUndoManager:] in AppDelegate.o
  -[AppDelegate saveAction:] in AppDelegate.o
  ...
"_objc_retainAutoreleasedReturnValue", referenced from:
  -[AppDelegate applicationFilesDirectory] in AppDelegate.o
  -[AppDelegate managedObjectModel] in AppDelegate.o
  -[AppDelegate persistentStoreCoordinator] in AppDelegate.o
  -[AppDelegate managedObjectContext] in AppDelegate.o
  -[AppDelegate windowWillReturnUndoManager:] in AppDelegate.o
  -[AppDelegate saveAction:] in AppDelegate.o
  -[AppDelegate applicationShouldTerminate:] in AppDelegate.o
  ...
"_objc_autoreleaseReturnValue", referenced from:
  -[AppDelegate applicationFilesDirectory] in AppDelegate.o
  -[AppDelegate managedObjectModel] in AppDelegate.o
  -[AppDelegate persistentStoreCoordinator] in AppDelegate.o
  -[AppDelegate managedObjectContext] in AppDelegate.o
  -[AppDelegate windowWillReturnUndoManager:] in AppDelegate.o
  -[MainWindowController viewForTag:] in MainWindowController.o
  -[MainWindowController tableView:objectValueForTableColumn:row:] in MainWindowController.o
  ...
"_objc_storeStrong", referenced from:
  -[AppDelegate persistentStoreCoordinator] in AppDelegate.o
  -[AppDelegate saveAction:] in AppDelegate.o
  -[AppDelegate applicationShouldTerminate:] in AppDelegate.o
  -[AppDelegate .cxx_destruct] in AppDelegate.o
  -[MainWindowController init] in MainWindowController.o
  -[MainWindowController viewForTag:] in MainWindowController.o
  -[MainWindowController showUserFinderView:] in MainWindowController.o
  ...
"_objc_retainAutoreleaseReturnValue", referenced from:
  +[MainWindowController sharedInstance] in MainWindowController.o
  -[FileMetaData getFileName] in FileMetaData.o
  -[FileMetaData getLastHash] in FileMetaData.o
  -[FileMetaData getCreationDate] in FileMetaData.o
  -[FileMetaData getLastModified] in FileMetaData.oe
  -[FileMetaData getLocalPath] in FileMetaData.o
  ...
"_objc_autorelease", referenced from:
  -[SBJsonParser objectWithString:error:] in SBJsonParser.o
  -[SBJsonTokeniser getStringToken:] in SBJsonTokeniser.o
  -[SBJsonTokeniser getNumberToken:] in SBJsonTokeniser.o
  -[SBJsonUTF8Stream getRetainedStringFragment:] in SBJsonUTF8Stream.o
  -[SBJsonWriter stringWithObject:error:] in SBJsonWriter.o
"_objc_retainAutorelease", referenced from:
  -[SBJsonTokeniser getStringToken:] in SBJsonTokeniser.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

It looks like an issue with ARC, but I have no clue where to start on fixing this. Any suggestions? Thanks.

A: I came across this question when I hit the same message today. I had the SDK set to 10.7 and the deployment target set to 10.6, but was still seeing this message.
My project was mostly using existing manual retain–release code, with only a couple of new files using ARC. Accordingly, I had ARC disabled in the main target settings, and had selectively enabled it for the two files by adding -fobjc-arc to the per-file build settings (under Build Phases).
On a hunch, I enabled ARC in the target, and then flopped the per-file settings (removing the flag for the two files, and adding -fno-objc-arc to all the others) and no longer got the dynamic link error on 10.6.

A: You need to set the SDK to 10.7 - but you can set the Deployment target to 10.6.  There are some caveats though detailed in this question: How to deploy to Snow Leopard with ARC enabled


text:
Q: Erro ao tentar acessar a sessão de admin no wordpress Meu site esta funcionando normalmente, porem quando vou acessa a sessão de admin começa a surgir esse erro, até o dia 29 estava funcionando normalmente, fiquei esses dias sem entrar.
O erro apresentado segue abaixo:

Fatal error: Uncaught Error: Class 'WP_Http_Cookie' not found in /home/steakvillecom/public_html/prod/wp-includes/class-wp-http-requests-response.php:165 Stack trace: #0 /home/steakvillecom/public_html/prod/wp-includes/class-wp-http-requests-response.php(192): WP_HTTP_Requests_Response-

A: Provavelmente no momento de fazer o upload via FTP o wp-includes/class-wp-http-cookie.php tenha ficado truncado (quebrou durante o upload), tente faze o upload novamente somente do class-wp-http-cookie.php para a pasta /public_html/prod/wp-includes/.
Se não funcionar tente enviar como BINÁRIO, se estiver usando o Filezilla, clique em Transfer > Transfer type > e troque Auto por Binary
Como na imagem:


text:
Q: Boost thread finally block handling I am porting C++ library from Windows to Linux. This is multi-threaded library. In Windows version there are __try/__finally block used for freeing resources and other activity after thread end. GCC doesn't support __try/__finally and C++ standard doesn't support it, because C++ have RAII. But how can i apply it to thread function?(destructor for function??).
I need to do some work then thread ended no matter which way (exception or normal return).
Is there any way to do this without writing catch(...) with "destructor" code and adding "destructor" code to all returns?


text:
Q: code igniter auth(Tank Auth) logs me out for no reason (i.e. overloaded may be) i have a controller and a view indicated as below which works perfect for some time, but after some requests are made to the server(i.e. keeps reloading every one second) it will fail on this line
 if (!$this->tank_auth->is_logged_in())

for no reason, i don't know weather it is congested or ...
when i try to debug the client code in firebug and hold a put a break point on this line
  $('#buy_reload').load('buy/reload'); //And press f8 every time

it woks like charm what is the problem? load?
Z controller
class Buy extends CI_Controller
{
function __construct()
{
    parent::__construct();

    $this->load->helper('url');
    $this->load->library('tank_auth');
    $this->load->model(array('tank_auth/users','players','cash','inventory','items','shopping_cart','purchases','processing'));
}

function reload()
{
    if (!$this->tank_auth->is_logged_in()) {
        redirect('/auth/login/');
    } else {
            //do those stuffs
           }

}
}

a script inside Z view
  <script>
   setInterval(function() {
   $('#buy_reload').load('buy/reload');
   }, 1 * 1000);
  </script>

A: I had a similar problem with Tank Auth and CodeIgniter 2.1 .
There seems to be an issue with sessions and Ajax calls.
The following links will help you
http://ellislab.com/forums/viewthread/199753/#962141
http://ellislab.com/forums/viewthread/203821/#951378
The problem is in the sess_update function of the session class, that generates a new session_id after X seconds. Every page have a session_id, if the session_id expires before the ajax call is made, that call will fail.


text:
Q: @EnableOAuth2Sso AND @EnableResourceServer in same app I'd like have a set of services that can be used with "Client Credential" (for machine to machine) and with OAuth2 Single Sign On for the regular webapp (which is served by the same application).
I tried setting both @EnableOAuth2Sso and @EnableResourceServer; I expected to have the app "try" the token based and then fall back to SSO redirect in case it doesn't find any and the user does not have a session.
Each config works fine on its own (with a:
@Bean
 public RemoteTokenServices ...

for @EnableResourceServer to configure the "CheckTokenEndpointUrl").
But as soon as I try with both I get:
APPLICATION FAILED TO START
Description:
Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a single bean, but 2 were found:
    - userInfoTokenServices: defined by method 'userInfoTokenServices' in class path resource [org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration$RemoteTokenServicesConfiguration$UserInfoTokenServicesConfiguration.class]
    - remoteTokenServices: defined by method 'remoteTokenServices' in class path resource [my/CustomWebSecurityConfigurerAdapter.class]

A: In your spring boot application class use the @EnableOAuth2Sso annotation and in the configuration class use @EnableResourceServer annotation and in this class define the endpoints to be used with access tokens.
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  @Override
  public void configure(HttpSecurity http) throws Exception {
    http
      .antMatcher("/user")  //end point that needs access token in header
      .antMatcher("/info")  //end point that needs access token in header
      .authorizeRequests().anyRequest().authenticated();
  }
}

For more information refer the link


text:
Q: Getting undefined with custom function execution in grunt task Try to execute below custom task:
'use strict';
module.exports = function(grunt) {
    grunt.initConfig({

        log: {
            one: [1, 2, 3],
            two: "Hello World",
            three: true,
            four: {
                five: function() {
                    grunt.log.writeln("Hi");
                },
                six: function() {
                    grunt.log.writeln("Welcome");
                }
            }
        }

    });
    grunt.registerMultiTask('log', 'Log stuff', function() {
        grunt.log.writeln(this.target + ": " + this.data + "\n");

        if (this.target === 'four') {
            console.log(this.data);

            for(var d in this.data) {
                console.log(this.data['five']());

                console.log(this.data['six']());
            }
        }
    });

    grunt.registerTask('default', 'log');
};

I am getting below output:
Running "log:one" (log) task
one: 1,2,3

Running "log:two" (log) task
two: Hello World

Running "log:three" (log) task
three: true

Running "log:four" (log) task
four: [object Object]

{ five: [Function], six: [Function] }
Hi
undefined
Welcome
undefined
Hi
undefined
Welcome
undefined

Done, without errors.

I am not able to understand while executing function five and six; it displaying correct output with "undefined". From where this undefined comes ?

A: When you write console.log(this.data['five']()); it means "print out the return value of the function that is defined at this.data.five, that is:
function() {
    grunt.log.writeln("Hi");
}

This function has no explicit return, so its return value is undefined, and your code prints it out.
To avoid this, change your code to:
for(var d in this.data) {
    this.data['five']();
    this.data['six']();
}

Or even better, avoid the duplication:
for(var d in this.data) {
    this.data[d]();
}


text:
Q: How to delete a folder with content to recycle bin in Matlab I am running Matlab R2020b on Windows 10.
Is there a way to move a folder with content to recycle bin programmatically in Matlab?
For example, the following works for single files
previousState=recycle('on');
delete(filename); % if replaced with rmdir(DIR,'s');, folder is deleted permanently
recycle(previousState);

but the same toggle doesn't work for folders. Is there a way?

The only possible workaround I can think of is to use wildcard: delete(fullfile(DIR,'*') and then rmdir(DIR) on the empty folder. But that doesn't work for my application. I wish to preserve temporary copies of folders in recycle bin in case my script that manipulate them throws warning in some unexpected way, in which case I can have a second chance to see the original files. There are hundreds of folders, each contain hundreds to thousands of files in this particular use case. The wildcard approach does put individual files into recycle bin but it loses the original folder structure, making it impractical to selectively recover folders. Hence the question.

A: Since the OS is specifically Windows 10, one can use powershell as shown here.
For example, with the following recycleFile.ps1 file in C:\
Param(
  [string]$filePath # can be folder
)

$sh = new-object -comobject "Shell.Application"
$ns = $sh.Namespace(0).ParseName($filePath)
$ns.InvokeVerb("delete")

the following passage in Matlab will move the folder fullfilepath to recycle bin,
[status,cmdout]=system(['powershell.exe -ExecutionPolicy Bypass -File "',...
                            fullfile('C:','recycleFile.ps1'),'" "',...
                            fullfilepath),'"']);

There are several downsides, however.
The operation is equivalent to context menu -> delete. It will bring up the recycle progress UI which seizes foreground. It is also somewhat slow. It may even require user confirmation if the folder in question is not eligible for recycling but only for direct deletion.


text:
Q: Can't get plain text google maps api html_instructions in php I'm trying my best to get plain text from google maps directions api where it says html_instructions in json. everything is encoded in html and i want to output plain text.
here is what I'm getting
image 1
this is what i want : image 2
I tried ay type of preg_replace, it couldn't help me out.
Google maps api link
Link

A: EDIT: Previous code snippet removed and replaced by workable small program.
Note that when you process the data with json_decode() the unicode segments like \u003cb\u003eFlintergata\u003c/b\u003e are converted to Flintergata. This helps a lot to make the Regex more readable.
Note the $details array is a multilevel associative array, so you need to dig down as shown to find the data you need.
Note also the URL you provided results in 1  route, with 1 leg. So the code I provided shows and processes the first leg of the first route.
If you use a different URL you may get multiple routes each with multiple steps. The code will still process the first leg of the first route, but its each (with outer loops) to show all of them (not shown below).
The explanation of the regex string '"~>([A-Z].*?)<~"' is as follows.
The '#' at each side are the PHP delimiters - but you can use other chars also and would not make any difference.
The  and  are saying that each matched string must start with  and end with .
Inside the (  ) a "capture group" that says we want to extract that part of the string only (excluding the  and ).
[A-Z] says begin with a capital letter
.* says follow with 0 or more of any character.
The ? makes the * non_greedy so this case, stop current match when it meets the next <.
The list of matches for each string goes into an array called $matches and $matches[1] is an array of capture group matches ( ie text within the  and  is removed).
<?php

$json = file_get_contents("https://maps.googleapis.com/maps/api/directions/json?origin=sandnes&destination=vigrestad&key=");
$details = json_decode($json,true);

// $details is a large associative array
// print all the instructions for the first step of the fist leg of the first route
echo PHP_EOL."Here are the unfiltered html instructions for first leg of first route ".PHP_EOL.PHP_EOL;
$steps = $details['routes'][0]['legs'][0]['steps'];
foreach($steps as $step){
    echo($step['html_instructions']).PHP_EOL;  // print to see format
    // we see unicode html_entities have been replaced and now look like    etc
}

// now extra the required information from each step
echo PHP_EOL."Here are the filtered html instructions for first leg of first route ".PHP_EOL.PHP_EOL;
foreach ($steps as $step)
{
    //preg_match_all("~003e([A-Z].*?)\\\\u003c~", $step['html_instructions'], $match); // not needed now
    preg_match_all('#,([A-Z].*?)#, $step['html_instructions'], $match);  // now detects strings between '>' and '<'
    foreach($match[1] as $instructionPart)
    {
        echo $instructionPart." ";
    }
    echo PHP_EOL;

}
?>


text:
Q: Increment self variable from a list I have self variable total in a list and want to update the value using a for loop.
However what I've tried doesn't increase the total.
class Example:
    def __init__(self):
        self.total = 0

        self.list = [self.total,
                     self.total]

        for item in self.list:
            item += 5

        print(self.total)

Example()

The printed output in the example is 0, whereas I'm wanting to know what I need to change to get this to equal 10.
Many thanks

A: Variables like int, float str and tuple are not mutables and are passed around by value. Therefore
self.list = [self.total, self.total]

is equivalent to
self.list = [0, 0]

and where 0 is the number zero and not a references to self.total. So when you do:
for item in self.list:
    item += 5

in each iteration you initialize the variable item to 0, then increase it by 5. Since you alway do the same, at the end of the loop item will always be 5, independently of the number of iterations. And self.total is never modified.
If you want to increase self.total you have to do it explicitly:
for i in range(2):
    self.total += 5

EDIT according to the comment below
It is possible to modify variables in place when using mutables, e.g. list. A possible solution to your problem might be:
class Example:
    def __init__(self):
        self.total1, self.total2 = [], []
        self.list = [self.total1, self.total2, self.total1]

        for item in self.list:
            item.append(5)
        print(sum(self.total1), sum(self.total2))

If you don't what to do sums at the end, in the for loop you can use list.pop and list.append to remove the existing value from item, update it and re-insert it into item.

A: try this:-
class Example:
    def __init__(self):
        self.total = 0

        self.list = [self.total,
                     self.total]

        for item in self.list:
            item += 5
            self.total += item

        print(self.total)

Example()


text:
Q: How to retrieve data from database and set into the check-boxes I have a form in a c# application in which I am saving values from checkboxes to database. Now what I need to do is that to retrieve the saved values on same form for updating and editing purpose.
For example I have used this query to retrieve the data:
     "Select * from tblComplaints where ID = txtID.Text"

Here I want to know that How can I set the !null values on check-boxes?


text:
Q: Wpf designer cannot apply Style In Wpf I inherit from the Button class:
public class MenuButton : Button
    {
        public MenuButton()
        {
            this.Style = FindResource("MenuButton") as Style;
        }
        public MenuButton(string caption, ICommand command)
        : this()
    {
        SetValue(ContentProperty, caption);
        this.command = command;
    }
}

In a window I added a control
<c:MenuButtons x:Name="MenuProject" c:MenuItems="{x:Static d:MenuItems.Project}" />

Where c: en d: are my namespaces.
MenuItems is a dependencyproperty of usercontrol MenuButtons and is declared in a class like:
public readonly static MenuButton[] Project = new MenuButton[] { new MenuButton("Open", new Command()), ..etc };
The resource is defined like:
 <Style x:Key="MenuButton"
           BasedOn="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
           TargetType="{x:Type c:MenuButton}">

The visual studio designer says: 'MenuButton' TargetType does not match type of element 'MenuButton'. The code runs fine, but the designer has trouble invoking the constructor of my MenuButton class. When commenting out that line the error disappears, but then the style is not applied and vice versa.

A: this.Style = FindResource("MenuButton") as Style; should not appear in the constructor.
You can apply it in the OnApplyTemplate method
public overrride OnApplyTemplate()
{
     this.Style = FindResource("MenuButton") as Style;
     base.OnApplyTemplate();
}

Hope this helps


text:
Q: Mismatched argument count to recur in syntax quoted macro I'm creating a macro that will accept a sum in infix notation and return an equivalent list in prefix notation. Whilst the code probably isn't logically correct yet, I've run into the following error when calling the macro:
CompilerException java.lang.IllegalArgumentException: Mismatched argument count to recur, expected: 0 args, got: 5, compiling:(/tmp/form-init1201331851685991945.clj:1:1)
Here's the macro's code:
(defmacro infixer [o1 outlist i1 i2 i3]
  `(if (empty? ~i3)
    (concat ~i1 ~i2)
    (if (= ~i2 ~o1)
      ;then recur list of i2 i1 i3 at outlist tail
      (recur ~o1
             (concat ~outlist (~i2 ~i1 ~(first i3)))
             ()
             ~(second i3)
             ~(rest (rest i3)))
      ;else recur i1 at outlist tail
      (recur ~o1
             (concat ~outlist ~i1)
             ~i2
             ~i3
             ~(rest i3)
      ))))

I'm using the following to test it, after which the above error is thrown:
(def s1 '(1 + 3 * 2 / 2 * 5 - 3))
(infixer * () (first s1)(second s1)(rest (rest s1)))

I can't see any recur targets, so shouldn't recur be seeing the five arguments after the macro name? I haven't used syntax quoting before, so my suspicions are that I've misunderstood how to use it. Please can someone explain why the error is being thrown?
Also, if I'm way off on the logic of trying to convert infix to prefix, feel free to point me in the right direction! I'm new to Clojure and FP so any guidance is extremely appreciated - thanks in advance.


text:
Q: htaccess URL wrong redirection I want to redirect

*

*/about

*/about/

*/about.html

*/about.html/

*/weare/

*/weare

*/weare.html

*/weare.html/
All these pages should be redirected to about.html and I want to do this with .htaccess.
I wast trying by
RewriteRule ^(about|weare).*/ about.html [R=Permanent]

This is somewhat working, but not exactly what I want. It is also redirecting some other pages.
I have added as said by ThinkingMonkey
If you want to do a permanent redirect:
    RewriteCond %{REQUEST_URI} !^/about\.html$ [NC]
    RewriteRule ^(about|weare)(\.html)?/?$ about.html [L,R=301]

This is working But it is going for infinite loop.

A: Do this:
RewriteRule ^(about|weare)(/|\.html/?)?$ about.html [L]

If you want to do a permanent redirect:
RewriteCond %{REQUEST_URI} !^/about\.html$ [NC]
RewriteRule ^(about|weare)(\.html)?/?$ about.html [L,R=301]

A: RewriteRule ^((about|weare)(.|/)?(html)?) about.html [NC]


text:
Q: How to deal with duplicates using python/mysql? I have a sql query which returns a list of duplicates with their id, from my table Person :
1   hudson
43  hudson
67  hudson
34  roger
79  roger
89  kerry
403 kerry

Using a Python script, I would like to automate this kind of query, for example for the "hudson" case :
UPDATE Customer SET person_id = 1 WHERE person_id = 43;

When the number of duplicates is set (for example 2), I think we can do something like :
cursor.execute(*myquery that returns list of duplicates*)
rows=cursor.fetchmany(2)
row1=rows[1] #??
row2=rows[2] #??
cursor.execute('UPDATE Customer SET person_id = row1[0] WHERE person_id = row2[0];')

I really don't know how to do when the number of duplicates is variable.
Thanks a lot for your help

A: Group by the names and select the minimum person ID from each group.
Also consider using Python Pandas and just dumping all of the data into a Pandas DataFrame, then you can just use the drop_duplicates function. I've found it was well worth my effort to create my own SQL-to-h5 and SQL-to-Pandas backend code to let me just do all my Python work in Pandas and never mess with the SQL directly.


text:
Q: How can I remove duplicated from my code in Java? I wrote a test that will run recursion Fibonacci for 40 and run memoization recursion Fibonacci for 40 and compare the time to be at least one order of magnitude different. This is what I get so far:
      @Test
  void MemoizedMagnitudeDifferentFromRecursion(){
    Fibonacci simpleRecursiveFibonacci = new SimpleRecursiveFibonacci();
    Fibonacci memoizedRecursiveFibonacci = new MemoizedRecursiveFibonacci();
    int n = 40;

    long recursionStartTime = System.nanoTime();
    simpleRecursiveFibonacci.fibonacci(n);
    long recursionTime = System.nanoTime() - recursionStartTime;

//The code below does the same as the code above, how can I remove duplicated code?
    long memoizedStartTime = System.nanoTime();
    memoizedRecursiveFibonacci.fibonacci(n);
    long memoizedTime = System.nanoTime() - memoizedStartTime;

    assertTrue(recursionTime/memoizedTime > 1);
  }

A: Extract the logic to a function and pass the logic to be run as a Runnable. Let the function run the piece of logic passed in and return the time it took to run it.
private long execute(Runnable runnable) {
    long startTime = System.nanoTime();
    runnable.run();
    return System.nanoTime() - startTime;
}

Call it as
long recursionTime = execute(() -> simpleRecursiveFibonacci.fibonacci(n));
long memoizedTime = execute(() -> memoizedRecursiveFibonacci.fibonacci(n));
assertTrue(recursionTime/memoizedTime > 1);

One more option (as suggested by SystemGlitch@) is to pass an instance of Fibonacci and an int and call fibonacci inside the method.
private long execute(Fibonacci fibonacciInstance, int n) {
    long startTime = System.nanoTime();
    fibonacciInstance.fibonacci(n);
    return System.nanoTime() - startTime;
}

Call it as
long recursionTime = execute(simpleRecursiveFibonacci, n);
long memoizedTime = execute(memoizedRecursiveFibonacci, n);
assertTrue(recursionTime/memoizedTime > 1);


text:
Q: kill Winword.exe after the vbscript When i run the below VB script i get the desired output as expected.
But, a new winword.exe process is ran, which i wanted to kill after the script ends.
Set Wshshell= CreateObject("Word.Basic")
WshShell.sendkeys"%{prtsc}"
WScript.Sleep 1500
Set wshshell = Nothing

set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "mspaint"
WScript.Sleep 1000
Set wshshell = Nothing

Set Wshshell= CreateObject("Word.Basic")
WshShell.AppActivate "Paint"
WScript.Sleep 2000

WshShell.sendkeys"^(v)"
WScript.Sleep 1000

WshShell.sendkeys"^(s)"
WScript.Sleep 1500

WshShell.sendkeys"c:\testing.jpg"
WScript.Sleep 500
WshShell.sendkeys "{Enter}"

Set wshshell = Nothing

A: You will have to close the active process using
Wshshell.FileClose

or
Wshshell.AppClose


text:
Q: I have a problem login to my anyDesk remotely When i try to login to my anydesk remotely in my ubuntu 22.10, it show me that "The session has ended Status: display server unsupported."
And i found this command to solve it "sudo gedit /ect/gmd3/custom.conf" but it shows "sudo: gedit: command not found."
Please help...

A: On ubuntu 22.10 gnome-text-editor replaces gedit.
You have three options :

*

*you can use nano

*you can use gnome-text-editor

*You can install gedit back with sudo apt install gedit


text:
Q: How to get the column id value from table in entityframework Is there a way to get the column id value using Entity Framework 4?
The same like this SQL Query:
Select Orderid from OrderItems where Orderid  = 1;

A: You can get the key values of entities by querying EntityKeys from the ObjectStateManger. In EF4 (assuming you have an ObjectContext) it goes like this:
foreach (var ek in context.ObjectStateManager
            .GetObjectStateEntries(System.Data.EntityState.Unchanged)
            .Select(objectStateEntry => objectStateEntry.EntityKey))
{
    System.Data.EntityKeyMember[] keys = ek.EntityKeyValues;
    // Do something with keys
}

In EF6 (with DbContext) it's done like so:
var oc = ((IObjectContextAdapter)context).ObjectContext;
foreach (var ek in oc.ObjectStateManager
            .GetObjectStateEntries(System.Data.Entity.EntityState.Unchanged)
            .Select(objectStateEntry => objectStateEntry.EntityKey))
{
    System.Data.Entity.Core.EntityKeyMember[] keys = ek.EntityKeyValues;
    // Do something with keys
}

This will get the key values of entities that have been loaded into the context at this point.


text:
Q: Which TLS version is database mail using? How can we find out which TLS version our database mail is using for sending e-mails?
We have issues with database mail (mails are sometimes not sent, even after 10 repeats), and it seems that TLS 1.1 and TLS 1.0 are not supported anymore. But how can I find out which TLS version our database server is using?
SQL Server version is 12.0.5000.0 (which is SQL 2014 SP2, it seems)

A: If i'm right, SQL Server Database mail uses System.Net.Mail to do the work, and SQL Server 2014 database mail is built for .Net 3.5.
The System.Net.Mail is able to send mail using TLS 1.2 when the build runtime version is 4.6 or above. So SQL Server 2014 database mail should not be able to support TLS 1.2 until some CU/SP.
Maybe patching the 3.5 .NET framework would fix your issue.
MIcrosoft KB

A: SQL Server Database mail uses System.Net.Mail to do the work, and SQL Server 2014 database mail is built for .Net 3.5.
The System.Net.Mail is able to send mail using TLS 1.2 when the build runtime version is 4.6 or above. So SQL Server 2014 database mail does not support TLS 1.2.
Besides, you can try to install the .NET hotfix to enable Database Mail to use TLS 1.2.
https://support.microsoft.com/en-us/help/3154520/support-for-tls-system-default-versions-included-in-the-net-framework


text:
Q: Checking next row in table is incremented by 1 minute in datetime column I need to check alot of data in a Table to make sure my feed has not skipped anything.
Basically the table has the following columns
ID     Datetime      Price
The data in DateTime column is incremented by 1 minute in each successive row.  I need to check the next row of the current one to see if is 1 minute above the one being queries in that specific context.
The query will probably need some sort of loop, then grab a copy of the next row and compare it to the datetime row of the current to make sure it is incremented by 1 minute.

A: I created a test-table to match your description, and inserted 100 rows with 1 minute between each row like this:
CREATE TABLE [Test] ([Id] int IDENTITY(1,1), [Date] datetime, [Price] int);

WITH [Tally] AS (
  SELECT GETDATE() AS [Date]
  UNION ALL
  SELECT DATEADD(minute, -1, [Date]) FROM [Tally] WHERE [Date] > DATEADD(minute, -99, GETDATE())
)
INSERT INTO [Test] ([Date], [Price])
    SELECT [Date], 123 AS [Price]
    FROM [Tally]

Then i deleted a record in the middle to simulate a missing minute:
DELETE FROM [Test]
WHERE Id = 50

Now we can use this query to find missing records:
SELECT
    a.*
    ,CASE WHEN b.[Id] IS NULL THEN 'Next record is Missing!' ELSE CAST(b.[Id] as varchar) END AS NextId
FROM
    [Test] AS a
    LEFT JOIN [Test] AS b ON a.[Date] = DATEADD(minute,1,b.[Date])
WHERE
    b.[Id] IS NULL

The resullt will look like this:
Id          Date                    Price       NextId
----------- ----------------------- ----------- ------------------------------
49          2013-05-11 22:42:56.440 123         Next record is Missing!
100         2013-05-11 21:51:56.440 123         Next record is Missing!

(2 row(s) affected)

The key solution to the problem is to join the table with itself, but use datediff to find the record that is supposed to be found on the next minute. The last record of the table will of course report that the next row is missing, since it hasn't been inserted yet.

A: Borrowing TheQ's sample data you can use
WITH T
     AS (SELECT *,
                DATEDIFF(MINUTE, '20000101', [Date]) -
                        DENSE_RANK() OVER (ORDER BY [Date]) AS G
         FROM   Test)
SELECT MIN([Date]) AS StartIsland,
       MAX([Date]) AS EndIsland
FROM   T
GROUP  BY G


text:
Q: What is the relation between the Chern-Gauss-Bonnet theorem and the Hopf index theorem? I'm reading a paper where the following form of Chern-Gauss-Bonnet theorem is proved:

Let $R$ denote the Riemannian curvature tensor associated to the
Levi-Civita connection (the Riemannian connection) on a closed
Riemannian manifold $X$ of dimension $n$, and let $\text{Pf}(R)$ be the Pfaffian
density of the curvature. Then \begin{equation*}
     \frac{1}{(2\pi)^{\frac{n}{2}}}\int_X \text{Pf}(R)=
 \text{Index}(\nabla h), \end{equation*} where $h$ is any Morse
function on $X$ and $\text{Index}(\nabla h)$ is the Hopf index of the
gradient vector field $\nabla h$ of $h$.

Before stating this, the paper stated in its introduction as a side effect that
$$ \frac{1}{(2\pi)^{\frac{n}{2}}}\int_{\underline{\text{SM}}(\mathbb{R}^{0|2},X)}\exp(-\mathcal{S}_0(\phi)=
\chi(X), $$
without proof, where $\frac{1}{(2\pi)^{\frac{n}{2}}}\int_{\underline{\text{SM}}(\mathbb{R}^{0|2},X)}\exp(-\mathcal{S}_0(\phi)=\frac{1}{(2\pi)^{\frac{n}{2}}}\int_X \text{Pf}(R)$ by later computation, giving half the equality of the above Chern-Gauss-Bonnet theorem.
I've read before that in Bott & Tu's Differential Forms in Algebraic Topology, the Hopf index theorem is proved using the Euler class, giving
$$\chi (X)=\int_X e(TX)=\text{Index}(\nabla h). $$
My advisor told me that $\frac{1}{(2\pi)^{n/2}}\text{Pf}(R)$ is exactly the Euler class $e(TX)$, but he does not remember clearly how this can be deduced.
I haven't yet figured out what the formula of $\text{Pf}(R)$ is, but I'm confused by the relation between the Chern-Gauss-Bonnet theorem and Hopf index theorem. Under the assumption that $\frac{1}{(2\pi)^{n/2}}\text{Pf}(R)=e(TX)$, it seems that they are exactly the same -- then what's the point of distinguishing the two theorems?
To spell out, my question is:

*

*Can the fact that $\frac{1}{(2\pi)^{n/2}}\text{Pf}(R)=e(TX)$ be deduced by direct computation? Or does it follow as a corollary from the two theorems that $$\frac{1}{(2\pi)^{\frac{n}{2}}}\int_X \text{Pf}(R)=
 \text{Index}(\nabla h)=\int_Xe(TX)$$ and the fact that $H_{DR}^n(X)=\mathbb{R}$?

*Is there any good reason to distinguish the Chern-Gauss-Bonnet theorem and the Hopf index theorem, which makes sense even if $\frac{1}{(2\pi)^{n/2}}\text{Pf}(R)=e(TX)$ could be given by direct computation?


text:
Q: TextField that accepts only numbers and one decimal point in SwiftUI I searched for a good approach for this problem and none of the questions I'v found answered my needs. I'm struggling with this.
What I need is a TextField that would accept only 0123456789. with format of %.2f and wouldn't require to press Return key to submit. Receiving the value as Double and return as Double.
The results should be 123.45 or 1.23.
My attempt:
    var title: String
    let numberFormatter = NumberFormatter()

    @Binding var value: Double

    var amountProxy: Binding<String> {
        Binding<String>(
            get: { String(format: "%.2f", value) },
            set: {
                if let value = numberFormatter.number(from: $0) {
                    self.value = value.doubleValue
                }
            }
        )
    }

    var body: some View{
        HStack(spacing: 8){
            Text(LocalizedStringKey(title + ":"))
                .layoutPriority(1)
            TextField(LocalizedStringKey(""), text: amountProxy)
                .keyboardType(.decimalPad)
                .multilineTextAlignment(.trailing)
        }
        .lineLimit(1)
    }

This method results were forcing the user to type one number and move precisely after the decimal point to get the requested value 4.20. Something like type, move, repeat. Very poor UX.


text:
Q: Ckeditor 5 Ballon Block Edit Block Icon Change I am new to CKeditor. Need help with Ckeditor 5. I am using Balloon Block. I need to change the Edit Block icon to my own custom icon. Please refer to the image attached. I am using Angular 8

Thanks in advance.

A: **The easiest way is to use webpack's NormalModuleReplacementPlugin plugin. For example, to replace the bold icon use the following code in your webpack.config.js: **
plugins: [
new webpack.NormalModuleReplacementPlugin(
    /bold\.svg/,
    '/absolute/path/to/my/icon.svg'
)

]


text:
Q: TypeError: JwtStrategy requires a secret or key I've read the million threads with the same issue but I couldn't solve it :(
This is an old project I made and I need to access to it again but I'm getting the following error when running npm start:
> express-typescript-starter@0.1.0 start
> npm run tsc && npm run serve

> express-typescript-starter@0.1.0 tsc
> tsc

> express-typescript-starter@0.1.0 serve
> ts-node src/server.ts

{"level":"debug","message":"Logging initialized at debug level"}

C:\Users\alan_\Desktop\cdng\mern-finance-server-master\node_modules\passport-jwt\lib\strategy.js:45
        throw new TypeError('JwtStrategy requires a secret or key');
              ^
TypeError: JwtStrategy requires a secret or key
    at new JwtStrategy (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\node_modules\passport-jwt\lib\strategy.js:45:15)
    at Object.<anonymous> (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\src\config\passport.ts:6:28)
    at Module._compile (node:internal/modules/cjs/loader:1149:14)
    at Module.m._compile (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\node_modules\ts-node\src\index.ts:858:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
    at Object.require.extensions.<computed> [as .ts] (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\node_modules\ts-node\src\index.ts:861:12)
    at Module.load (node:internal/modules/cjs/loader:1027:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Module.require (node:internal/modules/cjs/loader:1051:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\src\app.ts:16:1)
    at Module._compile (node:internal/modules/cjs/loader:1149:14)
    at Module.m._compile (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\node_modules\ts-node\src\index.ts:858:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
    at Object.require.extensions.<computed> [as .ts] (C:\Users\alan_\Desktop\cdng\mern-finance-server-master\node_modules\ts-node\src\index.ts:861:12)
    at Module.load (node:internal/modules/cjs/loader:1027:32)

This is src/config/passport.ts:
import passport from 'passport'
import { Strategy as JwtStrategy, ExtractJwt } from 'passport-jwt'
import userServices from '../services/userServices'
import { JWT_SECRET } from '../util/secret'

export const jwtStrategy = new JwtStrategy(
  {
    secretOrKey: JWT_SECRET,
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  },
  async (payload: any, done: any) => {
    const userEmail = payload.email
    const foundUser = await userServices.findUserByEmail(userEmail)
    done(null, foundUser)
  }
)

When running "npm i" I'm getting a bunch of errors as well but I could --force it:
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: jest-config@27.5.1
npm WARN Found: ts-node@8.10.2
npm WARN node_modules/ts-node
npm WARN   dev ts-node@"^8.6.2" from the root project
npm WARN
npm WARN Could not resolve dependency:
npm WARN peerOptional ts-node@">=9.0.0" from jest-config@27.5.1
npm WARN node_modules/jest-config
npm WARN   jest-config@"^27.5.1" from @jest/core@27.5.1
npm WARN   node_modules/@jest/core
npm WARN   1 more (jest-cli)
npm WARN
npm WARN Conflicting peer dependency: ts-node@10.9.1
npm WARN node_modules/ts-node
npm WARN   peerOptional ts-node@">=9.0.0" from jest-config@27.5.1
npm WARN   node_modules/jest-config
npm WARN     jest-config@"^27.5.1" from @jest/core@27.5.1
npm WARN     node_modules/@jest/core
npm WARN     1 more (jest-cli)
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: ts-jest@26.5.6
npm ERR! Found: jest@27.5.1
npm ERR! node_modules/jest
npm ERR!   dev jest@"^27.5.1" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer jest@">=26 <27" from ts-jest@26.5.6
npm ERR! node_modules/ts-jest
npm ERR!   dev ts-jest@"^26.5.1" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: jest@26.6.3
npm ERR! node_modules/jest
npm ERR!   peer jest@">=26 <27" from ts-jest@26.5.6
npm ERR!   node_modules/ts-jest
npm ERR!     dev ts-jest@"^26.5.1" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

You can see the whole repo here.
Thanks!

A: I'm not going to attempt to fix your conflicts, but npm i -force will allow everything to be installed.
You will also need to place a .env file in the root and ensure it has a JWT_SECRET secret value.
There are also a lot of other .env values required. Your .env should look like this (or production):
JWT_SECRET = 'jhagdhjwf'
MONGODB_URI = 'mongodb://localhost:27017/local'
PORT = 3000

CLOUD_NAME = 'Your cloud name'
CLOUDINARY_API_KEY = '123123123123'
CLOUDINARY_API_SECRET = 'abc123abc123abc123abc123'

NODE_ENV = 'production'

I don't know why you didn't think an .env was not required. I thought you said this was your project?
As you will also know, you have to have cloudinary API config and also a running mongodb server, on which you store your data.
Eg, install docker and run the command to get a quick running local version:
docker run -d -p 27017:27017 --name test-mongo mongo:latest
I did a pull of the code and everything works locally. Add this .env and it will work:

> express-typescript-starter@0.1.0 start
> npm run tsc && npm run serve

> express-typescript-starter@0.1.0 tsc
> tsc

> express-typescript-starter@0.1.0 serve
> ts-node src/server.ts

{"level":"debug","message":"Logging initialized at debug level"}
(node:78699) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
App running on port 3000

Opening http://localhost:3000/api/v1/users will give you the expected [] response. I assume you have a front end somewhere.
Everything should be working as expected.
Extra: Your import { JWT_SECRET } from '../util/secret' is not the right file name. In your repo it is https://github.com/AlanFPS/mern-finance-server/blob/master/src/util/seccret.ts. Your import is looking for secret but your file is called seccret (two c's).


text:
Q: What constitutes valid justification for more IP addresses? I host a small website with a well known VPS service. They provided me with one IPv4 address upon registering and said additional addresses would require justification. I requested one additional IPv4 address so as to have one for a production environment and one for a testing/QA environment. They said this was unnecessary as I could just use alternative TCP ports for the test environment.
I can live with using a non-standard port for non-production hosting, but it got me thinking, what would be valid justification? (I asked them and they didn't want to answer). Is there an industry standard for what counts as "valid" justification for additional IPv4 addresses?

A: With the IPv4 shortage globally waste in the IPv4 space is not wanted so 'any' reason really is not the case any more.
Generally speaking anything that you cant use NAT or ports for without a load of hassle or impractical amounts of work is valid, SSL is the main justification these days however that will change soon with new methods, and a lot of hosts will check you really are using it for this by asking you what the domain is going to be and checking it within 14 days.
They dont want to answer not because they dont want to tell you but sadly so many people waste them they dont want people giving stock answers just to get IP's without discussion.
If you need an IP for a production site/service and it really does need an dedicated external IP then giving them an explanation as to why would constitute a valid reason.
If those host does not own its own IP space issued through RIPE/ARIN then it is also possible they are leasing them from the data centre in which case the host will also have a hard limit on how many IP's they can assign to a physical server so if they sell you an IP for $2 p/month then that is an IP they cannot use for another virtual server that they could charge a bit more for so they really want to make sure it is not going to be wasted.
Hope that brings some clarity to your question(s)

A: just about any reason would be considered "valid".  typically, unless you have wildcard or multihost certs, ssl is 1:1 IP addr to https site.  so you can say you just got 10 different https customers.
it can also be a propriatary reason, such as my super secret code / app must run on its own ip, so that i can iptables deny everything except udp/5998.
interestingly enough, i have seen vps service providers give 2 ips, so that customers can run bind named, but both ips are on the same vlan/network which goes against dns authoritative RFC requirements.
there is a bit of an ip shortage, as massive /16's were just handed out like candy many years ago.... so if you request a /20, and say its cuz you have a few https customers, you will rightly be denyed.

A: This can really depend on your provider, what services you have with that provider, and how much you're paying for it.
From my experience, if you're dropping several grand a month on services, you can get additional address space without a quarrel.  You still have to fill out the paperwork but nobody cares how you use the IPs.
With other providers, they will charge a fee for additional IPs.  If you agree to pay what they ask for the address space, you can usually justify it however you want.  To be clear, you still have to provide documentation on what you will 'allegedly' use the IPs for - but I've never had a provider bother to go and check that it's really true.
If you're trying to get the IPs for free or you've got a hard-nosed provider, the justification has to demonstrate real need.  Some examples of "real need" would be:

*

*You're a reseller

*You have multiple WAN edge appliances (firewall, VPN, etc)

*You have production websites/services that are dependent on a certain port

A: IANA justification is typically that there will be hosts responding on the assigned IP addresses.  Their benchmark was 80% utilization before additional space could be assigned, last I checked.
Any reasonable person assigning IP addresses would surely follow this criterion, as it is all that would be needed to acquire more (space permitting).

A: This is simply an arbitrary constraint dictated by the rules & resources of your provider. Simple as that. Some providers have no issue granting more IPs. Others have more hoops to jump through. There is no one generic answer.


text:
Q: Proving that the intersection of vertices in graphs in not empty.
Let $G=(V,E)$ be an undirected graph with no simple cycles in it.
Let $G_i=(V_i,E_i) (i=1,2,3)$ be two sub-graphs of G, such that $G_i$ is a tree.
There are no $i,j$ such that $V_i \cap V_j=\emptyset$
Prove that $V_1\cap V_2 \cap V_3\neq \emptyset$

I have been sitting on this one for a while but I haven't managed to prove this.
I tried to assume that the intersection is empty, but wasn't able to reach anything.
I have noticed that $G_1\cup G_2\cup G_3$ is a tree, but couldn't make something out of it as well.
Can someone help out?

A: If for any $i,j, V_i \subseteq V_j$ the proof is clear and straightforward. Let it not to be this way.
Since $V_1 \cap V_2 \neq \emptyset$, hence there is a common vertex between two sets. We also know $V_3 \cap V_2 \neq \emptyset$ and $V_1 \cap V_3 \neq \emptyset$.
Now you need to prove $V_3$ must contain the common vertex of $V_1$ and $V_2$. Prove it by contradiction. Suppose it is not so. If $G_3$ has a vertex from $G_1$, say $v$ and $v \notin V_2$, and a vertex from $G_2$, say $u$ and $u \notin V_1$, it makes a path between $v$ and $u$ ($u \leftrightsquigarrow v$) because $G_3$ is a tree, and because $G_1 \cup G_2$ is also a tree (it is not jungle because they have common vertex), it means there is exactly a path between $u$ and $v$ in  $G_1 \cup G_2$ as well which is different with the path $u \leftrightsquigarrow v$ in $G_3$. Hence  $G_1 \cup G_2 \cup G_3$ must create a cycle which contradicting the fact that $G$ has no cycle. $\blacksquare$


text:
Q: throw exception in the method
Possible Duplicate:
The throws keyword for exceptions in Java

In Java, a lot of method are ended with throws Exception. Why it is neccessary to add this?

A: It's generally considered that methods that throws Exception is a bad idea. The reason being that it gives no clues to the calling code as to what category of exceptions they might be expected to handle. Therefore seeing throws Exception is usually the sign of either poorly designed code or lazy developers.
The recommended practices are to either handle the exceptions generated or to throw explicit exceptions that give more context. For example, from the JDK, java.io.IOException is a commonly thrown exception which to some degree is still general, but at least gives you an idea of what sort of error occurred.
You should only add a throws Exception if you have no other choice.

A: I assume that you really mean "... a lot of method are ended with throws SomeException " ... where SomeException is some exception name.
The answer is that the Java language requires a method to list all checked exceptions that may be thrown in a method or some other method that it calls.  This is how you do it.

As @Derek Clarkson notes, declaring a method as throwing Exception is bad practice.  Since Exception is a checked exception, the calling method is forced to deal with it.  And you are declaring that any exception is possible, so how can it deal with that in any sensible fashion.
Best practice is to only declare checked exceptions that are actually going to be thrown.


text:
Q: How to use Active directory docker image for authorization in spring boot application This is my first time to work with Docker and AD.
I am implementing a spring boot application that uses Active directory for authorization.
I have gone through LDAP tutorial https://spring.io/guides/gs/authenticating-ldap/
I have downloaded a docker image of Active Directory.
https://hub.docker.com/r/pitkley/samba-ad-dc/#environment-variables
Now i want to use this docker image for authorization in my local machine.
Docker image is running,
$ docker run -i -t 041144877f9f /bin/bash
root@3c01c419c248:/#
How i can use this image in my spring boot app for authorization?
What should i expect from this docker image?
I use mac, java, spring boot.
Below is my code,
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest()
                .fullyAuthenticated()
                    .and()
                .formLogin();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
        .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource(contextSource())
            .passwordCompare()
                .passwordEncoder(new LdapShaPasswordEncoder())
                .passwordAttribute("userPassword");
    }

    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        return  new DefaultSpringSecurityContextSource(Arrays.asList("ldap://localhost:8389/"), "dc=springframework,dc=org");
    }
}


text:
Q: How to test for a potential linear and/or categorical or binary relationships between two variables in the same column? I want to use Scipy and Pandas to find if there is a correlation between pageviews and clicks of the event column. As far as I know, I can find the linear or binary relationship between two different columns using Pandas and Scipy and test for the significance of the relationship. However, I do not know how to test for the relationship between two variables that belong to the same column.
In summary here is what I am trying to do:
Is there any correlation between clicks and previews on a link? Is it significant? How large is the effect? And I want to test for potential linear as well as categorical (think binary) relationships between both variables
Below is a sample from my data frame:

And this is what I tried to do:
I got all the value counts of the different variables in the event columns
    df.event.value_counts()

I then filtered out the click and pageview events as follows
    pageviews = df.loc[df.event == 'pageview']
    clicks = df.loc[df.event == 'click']

And tried to run the corr() function on the two variables like this
    df.pageviews.corr(clicks)

But the corr() method did not work.
But this solution certainly does not work. How could I use Scipy and Pandas to test for the relationship between the pageview and click in the event column?


text:
Q: Reading SQL table from Python with merge condition
import pandas as pd

conn = pyodbc.connect("Driver={??};"
                      "Server=??;"
                      "Database=??;"
                      "Trusted_Connection=yes;")

df1 = pd.read_sql_query("SELECT TOP 10000 * FROM table1", conn)

df2 = pd.read_sql_query("SELECT * FROM table2  (((where id_key = id(from table1) ))) ", conn)

Hello,
I have two tables in SQL server. I wanted to pull the data from table2 that has the same ID which mean id_key = id(from table1).

A: get df1's id as a tuple:
ids = tuple(df1['id'].to_list())
print(ids)
'''
(1, 2)
'''

then, use format and read sql:
sql= 'select*from table where id_key in {}'.format(ids)
print(sql)
'''
select*from table where id_key in (1, 2)
'''

df2=pd.read_sql(sql,conn)

full code:
import pandas as pd

conn = pyodbc.connect("Driver={??};"
                      "Server=??;"
                      "Database=??;"
                      "Trusted_Connection=yes;")

df1 = pd.read_sql_query("SELECT TOP 10000 * FROM table1", conn)

ids = tuple(df1['id'].to_list())
df2_sql = 'SELECT * FROM table2 where id_key in {}'.format(ids)

df2 = pd.read_sql_query(df2_sql, conn)


text:
Q: A flea jumps on a regular $n$-gon A flea jumps on a regular $n$-gon with center $O$ with the following rules: it starts in $O$; if it's in $O$ it can jump to any vertex (with equal probability); if it's on a vertex it can jump in $O$ or to an adiacent vertex (with equal probability). Which is the probability that, after $n$ jumps, the flea is again in $O$?

A: HINT: The probability that the flea is at $O$ after $m$ rounds, can be computed recursively as
$$p_m=\frac13(1-p_{m-1}). $$


text:
Q: How to set variable values to specific cell or element in BIRT I have declared variable in beforeFactory of BIRT Report.
For example:

This variable I am incrementing in table row render like:

Now when all the rows are rendered I want to set above variable to specific cell/ element. I tried

document.getElementName("numberOfMobilityFilesProcessed").text = numberOfMobilityFiles;

AND

reportContext.getDesignHandle().getElementByID

but they are not working out for me.

A: I had some problems with temporaly local variables used at multiple steps of datasource scripting so I always used global persisting.
After changing your variable you convert it to a String (because only Strings can be persisted) and before editing your variable again, you load the String from persisted context and convert it to the type you want (String to Integer are automatically converted by JavaScripts dynamic typed variables, but don't forget the toString() when you are saving otherwise you will risk an error).
Because you are using reportContext.setPersistentGlobalVariable your variable is accessable in every Element of your Report.
Example:
var rowNum = reportContext.getPersistentGlobalVariable("row_number");
if(rowNum == null){
  rowNum = -1;
}
rowNum++;
reportContext.setPersistentGlobalVariable("row_number", rowNum.toString());

A: Ok, you have a text element displaying a number of row in a table element. The text element appears before the table in the report.
If you are using two separate tasks RunTask and RenderTask:
Add a report variable in your report (see "variable" node on the Data Explorer view). Then you can change the report variable in onCreate() event handler of the table row:
vars["numberOfSomething"] = vars["numberOfSomething"] + 1;

and access its value in an onRender() evenet handler of some text element, for instance DynamicText:
this.text = "Number of something: " + vars["numberOfSomething"];

If you are using RunAndRenderTask, you must look for another approach. In this case an order of onCreate() and onRender() calls is different. You could bind the same DataSet to the text element displaying the counter, as the one bound to the table. Than you can add an aggregation binding to the text element that will count all rows in the dataset.


text:
Q: convert text/string to number/int for python dataframe may I know how to convert text/string data to numbers for a column in Dataframe ?
If the same text/string appear again, they should return the same number.
Looking for a general way to convert since there are thousands of fruit in the world
Example :
   Fruit         Number (expected outcome)
1  Apple         1
2  Orange        2
3  Apple         1
4  Banana        3
5  Blackberries  4
6  Avocado       5
7  Grapes        6
8  Orange        2
9  Apple         1
10 Mango         7
.  .             .
.  .             .
.  .             .

A: import pandas as pd

fruitList={'name':[ "Apple","Orange","Apple","Banana","Blackberries","Avocado","Grapes","Orange","Apple","Mango"] }
df = pd.DataFrame(fruitList)

# get distinct fruit names
unique=df.name.unique()
# generating a dictionary based on Id of unique fruit names using list comprehension
dict={ x:index+1 for index, x in enumerate(unique) }
# assigning new column 'Id' values from the dictionary using the map function
df['Id']  = df["name"].map(dict)
print(df)

The Output is :
        name      Id
0         Apple   1
1        Orange   2
2         Apple   1
3        Banana   3
4  Blackberries   4
5       Avocado   5
6        Grapes   6
7        Orange   2
8         Apple   1
9         Mango   7