问:
Mocha not exiting
I'm running into an issue where Mocha is not exiting.

I read that it can be because I have dangling resources, but I'm not sure where.

My code is:

import express from 'express';

let app = express();

app.get('/', (req, res) => {
    res.end('Done');
});

app.listen(3000);

export default app;
```

<p>And my test is:</p>

<pre class="lang-js prettyprint-override"><code>import { describe, it } from 'mocha';
import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
import app from '../app';

chai.use(chaiHttp);

describe('Simple test', () => {
    it('Should', async () => {
        let response = await chai.request(app).get('/');
        expect(response).to.have.status(200);
    });
});
</code>```

答:
The call to app.listen(3000) is blocking the process from exiting.

Import the app object without calling app.listen(3000) when running your tests.

app.js

```<code>import express from 'express';

let app = express();

app.get('/', (req, res) => {
    res.end('Done');
});

export default app;
</code>```

test.js

```<code>import chaiHttp from 'chai-http';
import { describe, it } from 'mocha';
import app from './app';

chai.use(chaiHttp);

describe('Simple test', () => {
  it('Should', async () => {
    let response = await chai.request(app).get('/');
    chai.expect(response).to.have.status(200);
  });
});

</code>```

In another module import app and start it listening to run your server as normal.

main.js

```<code>import app from './app'

app.listen(3000)
</code>```

Title: Mocha not exiting

Body:
I'm running into an issue where Mocha is not exiting.

I read that it can be because I have dangling resources, but I'm not sure where.

My code is:

import express from 'express';

let app = express();

app.get('/', (req, res) => {
    res.end('Done');
});

app.listen(3000);

export default app;

And my test is:

import { describe, it } from 'mocha';
import chai, { expect } from 'chai';
import chaiHttp from 'chai-http';
import app from '../app';

chai.use(chaiHttp);

describe('Simple test', () => {
    it('Should', async () => {
        let response = await chai.request(app).get('/');
        expect(response).to.have.status(200);
    });
});

Body:
The call to app.listen(3000) is blocking the process from exiting.

Import the app object without calling app.listen(3000) when running your tests.

app.js

import express from 'express';

let app = express();

app.get('/', (req, res) => {
    res.end('Done');
});

export default app;

test.js

import chaiHttp from 'chai-http';
import { describe, it } from 'mocha';
import app from './app';

chai.use(chaiHttp);

describe('Simple test', () => {
  it('Should', async () => {
    let response = await chai.request(app).get('/');
    chai.expect(response).to.have.status(200);
  });
});

In another module import app and start it listening to run your server as normal.

main.js

import app from './app'

app.listen(3000)


来源: stackexchange

问:
JAXB @XmlElements to have minOccurs = 1
So I want to have a list to be annotated with @XmlElements like the following

```<code>@XmlElements(
        {
            @XmlElement(name = "Apple", type = Apple.class),
            @XmlElement(name = "Orange", type = Orange.class),
            @XmlElement(name = "Mango", type = Mango.class)
        }
)
public List<Fruit> getEntries() {
        return fruitList;
}
</code>```

I am wondering whether there is a way to enforce the list to contain at least 1 element, because right now, the xsd looks like

```<code><xs:complexType name="fruitList">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Apple" type="tns:apple"/>
        <xs:element name="Orange" type="tns:orange"/>
        <xs:element name="Mango" type="tns:mango"/>
      </xs:choice>
    </xs:sequence>
  </xs:complexType>
</code>```

答:
Assuming that Apple, Orange, and Mango are subclasses of Fruit you may want to annotate the entries property with @XmlElementRef which corresponds to substitution groups in XML schema, rather than @XmlElements which corresponds to the concept of choice.

```<code>@XmlElementRef
public List<Fruit> getEntries() {
        return fruitList;
}
</code>```

This assumes that the Apple, Orange, and Mango classes extend the Fruit class, and are annotated with @XmlRootElement

```<code>@XmlRootElement
public class Apple extends Fruit {
   ...
}
</code>```

For More Information

http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-using-substitution.html

http://bdoughan.blogspot.com/2010/10/jaxb-and-xsd-choice-xmlelements.html

ContentLicense: CC BY-SA 3.0

Title: JAXB @XmlElements to have minOccurs = 1

Body:
So I want to have a list to be annotated with @XmlElements like the following

@XmlElements(
        {
            @XmlElement(name = "Apple", type = Apple.class),
            @XmlElement(name = "Orange", type = Orange.class),
            @XmlElement(name = "Mango", type = Mango.class)
        }
)
public List<Fruit> getEntries() {
        return fruitList;
}

I am wondering whether there is a way to enforce the list to contain at least 1 element, because right now, the xsd looks like

<xs:complexType name="fruitList">
    <xs:sequence>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Apple" type="tns:apple"/>
        <xs:element name="Orange" type="tns:orange"/>
        <xs:element name="Mango" type="tns:mango"/>
      </xs:choice>
    </xs:sequence>
  </xs:complexType>

Body:
Assuming that Apple, Orange, and Mango are subclasses of Fruit you may want to annotate the entries property with @XmlElementRef which corresponds to substitution groups in XML schema, rather than @XmlElements which corresponds to the concept of choice.

@XmlElementRef
public List<Fruit> getEntries() {
        return fruitList;
}

This assumes that the Apple, Orange, and Mango classes extend the Fruit class, and are annotated with @XmlRootElement

@XmlRootElement
public class Apple extends Fruit {
   ...
}

For More Information

http://bdoughan.blogspot.com/2010/11/jaxb-and-inheritance-using-substitution.html

http://bdoughan.blogspot.com/2010/10/jaxb-and-xsd-choice-xmlelements.html


问:
Binary output for Change Detection using Convolutional Neural Networks
Let's say I have 2 images taken at the same location but at different times. I need to build a model that detects if there is any change between these 2 images.

This is somehow similar to the foreground segmentation/background subtraction/scene change detection problems whose plenty of research works was deployed (For reference):

However, the scope of those problems is far beyond what I want to do. They extract features by CNN from original images and then concatenate extracted features to a greyscale output image by Deconvolutional techniques. For me, I just want to extract features and eventually output a binary (1 or 0) value: 1 if there is any change between 2 images, 0 if there is not. In other words, I don't want to implement the Deconvolutional part.

I have 2 problems:

The CD2014 dataset (and also other relevant datasets) have only
ground truths in greyscale images format, not my desired output
(binary 1/0 format).

Furthermore, since my problem is different from
those papers, I cannot find a suitable model to use, I tend to use
VGG-16 but there is no proof that it will work in my problem.

Can you suggest me any solutions or materials in this scope?

答:
There is this paper : https://arxiv.org/pdf/1810.09111.pdf

Its look like what you want to do !

In the paper they output a Heatmap of the changes between the two images, but you could just detect if there is activation or certain amount of activations to output your binary classification.

ContentLicense: CC BY-SA 4.0


问:
display records for first day from selcted date range and end date from selected date range.Date range could be any date
I need to show open and close stock for a user input date range.

For open stock it should take the stock in first day from selected date range and close stock it should take stock in end date from selected date range.

Let say I have data from 3rd Jan. to 30th Jan. (in database) and user has selected date range (1st Jan. to 31st Jan.) so in open stock it should display stock for 3rd Jan. and in close stock it should display stock for 30th Jan.

How can I do this in SAP HANA Studio?

答:
The following query might do what you are looking for :

```<code>SELECT
 MAX(CASE WHEN S.dateStock = DT.minDate THEN S.dateStock END) AS openDate,
 MAX(CASE WHEN S.dateStock = DT.minDate THEN S.value END) AS openStock,
 MAX(CASE WHEN S.dateStock = DT.maxDate THEN S.dateStock END) AS closeDate,
 MAX(CASE WHEN S.dateStock = DT.maxDate THEN S.value END) AS closeStock
FROM
 stock S
JOIN(
 SELECT
  min(dateStock) as minDate,
  max(dateStock) as maxDate
 FROM stock
 WHERE dateStock BETWEEN '2020-01-01' AND '2020-01-31'
) DT ON S.dateStock = DT.minDate OR S.dateStock = DT.maxDate
</code>```

SEE DEMO HERE

Body:
The following query might do what you are looking for :

SELECT
 MAX(CASE WHEN S.dateStock = DT.minDate THEN S.dateStock END) AS openDate,
 MAX(CASE WHEN S.dateStock = DT.minDate THEN S.value END) AS openStock,
 MAX(CASE WHEN S.dateStock = DT.maxDate THEN S.dateStock END) AS closeDate,
 MAX(CASE WHEN S.dateStock = DT.maxDate THEN S.value END) AS closeStock
FROM
 stock S
JOIN(
 SELECT
  min(dateStock) as minDate,
  max(dateStock) as maxDate
 FROM stock
 WHERE dateStock BETWEEN '2020-01-01' AND '2020-01-31'
) DT ON S.dateStock = DT.minDate OR S.dateStock = DT.maxDate

SEE DEMO HERE


问:
String format for currency(negative value formatted with braces)
When we convert like String.Format("{0:C}", 126.45) it returns $126.45

but if we convert like  String.Format("{0:C}", -126.45) it returns ($126.45)

Why negative conversion return braces?
What to do if we don't want this braces?

答:
Swift 5 Here is best solution if you get after formate this kind of value (-300)

```<code>extension Double {
static let twoFractionDigits: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.minimumFractionDigits = 2
    formatter.maximumFractionDigits = 2
    formatter.currencySymbol = "$"
    formatter.currencyCode = "USD"
    formatter.numberStyle = .currency
    formatter.usesGroupingSeparator = true

    return formatter
}()
var formatted: String {
    return Double.twoFractionDigits.string(for: self) ?? ""
}
</code>```

}

Body:
Swift 5 Here is best solution if you get after formate this kind of value (-300)

extension Double {
static let twoFractionDigits: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.minimumFractionDigits = 2
    formatter.maximumFractionDigits = 2
    formatter.currencySymbol = "$"
    formatter.currencyCode = "USD"
    formatter.numberStyle = .currency
    formatter.usesGroupingSeparator = true

    return formatter
}()
var formatted: String {
    return Double.twoFractionDigits.string(for: self) ?? ""
}

}


问:
Display the character after a white space
I am new to PowerBuilder, I have this dropdown list box which displays the names of employees.
Jerry Casimera Fondrada, Joy Valdez Cortez, Kyle Vincent Korver and Joe Pring. Out from those names, I would like to generate a username using the first letters of their first name together with the last name. Example JCFondera, JVCortez, KVKorver and JPring.</p>

答:
```<code>string name, namepart, username

integer i, length

name = this.text
length = len(this.text)

for i = 1 to length
    if left(name, 1) = ' ' then
        username += left(namepart, 1)
        namepart = ''
    else
        namepart += left(name, 1)
    end if
    name = right(name, len(name) - 1)
next

username += namepart
</code>```

This is in the selectionchanged event from the drop down listbox.
The string "username" is the output.

Body:
string name, namepart, username

integer i, length

name = this.text
length = len(this.text)

for i = 1 to length
    if left(name, 1) = ' ' then
        username += left(namepart, 1)
        namepart = ''
    else
        namepart += left(name, 1)
    end if
    name = right(name, len(name) - 1)
next

username += namepart

This is in the selectionchanged event from the drop down listbox.
The string "username" is the output.


问:
Splitting Character String to Extract Date and Time
I have a character string in a column of a tibble that looks like Nov 01, 2019 8:00:41 AM CDT.

I would like to create new columns of the mentioned column, Date and Time.

What is the best approaches into doing this? Lubridate?

```<code>Time <- tibble(Call = 1, Date_Time = 'Nov 01, 2019 8:00:41 AM CDT')
Time %>%
    mutate(Date_Time = mdy(`Contact Start Date/Time`))
</code>```

I tried the code above but, my new column had nothing, but "NAs" in them.

答:
We can use lubridates mdy_hms function to convert Date_Time to POSIXct format and then extract Date and Time using as.Date and format respectively.

```<code>library(dplyr)
library(lubridate)

Time %>%
  mutate(Date_Time = mdy_hms(Date_Time),
         Date = as.Date(Date_Time),
         Time = format(Date_Time, "%T"))

#   Call Date_Time           Date       Time
#  <dbl> <dttm>              <date>     <chr>
#1     1 2019-11-01 08:00:41 2019-11-01 08:00:41
</code>```

Body:
I have a character string in a column of a tibble that looks like Nov 01, 2019 8:00:41 AM CDT.

I would like to create new columns of the mentioned column, Date and Time.

What is the best approaches into doing this? Lubridate?

Time <- tibble(Call = 1, Date_Time = 'Nov 01, 2019 8:00:41 AM CDT')
Time %>%
    mutate(Date_Time = mdy(`Contact Start Date/Time`))

I tried the code above but, my new column had nothing, but "NAs" in them.

Body:
We can use lubridates mdy_hms function to convert Date_Time to POSIXct format and then extract Date and Time using as.Date and format respectively.

library(dplyr)
library(lubridate)

Time %>%
  mutate(Date_Time = mdy_hms(Date_Time),
         Date = as.Date(Date_Time),
         Time = format(Date_Time, "%T"))

#   Call Date_Time           Date       Time
#  <dbl> <dttm>              <date>     <chr>
#1     1 2019-11-01 08:00:41 2019-11-01 08:00:41


问:
How do I solve the staircase problem on Hacker rank
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

```<code>int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}
</code>```

}

But all the test cases are failing for the following code, any input would be really helpful :)

答:
In this loop

```<code>for(j=i;j<n;j++)
{
    printf(" ");
}
</code>```

there is outputted one redundant space.

Also according to the assignment presented at the provided reference n shall be between (0, 100]. Maybe you should check in the function that outputs the pattern that the passed argument has a value in this range.

And if I am not mistaken the program should be written in C++. Something like the following

```<code>#include <bits/stdc++.h>

using namespace std;

// Complete the staircase function below.
void staircase(int n)
{
    const int MAX_VALUE = 100;

    if ( 0 < n && n <= MAX_VALUE )
    {
        for ( int i = 0; i < n; i++ )
        {
            std::cout << std::setw( n - i )
                      << std::setfill( ' ' )
                      << '#';
            std::cout << std::setw( i + 1 )
                      << std::setfill( '#' )
                      << '\n';
        }
    }
}

int main()
{
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    staircase(n);

    return 0;
}
</code>```

In C the completed program template can look like

```<code>#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

// Complete the staircase function below.
void staircase(int n)
{
    const int MAX_VALUE = 100;

    if ( 0 < n && n <= MAX_VALUE )
    {
        for ( int i = 0; i < n; i++ )
        {
            printf( "%*c", n - i, '#' );
            for ( size_t j = 0; j < i; j++ ) putchar( '#' );
            putchar( '\n' );
        }
    }

}

int main()
{
    char* n_endptr;
    char* n_str = readline();
    int n = strtol(n_str, &n_endptr, 10);

    if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }

    staircase(n);

    return 0;
}

char* readline() {
    size_t alloc_length = 1024;
    size_t data_length = 0;
    char* data = malloc(alloc_length);

    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);

        if (!line) { break; }

        data_length += strlen(cursor);

        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

        size_t new_length = alloc_length << 1;
        data = realloc(data, new_length);

        if (!data) { break; }

        alloc_length = new_length;
    }

    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';
    }

    data = realloc(data, data_length);

    return data;
}
</code>```

Perhaps instead of the test

```<code>    if ( 0 < n && n <= MAX_VALUE )
</code>```

you should use an assert.

Body:
So, I'm trying to do the staircase problem in hacker rank, I'm trying to achieve it with C

The problem : https://www.hackerrank.com/challenges/staircase/problem

int i,j,k;
for(i=0;i<n;i++)
{
    for(j=i;j<n;j++)
    {
        printf(" ");
    }
    for(k=0;k<=i;k++)
    {
        printf("#");
    }
    printf("\n");
}

}

But all the test cases are failing for the following code, any input would be really helpful :)

Body:
In this loop

for(j=i;j<n;j++)
{
    printf(" ");
}

there is outputted one redundant space.

Also according to the assignment presented at the provided reference n shall be between (0, 100]. Maybe you should check in the function that outputs the pattern that the passed argument has a value in this range.

And if I am not mistaken the program should be written in C++. Something like the following

#include <bits/stdc++.h>

using namespace std;

// Complete the staircase function below.
void staircase(int n)
{
    const int MAX_VALUE = 100;

    if ( 0 < n && n <= MAX_VALUE )
    {
        for ( int i = 0; i < n; i++ )
        {
            std::cout << std::setw( n - i )
                      << std::setfill( ' ' )
                      << '#';
            std::cout << std::setw( i + 1 )
                      << std::setfill( '#' )
                      << '\n';
        }
    }
}

int main()
{
    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    staircase(n);

    return 0;
}

In C the completed program template can look like

#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* readline();

// Complete the staircase function below.
void staircase(int n)
{
    const int MAX_VALUE = 100;

    if ( 0 < n && n <= MAX_VALUE )
    {
        for ( int i = 0; i < n; i++ )
        {
            printf( "%*c", n - i, '#' );
            for ( size_t j = 0; j < i; j++ ) putchar( '#' );
            putchar( '\n' );
        }
    }

}

int main()
{
    char* n_endptr;
    char* n_str = readline();
    int n = strtol(n_str, &n_endptr, 10);

    if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); }

    staircase(n);

    return 0;
}

char* readline() {
    size_t alloc_length = 1024;
    size_t data_length = 0;
    char* data = malloc(alloc_length);

    while (true) {
        char* cursor = data + data_length;
        char* line = fgets(cursor, alloc_length - data_length, stdin);

        if (!line) { break; }

        data_length += strlen(cursor);

        if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; }

        size_t new_length = alloc_length << 1;
        data = realloc(data, new_length);

        if (!data) { break; }

        alloc_length = new_length;
    }

    if (data[data_length - 1] == '\n') {
        data[data_length - 1] = '\0';
    }

    data = realloc(data, data_length);

    return data;
}

Perhaps instead of the test

    if ( 0 < n && n <= MAX_VALUE )

you should use an assert.


问:
Eager java class loading
I'm trying to do some benchmarking of JVMs running on various hardware and OS platforms.  I've created an algorithm to exercise the parts of the JVM I'm interested in and intend to run this algorithm many times to find a decent average.

When I run the benchmark, I find that the first run is significantly longer than subsequent runs:

```<code>132ms
86ms
77ms
89ms
72ms
</code>```

My suspicion is that classes are loaded lazily, putting a large overhead on the first run.  While this is indeed a feature that I assume is unique to each JVM, it's not one I'm interested in at this point.

Is there a standard command line option or property to eagerly load classes?  or does anyone have any other theories?

答: Once you have the classes loaded, to avoid running the interpreter use -Xcomp (on Sun implementations) to run compiled code only. It can be very slow running normal applications this way as all of the code has to be compiled rather than just a few pieces.

OwnerDisplayName: Cogsy

ContentLicense: CC BY-SA 2.5

Title: Eager java class loading

Body:
I'm trying to do some benchmarking of JVMs running on various hardware and OS platforms.  I've created an algorithm to exercise the parts of the JVM I'm interested in and intend to run this algorithm many times to find a decent average.

When I run the benchmark, I find that the first run is significantly longer than subsequent runs:

132ms
86ms
77ms
89ms
72ms

My suspicion is that classes are loaded lazily, putting a large overhead on the first run.  While this is indeed a feature that I assume is unique to each JVM, it's not one I'm interested in at this point.

Is there a standard command line option or property to eagerly load classes?  or does anyone have any other theories?

OwnerDisplayName: Tom Hawtin - tackline


问:
How to standardize address type properly
I'm trying to standardize street address by converting the abbreviations to the full word (e.g. RD - Road). I created many lines to account for different spellings and ran into an issue where one replace code overrode another one

```<code>import pandas as pd

mydata = {'Street_type': ['PL', 'pl', 'Pl', 'PLACE', 'place']}
mydata = pd.DataFrame(mydata)

mydata['Street_type'] = mydata['Street_type'].replace('PL','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('pl','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('Pl','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('PLACE','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('place','Place',regex=True)
</code>```

Instead of Place, I got Placeace. What is the best way to avoid this error? Do I write a if-else statement or any function? Thanks in advance!

答:
```<code>#Needlemanwunch
def zeros(shape):
    retval = []
    for x in range(shape[0]):
        retval.append([])
        for y in range(shape[1]):
            retval[-1].append(0)
    return retval

match_award      = 10
mismatch_penalty = -3
gap_penalty      = -4 # both for opening and extanding

def match_score(alpha, beta):
    if alpha == beta:
        return match_award
    elif alpha == '-' or beta == '-':
        return gap_penalty
    else:
        return mismatch_penalty

def finalize(align1, align2):
    align1 = align1[::-1]    #reverse sequence 1
    align2 = align2[::-1]    #reverse sequence 2

    i,j = 0,0

    #calcuate identity, score and aligned sequeces
    symbol = ''
    found = 0
    score = 0
    identity = 0
    for i in range(0,len(align1)):
        # if two AAs are the same, then output the letter
        if align1[i] == align2[i]:
            symbol = symbol + align1[i]
            identity = identity + 1
            score += match_score(align1[i], align2[i])

        # if they are not identical and none of them is gap
        elif align1[i] != align2[i] and align1[i] != '-' and align2[i] != '-':
            score += match_score(align1[i], align2[i])
            symbol += ' '
            found = 0

        #if one of them is a gap, output a space
        elif align1[i] == '-' or align2[i] == '-':
            symbol += ' '
            score += gap_penalty

    identity = float(identity) / len(align1) * 100

    print('Similarity =', "%3.3f" % identity, 'percent')
    print('Score =', score)
#     print(align1)
#     print(symbol)
#     print(align2)

def needle(seq1, seq2):
    m, n = len(seq1), len(seq2)  # length of two sequences

    # Generate DP table and traceback path pointer matrix
    score = zeros((m+1, n+1))      # the DP table

    # Calculate DP table
    for i in range(0, m + 1):
        score[i][0] = gap_penalty * i
    for j in range(0, n + 1):
        score[0][j] = gap_penalty * j
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            match = score[i - 1][j - 1] + match_score(seq1[i-1], seq2[j-1])
            delete = score[i - 1][j] + gap_penalty
            insert = score[i][j - 1] + gap_penalty
            score[i][j] = max(match, delete, insert)

    # Traceback and compute the alignment
    align1, align2 = '', ''
    i,j = m,n # start from the bottom right cell
    while i > 0 and j > 0: # end toching the top or the left edge
        score_current = score[i][j]
        score_diagonal = score[i-1][j-1]
        score_up = score[i][j-1]
        score_left = score[i-1][j]

        if score_current == score_diagonal + match_score(seq1[i-1], seq2[j-1]):
            align1 += seq1[i-1]
            align2 += seq2[j-1]
            i -= 1
            j -= 1
        elif score_current == score_left + gap_penalty:
            align1 += seq1[i-1]
            align2 += '-'
            i -= 1
        elif score_current == score_up + gap_penalty:
            align1 += '-'
            align2 += seq2[j-1]
            j -= 1

    # Finish tracing up to the top left cell
    while i > 0:
        align1 += seq1[i-1]
        align2 += '-'
        i -= 1
    while j > 0:
        align1 += '-'
        align2 += seq2[j-1]
        j -= 1

    finalize(align1, align2)

needle('kizlerlo','killerpo' )

***********************************************************************************************************************

#import textdistance as txd
import numpy
txd.overlap('kizlerlo','kilerpo' )
txd.jaro('kizlerlo','killerpo' )
txd.cosine('kizlerlo','killerpo' )
#txd.needleman_wunsch('kizlerlo','killerpo' )
txd.jaro_winkler('kizlerlo','killerpo' )
#txd.smith_waterman('Loans and Accounts','Loans Accounts' )
#txd.levenshtein.normalized_similarity('Loans and Accounts','Loans Accounts' )
from scipy.spatial import distance
a = 'kizlerlo'
b = 'kilerpoo'
#txd.gotoh('Loans and Accounts','Loans Accounts' )
print(txd.needleman_wunsch.normalized_similarity('Loans and Accounts','Loans Accounts' ))

***************************************************************************************************************************

#Euclidean
import math
import numpy as np
def euclid(str1,str2):
    dist=0.0
    x=str1
    y=str2
    set1=set()
    for a in range(0,len(x)):
        set1.add(x[a])
    for a in range(0,len(y)):
        set1.add(y[a])
    vec1=[None]*len(set1)
    vec2=[None]*len(set1)
    for counter,each_char in enumerate(set1):
        vec1[counter]=x.count(each_char)
        vec2[counter]=y.count(each_char)
    dist=1/(1+math.sqrt(sum([(a - b) ** 2 for a, b in zip(vec1, vec2)])))
    print(dist)
euclid('kizlerlo','killerpo')

***************************************************************************************************************************

from similarity.qgram import QGram
import affinegap
qgram = QGram(2)
#print(qgram.distance('kizlerlo', 'killerpo'))
affinegap.affineGapDistance('kizlerlokill' ,'erpozlerlzler')

***************************************************************************************************************************

#manhattan
def manhattan(str1,str2):
    dist=0.0
    x=str1
    y=str2
    set1=set()
    for a in range(0,len(x)):
        set1.add(x[a])
    for a in range(0,len(y)):
        set1.add(y[a])
    vec1=[None]*len(set1)
    vec2=[None]*len(set1)
    for counter,each_char in enumerate(set1):
        vec1[counter]=x.count(each_char)
        vec2[counter]=y.count(each_char)
    #dist= sum([np.abs(a - b) for a, b in zip(vec1, vec2)])
    dist=1/(1+sum([np.abs(a - b) for a, b in zip(vec1, vec2)]))
    print(dist)
manhattan('kizlerlo','killerpo')

import jellyfish
import json
from Levenshtein import distance,jaro_winkler,jaro,ratio,seqratio

def comp(a,b):
    return jellyfish.jaro_winkler(a,b)*100 + distance(a,b) + jaro(a,b)*100
ip = {"CED":"WALMART INC_10958553"}

ala = {}
for index,row in df_ala.iterrows():
    a = ip.get("CED")
    b = row['NN_UID']
    c = comp(a,b)
    ala.update({row['N_UID'] : c})

ala_max = max(ala, key=ala.get)

ala_f = {"ALACRA" : ala_max}
ces_f = {"CESIUM" : "WALMART_10958553_CESIUM"}
dun_f = {"DUNS" : "WALMART_10958053_DUNS"}
ref_f = {"REF" : "WALMART INC_10958553_REF"}
cax_f = {"CAX" : "WALMART LTD_10958553_CAX"}
final_op = {**ala_f,**ces_f,**dun_f,**ref_f,**cax_f }
final_json = json.dumps(final_op)
print(final_json)

from flask import Flask,request, jsonify

app = Flask(__name__)
@app.route('/test',methods = ['GET','POST'])
def test():
    if request.method == "GET":
        return jsonify({"response":"Get request called"})
    elif request.method == "POST":
        req_Json = request.json
        name = req_Json['name']
        return jsonify({"response": "Hi" + name})

if __name__ == '__main__':
    app.run(debug = True,port = 9090)

{
    "name": "Mike"
}

import usaddress
import pandas as pd
import statistics

#sa = dict(usaddress.parse('123 Main St. Suite  Chicago, IL' ))
adr = pd.read_excel('C:\\VINAYAK\\Address.xlsx')
adr.columns = ['Address']

strlen = []
scr = []
loop = adr['Address'].tolist()
for i in loop:
    strlen.append(len(i))
x = statistics.median(strlen)
for i in loop:
    sa = dict(usaddress.parse(i))
    sa = list(sa.values())
    a = 0
    if len(i) > x :
        a+= 5
    if 'AddressNumber' in sa :
        a+= 23
    if 'StreetName' in sa :
        #a = a + 20
        a+= 17
    if 'OccupancyType' in sa :
        a+= 6
    if 'OccupancyIdentifier' in sa :
        a+= 12
    if 'PlaceName' in sa :
        a+= 12
    if 'StateName' in sa :
        a+= 13
    if 'ZipCode' in sa :
        a+= 12
    scr.append(a)
adr['Adr_Score'] = scr
adr.head()
#(pd.DataFrame([(key) for  key in sa.items()])).transpose()
#pd.DataFrame(dict([(value, key) for key, value in sa.items()]))
#pd.DataFrame(dict([(value, key) for key, value in sa.items()]))
# df_ts = pd.DataFrame(columns = ['AddressNumber' , 'Age', 'City' , 'Country'])
# df_ts.append(sa, ignore_index=False, verify_integrity=False, sort=None)
# df_ts.head()
import pandas as pd
from zipfile import ZipFile
# core = []
# f = open('C:/Users/s.natarajakarayalar/1.txt','r')
# core.append(str(f.readlines()))
# print(core)
import os
import zipfile
import re
import nltk

import os
core = []
with zipfile.ZipFile('C:/Users/s.natarajakarayalar/TF.zip') as z:
    a = 0
    for filename in z.namelist():
        #if a < 1:
        #if not os.path.isdir(filename):
            # read the file
        with z.open(filename) as f:
                #a = 2
            x = f.readlines()
            core = core + x

with open('C:/Users/s.natarajakarayalar/fins.txt', 'w') as f:
    for item in core:
        f.write("%s\n" % item)
# for i in core:
#     if k < 5:
#         tkt = re.sub(r'.*CONTENT', '', i)
#         new_core.append(tkt)
#         k = k+1

# for item in core:
#     new_core.append(len(item.split()))
# print(sum(new_core))
# from nltk.tokenize import word_tokenize
# new_core = []
# stp = ['URL:https://','TITLE:b','META-KEYWORDS:','None','DOC ID:','CONTENT:b','URL:','TITLE:','META-CONTENT:']
# #new_core = [word for word in core if word not in stopwords]
# for i in core:
#     wk = word_tokenize(i)
#     for w in wk:
#         if w not in stp:
#             new_core.append(w)
</code>```

Body:
I'm trying to standardize street address by converting the abbreviations to the full word (e.g. RD - Road). I created many lines to account for different spellings and ran into an issue where one replace code overrode another one

import pandas as pd

mydata = {'Street_type': ['PL', 'pl', 'Pl', 'PLACE', 'place']}
mydata = pd.DataFrame(mydata)

mydata['Street_type'] = mydata['Street_type'].replace('PL','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('pl','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('Pl','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('PLACE','Place',regex=True)
mydata['Street_type'] = mydata['Street_type'].replace('place','Place',regex=True)

Instead of Place, I got Placeace. What is the best way to avoid this error? Do I write a if-else statement or any function? Thanks in advance!


问:
How to change the branching point in Git?
Suppose I have the following structure in my git repo:

```<code>          C'---D'---E'---F'    (dev)
        /
A---B---C---D---E---F       (master)
</code>```

I would like to pull C' into the master branch and change the branching point to C', i.e., I want to turn the above into

```<code>              D'---E'---F'     (dev)
             /
A---B---C---C'---D---E---F  (master)
</code>```

I believe I should use a combination of cherry-picking and rebasing, but I am confused about how to do so exactly.  Which sequence of operations should I perform?

Suggestion after comments for a clearer schema (since same-letter commits in the original were in fact unnecessary)

```<code>          G---H---I---J   (dev)
         /
A---B---C---D---E---F     (master)
</code>```

with the associated expected result :

```<code>              H---I---J    (dev)
             /
A---B---C---G---D---E---F  (master)
</code>```

答:
The short answer, for your new diagram, is you rebase off G with:

```<code>git checkout master
git rebase <commit_id_G>
</code>```

The longer answer is that you're having difficulty seeing this because you're thinking of master as the "main" branch, and thinking of dev as the "offshoot". But, of course, these branch names are just labels, and you can consider either of them as the "main" branch.

And, since master is the branch we actually want to change, we can redraw the diagram like this:

```<code>          H---I---J        (master)
         /
A---B---C---D---E---F---G  (dev)
</code>```

with the associated expected result :

```<code>              H'--I'--J'    (master)
             /
A---B---C---D---E---F---G   (dev)
</code>```

Hopefully it's easier to see here, that we simply need to rebase master off this new D instead of C.

Body:
Suppose I have the following structure in my git repo:

          C'---D'---E'---F'    (dev)
        /
A---B---C---D---E---F       (master)

I would like to pull C' into the master branch and change the branching point to C', i.e., I want to turn the above into

              D'---E'---F'     (dev)
             /
A---B---C---C'---D---E---F  (master)

I believe I should use a combination of cherry-picking and rebasing, but I am confused about how to do so exactly.  Which sequence of operations should I perform?

Suggestion after comments for a clearer schema (since same-letter commits in the original were in fact unnecessary)

          G---H---I---J   (dev)
         /
A---B---C---D---E---F     (master)

with the associated expected result :

              H---I---J    (dev)
             /
A---B---C---G---D---E---F  (master)

Body:
The short answer, for your new diagram, is you rebase off G with:

git checkout master
git rebase <commit_id_G>

The longer answer is that you're having difficulty seeing this because you're thinking of master as the "main" branch, and thinking of dev as the "offshoot". But, of course, these branch names are just labels, and you can consider either of them as the "main" branch.

And, since master is the branch we actually want to change, we can redraw the diagram like this:

          H---I---J        (master)
         /
A---B---C---D---E---F---G  (dev)

with the associated expected result :

              H'--I'--J'    (master)
             /
A---B---C---D---E---F---G   (dev)

Hopefully it's easier to see here, that we simply need to rebase master off this new D instead of C.


问:
Kubespray: How to add multiple GlusterFS disk volume devices for one node
I am playing with Kubespray and want to add GlusterFS persistent volumes. My inventory.ini looks like this:

```<code>[all]
k8s-master    ansible_host=x.x.x.x
k8s-node-1    ansible_host=y.y.y.y disk_volume_device_1=/media/125GB_HDD.img

[kube-master]
k8s-master

[etcd]
k8s-master

[kube-node]
k8s-master
k8s-node-1

[k8s-cluster:children]
kube-node
kube-master

[gfs-cluster]
k8s-node-1

[network-storage:children]
gfs-cluster
</code>```

But I would like to add more devices than just disk_volume_device_1. I tried disk_volume_device_2=/media/20GB_HDD.img but it did not work.

答:
Kubespray is for deploying a cluster.

If you want to change the capacity of deployed Persistent Volumes, you can edit (kubectl edit pv <name_of_pv>) the PersistenVolume.spec and change the capacity.storage value.

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: glusterfs
spec:
  capacity:
      storage: "150Gi"
  accessModes:
    - ReadWriteMany
  glusterfs:
    endpoints: glusterfs
    path: gluster
    readOnly: false
  persistentVolumeReclaimPolicy: Retain
</code>```

I recommend reading Resizing Persistent Volumes using Kubernetes.

Also you can read these docs Deploying a Kubespray Kubernetes Cluster with GlusterFS.

If you would be interested in using Heketi, please check this guide Increase GlusterFS volume size in Kubernetes.

Body:
I am playing with Kubespray and want to add GlusterFS persistent volumes. My inventory.ini looks like this:

[all]
k8s-master    ansible_host=x.x.x.x
k8s-node-1    ansible_host=y.y.y.y disk_volume_device_1=/media/125GB_HDD.img

[kube-master]
k8s-master

[etcd]
k8s-master

[kube-node]
k8s-master
k8s-node-1

[k8s-cluster:children]
kube-node
kube-master

[gfs-cluster]
k8s-node-1

[network-storage:children]
gfs-cluster

But I would like to add more devices than just disk_volume_device_1. I tried disk_volume_device_2=/media/20GB_HDD.img but it did not work.

Body:
Kubespray is for deploying a cluster.

If you want to change the capacity of deployed Persistent Volumes, you can edit (kubectl edit pv <name_of_pv>) the PersistenVolume.spec and change the capacity.storage value.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: glusterfs
spec:
  capacity:
      storage: "150Gi"
  accessModes:
    - ReadWriteMany
  glusterfs:
    endpoints: glusterfs
    path: gluster
    readOnly: false
  persistentVolumeReclaimPolicy: Retain

I recommend reading Resizing Persistent Volumes using Kubernetes.

Also you can read these docs Deploying a Kubespray Kubernetes Cluster with GlusterFS.

If you would be interested in using Heketi, please check this guide Increase GlusterFS volume size in Kubernetes.


问:
SparkStreaming/Scala/Twitter java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
I'm trying to get tweets with IntelliJ and SBT, I'm using Spark 2.4.4, Scala 2.11.12, jdk1.8.0_231. The connection is local, I am not using cluster.

However I get this error, and I can't fix it, I have changed the dependencies in several ways, but I don't know what I'm doing wrong ... does anyone have any ideas that can help me find the solution?

```<code>package com.sparkStreaming.twitter

import org.apache.spark
import org.apache.spark.rdd._
import org.apache.spark.rdd.RDD
import org.apache.spark.sql
import org.apache.spark.sql.{Row, SQLContext, SparkSession}
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.{StringType, StructField}
import org.apache.spark.streaming
import org.apache.spark.streaming.twitter.TwitterUtils

import org.apache.spark.storage.StorageLevel
import scala.io.Source
import scala.collection.mutable.HashMap
import java.io.File
import org.apache.log4j.Logger
import org.apache.log4j.Level
import sys.process.stringSeqToProcess

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

import org.apache.spark.streaming._
import org.apache.spark.streaming.{Seconds, StreamingContext}

object Tweets {

  def main(args: Array[String]) {

      //Configure Twitter credentials
      val consumerKey = "******"
      val consumerSecret = "******"
      val accessToken = "******"
      val accessTokenSecret = "******"

      System.setProperty("twitter4j.oauth.consumerKey", consumerKey)
      System.setProperty("twitter4j.oauth.consumerSecret", consumerSecret)
      System.setProperty("twitter4j.oauth.accessToken", accessToken)
      System.setProperty("twitter4j.oauth.accessTokenSecret", accessTokenSecret)

      val conf = new SparkConf().setAppName("Tweets")
      conf.setMaster("local[2]")

      //Window and stream parameter to process
      var timeSec = 10

      //Filter tweets
      var filterTag = Array("@realmadrid,$SAN") //@businessinsider,

      //Create streaming context
      val ssc = new StreamingContext(conf, Seconds(timeSec)) //creo el streaming context

      val tweets = TwitterUtils.createStream(ssc, None, filterTag) // creo el TwitterUtils

      val rowRDD = tweets.map(rddTweet => rddTweet.getText)
      rowRDD.print()

      ssc.start()
      ssc.awaitTermination()
  }
}
</code>```

This is the SBT

```<code>// https://mvnrepository.com/artifact/org.apache.spark/spark-core
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.4.4"

// https://mvnrepository.com/artifact/org.apache.spark/spark-sql
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.4.4"

// https://mvnrepository.com/artifact/org.apache.spark/spark-streaming
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "2.4.4" //% "provided"

// https://mvnrepository.com/artifact/org.twitter4j/twitter4j-core
libraryDependencies += "org.twitter4j" % "twitter4j-core" % "4.0.7"

// https://mvnrepository.com/artifact/org.twitter4j/twitter4j-stream
libraryDependencies += "org.twitter4j" % "twitter4j-stream" % "4.0.7"

// https://mvnrepository.com/artifact/org.apache.bahir/spark-streaming-twitter
libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter" % "2.1.0"
</code>```

This is the error:

```<code>20/02/06 17:52:38 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
20/02/06 17:52:38 WARN TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): java.lang.NoSuchMethodError:
twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

20/02/06 17:52:38 ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times; aborting job
20/02/06 17:52:38 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/02/06 17:52:38 INFO TaskSchedulerImpl: Cancelling stage 0
20/02/06 17:52:38 INFO TaskSchedulerImpl: Killing all running tasks in stage 0: Stage cancelled
20/02/06 17:52:38 INFO DAGScheduler: ResultStage 0 (start at Tweets.scala:80) failed in 0,248 s due to Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
20/02/06 17:52:38 ERROR ReceiverTracker: Receiver has been stopped. Try to restart it.
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1889)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1877)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1876)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at scala.Option.foreach(Option.scala:257)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
</code>```

答:
I got it with the dependencies:

{

```<code><dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-streaming_2.11</artifactId>
  <version>1.5.2</version>
</dependency>

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-core_2.11</artifactId>
  <version>1.5.2</version>
</dependency>

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-sql_2.11</artifactId>
  <version>2.4.4</version>
</dependency>

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-streaming-twitter_2.11</artifactId>
  <version>1.6.2</version>
</dependency>
</code>```

}

These posts helped me:

Spark Twitter Streaming exception : (org.apache.spark.Logging) classnotfound

Dependencies for Spark-Streaming and Twiter-Streaming in SBT

Body:
I'm trying to get tweets with IntelliJ and SBT, I'm using Spark 2.4.4, Scala 2.11.12, jdk1.8.0_231. The connection is local, I am not using cluster.

However I get this error, and I can't fix it, I have changed the dependencies in several ways, but I don't know what I'm doing wrong ... does anyone have any ideas that can help me find the solution?

package com.sparkStreaming.twitter

import org.apache.spark
import org.apache.spark.rdd._
import org.apache.spark.rdd.RDD
import org.apache.spark.sql
import org.apache.spark.sql.{Row, SQLContext, SparkSession}
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.{StringType, StructField}
import org.apache.spark.streaming
import org.apache.spark.streaming.twitter.TwitterUtils

import org.apache.spark.storage.StorageLevel
import scala.io.Source
import scala.collection.mutable.HashMap
import java.io.File
import org.apache.log4j.Logger
import org.apache.log4j.Level
import sys.process.stringSeqToProcess

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

import org.apache.spark.streaming._
import org.apache.spark.streaming.{Seconds, StreamingContext}

object Tweets {

  def main(args: Array[String]) {

      //Configure Twitter credentials
      val consumerKey = "******"
      val consumerSecret = "******"
      val accessToken = "******"
      val accessTokenSecret = "******"

      System.setProperty("twitter4j.oauth.consumerKey", consumerKey)
      System.setProperty("twitter4j.oauth.consumerSecret", consumerSecret)
      System.setProperty("twitter4j.oauth.accessToken", accessToken)
      System.setProperty("twitter4j.oauth.accessTokenSecret", accessTokenSecret)

      val conf = new SparkConf().setAppName("Tweets")
      conf.setMaster("local[2]")

      //Window and stream parameter to process
      var timeSec = 10

      //Filter tweets
      var filterTag = Array("@realmadrid,$SAN") //@businessinsider,

      //Create streaming context
      val ssc = new StreamingContext(conf, Seconds(timeSec)) //creo el streaming context

      val tweets = TwitterUtils.createStream(ssc, None, filterTag) // creo el TwitterUtils

      val rowRDD = tweets.map(rddTweet => rddTweet.getText)
      rowRDD.print()

      ssc.start()
      ssc.awaitTermination()
  }
}

This is the SBT

// https://mvnrepository.com/artifact/org.apache.spark/spark-core
libraryDependencies += "org.apache.spark" %% "spark-core" % "2.4.4"

// https://mvnrepository.com/artifact/org.apache.spark/spark-sql
libraryDependencies += "org.apache.spark" %% "spark-sql" % "2.4.4"

// https://mvnrepository.com/artifact/org.apache.spark/spark-streaming
libraryDependencies += "org.apache.spark" %% "spark-streaming" % "2.4.4" //% "provided"

// https://mvnrepository.com/artifact/org.twitter4j/twitter4j-core
libraryDependencies += "org.twitter4j" % "twitter4j-core" % "4.0.7"

// https://mvnrepository.com/artifact/org.twitter4j/twitter4j-stream
libraryDependencies += "org.twitter4j" % "twitter4j-stream" % "4.0.7"

// https://mvnrepository.com/artifact/org.apache.bahir/spark-streaming-twitter
libraryDependencies += "org.apache.bahir" %% "spark-streaming-twitter" % "2.1.0"

This is the error:

20/02/06 17:52:38 ERROR Executor: Exception in task 0.0 in stage 0.0 (TID 0)
java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
20/02/06 17:52:38 WARN TaskSetManager: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): java.lang.NoSuchMethodError:
twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

20/02/06 17:52:38 ERROR TaskSetManager: Task 0 in stage 0.0 failed 1 times; aborting job
20/02/06 17:52:38 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool
20/02/06 17:52:38 INFO TaskSchedulerImpl: Cancelling stage 0
20/02/06 17:52:38 INFO TaskSchedulerImpl: Killing all running tasks in stage 0: Stage cancelled
20/02/06 17:52:38 INFO DAGScheduler: ResultStage 0 (start at Tweets.scala:80) failed in 0,248 s due to Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
20/02/06 17:52:38 ERROR ReceiverTracker: Receiver has been stopped. Try to restart it.
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times, most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost, executor driver): java.lang.NoSuchMethodError: twitter4j.TwitterStream.addListener(Ltwitter4j/StreamListener;)V
at org.apache.spark.streaming.twitter.TwitterReceiver.onStart(TwitterInputDStream.scala:72)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.startReceiver(ReceiverSupervisor.scala:149)
at org.apache.spark.streaming.receiver.ReceiverSupervisor.start(ReceiverSupervisor.scala:131)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:601)
at org.apache.spark.streaming.scheduler.ReceiverTracker$ReceiverTrackerEndpoint$$anonfun$9.apply(ReceiverTracker.scala:591)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.SparkContext$$anonfun$37.apply(SparkContext.scala:2212)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)

Driver stacktrace:
at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1889)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1877)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1876)
at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1876)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:926)
at scala.Option.foreach(Option.scala:257)
at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:926)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2110)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2059)
at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2048)
at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)

Body:
I got it with the dependencies:

{

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-streaming_2.11</artifactId>
  <version>1.5.2</version>
</dependency>

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-core_2.11</artifactId>
  <version>1.5.2</version>
</dependency>

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-sql_2.11</artifactId>
  <version>2.4.4</version>
</dependency>

<dependency>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-streaming-twitter_2.11</artifactId>
  <version>1.6.2</version>
</dependency>

}

These posts helped me:

Spark Twitter Streaming exception : (org.apache.spark.Logging) classnotfound

Dependencies for Spark-Streaming and Twiter-Streaming in SBT


问:
Replacing multiple words in a string sentence C#
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.

/* Excersice: use with stringbuilder
             * cat becomes littlecat
             * dog becomes littledog
             * mouse becomes littlemouse
             * words the must be replace by a
             * do not use a loop*/

```<code>
using System;
using System.Collections.Generic;
using System.Text;

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        static string Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            string dogCat = new string("Can the cat find the mouse without waking the dog.");

            static string replacethisstring(string dogCat);
            {
                hondKat = dogCat.Replace("cat", "littlecat");
                hondKat = dogCat.Replace("dog", "littldog");
                hondKat = dogCat.Replace("mouse", "littlemouse");
                hondKat = dogCat.Replace("the", "a");
                return dogCat;
            }
        }
    }
}

</code>```

Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )

Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )

答:
Your main should have a void as return type. string is not allowed but int is an option (see reference)

You cannot have ; at the end of a function declaration that has a body to it.

You have to declare a variable before you can use it ... string hondKat;

See the use of StringBuilder in the below code instead of string.

```<code>namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        public static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Can the cat find the mouse without waking the dog.");
            sb = replacethisstring(sb);

            Console.WriteLine(sb.ToString());
            Console.ReadLine(); // To Stop the Console from closing.

            static StringBuilder replacethisstring(StringBuilder dogCat)
            {
                dogCat = dogCat.Replace("cat", "littlecat");
                dogCat = dogCat.Replace("dog", "littldog");
                dogCat = dogCat.Replace("mouse", "littlemouse");
                dogCat = dogCat.Replace("the", "a");
                return dogCat;
            }

        }
    }
}
</code>```

You can place the function within the Main or outside. Normally you would find functions outside of the Main class.

```<code>    public static void Main(string[] args)
    {
    ...
    }

    public static string replacethisstring(string dogCat)
    {
    ...
    }
</code>```

Body:
Hello guys, I don't need the answer but I would look to know and find out what I'm doing wrong. As a beginner I got a very "easy" assignment in my studies. I need to create a string and inside this string I need to replace some words by other words without using the for loop as so: ( also I want to print it but I got no clue where to put Console.WriteLine and google searching for 1 hour didn't work or asking a colleage.

/* Excersice: use with stringbuilder
             * cat becomes littlecat
             * dog becomes littledog
             * mouse becomes littlemouse
             * words the must be replace by a
             * do not use a loop*/

using System;
using System.Collections.Generic;
using System.Text;

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        static string Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            string dogCat = new string("Can the cat find the mouse without waking the dog.");

            static string replacethisstring(string dogCat);
            {
                hondKat = dogCat.Replace("cat", "littlecat");
                hondKat = dogCat.Replace("dog", "littldog");
                hondKat = dogCat.Replace("mouse", "littlemouse");
                hondKat = dogCat.Replace("the", "a");
                return dogCat;
            }
        }
    }
}

Error CS5001: Program does not contain a static "Main" method suitable for an entry point ( I don't get this doesn't almost any program starts with this static Main args? )

Error CS8112: replacethisstring(string)' is a local function and must therefore always have a body. ( I just gave it a body right? I opened the { and close it } and put a replace with return. )

Body:
Your main should have a void as return type. string is not allowed but int is an option (see reference)

You cannot have ; at the end of a function declaration that has a body to it.

You have to declare a variable before you can use it ... string hondKat;

See the use of StringBuilder in the below code instead of string.

namespace Opgavens_leerpad_3_oefening
{
    class Program
    {
        public static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("Can the cat find the mouse without waking the dog.");
            sb = replacethisstring(sb);

            Console.WriteLine(sb.ToString());
            Console.ReadLine(); // To Stop the Console from closing.

            static StringBuilder replacethisstring(StringBuilder dogCat)
            {
                dogCat = dogCat.Replace("cat", "littlecat");
                dogCat = dogCat.Replace("dog", "littldog");
                dogCat = dogCat.Replace("mouse", "littlemouse");
                dogCat = dogCat.Replace("the", "a");
                return dogCat;
            }

        }
    }
}

You can place the function within the Main or outside. Normally you would find functions outside of the Main class.

    public static void Main(string[] args)
    {
    ...
    }

    public static string replacethisstring(string dogCat)
    {
    ...
    }


问:
Can I mimic multiple passed-object dummy arguments without adding dependencies?
I previously asked Can I mimic multiple passed-object dummy arguments in Fortran?

I over-simplified my problem for that question, and a better example of the code I would like to write is

```<code>module m_Parent
  type, abstract :: Parent
  contains
    procedure(f_Parent), deferred :: f
  end type

  abstract interface
    subroutine f_Parent(foo,bar)
      import Parent
      implicit none
      class(Parent), intent(in) :: foo
      class(Parent), intent(in) :: bar
    end subroutine
  end interface
end module

module m_Child
  use m_Parent

  type, extends(Parent) :: Child
  contains
    procedure, public :: f => f_Child
  end type
contains
  subroutine f_Child(foo,bar)
    implicit none
    class(Child), intent(in) :: foo
    class(Child), intent(in) :: bar
  end subroutine
end module
</code>```

with the constraint that m_Parent may not have dependencies on m_Child, to avoid circular dependencies and to allow for many Child classes without having to update m_Parent with the details of each.

As before:

the code presented here is forbidden by the Fortran standard.

the select type construct is too slow.

Can I mimic the behaviour that the above code would produce if multiple passed-object dummy arguments were allowed by the Fortran standard?

答:
The standard forbids multiple passed-object dummy arguments, along with passed-object dummy arguments which are arrays or pointers. The standard does not forbid passed-object dummy arguments which are classes containing arrays or pointers.

This can be implemented as

```<code>module m_Parent
  type, abstract :: Parent
  end type

  type, abstract :: ParentPair
  contains
    procedure(f_ParentPair), deferred :: f
  end type

  abstract interface
    subroutine f_ParentPair(foobar)
      import ParentPair
      implicit none
      class(ParentPair), intent(in) :: foobar
    end subroutine
  end interface
end module

module m_Child
  use m_Parent

  type, extends(Parent) :: Child
  contains
    procedure, public :: f => f_Child
  end type

  type, extends(ParentPair) :: ChildPair
    type(Child) :: foo
    type(Child) :: bar
  contains
    procedure, public :: f => f_ChildPair
  end type

contains

  subroutine f_ChildPair(foobar)
    implicit none
    class(ChildPair), intent(in) :: foobar
    call foobar%foo%f(foobar%bar)
  end subroutine

  subroutine f_Child(foo,bar)
    implicit none
    class(Child), intent(in) :: foo
    class(Child), intent(in) :: bar
  end subroutine
end module
</code>```

This is not the most elegant solution, and it requires the creation and maintenance of an entire ChildPair class for every implementation of Child.

According to operf, in ifort 19.1 this has a negligible overhead compared to a select type statement.

Body:
I previously asked Can I mimic multiple passed-object dummy arguments in Fortran?

I over-simplified my problem for that question, and a better example of the code I would like to write is

module m_Parent
  type, abstract :: Parent
  contains
    procedure(f_Parent), deferred :: f
  end type

  abstract interface
    subroutine f_Parent(foo,bar)
      import Parent
      implicit none
      class(Parent), intent(in) :: foo
      class(Parent), intent(in) :: bar
    end subroutine
  end interface
end module

module m_Child
  use m_Parent

  type, extends(Parent) :: Child
  contains
    procedure, public :: f => f_Child
  end type
contains
  subroutine f_Child(foo,bar)
    implicit none
    class(Child), intent(in) :: foo
    class(Child), intent(in) :: bar
  end subroutine
end module

with the constraint that m_Parent may not have dependencies on m_Child, to avoid circular dependencies and to allow for many Child classes without having to update m_Parent with the details of each.

As before:

the code presented here is forbidden by the Fortran standard.

the select type construct is too slow.

Can I mimic the behaviour that the above code would produce if multiple passed-object dummy arguments were allowed by the Fortran standard?

Body:
The standard forbids multiple passed-object dummy arguments, along with passed-object dummy arguments which are arrays or pointers. The standard does not forbid passed-object dummy arguments which are classes containing arrays or pointers.

This can be implemented as

module m_Parent
  type, abstract :: Parent
  end type

  type, abstract :: ParentPair
  contains
    procedure(f_ParentPair), deferred :: f
  end type

  abstract interface
    subroutine f_ParentPair(foobar)
      import ParentPair
      implicit none
      class(ParentPair), intent(in) :: foobar
    end subroutine
  end interface
end module

module m_Child
  use m_Parent

  type, extends(Parent) :: Child
  contains
    procedure, public :: f => f_Child
  end type

  type, extends(ParentPair) :: ChildPair
    type(Child) :: foo
    type(Child) :: bar
  contains
    procedure, public :: f => f_ChildPair
  end type

contains

  subroutine f_ChildPair(foobar)
    implicit none
    class(ChildPair), intent(in) :: foobar
    call foobar%foo%f(foobar%bar)
  end subroutine

  subroutine f_Child(foo,bar)
    implicit none
    class(Child), intent(in) :: foo
    class(Child), intent(in) :: bar
  end subroutine
end module

This is not the most elegant solution, and it requires the creation and maintenance of an entire ChildPair class for every implementation of Child.

According to operf, in ifort 19.1 this has a negligible overhead compared to a select type statement.


问:
Can't get element SELENIUM PYTHON
I need to get element from page and then print it out
But it always print out this:

```<code>[<selenium.webdriver.remote.webelement.WebElement (session="636e500d9db221d6b7b10b8d7849e1b5",
    element="4f0ccc3b-44b0-4cf2-abd4-95a70278bf77")>...
</code>```

My code:

```<code>film_player = free_filmy_url + filmPlayerPart
dr = webdriver.Chrome()
dr.get(film_player)
captcha_button = dr.find_element_by_xpath('/html/body/form/div/input[1]')
captcha_items = dr.find_elements_by_class_name('captchaMyImg')
print(captcha_items)
</code>```

答:
Through your lines of code:

```<code>captcha_items = dr.find_elements_by_class_name('captchaMyImg')
print(captcha_items)
</code>```

You are printing the elements.

Rather you must be looking to print an attribute of the elements and you can use the following solution:

```<code>print([my_elem.get_attribute("attribute") for my_elem in dr.find_elements_by_class_name('captchaMyImg')])
</code>```

Note: You need to replace the text attribute with any of the existing attributes for those elements, e.g. src, href, innerHTML, etc.

Title: Can't get element SELENIUM PYTHON

Body:
I need to get element from page and then print it out
But it always print out this:

[<selenium.webdriver.remote.webelement.WebElement (session="636e500d9db221d6b7b10b8d7849e1b5",
    element="4f0ccc3b-44b0-4cf2-abd4-95a70278bf77")>...

My code:

film_player = free_filmy_url + filmPlayerPart
dr = webdriver.Chrome()
dr.get(film_player)
captcha_button = dr.find_element_by_xpath('/html/body/form/div/input[1]')
captcha_items = dr.find_elements_by_class_name('captchaMyImg')
print(captcha_items)

Body:
Through your lines of code:

captcha_items = dr.find_elements_by_class_name('captchaMyImg')
print(captcha_items)

You are printing the elements.

Rather you must be looking to print an attribute of the elements and you can use the following solution:

print([my_elem.get_attribute("attribute") for my_elem in dr.find_elements_by_class_name('captchaMyImg')])

Note: You need to replace the text attribute with any of the existing attributes for those elements, e.g. src, href, innerHTML, etc.


问:
JavaFX: Set gap between graphic node and text in MenuItem
What is the way to set a gap between the text and graphic of a MenuItem.

JavaFX Labeled subclasses have a setGraphicTextGap(double value) method that does exactly what I'm looking for, but MenuItem class doesn't inherit from Labeled.

Sample code:

ImageView newFilterIcon = new ImageView(new Image(newFilterIconUrl));
MenuItem newFilterMenuItem = new MenuItem("New Filter", newFilterIcon);
Menu filterMenu = new Menu("Filter");
filterMenu.getItems().add(newFilterMenuItem);
```

答:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class MenuGapApp extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        ImageView imageView = new ImageView("https://image.shutterstock.com/image-vector/home-flat-icon-you-can-260nw-451922449.jpg");
        MenuItem menuItem = new MenuItem("New filter", imageView);
        Menu menu = new Menu("Filter", null, menuItem);
        MenuBar menuBar = new MenuBar(menu);
        Scene scene = new Scene(menuBar);
        scene.getStylesheets().add(getClass().getResource("/menu-gap.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }
}
```

<p>menu-gap.css</p>

<pre class="lang-css prettyprint-override"><code>.menu-item > .graphic-container {
    -fx-padding: 0em 10em 0em 0em;
}
</code>```

Body:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;

public class MenuGapApp extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        ImageView imageView = new ImageView("https://image.shutterstock.com/image-vector/home-flat-icon-you-can-260nw-451922449.jpg");
        MenuItem menuItem = new MenuItem("New filter", imageView);
        Menu menu = new Menu("Filter", null, menuItem);
        MenuBar menuBar = new MenuBar(menu);
        Scene scene = new Scene(menuBar);
        scene.getStylesheets().add(getClass().getResource("/menu-gap.css").toExternalForm());
        stage.setScene(scene);
        stage.show();
    }
}

menu-gap.css

.menu-item > .graphic-container {
    -fx-padding: 0em 10em 0em 0em;
}


问:
The position and size of the buttons are changing?
I set my background image to "scale to fiil".But buttons are not growing. Their location is changing.Does anyone have advice on this?

答: Your Button size will not increase with respect to the background image. you have to apply constraints with the multiplier of Superview. like Equal Width and Equal Height</p>


问:
Swift - Hide navigation bar shows in animation
I am attempting to hide the navigation bar in the app. I did this with the following:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationController?.setNavigationBarHidden(true, animated: animated)

}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.setNavigationBarHidden(false, animated: animated)

}
</code>```

With this, I am hiding the bar at the top but when the transition is happening I can still see the bar for a split second then it disappears. Image below shows what I mean:

Screenshot showing top nav bar when transitioning from view to another

答: In your method parameters change ‘animated: animated’ to ‘animated: false’</p>

Body:
I am attempting to hide the navigation bar in the app. I did this with the following:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationController?.setNavigationBarHidden(true, animated: animated)

}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.setNavigationBarHidden(false, animated: animated)

}

With this, I am hiding the bar at the top but when the transition is happening I can still see the bar for a split second then it disappears. Image below shows what I mean:

Screenshot showing top nav bar when transitioning from view to another


问:
Difference between "Red Hat Satellite" and "Red Hat Network Satellite"?
Im trying to understand what differences are there between this products. Can someone explain me main differences and what is each one's functionality?</p>

答:
Red hat network sometimes want to say the internal network of red hat for customers

Red Hat Network (abbreviated to RHN) is a family of systems-management services operated by Red Hat. RHN makes updates, patches, and bug fixes of packages included within Red Hat Linux and Red Hat Enterprise Linux available to subscribers. Other available features include the deployment of custom content to, and the provisioning, configuration, reporting, monitoring of client systems.

Users of these operating systems can then invoke the up2date or yum program to download and install updates from RHN. The updates portion of RHN is akin to other types of automatic system maintenance tools such as Microsoft Update for Microsoft Windows operating systems. The system requires a subscription to allow access to updates. (Red Hat's yum and Advanced Packaging Tool repositories provide free access to updates for Fedora systems.)

On June 18, 2008 Red Hat CEO Jim Whitehurst announced plans for the RHN Satellite software to be open-sourced following the Fedora/RHEL model.[1] Subsequently, project Spacewalk was launched.


问:
Exit from if block in Javascript
I want to exit from the below if block in Javascript. if I return, then it does not check for the next if condition. How do I do that?</p>

```<code>if ($('#id1').length > 0) {

    if(yester_energy == "NaN" || yester_energy == 0){
      //break from #id1
    }

    else{
      //something
    }
    $("#abc").html(somthing)
}

if ($('#id2').length > 0) {

        if(yester_energy == "NaN" || yester_energy == 0){
          //break from #id2
        }

        else{
          //something
        }
}
</code>```

答:
Even later to the party... Typically in such situations, I use a combination of if and do...while as follows...

```<code>if ( condition ) do {

  // processing

  if ( exit_condition ) break;

  // more processing...

} while ( false );
</code>```

Thus, when the break is encountered, it applies to the do...while loop, and processing continues after the while, effectively breaking out of the outer if statement...

Title: Exit from if block in Javascript

Body:
I want to exit from the below if block in Javascript. if I return, then it does not check for the next if condition. How do I do that?

if ($('#id1').length > 0) {

    if(yester_energy == "NaN" || yester_energy == 0){
      //break from #id1
    }

    else{
      //something
    }
    $("#abc").html(somthing)
}

if ($('#id2').length > 0) {

        if(yester_energy == "NaN" || yester_energy == 0){
          //break from #id2
        }

        else{
          //something
        }
}

Body:
Even later to the party... Typically in such situations, I use a combination of if and do...while as follows...

if ( condition ) do {

  // processing

  if ( exit_condition ) break;

  // more processing...

} while ( false );

Thus, when the break is encountered, it applies to the do...while loop, and processing continues after the while, effectively breaking out of the outer if statement...


问:
Randomnly swapping items betwen lists
I'm working on a small script that involves changing one codon (a item on my list) to another, randonmly.
I start by converting the DNA sequence into a list of codons, and then I want the script to choose a random one  and change it to another from a list of codons. The problem is that it only works for the first time that said item apears on the list. (Even if it chooses the last item, it replaces it for the first items that appears on the list that  is equal to that item).
I don't know if I have been clear enough, I'm still learning.
Here's the code: </p>

```<code>import random

codones = ['ATA', 'ATC', 'ATT', 'ATG',
           'ACA', 'ACC', 'ACG', 'ACT',
           'AAC', 'AAT', 'AAA', 'AAG',
           'AGC', 'AGT', 'AGA', 'AGG',
           'CTA', 'CTC', 'CTG', 'CTT',
           'CCA', 'CCC', 'CCG', 'CCT',
           'CAC', 'CAT', 'CAA', 'CAG',
           'CGA', 'CGC', 'CGG', 'CGT',
           'GTA', 'GTC', 'GTG', 'GTT',
           'GCA', 'GCC', 'GCG', 'GCT',
           "GAC", 'GAT', 'GAA', 'GAG',
           'GGA', 'GGC', 'GGG', 'GGT',
           'TCA', 'TCC', 'TCG', 'TCT',
           'TTC', 'TTT', 'TTA', 'TTG',
           'TAC', 'TAT', 'TGC', 'TGT',
           'TGG']

dna = "atgaaaagcatgaaaagc"
DNA = dna.upper()

print(DNA)

print("El gen tiene " + str(int(len(dna)/3)) + " Aa:")

def codones_dna(seq):
    codon = []
    for i in range(0, len(seq), 3):
        codon.append(seq[i:i +3])
    return codon
lista_codones = codones_dna(DNA)
print(lista_codones)

def translate(seq):
    table = {
        'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
        'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
        'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
        'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
        'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
        'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
        'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
        'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
        'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
        'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
        'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
        'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
        'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
        'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
        'TAC':'Y', 'TAT':'Y', 'TGC':'C', 'TGT':'C',
        'TGG':'W'
    }
    protein = " "
    if len(seq) % 3 == 0:
        for i in range(0, len(seq), 3):
            codon = seq[i:i + 3]
            protein += table[codon].lower()
    return protein
protein = translate(DNA)
print(protein)

def mutation(seq):
    for i in range(0, len(seq), 3):
        dna_mut = seq[i:i]
        wt = random.choice(lista_codones)
        mutado = random.choice(codones)
        if wt != mutado:
            dna_mut += seq.replace(wt, mutado, 1)

    return dna_mut

dna_mut = mutation(DNA)
</code>```

答:
First, this line:

```<code>print("El gen tiene " + str(int(len(dna)/3)) + " Aa:")
</code>```

is terribly redundant, it does the same as:

```<code>print("El gen tiene", len(dna)/3, "Aa:")
</code>```

only in less readable way. Second, your mutation function should be like:

```<code>def mutation(seq):
    dna_as_list = [ seq[i:i+3] for i in range(0, len(seq), 3) ] # here you split seq into codons
    wt = random.choice(lista_codones)
    mutado = random.randint(0,len(dna_as_list)-1) # here you generate a random index
    dna_as_list[mutado] = wt # replace the codon at the generated index
    return ''.join(dna_as_list)
</code>```

Title: Randomnly swapping items betwen lists

Body:
I'm working on a small script that involves changing one codon (a item on my list) to another, randonmly.
I start by converting the DNA sequence into a list of codons, and then I want the script to choose a random one  and change it to another from a list of codons. The problem is that it only works for the first time that said item apears on the list. (Even if it chooses the last item, it replaces it for the first items that appears on the list that  is equal to that item).
I don't know if I have been clear enough, I'm still learning.
Here's the code:

import random

codones = ['ATA', 'ATC', 'ATT', 'ATG',
           'ACA', 'ACC', 'ACG', 'ACT',
           'AAC', 'AAT', 'AAA', 'AAG',
           'AGC', 'AGT', 'AGA', 'AGG',
           'CTA', 'CTC', 'CTG', 'CTT',
           'CCA', 'CCC', 'CCG', 'CCT',
           'CAC', 'CAT', 'CAA', 'CAG',
           'CGA', 'CGC', 'CGG', 'CGT',
           'GTA', 'GTC', 'GTG', 'GTT',
           'GCA', 'GCC', 'GCG', 'GCT',
           "GAC", 'GAT', 'GAA', 'GAG',
           'GGA', 'GGC', 'GGG', 'GGT',
           'TCA', 'TCC', 'TCG', 'TCT',
           'TTC', 'TTT', 'TTA', 'TTG',
           'TAC', 'TAT', 'TGC', 'TGT',
           'TGG']

dna = "atgaaaagcatgaaaagc"
DNA = dna.upper()

print(DNA)

print("El gen tiene " + str(int(len(dna)/3)) + " Aa:")

def codones_dna(seq):
    codon = []
    for i in range(0, len(seq), 3):
        codon.append(seq[i:i +3])
    return codon
lista_codones = codones_dna(DNA)
print(lista_codones)

def translate(seq):
    table = {
        'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
        'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
        'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
        'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
        'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
        'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
        'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q',
        'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R',
        'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V',
        'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A',
        'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E',
        'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G',
        'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S',
        'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L',
        'TAC':'Y', 'TAT':'Y', 'TGC':'C', 'TGT':'C',
        'TGG':'W'
    }
    protein = " "
    if len(seq) % 3 == 0:
        for i in range(0, len(seq), 3):
            codon = seq[i:i + 3]
            protein += table[codon].lower()
    return protein
protein = translate(DNA)
print(protein)

def mutation(seq):
    for i in range(0, len(seq), 3):
        dna_mut = seq[i:i]
        wt = random.choice(lista_codones)
        mutado = random.choice(codones)
        if wt != mutado:
            dna_mut += seq.replace(wt, mutado, 1)

    return dna_mut

dna_mut = mutation(DNA)

Body:
First, this line:

print("El gen tiene " + str(int(len(dna)/3)) + " Aa:")

is terribly redundant, it does the same as:

print("El gen tiene", len(dna)/3, "Aa:")

only in less readable way. Second, your mutation function should be like:

def mutation(seq):
    dna_as_list = [ seq[i:i+3] for i in range(0, len(seq), 3) ] # here you split seq into codons
    wt = random.choice(lista_codones)
    mutado = random.randint(0,len(dna_as_list)-1) # here you generate a random index
    dna_as_list[mutado] = wt # replace the codon at the generated index
    return ''.join(dna_as_list)


问:
Live reload Prometheus configuration in docker(-compose)
I have a new server running Prometheus in docker-compose.
I want to be able to re-load the configuration file (prometheus.yml) without have to stop and start the container.

Of course since I persist the storage of promethues in a volume the stop and start isn't really a problem but it seems like overkill, especially since prometheus itself has such a handy api to reload configs.

I see other people with similar questions (e.g. here) but I have been unable to get those solutions to work for me. Maybe I'm overlooking something there.

docker-compose.yml

```<code>version: "3"

services:

  grafana:
    restart: always
    container_name: grafana
    image: grafana/grafana:6.2.1
    ports:
      - 3000:3000
    volumes:
      - grafanadata:/var/lib/grafana

  prometheus:
    restart: always
    container_name: prometheus
    image: prom/prometheus:v2.10.0
    privileged: true
    volumes:
      - ./configuration/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheusdata:/prometheus

    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--web.enable-admin-api'
      - '--web.enable-lifecycle'
    ports:
      - 9090:9090

  node:
    restart: always
    container_name: node
    image: prom/node-exporter:v0.18.0
    ports:
      - 9100:9100

volumes:
  grafanadata:
  prometheusdata:
</code>```

Alas, my results..

When I run curl -X POST http://localhost:9090/-/reload the docker-compose logs give:

```<code>prometheus    | level=info ts=2019-06-17T15:33:02.690Z caller=main.go:730 msg="Loading configuration file" filename=/etc/prometheus/prometheus.yml
prometheus    | level=info ts=2019-06-17T15:33:02.691Z caller=main.go:758 msg="Completed loading of configuration file" filename=/etc/prometheus/prometheus.yml
</code>```

So the prometheus' end is working fine.. All good so far.

However, when I edit ./configuration/prometheus/prometheus.yml the changes don't propogate to the container.
Furthermore, when I try to edit /etc/promethus/prometheus.yml in container I see that it is read only (and as an aside, the container does not have a 'sudo' command).

Is there a docker native way to hot/live reload these config files to the container directory?

As stated, the down/start option works for now but I'm curious if there is a more elegant solution.

答:
It looks like

```<code>      - ./configuration/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
</code>```

should be reversed.

Body:
I have a new server running Prometheus in docker-compose.
I want to be able to re-load the configuration file (prometheus.yml) without have to stop and start the container.

Of course since I persist the storage of promethues in a volume the stop and start isn't really a problem but it seems like overkill, especially since prometheus itself has such a handy api to reload configs.

I see other people with similar questions (e.g. here) but I have been unable to get those solutions to work for me. Maybe I'm overlooking something there.

docker-compose.yml

version: "3"

services:

  grafana:
    restart: always
    container_name: grafana
    image: grafana/grafana:6.2.1
    ports:
      - 3000:3000
    volumes:
      - grafanadata:/var/lib/grafana

  prometheus:
    restart: always
    container_name: prometheus
    image: prom/prometheus:v2.10.0
    privileged: true
    volumes:
      - ./configuration/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml
      - prometheusdata:/prometheus

    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--web.enable-admin-api'
      - '--web.enable-lifecycle'
    ports:
      - 9090:9090

  node:
    restart: always
    container_name: node
    image: prom/node-exporter:v0.18.0
    ports:
      - 9100:9100

volumes:
  grafanadata:
  prometheusdata:

Alas, my results..

When I run curl -X POST http://localhost:9090/-/reload the docker-compose logs give:

prometheus    | level=info ts=2019-06-17T15:33:02.690Z caller=main.go:730 msg="Loading configuration file" filename=/etc/prometheus/prometheus.yml
prometheus    | level=info ts=2019-06-17T15:33:02.691Z caller=main.go:758 msg="Completed loading of configuration file" filename=/etc/prometheus/prometheus.yml

So the prometheus' end is working fine.. All good so far.

However, when I edit ./configuration/prometheus/prometheus.yml the changes don't propogate to the container.
Furthermore, when I try to edit /etc/promethus/prometheus.yml in container I see that it is read only (and as an aside, the container does not have a 'sudo' command).

Is there a docker native way to hot/live reload these config files to the container directory?

As stated, the down/start option works for now but I'm curious if there is a more elegant solution.

Body:
It looks like

      - ./configuration/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml

should be reversed.