问:
How to influence div with checked input if div is far away and not a relative?
A have CSS-code:

```<code> .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}
</code>```

It allows me to manipulate div next to label next to checked input.

It works fine, but is there a way, that I can manipulate div with checked/unchecked that is far away from input?

My div has class "dropdown-menu" and it is not related to input in any way and like 50 lines of code after the input.

Can I connect checked value with my "dropdown-menu" div in any way with CSS?

答:
CSS is limited in terms of how one selected element is able to help select and affect other elements in the DOM. You've highlighted two of the very cool combinators available to use already: the adjacent sibling combinator (+) and the general sibling combinator (~). You're no doubt familiar with the descendant combinator (_) <- that's a space. Finally, there's the child combinator (>).

Of these, the only two that I can imagine would be even potentially helpful are the general sibling combinator (~) and the descendant combinator(_). The other two describe relationships that assume very specific proximity relationships (+, >).

You can do what (I think) you're describing with the general sibling selector (at least you can if your markup structure has the dropdown menu div as a general sibling of the label element above it). I don't think it's likely to be in real life, but (assuming it is) here's a contrived example.

.me-too {
  padding: 8px;
  background-color: #fafafa;
  margin-top: 16px;
  margin-bottom: 16px;
}

.hider+label+div {
  display: none;
}

.hider:checked+label+div {
  display: block;
}

.hider+label~.dropdown-menu {
  display: none;
}

.hider:checked+label~.dropdown-menu {
  display: block;
}

.dropdown-menu {
  margin-top: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <input id="my-checkbox" class="hider" name="my-checkbox" type="checkbox">
  <label for="my-checkbox">Check me!</label>
  <div>I can be hidden and revealed</div>

  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>

  <div class="me-too dropdown-menu">
    <h2>DROPDOWN MENU</h2>
    <p>I too can be hidden and revealed!</p>

    Link 1
    Link 2
    Link 3
    Link 3

  </div>

</header></code>```

Personally, I really appreciate that you're trying to accomplish this using CSS. I think it's always better to use the simplest tool that can get the job done (HTML, CSS, HTML+CSS, or finally HTML+CSS+JS).

But if my contrived example above doesn't mirror your actual use case, you could surely use JavaScript to cover the gap right?

Let me know if I've misunderstood the intent of your question.

Body:
A have CSS-code:

 .hide, .hide + label ~ div {
    display: none;
}

.hide:checked + label + div {
    display: block;
}

It allows me to manipulate div next to label next to checked input.

It works fine, but is there a way, that I can manipulate div with checked/unchecked that is far away from input?

My div has class "dropdown-menu" and it is not related to input in any way and like 50 lines of code after the input.

Can I connect checked value with my "dropdown-menu" div in any way with CSS?

Body:
CSS is limited in terms of how one selected element is able to help select and affect other elements in the DOM. You've highlighted two of the very cool combinators available to use already: the adjacent sibling combinator (+) and the general sibling combinator (~). You're no doubt familiar with the descendant combinator (_) <- that's a space. Finally, there's the child combinator (>).

Of these, the only two that I can imagine would be even potentially helpful are the general sibling combinator (~) and the descendant combinator(_). The other two describe relationships that assume very specific proximity relationships (+, >).

You can do what (I think) you're describing with the general sibling selector (at least you can if your markup structure has the dropdown menu div as a general sibling of the label element above it). I don't think it's likely to be in real life, but (assuming it is) here's a contrived example.

.me-too {
  padding: 8px;
  background-color: #fafafa;
  margin-top: 16px;
  margin-bottom: 16px;
}

.hider+label+div {
  display: none;
}

.hider:checked+label+div {
  display: block;
}

.hider+label~.dropdown-menu {
  display: none;
}

.hider:checked+label~.dropdown-menu {
  display: block;
}

.dropdown-menu {
  margin-top: 16px;
}

<header>
  <input id="my-checkbox" class="hider" name="my-checkbox" type="checkbox">
  <label for="my-checkbox">Check me!</label>
  <div>I can be hidden and revealed</div>

  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit et ipsum aperiam dolor animi necessitatibus inventore tempora reiciendis magni a delectus quidem veritatis fuga, praesentium illo beatae voluptates magnam nulla.</div>

  <div class="me-too dropdown-menu">
    <h2>DROPDOWN MENU</h2>
    <p>I too can be hidden and revealed!</p>

    <a href="#0">Link 1</a>
    <a href="#0">Link 2</a>
    <a href="#0">Link 3</a>
    <a href="#0">Link 3</a>

  </div>

</header>

Personally, I really appreciate that you're trying to accomplish this using CSS. I think it's always better to use the simplest tool that can get the job done (HTML, CSS, HTML+CSS, or finally HTML+CSS+JS).

But if my contrived example above doesn't mirror your actual use case, you could surely use JavaScript to cover the gap right?

Let me know if I've misunderstood the intent of your question.


来源: stackexchange

问:
Simulring with Voicemails
I've got a basic twilio setup using studio for a simple IVR (like less than 20 minute setup kind of simple).

One thing I'm doing is using simulring to hit multiple parties and whoever answers. The issue I'm having is that if there is a voicemail to be hit, it appears to be ok with that and then plays the endpoints custom voicemail.

That's not really good with our setup.

Do you guys know how I can trigger the calls to multiple phones, detect a real person and then transfer the call, otherwise trigger a voicemail?

I can't imagine this is unique.

答:
Twilio developer evangelist here.

There are two options you can use here, either call screening/human detection, in which you ask the person answering the phone to, for example, dial 1. A voicemail won't do this and you can leave a message or hang up, a human will dial the number and you can then take them on to the rest of the call. Or there is answering machine detection (AMD). When making an outbound call with AMD, once detected Twilio will make the webhook callback with a parameter that describes whether the call was answered by a human or a machine.

I recommend reading this article on both options, which should help you to understand what will work best for your use-case.

ContentLicense: CC BY-SA 4.0

Title: Simulring with Voicemails


问:
how do i subset many variable in R?
i want to ask how do i subset many data from 5k variable.

i have a 500k data frame, the data was groceries data (super market). i want to subset all the reciept ID, but the ID is too many (about 24,5 k). i want ro find the total price of each reciept. How do i subset those ID without manual typing?

the data i use :
this is my data looks like
i want to subset all of the InvoiceID and count each price. then i want to convert it to data frame.

i already try to use "for" function, but it keeps looping. i also use dplyr package in R

the code i use :

test = data %>%
  group_by(InvoiceNo)%>%
  dplyr::summarise(n= n())

bon = test$InvoiceNo

result = for (i in bon){
  data = subset(data, subset = InvoiceNo == i)
  print(sum(data$Price_Total))
}

test =  data.frame("test" = bon,
                   "wiw" = result)

```

i want to make a plot out of the total of each reciept.
how should i subset it? or what package should i use ?
thankyouu

答:
You’re on the right track with group_by(InvoiceNo) %>% summarize(). Since you want to sum up price within each InvoiceNo, you would just put that within the call to summarize():

```<code>test = data %>%
  group_by(InvoiceNo)%>%
  summarise(Price_Total = sum(Price_Total))
</code>```

Title: how do i subset many variable in R?

Body:
i want to ask how do i subset many data from 5k variable.

i have a 500k data frame, the data was groceries data (super market). i want to subset all the reciept ID, but the ID is too many (about 24,5 k). i want ro find the total price of each reciept. How do i subset those ID without manual typing?

the data i use :
this is my data looks like
i want to subset all of the InvoiceID and count each price. then i want to convert it to data frame.

i already try to use "for" function, but it keeps looping. i also use dplyr package in R

the code i use :

test = data %>%
  group_by(InvoiceNo)%>%
  dplyr::summarise(n= n())

bon = test$InvoiceNo

result = for (i in bon){
  data = subset(data, subset = InvoiceNo == i)
  print(sum(data$Price_Total))
}

test =  data.frame("test" = bon,
                   "wiw" = result)

i want to make a plot out of the total of each reciept.
how should i subset it? or what package should i use ?
thankyouu

Body:
You’re on the right track with group_by(InvoiceNo) %>% summarize(). Since you want to sum up price within each InvoiceNo, you would just put that within the call to summarize():

test = data %>%
  group_by(InvoiceNo)%>%
  summarise(Price_Total = sum(Price_Total))


问:
Weird df.sort_values result - randomly leaves multiple rows empty but missing values are misplaced a row down in the wrong columns
I've run into a very weird problem when using pandas to sort my data frame using df.sort_values on my date-time column.

In some sense the code works, it does sort the rows by date, however, in doing so it cuts some of the rows in half leaving one half of the row where it should be but leaving the other half of the row empty. The other half is put in the next row down and put in the wrong columns.

It's easier to understand from the screenshots.

Pre-Sorted Data

Post-Sorted Data

It's difficult to see from the Post-Sorted date picture but not all rows are treated this way(only one isn't in the pic, second from the bottom). Some rows turn out just fine and others don't, it seems very random.

The problem code is shown below.

```<code>df = pd.read_csv('Pre-Sort.csv', low_memory=False, skiprows=0, lineterminator='\n')

df = df.sort_values(by="created")

df.to_csv('Post-Sort.csv')

</code>```

I've tried using inplace=True and ignore_index=True as well but both returned the same results.

I'm worried this is a problem with the data as I've used df.sort_values before with virtually the same data and it worked fine.

Originally, with the data that worked, I realized that for some reason two months' worth of data roughly 15% of total data vanished. The culprit was when I merged two data frames together both containing all months with df.append. For some reason, df.append would consistently skip these two months so, in the end, I merged them through the mac terminal which kept the missing months.

This is as far as I know the only major difference between the two times I tried the code. It could be a red herring though. I had to redo many of the operations from scratch, so I might have done something differently than before, so it could be that.

Also, this changes the file size from 192MB to 210.3MB which probably shouldn't happen with a sort.

I just need to sort the data so I can resample it into daily variables, so if anyone knows a way to resample without needing to sort that would work for me just as well.

答:
I think you're having problems with indexes (both in merging and sorting).

You can try the code above:

```<code>df = pd.read_csv('Pre-Sort.csv', low_memory=False, skiprows=0, lineterminator='\n')

# no assignments here, that was the reason of the NoneType happening
df.sort_values(by='created', inplace=True, ignore_index=True)

df.to_csv('Post-Sort.csv')

</code>```

Body:
I've run into a very weird problem when using pandas to sort my data frame using df.sort_values on my date-time column.

In some sense the code works, it does sort the rows by date, however, in doing so it cuts some of the rows in half leaving one half of the row where it should be but leaving the other half of the row empty. The other half is put in the next row down and put in the wrong columns.

It's easier to understand from the screenshots.

Pre-Sorted Data

Post-Sorted Data

It's difficult to see from the Post-Sorted date picture but not all rows are treated this way(only one isn't in the pic, second from the bottom). Some rows turn out just fine and others don't, it seems very random.

The problem code is shown below.

df = pd.read_csv('Pre-Sort.csv', low_memory=False, skiprows=0, lineterminator='\n')

df = df.sort_values(by="created")

df.to_csv('Post-Sort.csv')

I've tried using inplace=True and ignore_index=True as well but both returned the same results.

I'm worried this is a problem with the data as I've used df.sort_values before with virtually the same data and it worked fine.

Originally, with the data that worked, I realized that for some reason two months' worth of data roughly 15% of total data vanished. The culprit was when I merged two data frames together both containing all months with df.append. For some reason, df.append would consistently skip these two months so, in the end, I merged them through the mac terminal which kept the missing months.

This is as far as I know the only major difference between the two times I tried the code. It could be a red herring though. I had to redo many of the operations from scratch, so I might have done something differently than before, so it could be that.

Also, this changes the file size from 192MB to 210.3MB which probably shouldn't happen with a sort.

I just need to sort the data so I can resample it into daily variables, so if anyone knows a way to resample without needing to sort that would work for me just as well.

Body:
I think you're having problems with indexes (both in merging and sorting).

You can try the code above:

df = pd.read_csv('Pre-Sort.csv', low_memory=False, skiprows=0, lineterminator='\n')

# no assignments here, that was the reason of the NoneType happening
df.sort_values(by='created', inplace=True, ignore_index=True)

df.to_csv('Post-Sort.csv')


问:
adding labels to barchart,coreplot
Hi M getting  problem with adding labels..M adding labels statically by passing array inside a loop and setting positions of x &y-axis..m passing color images array and label array..even here M getting upside down labels and color images..wat the problem might be..down is the code:</p>

```<code>for( int i=0;i< [PieChartColorDescriptionArray count]; i++)
    {
        UIButton* blueButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [blueButton setFrame:CGRectMake(165+80,65+(40*i),10,20)];
        [blueButton setTitle:@"" forState:UIControlStateNormal];
        [blueButton setAutoresizingMask:UIViewAutoresizingFlexibleWidth ];
        [blueButton setBackgroundImage:[UIImage imageNamed:[PieChartButtonImagesArray objectAtIndex:i]] forState:UIControlStateNormal];
        [blueButton setAutoresizingMask:AUTORESIZEMASK];
        [blueButton setUserInteractionEnabled:FALSE];
        [self.view addSubview:blueButton];
        [blueButton retain];
        UILabel* loLabel1=[[UILabel alloc]initWithFrame:CGRectMake(178+80,50+(40*i),50,50)];
        [loLabel1 setBackgroundColor:[UIColor clearColor]];
        [loLabel1 setTag:101];
        [loLabel1 setTextColor:[UIColor blackColor]];
        [loLabel1 setTextAlignment:UITextAlignmentCenter];
        [loLabel1 setAdjustsFontSizeToFitWidth:NO];
        [loLabel1 setNumberOfLines:1];
        [loLabel1 setFont:[UIFont systemFontOfSize:11]];
        [loLabel1 setText:[PieChartColorDescriptionArray objectAtIndex:i]];
       //loLabel1.transform=CGAffineTransformMakeRotation(-360.0);
        [loLabel1 setAutoresizingMask:AUTORESIZEMASK];
        [self.view addSubview:loLabel1];

        [loLabel1 retain];

    }
</code>```

答: Is self.view the Core Plot hosting view? If so, don't add any subviews to it. Instead, create a hierarchy of views with some sort of container view at the top. Add the hosting view and your labels and buttons as subviews of the container view.

ContentLicense: CC BY-SA 3.0

Title: adding labels to barchart,coreplot

Body:
Hi M getting  problem with adding labels..M adding labels statically by passing array inside a loop and setting positions of x &y-axis..m passing color images array and label array..even here M getting upside down labels and color images..wat the problem might be..down is the code:

for( int i=0;i< [PieChartColorDescriptionArray count]; i++)
    {
        UIButton* blueButton=[UIButton buttonWithType:UIButtonTypeCustom];
        [blueButton setFrame:CGRectMake(165+80,65+(40*i),10,20)];
        [blueButton setTitle:@"" forState:UIControlStateNormal];
        [blueButton setAutoresizingMask:UIViewAutoresizingFlexibleWidth ];
        [blueButton setBackgroundImage:[UIImage imageNamed:[PieChartButtonImagesArray objectAtIndex:i]] forState:UIControlStateNormal];
        [blueButton setAutoresizingMask:AUTORESIZEMASK];
        [blueButton setUserInteractionEnabled:FALSE];
        [self.view addSubview:blueButton];
        [blueButton retain];
        UILabel* loLabel1=[[UILabel alloc]initWithFrame:CGRectMake(178+80,50+(40*i),50,50)];
        [loLabel1 setBackgroundColor:[UIColor clearColor]];
        [loLabel1 setTag:101];
        [loLabel1 setTextColor:[UIColor blackColor]];
        [loLabel1 setTextAlignment:UITextAlignmentCenter];
        [loLabel1 setAdjustsFontSizeToFitWidth:NO];
        [loLabel1 setNumberOfLines:1];
        [loLabel1 setFont:[UIFont systemFontOfSize:11]];
        [loLabel1 setText:[PieChartColorDescriptionArray objectAtIndex:i]];
       //loLabel1.transform=CGAffineTransformMakeRotation(-360.0);
        [loLabel1 setAutoresizingMask:AUTORESIZEMASK];
        [self.view addSubview:loLabel1];

        [loLabel1 retain];

    }


问:
XPath for element with child X with no leading text, and no child Y
With this:

```<code><p>Some variable length text <abbr>abc</abbr> and more text.</p>
<p><abbr>abc</abbr>Some variable length text.</p>
<p><abbr>abc</abbr>Some variable length text. <a href="somelink">blah</a></p>
</code>```

I'm trying to build an Xpath that will find p elements that:

Have a child  with value of "abc", but that child has no intervening text between the parent and the child.

Does not have a child .

#1 means the first line should not match, because it has text between the parent
 and the child .
#2 means the third line should not match, because although there is a child  and no leading text, it also has a child .

Thus, only the second line,

```<code><p><abbr>abc</abbr>Some variable length text.</p>
</code>```

should match: no leading text, and no child .

I've played with an XPath testbed for an hour, and done quite a bit of searching, but haven't figured out how to handle both of those requirements, but especially #1.

答:
Try this XPath-1.0 expression:

```<code>//p[node()[1]!=text()[1] and abbr='abc' and not(a)]
</code>```

It checks if the first child node is a text() node. Further checks are that it has a child "abbr" with the content 'abc' and no children named "a".

Body:
With this:

Some variable length text abc and more text.

abcSome variable length text.

abcSome variable length text. blah

I'm trying to build an Xpath that will find p elements that:

Have a child  with value of "abc", but that child has no intervening text between the parent and the child.

Does not have a child .

#1 means the first line should not match, because it has text between the parent
 and the child .
#2 means the third line should not match, because although there is a child  and no leading text, it also has a child .

Thus, only the second line,

abcSome variable length text.

should match: no leading text, and no child .

I've played with an XPath testbed for an hour, and done quite a bit of searching, but haven't figured out how to handle both of those requirements, but especially #1.

Body:
Try this XPath-1.0 expression:

//p[node()[1]!=text()[1] and abbr='abc' and not(a)]

It checks if the first child node is a text() node. Further checks are that it has a child "abbr" with the content 'abc' and no children named "a".


问:
How do I scan each consecutively entered data point into subsequent nodes in a linear linked list?
I'm doing this as a part of a beginner C programming course, and I am trying to debug using print statements. The assignment is as follows:

Here is my code:

```<code>/* A program that takes in user input providing name, symbol, and atomic weight of first 10 elements from a table,  then prints that data out.
   By John
   January 17 2022
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct element
{
    char * name;
    char * symbol;
    float * weight;
} element;

typedef struct list
{
    element data;
    struct list* next;
} list;

list * create_list(char * name, char * symbol, float * weight_ptr)
{
    list * head = malloc(sizeof(list));
    head -> data.name = name;
    head -> data.symbol = symbol;
    head -> data.weight = weight_ptr;
    head -> next = NULL;
    return head;
}

list * add_to_front(char * name, char * symbol, float * weight_ptr, list * head)
{
    list * h;
    h = create_list(name, symbol, weight_ptr);
    printf("\nold head name = %s\n\nnew head name = %s\n\n",
             head -> data.name, h -> data.name);
    h -> next = head;
    return h;
}

list * info_to_list(char * name, char * symbol, float * weight_ptr)
{
    /* char * name;
    char * symbol;
    float weight; */
    list * head;

    for (int counter = 0; counter < 10; counter++)
    {
        printf("Enter the name:");
        scanf("%s", name);
        printf("\n");
        printf("Enter the symbol:");
        scanf("%s", symbol);
        printf("\n");
        printf("Enter the weight:");
        scanf("%f", weight_ptr);
        if(counter == 0)
        {
            head = create_list(name, symbol, weight_ptr);
        }
        else
        {
            printf("inside info to list function, name in prior head is: %s",
                    head -> data.name);
            head = add_to_front(name, symbol, weight_ptr, head);
            printf("\ninside info to list function: name in new first head: %s\n",
                     head -> data.name);
        }
    }
    return head;
}

void print_list(list * h)
{
    while(h != NULL)
    {
        printf("\n\nName: %s\n", h -> data.name);
        printf("Symbol: %s\n", h -> data.symbol);
        printf("Weight: %.3f\n\n", *(h -> data.weight));
        h = h -> next;
    }
}

int main(void)
{
    list * head;
    //float weight = 0.0;

    int name_size = 15; //no element name in first 10 reaches even 14 characters
    int symbol_size = 3; // symbol size up to  2 letters plus 1 for sentinel
    //int float_size = 30;

    char * name = (char *)malloc(name_size * sizeof(char));
    char * symbol = (char *)malloc(symbol_size * sizeof(char));
    //float * weight_ptr = (float *) malloc(float_size * sizeof(float));
    float * weight_ptr = (float *) malloc(sizeof(float));

    head = info_to_list(name, symbol, weight_ptr);
    print_list(head);

    free(head);
    free(name);
    free(symbol);
    free(weight_ptr);

    return 0;
}
</code>```

however when I compile and run this code, whenever I enter an element name, for example, Hydrogen, the printed statements say that the element name in the old "head" is hydrogen, and in the new "head" in hydrogen. How can I ensure that each consecutive element name I enter is scanned into each consecutive node in the linked list?

In the add_to_front function, my understanding is that I am passing the old head as an argument, and creating a new head, and inserting the newly input info from the console to the new head, hence I should have the old element info in the old head, and the new one in the new head, however that is not the case.

Thank you!

答:
The commentators guided me to the right answer(s). Basically I needed to allocate pointees to the pointers that are head ->data.name, head ->data.symbol, and head ->data.weight, other than having them point to the buffers, which was my original mistake. I did that as follows:</p>
```<code> list * create_list(char * name, char * symbol, float * weight_ptr)
{
    list * head = malloc(sizeof(list));

    head -> data.name = strdup(name);
    head -> data.symbol = strdup(symbol);
    float local_weight = *weight_ptr;
    head -> data.weight = &local_weight;
    head -> next = NULL;
    return head;
}
</code>```

Body:
I'm doing this as a part of a beginner C programming course, and I am trying to debug using print statements. The assignment is as follows:

Here is my code:

/* A program that takes in user input providing name, symbol, and atomic weight of first 10 elements from a table,  then prints that data out.
   By John
   January 17 2022
*/

#include <stdio.h>
#include <stdlib.h>

typedef struct element
{
    char * name;
    char * symbol;
    float * weight;
} element;

typedef struct list
{
    element data;
    struct list* next;
} list;

list * create_list(char * name, char * symbol, float * weight_ptr)
{
    list * head = malloc(sizeof(list));
    head -> data.name = name;
    head -> data.symbol = symbol;
    head -> data.weight = weight_ptr;
    head -> next = NULL;
    return head;
}

list * add_to_front(char * name, char * symbol, float * weight_ptr, list * head)
{
    list * h;
    h = create_list(name, symbol, weight_ptr);
    printf("\nold head name = %s\n\nnew head name = %s\n\n",
             head -> data.name, h -> data.name);
    h -> next = head;
    return h;
}

list * info_to_list(char * name, char * symbol, float * weight_ptr)
{
    /* char * name;
    char * symbol;
    float weight; */
    list * head;

    for (int counter = 0; counter < 10; counter++)
    {
        printf("Enter the name:");
        scanf("%s", name);
        printf("\n");
        printf("Enter the symbol:");
        scanf("%s", symbol);
        printf("\n");
        printf("Enter the weight:");
        scanf("%f", weight_ptr);
        if(counter == 0)
        {
            head = create_list(name, symbol, weight_ptr);
        }
        else
        {
            printf("inside info to list function, name in prior head is: %s",
                    head -> data.name);
            head = add_to_front(name, symbol, weight_ptr, head);
            printf("\ninside info to list function: name in new first head: %s\n",
                     head -> data.name);
        }
    }
    return head;
}

void print_list(list * h)
{
    while(h != NULL)
    {
        printf("\n\nName: %s\n", h -> data.name);
        printf("Symbol: %s\n", h -> data.symbol);
        printf("Weight: %.3f\n\n", *(h -> data.weight));
        h = h -> next;
    }
}

int main(void)
{
    list * head;
    //float weight = 0.0;

    int name_size = 15; //no element name in first 10 reaches even 14 characters
    int symbol_size = 3; // symbol size up to  2 letters plus 1 for sentinel
    //int float_size = 30;

    char * name = (char *)malloc(name_size * sizeof(char));
    char * symbol = (char *)malloc(symbol_size * sizeof(char));
    //float * weight_ptr = (float *) malloc(float_size * sizeof(float));
    float * weight_ptr = (float *) malloc(sizeof(float));

    head = info_to_list(name, symbol, weight_ptr);
    print_list(head);

    free(head);
    free(name);
    free(symbol);
    free(weight_ptr);

    return 0;
}

however when I compile and run this code, whenever I enter an element name, for example, Hydrogen, the printed statements say that the element name in the old "head" is hydrogen, and in the new "head" in hydrogen. How can I ensure that each consecutive element name I enter is scanned into each consecutive node in the linked list?

In the add_to_front function, my understanding is that I am passing the old head as an argument, and creating a new head, and inserting the newly input info from the console to the new head, hence I should have the old element info in the old head, and the new one in the new head, however that is not the case.

Thank you!

Body:
The commentators guided me to the right answer(s). Basically I needed to allocate pointees to the pointers that are head ->data.name, head ->data.symbol, and head ->data.weight, other than having them point to the buffers, which was my original mistake. I did that as follows:

 list * create_list(char * name, char * symbol, float * weight_ptr)
{
    list * head = malloc(sizeof(list));

    head -> data.name = strdup(name);
    head -> data.symbol = strdup(symbol);
    float local_weight = *weight_ptr;
    head -> data.weight = &local_weight;
    head -> next = NULL;
    return head;
}


问:
requestIdleCallback vs promise
I've just found out about window.requestIdleCallback and I am wondering on the difference with just a plain promise.

As far as I know JS is already good at queuing promises, so I do not see any benefit unless requestIdleCallback uses a different queue with lower priority. In that case I would assume it is great because I would like having a way to make clear which code has lower priority than rendering.

答:
window.requestIdleCallback simply runs the function during the browser idle periods to avoid impacting animations and input responses etc.

Promises are just a way of using asynchronous code. That code may be run while the browser is not idle (if the promise is not pending), and could possibly impact latency critical events.

Therefore, promises may or may not run during the browser idle period, but the requestIdleCallback will always run in the idle period (assuming the timeout isn't exceeded).

Please note, these 2 concepts are not interchangeable. Yes, you can run asynchronous "promise" code within the requestIdleCallback, but the callback should not be used to replace the functionality of a promise. That is, you shouldn't replace the use of promises with the callback, but use them together if appropriate.

Here's some info about window.requestIdleCallback:

https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback

And Promises here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Title: requestIdleCallback vs promise


问:
Not getting the decrypted OpenVPN Username from the Registry the same way that works for getting the decrypted Password
I have a Powershell script that I am successfully using to get the decrypted OpenVPN Password stored in Registry.

This is the script that successfully fetches the stored OpenVPN Password from registry that too as decrypted string:

```<code>Add-Type -AssemblyName System.Core
Add-Type -AssemblyName System.Security
$keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs"
$items = $keys | ForEach-Object {Get-ItemProperty $_.PsPath}

foreach ($item in $items)
{
  $encryptedbytes=$item.'auth-data'
  $entropy=$item.'entropy'
  $entropy=$entropy[0..(($entropy.Length)-2)]

  $decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
    $encryptedBytes,
    $entropy,
    [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

  Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes))
}
</code>```

But if I do some modification to this for fetching the decrypted username from the same OpenVPN Registry section and using the correct key username like below, it doesn't fetch the decrypted Username:

```<code>Add-Type -AssemblyName System.Core
Add-Type -AssemblyName System.Security
$keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs"
$items = $keys | ForEach-Object {Get-ItemProperty $_.PsPath}

foreach ($item in $items)
{
  $entropy=$item.'entropy'
  $username=$item.'username'
  $encryptedbytes=$item.'auth-data'
  $entropy=$entropy[0..(($entropy.Length)-2)]
  $username=$username[0..(($username.Length)-2)]

  $decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
    $encryptedBytes,
    $username,
    [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

  Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes))
}
</code>```

Can anyone help out in knowing what am I doing wrong here and fix this ?

答: Currently the username is stored unencrypted. Just decode it as Unicode. This may change in future versions. For encrypted data, the call to Unprotect() would take $entropy as the second argument, not $username.</p>

Body:
I have a Powershell script that I am successfully using to get the decrypted OpenVPN Password stored in Registry.

This is the script that successfully fetches the stored OpenVPN Password from registry that too as decrypted string:

Add-Type -AssemblyName System.Core
Add-Type -AssemblyName System.Security
$keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs"
$items = $keys | ForEach-Object {Get-ItemProperty $_.PsPath}

foreach ($item in $items)
{
  $encryptedbytes=$item.'auth-data'
  $entropy=$item.'entropy'
  $entropy=$entropy[0..(($entropy.Length)-2)]

  $decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
    $encryptedBytes,
    $entropy,
    [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

  Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes))
}

But if I do some modification to this for fetching the decrypted username from the same OpenVPN Registry section and using the correct key username like below, it doesn't fetch the decrypted Username:

Add-Type -AssemblyName System.Core
Add-Type -AssemblyName System.Security
$keys = Get-ChildItem "HKCU:\Software\OpenVPN-GUI\configs"
$items = $keys | ForEach-Object {Get-ItemProperty $_.PsPath}

foreach ($item in $items)
{
  $entropy=$item.'entropy'
  $username=$item.'username'
  $encryptedbytes=$item.'auth-data'
  $entropy=$entropy[0..(($entropy.Length)-2)]
  $username=$username[0..(($username.Length)-2)]

  $decryptedbytes = [System.Security.Cryptography.ProtectedData]::Unprotect(
    $encryptedBytes,
    $username,
    [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

  Write-Host ([System.Text.Encoding]::Unicode.GetString($decryptedbytes))
}

Can anyone help out in knowing what am I doing wrong here and fix this ?


问:
tree visualization with libgraphviz / dot
does anyone have some experience with libgraphviz using the standard c library?

For my current project i would like to write a simple tool which visualize one of my abstract syntax tree in a jpg image or maybe even on a small X11 window. Graphviz itself provides
seven, different libraries i could use and link to my application:

cdt

cgraph

gvc

pack

pathplan

xdot

Unfortanetly, i have no idea which library is necessary for my task. I also don't need to translate my tree representation to the dot language and would like write it directly to an image. (Of course, it Would be also great using an API that abstracts the transformation to the dot language).

Thanks for each advice :)

答:
If you chart isn't too big and if you are ok with a bargain basement hack, you could try Google Charts.

http://code.google.com/apis/chart/image/docs/gallery/graphviz.html

You build a URL and Google builds an image.


问:
Liquibase Java, changesets don't apply
I'm currently building a project for my internship, and I'm stuck since two days trying to use Liquibase in java. Everything seems right : the changelog file is found, correct URI, username and password; but when I run it, my changesets are not processed.

I use this class to manage liquibase actions from my program, such as rollback, update, updateSQL and futureRollbackSQL, given a changelog and eventually a destination file. If the source or destination is from a remote server, I use some SSH interactions (scp to, scp from) with JSch and temporary files (but it's not the topic).

This is the java code I have for now, given db, user, passwd, realAction are set previously, changelogpath and dest are some data storage class.

Connection c = null;
Database database = null;
PrintWriter pw = null;
File file = null;
liquibase.Liquibase liquibase = null;
contexts = db+"."+user;
try {
    pw = new PrintWriter(new FileWriter(file));
    // Get connection
    c = SQLManager.getInstance().getConnection(db, user, passwd);
    // Get liquibase connection
    database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c));
    liquibase = new liquibase.Liquibase(new DatabaseChangeLog(fsource), new FileSystemResourceAccessor(),
            database);
    // Run liquibase action
    switch (realAction) {
        case Constants.LIQUIBASE_ACTION_FUTUREROLLBACKSQL:
            liquibase.futureRollbackSQL(pw);
            break;
        case Constants.LIQUIBASE_ACTION_UPDATESQL:
            liquibase.update(contexts, pw);
            break;
        case Constants.LIQUIBASE_ACTION_UPDATE:
            liquibase.update(contexts);
            if (!c.getAutoCommit())
                c.commit();
            break;
        default:
            throw new OdewipElementRuntimeException(this, "Action not implemented");
    }
    pw.close();
    database.close();
    c.close();
} catch (IOException | SQLException | LiquibaseException e) {
    throw new Exception(e.getMessage());
} finally {
    if (c != null) {
        try {
            c.close();
        } catch (SQLException e) {
            // nothing to do
            throw new RuntimeException(e.getClass() + ": " + e.getMessage());
        }
    }
}
```

<p>And here is my changelog:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:ora="http://www.liquibase.org/xml/ns/dbchangelog-ext"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd    http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <changeSet id="mychangeset" author="testy">
        <preConditions onSqlOutput="TEST" onFail="MARK_RAN">
            <not>
                <tableExists tableName="abcd"/>
            </not>
        </preConditions>
        <createTable tableName="abcd">
            <column name="id" type="number">
                <constraints primaryKey="true"/>
            </column>
        </createTable>
    </changeSet>

</databaseChangeLog>
</code>```

Liquibase seems to do something, except parsing my changeset. When I launch my actions, sql generated files only contains the creation of the two tables of liquibase (databasechangelog and databasechangeloglock) and that's all. The update action won't modify anything at all (not even creating the two previously mentioned tables). I'm (100%) sure that the table abcd does not exist in the database before execution.

So I think I need some help at this point, to figure out what isn't working. I tried to look at some examples from the liquibase forum, but nothing helped.
I'm currently using Maven's liquibase 3.4.0:

```<code><dependency>
    <groupId>org.liquibase</groupId>
    <artifactId>liquibase-core</artifactId>
    <version>3.4.0</version>
</dependency>
</code>```

Is there another dependency to include I missed?
One small other question is how do I include a special oracle database driver(ojdbc6.jar)?

Thank you for your answers.

EDIT 06/08/2015:
I got the logs in debug mode (deliberately changed the schema name):

```<code>DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Create Database Lock Table
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: CREATE TABLE MYSCHEMA.DATABASECHANGELOGLOCK (ID NUMBER(10) NOT NULL, LOCKED NUMBER(1) NOT NULL, LOCKGRANTED TIMESTAMP, LOCKEDBY VARCHAR2(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID))
DEBUG 06/08/15 09:28: liquibase: Created database lock table with name: MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Initialize Database Lock Table
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: DELETE FROM MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: INSERT INTO MYSCHEMA.DATABASECHANGELOGLOCK (ID, LOCKED) VALUES (1, 0)
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: SELECT LOCKED FROM MYSCHEMA.DATABASECHANGELOGLOCK WHERE ID=1 FOR UPDATE
DEBUG 06/08/15 09:28: liquibase: Lock Database
DEBUG 06/08/15 09:28: liquibase: Executing UPDATE database command: UPDATE MYSCHEMA.DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = 'CRO09177 (xx.xx.xx.xxx)', LOCKGRANTED = to_date('2015-08-06 09:28:28', 'YYYY-MM-DD HH24:MI:SS') WHERE ID = 1 AND LOCKED = 0
INFO 06/08/15 09:28: liquibase: Successfully acquired change log lock
DEBUG 06/08/15 09:28: liquibase: Create Database Change Log Table
INFO 06/08/15 09:28: liquibase: Creating database history table with name: MYSCHEMA.DATABASECHANGELOG
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: CREATE TABLE MYSCHEMA.DATABASECHANGELOG (ID VARCHAR2(255) NOT NULL, AUTHOR VARCHAR2(255) NOT NULL, FILENAME VARCHAR2(255) NOT NULL, DATEEXECUTED TIMESTAMP NOT NULL, ORDEREXECUTED NUMBER(10) NOT NULL, EXECTYPE VARCHAR2(10) NOT NULL, MD5SUM VARCHAR2(35), DESCRIPTION VARCHAR2(255), COMMENTS VARCHAR2(255), TAG VARCHAR2(255), LIQUIBASE VARCHAR2(20), CONTEXTS VARCHAR2(255), LABELS VARCHAR2(255))
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOG
INFO 06/08/15 09:28: liquibase: Reading from MYSCHEMA.DATABASECHANGELOG
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: SELECT FILENAME,AUTHOR,ID,MD5SUM,DATEEXECUTED,ORDEREXECUTED,EXECTYPE,DESCRIPTION,COMMENTS,TAG,LIQUIBASE,LABELS,CONTEXTS FROM MYSCHEMA.DATABASECHANGELOG ORDER BY DATEEXECUTED ASC, ORDEREXECUTED ASC
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Release Database Lock
DEBUG 06/08/15 09:28: liquibase: Executing UPDATE database command: UPDATE MYSCHEMA.DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1
INFO 06/08/15 09:28: liquibase: Successfully released change log lock
</code>```

答:
I'm sharing the solution I found to fix changes not being applied when running liquibase update. Please note, I am not using Java, I managing my changelog as a .sql file. I am using the Snowflake JDBC driver. The thing that fixed it for me was explicitly defining the defaultCatalogName and defaultSchemaName properties in the liquibase.properties file. Simply providing these parameters in the JDBC url was insufficient. My liquibase.properties file looks like so:

```<code>changeLogFile: sql/changelog.sql
url:  jdbc:snowflake://<url>?db=<database name>&schema=PUBLIC&role=SYSADMIN&warehouse=COMPUTE_WH
driver: net.snowflake.client.jdbc.SnowflakeDriver
username:  <username>
password:  <password>
classpath:  snowflake-jdbc-3.13.14.jar
defaultCatalogName: <database name>
defaultSchemaName: PUBLIC
liquibase.hub.mode=off
</code>```

I hope this helps someone who comes across this StackOverflow post like I did.

Title: Liquibase Java, changesets don't apply

Body:
I'm currently building a project for my internship, and I'm stuck since two days trying to use Liquibase in java. Everything seems right : the changelog file is found, correct URI, username and password; but when I run it, my changesets are not processed.

I use this class to manage liquibase actions from my program, such as rollback, update, updateSQL and futureRollbackSQL, given a changelog and eventually a destination file. If the source or destination is from a remote server, I use some SSH interactions (scp to, scp from) with JSch and temporary files (but it's not the topic).

This is the java code I have for now, given db, user, passwd, realAction are set previously, changelogpath and dest are some data storage class.

Connection c = null;
Database database = null;
PrintWriter pw = null;
File file = null;
liquibase.Liquibase liquibase = null;
contexts = db+"."+user;
try {
    pw = new PrintWriter(new FileWriter(file));
    // Get connection
    c = SQLManager.getInstance().getConnection(db, user, passwd);
    // Get liquibase connection
    database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(c));
    liquibase = new liquibase.Liquibase(new DatabaseChangeLog(fsource), new FileSystemResourceAccessor(),
            database);
    // Run liquibase action
    switch (realAction) {
        case Constants.LIQUIBASE_ACTION_FUTUREROLLBACKSQL:
            liquibase.futureRollbackSQL(pw);
            break;
        case Constants.LIQUIBASE_ACTION_UPDATESQL:
            liquibase.update(contexts, pw);
            break;
        case Constants.LIQUIBASE_ACTION_UPDATE:
            liquibase.update(contexts);
            if (!c.getAutoCommit())
                c.commit();
            break;
        default:
            throw new OdewipElementRuntimeException(this, "Action not implemented");
    }
    pw.close();
    database.close();
    c.close();
} catch (IOException | SQLException | LiquibaseException e) {
    throw new Exception(e.getMessage());
} finally {
    if (c != null) {
        try {
            c.close();
        } catch (SQLException e) {
            // nothing to do
            throw new RuntimeException(e.getClass() + ": " + e.getMessage());
        }
    }
}

And here is my changelog:

<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:ora="http://www.liquibase.org/xml/ns/dbchangelog-ext"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd    http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd">

    <changeSet id="mychangeset" author="testy">
        <preConditions onSqlOutput="TEST" onFail="MARK_RAN">
            <not>
                <tableExists tableName="abcd"/>
            </not>
        </preConditions>
        <createTable tableName="abcd">
            <column name="id" type="number">
                <constraints primaryKey="true"/>
            </column>
        </createTable>
    </changeSet>

</databaseChangeLog>

Liquibase seems to do something, except parsing my changeset. When I launch my actions, sql generated files only contains the creation of the two tables of liquibase (databasechangelog and databasechangeloglock) and that's all. The update action won't modify anything at all (not even creating the two previously mentioned tables). I'm (100%) sure that the table abcd does not exist in the database before execution.

So I think I need some help at this point, to figure out what isn't working. I tried to look at some examples from the liquibase forum, but nothing helped.
I'm currently using Maven's liquibase 3.4.0:

<dependency>
    <groupId>org.liquibase</groupId>
    <artifactId>liquibase-core</artifactId>
    <version>3.4.0</version>
</dependency>

Is there another dependency to include I missed?
One small other question is how do I include a special oracle database driver(ojdbc6.jar)?

Thank you for your answers.

EDIT 06/08/2015:
I got the logs in debug mode (deliberately changed the schema name):

DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Create Database Lock Table
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: CREATE TABLE MYSCHEMA.DATABASECHANGELOGLOCK (ID NUMBER(10) NOT NULL, LOCKED NUMBER(1) NOT NULL, LOCKGRANTED TIMESTAMP, LOCKEDBY VARCHAR2(255), CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID))
DEBUG 06/08/15 09:28: liquibase: Created database lock table with name: MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Initialize Database Lock Table
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: DELETE FROM MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: INSERT INTO MYSCHEMA.DATABASECHANGELOGLOCK (ID, LOCKED) VALUES (1, 0)
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: SELECT LOCKED FROM MYSCHEMA.DATABASECHANGELOGLOCK WHERE ID=1 FOR UPDATE
DEBUG 06/08/15 09:28: liquibase: Lock Database
DEBUG 06/08/15 09:28: liquibase: Executing UPDATE database command: UPDATE MYSCHEMA.DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = 'CRO09177 (xx.xx.xx.xxx)', LOCKGRANTED = to_date('2015-08-06 09:28:28', 'YYYY-MM-DD HH24:MI:SS') WHERE ID = 1 AND LOCKED = 0
INFO 06/08/15 09:28: liquibase: Successfully acquired change log lock
DEBUG 06/08/15 09:28: liquibase: Create Database Change Log Table
INFO 06/08/15 09:28: liquibase: Creating database history table with name: MYSCHEMA.DATABASECHANGELOG
DEBUG 06/08/15 09:28: liquibase: Executing EXECUTE database command: CREATE TABLE MYSCHEMA.DATABASECHANGELOG (ID VARCHAR2(255) NOT NULL, AUTHOR VARCHAR2(255) NOT NULL, FILENAME VARCHAR2(255) NOT NULL, DATEEXECUTED TIMESTAMP NOT NULL, ORDEREXECUTED NUMBER(10) NOT NULL, EXECTYPE VARCHAR2(10) NOT NULL, MD5SUM VARCHAR2(35), DESCRIPTION VARCHAR2(255), COMMENTS VARCHAR2(255), TAG VARCHAR2(255), LIQUIBASE VARCHAR2(20), CONTEXTS VARCHAR2(255), LABELS VARCHAR2(255))
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOG
INFO 06/08/15 09:28: liquibase: Reading from MYSCHEMA.DATABASECHANGELOG
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: SELECT FILENAME,AUTHOR,ID,MD5SUM,DATEEXECUTED,ORDEREXECUTED,EXECTYPE,DESCRIPTION,COMMENTS,TAG,LIQUIBASE,LABELS,CONTEXTS FROM MYSCHEMA.DATABASECHANGELOG ORDER BY DATEEXECUTED ASC, ORDEREXECUTED ASC
DEBUG 06/08/15 09:28: liquibase: Executing QUERY database command: select count(*) from MYSCHEMA.DATABASECHANGELOGLOCK
DEBUG 06/08/15 09:28: liquibase: Release Database Lock
DEBUG 06/08/15 09:28: liquibase: Executing UPDATE database command: UPDATE MYSCHEMA.DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1
INFO 06/08/15 09:28: liquibase: Successfully released change log lock

Body:
I'm sharing the solution I found to fix changes not being applied when running liquibase update. Please note, I am not using Java, I managing my changelog as a .sql file. I am using the Snowflake JDBC driver. The thing that fixed it for me was explicitly defining the defaultCatalogName and defaultSchemaName properties in the liquibase.properties file. Simply providing these parameters in the JDBC url was insufficient. My liquibase.properties file looks like so:

changeLogFile: sql/changelog.sql
url:  jdbc:snowflake://<url>?db=<database name>&schema=PUBLIC&role=SYSADMIN&warehouse=COMPUTE_WH
driver: net.snowflake.client.jdbc.SnowflakeDriver
username:  <username>
password:  <password>
classpath:  snowflake-jdbc-3.13.14.jar
defaultCatalogName: <database name>
defaultSchemaName: PUBLIC
liquibase.hub.mode=off

I hope this helps someone who comes across this StackOverflow post like I did.


问:
Telegraf plugins - Telegraf send data to influxdb only for one plugin
Im new here, I have an issue with one plugin,

So im using telegraf to get data from ipmi sensor, and it’s working I can see that in Grafana dashboard via InfluxDB,

so until here everything is working correctly,
I added another input plugin to my telegraf.conf : telegraf-speedtest/speedtest.conf at master · Derek-K/telegraf-speedtest · GitHub

Once im checking telegraf -test , I can see that the first plugin(ipmi sensor) is OK and second plugin (speedtest) is OK as well.

But speedtest measurements are not stored in the influxdb I check it using

```<code>root@d5c51db15460:/# influx -execute ‘show measurements’ -database ‘telegraph’
name: measurements
name

ipmi_sensor
</code>```

Here as you can see there is only the ipmi_sensor :( .
Telegraf is restarted already, and both plugins are working with -test
im not sure where is the issue, I appreciate your help guys

thank you

答: The telegraf --test option does not send data to outputs. I would suggest using the --once option if you want to ensure data is making it to outputs as well.

Body:
Im new here, I have an issue with one plugin,

So im using telegraf to get data from ipmi sensor, and it’s working I can see that in Grafana dashboard via InfluxDB,

so until here everything is working correctly,
I added another input plugin to my telegraf.conf : telegraf-speedtest/speedtest.conf at master · Derek-K/telegraf-speedtest · GitHub

Once im checking telegraf -test , I can see that the first plugin(ipmi sensor) is OK and second plugin (speedtest) is OK as well.

But speedtest measurements are not stored in the influxdb I check it using

root@d5c51db15460:/# influx -execute ‘show measurements’ -database ‘telegraph’
name: measurements
name

ipmi_sensor

Here as you can see there is only the ipmi_sensor :( .
Telegraf is restarted already, and both plugins are working with -test
im not sure where is the issue, I appreciate your help guys

thank you


问:
Undefined index error
i am trying to Post something but keep getting Undefined index error. I have encountered this problem before and using  if(isset($_POST['in_come']) solved my previous problem. But, now it does not. What can cause this problem? Everything seems correct.Html posts an input and php should have gotten it
Thanks</p>

答: This error is caused by passing an invalid index to an array, whether it be a string or integer index. Using if(isset($_POST['in_come']) should return false if it doesn't exist though, and not throw an error. If you would post your code, people could be more helpful

Title: Undefined index error


问:
How can I compare two lists that contain sets?
I am trying to compare two lists that each contain multiple sets, I am sorting the list as a whole by length and the sets in the list, but for some reason it is not working. Here is an example

[{'b', 'a'}, {'c', 'd', 'a'}, {'e', 'c', 'a'}] == [{'b', 'a'}, {'c', 'e', 'a'}, {'c', 'd', 'a'}]

This outputs
False

But I was expecting for it to return true, since both contain the same sets of elements.

答: I am pretty sure you have a typo. Shouldn't both sets have to be written exactly the same for this to work?</p>


问:
How to create fake object from a data type in Typescript for testing
I'm looking for a way to simplify making fake data for unit testing in Angular solution.
I am using interfaces like:

```<code>export interface ReferenceDataItemCommon {
  codeDescription?: string;
  code: string;
  deleted?: boolean;
}
</code>```

As data types in application. Currently using Factory.ts + Faker to create fake objects for purpose of tests:

```<code>  export const fakeReferenceDataItemCommon = Factory.Sync.makeFactory<ReferenceDataItemCommon>({
    code: Factory.each(() => Faker.lorem.word()),
    codeDescription: Factory.each(() => Faker.lorem.sentence(4)),
  });
</code>```

But I'm curious if there is a way to simplify it even more for when you just want a object for your test and speed up creating it even more.
Is it possible in Typescript to have a generic method that would return a object of that datatype?

```<code>  const fake = createFake<ReferenceDataItemCommon>();
</code>```

What my initial idea was is to do something like:

```<code>Object.keys(object).forEach(key => {
  switch(typeof object[key]) {
    case 'string':
       object[key] = Faker.lorem.word();
       break;
  }
}
return object;
</code>```

And for complex object call this method recursively. Is that possible, and if what would be a better approach to do this as I feel a bit out of my depth?

答: I was searching for something similar too but also didn't find it. So, I create this lib https://www.npmjs.com/package/class-validator-mocker, which works with classes annotated with class-validator decorators. If you can work with data classes instead of interfaces to define certain types, I think it's worth taking a look at it.</p>

Body:
I'm looking for a way to simplify making fake data for unit testing in Angular solution.
I am using interfaces like:

export interface ReferenceDataItemCommon {
  codeDescription?: string;
  code: string;
  deleted?: boolean;
}

As data types in application. Currently using Factory.ts + Faker to create fake objects for purpose of tests:

  export const fakeReferenceDataItemCommon = Factory.Sync.makeFactory<ReferenceDataItemCommon>({
    code: Factory.each(() => Faker.lorem.word()),
    codeDescription: Factory.each(() => Faker.lorem.sentence(4)),
  });

But I'm curious if there is a way to simplify it even more for when you just want a object for your test and speed up creating it even more.
Is it possible in Typescript to have a generic method that would return a object of that datatype?

  const fake = createFake<ReferenceDataItemCommon>();

What my initial idea was is to do something like:

Object.keys(object).forEach(key => {
  switch(typeof object[key]) {
    case 'string':
       object[key] = Faker.lorem.word();
       break;
  }
}
return object;

And for complex object call this method recursively. Is that possible, and if what would be a better approach to do this as I feel a bit out of my depth?


问:
How do I find a point at a given distance along a route? epoly.js is giving me extremely inaccurate and unusable results
I'm trying to find the point along a Google Maps API Directions route given a distance from the starting point. I have my code working and it gives me very accurate results most of the time. However when I make very long directions requests (for example, 1,000+ kilometers), the results are less accurate, and the longer the directions route the more inaccurate the results are. Once I reach approximately 3,000 kilometers the results are off by about 4,000 meters, which is entirely unacceptable for my application.

The function I'm using to compute the point is from epoly.js, and the code is as follows:

```<code>google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
    if (metres == 0) return this.getPath().getAt(0);
    if (metres < 0) return null;
    if (this.getPath().getLength() < 2) return null;
    var dist=0;
    var olddist=0;
    for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
        olddist = dist;
        dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
    }
    if (dist < metres) {
        return null;
    }
    var p1= this.getPath().getAt(i-2);
    var p2= this.getPath().getAt(i-1);
    var m = (metres-olddist)/(dist-olddist);
    return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
}
</code>```

This epoly.js function has this dependency function:

```<code>google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
    var EarthRadiusMeters = 6378137.0;
    var lat1 = this.lat();
    var lon1 = this.lng();
    var lat2 = newLatLng.lat();
    var lon2 = newLatLng.lng();
    var dLat = (lat2-lat1) * Math.PI / 180;
    var dLon = (lon2-lon1) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = EarthRadiusMeters * c;
    return d;
}
</code>```

What is causing the result to be so inaccurate over large distances and what can I do to make it more accurate? (I need accuracy down to approximately 1-3 meters) Does the Google Maps API have any way to do this or is epoly.js my best bet? If so, then what can I change about the above code to make it give more accurate results?

I've been searching for an answer to this for a while, but everything I can find either recommends epoly.js or shows code snippets that perform exactly the same computations as epoly.js. It seems as though Google doesn't have any built-in way to do this, however I've seen something similar done in some applications like https://routeview.org, where you can clearly see the orange man tracing along the route perfectly even when navigating thousands of kilometers at a time, so I have to believe a higher level of accuracy is possible.

Here are two screenshots illustrating a short distance request and a long distance request. Note that it's very accurate over short distances but becomes wildly inaccurate over longer distances. Also note that the marker in the second image is being viewed from far away. It may look close to the path, but it's actually about 5,000 meters away on the other side of a large hill. (The marker in the first image is viewed from very close up, and even when viewed so closely it doesn't deviate from the path any noticeable amount)

This image is for a 20km route:

This image is for a 3326km route:

Here is code that demonstrated my issue. Zoom in on the marker to see that it misses the route by a long shot.

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Example</title>
    </head>
    <body>
        <div id="map" style="width: 600px;height: 600px;"></div>

        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY_HERE&v=weekly&channel=2"></script>

        <script>
            google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
                var EarthRadiusMeters = 6378137.0;
                var lat1 = this.lat();
                var lon1 = this.lng();
                var lat2 = newLatLng.lat();
                var lon2 = newLatLng.lng();
                var dLat = (lat2-lat1) * Math.PI / 180;
                var dLon = (lon2-lon1) * Math.PI / 180;
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                var d = EarthRadiusMeters * c;
                return d;
            }

            google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {// Stolen from http://www.geocodezip.com/scripts/v3_epoly.js
                if (metres == 0) return this.getPath().getAt(0);
                if (metres < 0) return null;
                if (this.getPath().getLength() < 2) return null;
                var dist=0;
                var olddist=0;
                for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
                    olddist = dist;
                    dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
                }
                if (dist < metres) {
                    return null;
                }
                var p1= this.getPath().getAt(i-2);
                var p2= this.getPath().getAt(i-1);
                var m = (metres-olddist)/(dist-olddist);
                return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
            }
        </script>

        <script>
            const map = new google.maps.Map(document.getElementById("map"),{
                center: { lat: 37, lng: -100 },
                zoom: 4,
                clickableIcons: false
            });

            const directionsRenderer = new google.maps.DirectionsRenderer();

            directionsRenderer.setMap(map);

            const directions = new google.maps.DirectionsService();

            directions.route({
                origin: "seattle, wa",
                destination: "chicago, il",
                travelMode: "DRIVING"
            },(data) => {
                const polyline = new google.maps.Polyline({
                    path: data.routes[0].overview_path
                });

                new google.maps.Marker({
                    map: map,
                    position: polyline.GetPointAtDistance(400000)
                });
                directionsRenderer.setDirections(data);
            });
        </script>

    </body>
</html>
</code>```

(You'll need to provide your own API key)

EDIT:

I found out that the issue is on Google's end. Google is giving me a "close enough" polyline. Epoly.js is tracing that polyline perfectly, but that polyline simply doesn't line up with the route itself. This picture demonstrates the issue:

The dark blue line is Google's "close enough" polyline, and the light blue line is where the actual route is.

Just thought I'd leave this here for anybody else who's confused by this in the future.

答:
Don't use the overview_path for long paths, it won't be accurate for close zoom levels. Use the concatenated steps polylines:

```<code>var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
  var steps = legs[i].steps;
  for (j=0;j<steps.length;j++) {
    var nextSegment = steps[j].path;
    for (k=0;k<nextSegment.length;k++) {
      polyline.getPath().push(nextSegment[k]);
    }
  }
}
</code>```

live example

Your original code (using the overview_path):

<!DOCTYPE html>

        <title>Example</title>

```
</div>
</div>
</p>
<p><img src="https://i.stack.imgur.com/OBFME.png" alt="screenshot at zoom 14 of original code" /></p>
<p><strong>updated code snippet using the detailed path:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Example</title>
    </head>
    <body>
        <div id="map" style="width: 600px;height: 600px;"></div>

        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&v=weekly&channel=2"></script>

        <script>
            google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
                var EarthRadiusMeters = 6378137.0;
                var lat1 = this.lat();
                var lon1 = this.lng();
                var lat2 = newLatLng.lat();
                var lon2 = newLatLng.lng();
                var dLat = (lat2-lat1) * Math.PI / 180;
                var dLon = (lon2-lon1) * Math.PI / 180;
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                var d = EarthRadiusMeters * c;
                return d;
            }

            google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {// Stolen from http://www.geocodezip.com/scripts/v3_epoly.js
                if (metres == 0) return this.getPath().getAt(0);
                if (metres < 0) return null;
                if (this.getPath().getLength() < 2) return null;
                var dist=0;
                var olddist=0;
                for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
                    olddist = dist;
                    dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
                }
                if (dist < metres) {
                    return null;
                }
                var p1= this.getPath().getAt(i-2);
                var p2= this.getPath().getAt(i-1);
                var m = (metres-olddist)/(dist-olddist);
                return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
            }
        </script>

        <script>
            const map = new google.maps.Map(document.getElementById("map"),{
                center: { lat: 37, lng: -100 },
                zoom: 14,
                clickableIcons: false
            });

            const directionsRenderer = new google.maps.DirectionsRenderer({preserveViewport: true});

            directionsRenderer.setMap(map);

            const directions = new google.maps.DirectionsService();

            directions.route({
                origin: "seattle, wa",
                destination: "chicago, il",
                travelMode: "DRIVING"
            },(data) => {
                const polyline = new google.maps.Polyline();

                var legs = data.routes[0].legs;
                for (i=0;i<legs.length;i++) {
                  var steps = legs[i].steps;
                  for (j=0;j<steps.length;j++) {
                    var nextSegment = steps[j].path;
                    for (k=0;k<nextSegment.length;k++) {
                      polyline.getPath().push(nextSegment[k]);
                    }
                  }
                }
                var marker = new google.maps.Marker({
                    map: map,
                    position: polyline.GetPointAtDistance(400000)
                });
                map.setCenter(marker.getPosition());
                directionsRenderer.setDirections(data);
            });
        </script>

    </body>
</html></code>```

result using the more detailed path (not the overview_path):

Body:
I'm trying to find the point along a Google Maps API Directions route given a distance from the starting point. I have my code working and it gives me very accurate results most of the time. However when I make very long directions requests (for example, 1,000+ kilometers), the results are less accurate, and the longer the directions route the more inaccurate the results are. Once I reach approximately 3,000 kilometers the results are off by about 4,000 meters, which is entirely unacceptable for my application.

The function I'm using to compute the point is from epoly.js, and the code is as follows:

google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
    if (metres == 0) return this.getPath().getAt(0);
    if (metres < 0) return null;
    if (this.getPath().getLength() < 2) return null;
    var dist=0;
    var olddist=0;
    for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
        olddist = dist;
        dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
    }
    if (dist < metres) {
        return null;
    }
    var p1= this.getPath().getAt(i-2);
    var p2= this.getPath().getAt(i-1);
    var m = (metres-olddist)/(dist-olddist);
    return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
}

This epoly.js function has this dependency function:

google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
    var EarthRadiusMeters = 6378137.0;
    var lat1 = this.lat();
    var lon1 = this.lng();
    var lat2 = newLatLng.lat();
    var lon2 = newLatLng.lng();
    var dLat = (lat2-lat1) * Math.PI / 180;
    var dLon = (lon2-lon1) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = EarthRadiusMeters * c;
    return d;
}

What is causing the result to be so inaccurate over large distances and what can I do to make it more accurate? (I need accuracy down to approximately 1-3 meters) Does the Google Maps API have any way to do this or is epoly.js my best bet? If so, then what can I change about the above code to make it give more accurate results?

I've been searching for an answer to this for a while, but everything I can find either recommends epoly.js or shows code snippets that perform exactly the same computations as epoly.js. It seems as though Google doesn't have any built-in way to do this, however I've seen something similar done in some applications like https://routeview.org, where you can clearly see the orange man tracing along the route perfectly even when navigating thousands of kilometers at a time, so I have to believe a higher level of accuracy is possible.

Here are two screenshots illustrating a short distance request and a long distance request. Note that it's very accurate over short distances but becomes wildly inaccurate over longer distances. Also note that the marker in the second image is being viewed from far away. It may look close to the path, but it's actually about 5,000 meters away on the other side of a large hill. (The marker in the first image is viewed from very close up, and even when viewed so closely it doesn't deviate from the path any noticeable amount)

This image is for a 20km route:

This image is for a 3326km route:

Here is code that demonstrated my issue. Zoom in on the marker to see that it misses the route by a long shot.

<!DOCTYPE html>

        <title>Example</title>

(You'll need to provide your own API key)

EDIT:

I found out that the issue is on Google's end. Google is giving me a "close enough" polyline. Epoly.js is tracing that polyline perfectly, but that polyline simply doesn't line up with the route itself. This picture demonstrates the issue:

The dark blue line is Google's "close enough" polyline, and the light blue line is where the actual route is.

Just thought I'd leave this here for anybody else who's confused by this in the future.

Body:
Don't use the overview_path for long paths, it won't be accurate for close zoom levels. Use the concatenated steps polylines:

var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
  var steps = legs[i].steps;
  for (j=0;j<steps.length;j++) {
    var nextSegment = steps[j].path;
    for (k=0;k<nextSegment.length;k++) {
      polyline.getPath().push(nextSegment[k]);
    }
  }
}

live example

Your original code (using the overview_path):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Example</title>
    </head>
    <body>
        <div id="map" style="width: 600px;height: 600px;"></div>

        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&v=weekly&channel=2"></script>

        <script>
            google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
                var EarthRadiusMeters = 6378137.0;
                var lat1 = this.lat();
                var lon1 = this.lng();
                var lat2 = newLatLng.lat();
                var lon2 = newLatLng.lng();
                var dLat = (lat2-lat1) * Math.PI / 180;
                var dLon = (lon2-lon1) * Math.PI / 180;
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                var d = EarthRadiusMeters * c;
                return d;
            }

            google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {// Stolen from http://www.geocodezip.com/scripts/v3_epoly.js
                if (metres == 0) return this.getPath().getAt(0);
                if (metres < 0) return null;
                if (this.getPath().getLength() < 2) return null;
                var dist=0;
                var olddist=0;
                for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
                    olddist = dist;
                    dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
                }
                if (dist < metres) {
                    return null;
                }
                var p1= this.getPath().getAt(i-2);
                var p2= this.getPath().getAt(i-1);
                var m = (metres-olddist)/(dist-olddist);
                return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
            }
        </script>

        <script>
            const map = new google.maps.Map(document.getElementById("map"),{
                center: { lat: 37, lng: -100 },
                zoom: 14,
                clickableIcons: false
            });

            const directionsRenderer = new google.maps.DirectionsRenderer({preserveViewport: true});

            directionsRenderer.setMap(map);

            const directions = new google.maps.DirectionsService();

            directions.route({
                origin: "seattle, wa",
                destination: "chicago, il",
                travelMode: "DRIVING"
            },(data) => {
                const polyline = new google.maps.Polyline({
                    path: data.routes[0].overview_path
                });

                var marker = new google.maps.Marker({
                    map: map,
                    position: polyline.GetPointAtDistance(400000)
                });
                map.setCenter(marker.getPosition());
                directionsRenderer.setDirections(data);
            });
        </script>

    </body>
</html>

updated code snippet using the detailed path:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Example</title>
    </head>
    <body>
        <div id="map" style="width: 600px;height: 600px;"></div>

        <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&v=weekly&channel=2"></script>

        <script>
            google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
                var EarthRadiusMeters = 6378137.0;
                var lat1 = this.lat();
                var lon1 = this.lng();
                var lat2 = newLatLng.lat();
                var lon2 = newLatLng.lng();
                var dLat = (lat2-lat1) * Math.PI / 180;
                var dLon = (lon2-lon1) * Math.PI / 180;
                var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
                var d = EarthRadiusMeters * c;
                return d;
            }

            google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {// Stolen from http://www.geocodezip.com/scripts/v3_epoly.js
                if (metres == 0) return this.getPath().getAt(0);
                if (metres < 0) return null;
                if (this.getPath().getLength() < 2) return null;
                var dist=0;
                var olddist=0;
                for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
                    olddist = dist;
                    dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
                }
                if (dist < metres) {
                    return null;
                }
                var p1= this.getPath().getAt(i-2);
                var p2= this.getPath().getAt(i-1);
                var m = (metres-olddist)/(dist-olddist);
                return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
            }
        </script>

        <script>
            const map = new google.maps.Map(document.getElementById("map"),{
                center: { lat: 37, lng: -100 },
                zoom: 14,
                clickableIcons: false
            });

            const directionsRenderer = new google.maps.DirectionsRenderer({preserveViewport: true});

            directionsRenderer.setMap(map);

            const directions = new google.maps.DirectionsService();

            directions.route({
                origin: "seattle, wa",
                destination: "chicago, il",
                travelMode: "DRIVING"
            },(data) => {
                const polyline = new google.maps.Polyline();

                var legs = data.routes[0].legs;
                for (i=0;i<legs.length;i++) {
                  var steps = legs[i].steps;
                  for (j=0;j<steps.length;j++) {
                    var nextSegment = steps[j].path;
                    for (k=0;k<nextSegment.length;k++) {
                      polyline.getPath().push(nextSegment[k]);
                    }
                  }
                }
                var marker = new google.maps.Marker({
                    map: map,
                    position: polyline.GetPointAtDistance(400000)
                });
                map.setCenter(marker.getPosition());
                directionsRenderer.setDirections(data);
            });
        </script>

    </body>
</html>

result using the more detailed path (not the overview_path):


问:
Why does my java program report "package not found" when it's clearly there in the classpath?
My kick-off of a new java application that imports a third-party java package has stalled right out of the gate.  The compiler is reporting that the package in question does not exist.  Although I began with VS Code and Gradle, I've simplified the problem down to just the java app code, the third-party jar file, and the javac compiler command.  Can someone please help me figure out why javac is reporting "package not present" for a jar file that seems clearly to be right there in the classpath?

Here's the command line:

```<code>javac -verbose -classpath . App.java
</code>```

Here's the java version:

```<code>javac 17.0.1
</code>```

Here's the directory listing:

```<code>-rw-rw-r-- 1 kevin kevin   1059 Feb  6 12:08 App.java
-rw-rw-r-- 1 kevin kevin 212231 Feb  5 17:14 neo4j-4.4.3.jar
</code>```

Here's the App.java code:

```<code>/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package neural;

import org.neo4j.*;

public class App {
    public String getGreeting() {
        return "Hello World!";
    }
    private static void registerShutdownHook( final DatabaseManagementService managementService )
    {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running application).
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                managementService.shutdown();
            }
        } );
    }
    public static void main(String[] args) {
        System.out.println(new App().getGreeting());

        managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
        graphDb = managementService.database( DEFAULT_DATABASE_NAME );
        registerShutdownHook( managementService );

        managementService.shutdown();
    }
}
</code>```

Here's the start of the errors:

```<code>App.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class App
App.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^
</code>```

Here's confirmation it's looking in the current directory:

```<code>[search path for source files: .]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,.]
</code>```

Here's an exerpt from the jar file:

```<code>META-INF/MANIFEST.MF
META-INF/
META-INF/services/
org/
org/neo4j/
org/neo4j/graphdb/
org/neo4j/graphdb/factory/
org/neo4j/graphdb/factory/module/
org/neo4j/graphdb/factory/module/id/
org/neo4j/graphdb/factory/module/edition/
org/neo4j/graphdb/factory/module/edition/context/
org/neo4j/graphdb/facade/
org/neo4j/server/
org/neo4j/server/startup/
org/neo4j/dbms/
org/neo4j/dbms/identity/
org/neo4j/dbms/systemgraph/
org/neo4j/dbms/systemgraph/versions/
org/neo4j/dbms/procedures/
org/neo4j/dbms/api/
org/neo4j/dbms/database/
org/neo4j/dbms/database/readonly/
</code>```

I've rerun (and since renamed some files for other reasons):

```<code>javac -verbose -classpath neo4j-4.4.3.jar /home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java
</code>```

which gives

```<code>[search path for source files: neo4j-4.4.3.jar]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,neo4j-4.4.3.jar]
[loading /modules/java.base/java/lang/Object.class]
[loading /modules/java.base/java/lang/String.class]
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class lib_neo4j
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^
</code>```

答:
Java requires that every .java file (and every .class file) be located in a directory that exactly matches that class’s declared package.  Since your App class contains package neural;, you must place App.java in a neural subdirectory and you must compile it as javac -verbose -classpath . neural/App.java.

Your third-party .jar file should not be inside the neural directory.  Each .jar file must be an explicit classpath entry:

```<code>javac -verbose -classpath .:neo4j-4.4.3.jar neural/App.java
</code>```

Update:

Your problem description has changed.  It now appears that neither the compile-time classpath nor your use of package-compliant directories is the problem.

It appears that the problem is simpler:  import statements ending with * do not cross package boundaries.  Different packages have no relationship to each other whatsoever, even when one is a prefix of the other.  A subpackage is not a “child” of the superpackage in any way, despite what appearances may imply.

This statement:

```<code>import org.neo4j.*;
</code>```

only imports classes in the org.neo4j package.  It does not import classes in org.neo4j.dbms and it does not import classes in org.neo4j.dbms.api.

The latter is important, because org.neo4j.dbms.api is where DatabaseManagementService is located.  If you want to use that class, I suggest importing it explicitly:

```<code>import org.neo4j.dbms.api.DatabaseManagementService;
</code>```

import statements ending with * are considered a bad practice.  Just import whatever you need explicitly, and you won’t have this problem again.

If you ever find that, without wildcard imports, you have too many import statements, it’s a sign that you probably should break up your class into smaller pieces.

Body:
My kick-off of a new java application that imports a third-party java package has stalled right out of the gate.  The compiler is reporting that the package in question does not exist.  Although I began with VS Code and Gradle, I've simplified the problem down to just the java app code, the third-party jar file, and the javac compiler command.  Can someone please help me figure out why javac is reporting "package not present" for a jar file that seems clearly to be right there in the classpath?

Here's the command line:

javac -verbose -classpath . App.java

Here's the java version:

javac 17.0.1

Here's the directory listing:

-rw-rw-r-- 1 kevin kevin   1059 Feb  6 12:08 App.java
-rw-rw-r-- 1 kevin kevin 212231 Feb  5 17:14 neo4j-4.4.3.jar

Here's the App.java code:

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
package neural;

import org.neo4j.*;

public class App {
    public String getGreeting() {
        return "Hello World!";
    }
    private static void registerShutdownHook( final DatabaseManagementService managementService )
    {
        // Registers a shutdown hook for the Neo4j instance so that it
        // shuts down nicely when the VM exits (even if you "Ctrl-C" the
        // running application).
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                managementService.shutdown();
            }
        } );
    }
    public static void main(String[] args) {
        System.out.println(new App().getGreeting());

        managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
        graphDb = managementService.database( DEFAULT_DATABASE_NAME );
        registerShutdownHook( managementService );

        managementService.shutdown();
    }
}

Here's the start of the errors:

App.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class App
App.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^

Here's confirmation it's looking in the current directory:

[search path for source files: .]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,.]

Here's an exerpt from the jar file:

META-INF/MANIFEST.MF
META-INF/
META-INF/services/
org/
org/neo4j/
org/neo4j/graphdb/
org/neo4j/graphdb/factory/
org/neo4j/graphdb/factory/module/
org/neo4j/graphdb/factory/module/id/
org/neo4j/graphdb/factory/module/edition/
org/neo4j/graphdb/factory/module/edition/context/
org/neo4j/graphdb/facade/
org/neo4j/server/
org/neo4j/server/startup/
org/neo4j/dbms/
org/neo4j/dbms/identity/
org/neo4j/dbms/systemgraph/
org/neo4j/dbms/systemgraph/versions/
org/neo4j/dbms/procedures/
org/neo4j/dbms/api/
org/neo4j/dbms/database/
org/neo4j/dbms/database/readonly/

I've rerun (and since renamed some files for other reasons):

javac -verbose -classpath neo4j-4.4.3.jar /home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java

which gives

[search path for source files: neo4j-4.4.3.jar]
[search path for class files: /usr/lib/jvm/java-17-oracle/lib/modules,neo4j-4.4.3.jar]
[loading /modules/java.base/java/lang/Object.class]
[loading /modules/java.base/java/lang/String.class]
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:12: error: cannot find symbol
    private static void registerShutdownHook( final DatabaseManagementService managementService )
                                                    ^
  symbol:   class DatabaseManagementService
  location: class lib_neo4j
/home/kevin/Projects/echo_ws/lib_neo4j/lib_neo4j/src/main/java/lib_neo4j/lib_neo4j.java:6: error: package org.neo4j does not exist
import org.neo4j.*;
^

Body:
Java requires that every .java file (and every .class file) be located in a directory that exactly matches that class’s declared package.  Since your App class contains package neural;, you must place App.java in a neural subdirectory and you must compile it as javac -verbose -classpath . neural/App.java.

Your third-party .jar file should not be inside the neural directory.  Each .jar file must be an explicit classpath entry:

javac -verbose -classpath .:neo4j-4.4.3.jar neural/App.java

Update:

Your problem description has changed.  It now appears that neither the compile-time classpath nor your use of package-compliant directories is the problem.

It appears that the problem is simpler:  import statements ending with * do not cross package boundaries.  Different packages have no relationship to each other whatsoever, even when one is a prefix of the other.  A subpackage is not a “child” of the superpackage in any way, despite what appearances may imply.

This statement:

import org.neo4j.*;

only imports classes in the org.neo4j package.  It does not import classes in org.neo4j.dbms and it does not import classes in org.neo4j.dbms.api.

The latter is important, because org.neo4j.dbms.api is where DatabaseManagementService is located.  If you want to use that class, I suggest importing it explicitly:

import org.neo4j.dbms.api.DatabaseManagementService;

import statements ending with * are considered a bad practice.  Just import whatever you need explicitly, and you won’t have this problem again.

If you ever find that, without wildcard imports, you have too many import statements, it’s a sign that you probably should break up your class into smaller pieces.