问:
React/JSX: Iterating through an object with key/value pairs
I have an object that I'm using to keep track of which checkboxes have been checked on a UI.

It looks something like this:

```<code>      checked: { key1: false, key2: false, key3: false, key4: false, key5: false, key6: false, key7: false, key8: false, key9: false, key10: false },

</code>```

I need to be able iterate through this object and set certain values to true/false, depending on the behavior the user wants from the UI.

I have two questions:

Is there a more elegant way to instantiate this?

How would I do this using the Object.entries method?

I'd like to do something like this, but it doesn't work:

```<code>
let obj = {k1: false, k2: false, k3: false}

Object.entries(obj).forEach(([key, value]) => {
    obj.value = true;
  console.log(`${key} ${value}`);

});
</code>```

Thank you!

答:
If you need to set all the values in the object to true, you can do something like this

Object.keys(obj).forEach(key => obj[key] = true);
```

Object.keys will return all the keys in that object in an array. By looping over that array and then using obj[key] we can access each key of the object and set it to true

Body:
I have an object that I'm using to keep track of which checkboxes have been checked on a UI.

It looks something like this:

      checked: { key1: false, key2: false, key3: false, key4: false, key5: false, key6: false, key7: false, key8: false, key9: false, key10: false },

I need to be able iterate through this object and set certain values to true/false, depending on the behavior the user wants from the UI.

I have two questions:

Is there a more elegant way to instantiate this?

How would I do this using the Object.entries method?

I'd like to do something like this, but it doesn't work:

let obj = {k1: false, k2: false, k3: false}

Object.entries(obj).forEach(([key, value]) => {
    obj.value = true;
  console.log(`${key} ${value}`);

});

Thank you!

Body:
If you need to set all the values in the object to true, you can do something like this

Object.keys(obj).forEach(key => obj[key] = true);

Object.keys will return all the keys in that object in an array. By looping over that array and then using obj[key] we can access each key of the object and set it to true


来源: stackexchange

问:
Changes made to NSGraphicsContext.current
I am making changes to the current NSGraphicContext, from inside the drawRect() method of a NSView, and everything works OK. Any changes made, are persistent through the subsequent calls to drawRect() method.

However, what i want to do, is to make changes to the current context, from within another object's method. This method is indeed called, from inside DrawRect() method. But these changes, are not persistent.

Code is like this:

```<code>class SomeView:NSView {

  override func drawRect(dirtyRect: NSRect) {
    // myAObject is an instance of a Class i create, and stored inside SomeView
    // myAObject's exexcuteCode() method, makes changes to the current NSGraphicsContext
    myAObjectIntance.executeCode()

    // In subsequent calls of drawRect, as the user keeps drawing using the
    // mouse, another object, say myBObject's executeCode() method, draws,
    // lets say a rectangle.
    myBObjectIntance.executeCode()

    // Problem is, that any changes done to the current context by myAObjectIntance.executeCode()
    // seem to be lost.

    // If i change the context and draw inside the same method call, everything is OK.
    // If changes and drawing are done by different objects, changes are lost.
  }
}
</code>```

From inside both methods, myAObjectIntance.executeCode() and myBObjectIntance.executeCode(), i get  the current NSGraphicsContext using code like this:

```<code>NSGraphicsContext.current!.compositeOperation = .copy
</code>```

or

```<code>NSGraphicsContext.current!.compositeOperation = .clear
</code>```

I added a small project that changes foreground color. Change in color is not preserved, between sequential calls of drawRect().
NSGraphicsContextTest.zip

答: The problem is you're expecting your drawing and changes to be preserved between multiple calls to drawRect; that's not going to happen. Each time drawRect is called, the state of the context is reset. That's by design. So each time drawRect is called, you need to set the state of the context to be whatever you need it to be, and draw to fill the area specified by the dirtyRect parameter.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am making changes to the current NSGraphicContext, from inside the drawRect() method of a NSView, and everything works OK. Any changes made, are persistent through the subsequent calls to drawRect() method.

However, what i want to do, is to make changes to the current context, from within another object's method. This method is indeed called, from inside DrawRect() method. But these changes, are not persistent.

Code is like this:

class SomeView:NSView {

  override func drawRect(dirtyRect: NSRect) {
    // myAObject is an instance of a Class i create, and stored inside SomeView
    // myAObject's exexcuteCode() method, makes changes to the current NSGraphicsContext
    myAObjectIntance.executeCode()

    // In subsequent calls of drawRect, as the user keeps drawing using the
    // mouse, another object, say myBObject's executeCode() method, draws,
    // lets say a rectangle.
    myBObjectIntance.executeCode()

    // Problem is, that any changes done to the current context by myAObjectIntance.executeCode()
    // seem to be lost.

    // If i change the context and draw inside the same method call, everything is OK.
    // If changes and drawing are done by different objects, changes are lost.
  }
}

From inside both methods, myAObjectIntance.executeCode() and myBObjectIntance.executeCode(), i get  the current NSGraphicsContext using code like this:

NSGraphicsContext.current!.compositeOperation = .copy

or

NSGraphicsContext.current!.compositeOperation = .clear

I added a small project that changes foreground color. Change in color is not preserved, between sequential calls of drawRect().
NSGraphicsContextTest.zip


问:
For-loop exiting prematurely
I'm having an issue where a python for loop is exiting prematurely. The loop iterates over SQL database entries by location.

If location is found, it will grab the IP address of those entries and send a configuration. If the job fails, or throws an exception in my case, within the exception it will go to a function to update the status, date/time. The expected result currently is an exception.

When it comes back to the original function, it exits the loop and doesn't go to the next DB entry (which I know is there.) If I remove the function from within the exception then everything works fine.

Current results. It shows the loop working from function to function. I should see twice, or 6 lines:

Return to Function,
Back to function,
Finished,

Return to Function,
Back to function,
Finished,
```

<hr>

<p>Here's what I'm getting</p>

<pre class="lang-none prettyprint-override"><code>1. IP
2. Status
3. Location
4. Main

Selection: 3

Location: Test

Return to Function,
Back to function,
Finished,
</code>```

Code shown below:

def db_entry(Device, status):

    int = 0

    while int < 1:

        c.execute('SELECT * FROM Automation WHERE Device=?', (Device,))

        if bool(c.fetchone()) == True:
            c.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?"(time.strftime("%H:%M:%S +0000"), date.today(), status, Device))
            mydb.commit()
            int = int + 1
        else:
            c.execute("INSERT INTO Automation VALUES ('%s','NETCONF','POC', '%s', '%s', '%s')" % (Device, status, date.today(), time.strftime("%H:%M:%S +0000")))
            mydb.commit()
            int = int + 1
    else:
        print("Return to Function")

def send_single_configuration(file):

    status_1 = "Success"
    status_2 = "Fail"

    print("\n")
    view_database()
    print("\n")
    retries = 0

    print("1. IP")
    print("2. Status")
    print("3. Location")
    print("4. Main")
    print("\n")

    input_selection = input("Selection: ")
    print("\n")

    if input_selection == "3":

        location = input("Location: ")

        for row in c.execute('SELECT * FROM Automation WHERE Location=?', (location, )):
            try:
                m = manager.connect(row[0], 830, "cisco", "cisco", {'name': 'csr'})
                config_file = open(file=file).read()
                m.edit_config(config_file, target="running")
                db_entry(row[0], status_1)
                print("\n")
                print("Configuration Complete!")
                print("\n")

            except AttributeError:
                db_entry(row[0], status_2)
                print("Back to function")

        else:
            print("Finished")
```

```Traceback (most recent call last):
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 412, in <module>
    main()
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 82, in main
    snmp_configuration()
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 326, in snmp_configuration
    send_single_configuration(SNMP_file)
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 395, in send_single_configuration
    m.edit_config(config_file, target="running")
AttributeError: 'NoneType' object has no attribute 'edit_config'
```

<hr>

<p>More Testing:</p>

<p>If i remove everything but a print statement from the db_entry function which gave the expected result.</p>

<p>I'm thinking something withing this line of code or something with the module/progam interaction.</p>

```    c.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE
    Device=?",(time.strftime("%H:%M:%S +0000"), date.today(), status,
    Device))
```

答:
It was the sqlite3 module. I found an old answer from 8 years ago here, python sqlite3 for loop update.

sqllitle3 module doesn't allow for multi-threading.

I created another connection object and used it to update the DB entry

```<code>    c = mydb.cursor() # Find the location
    d = mydb.cursor() # Update the entry

            for row in c.execute('SELECT * FROM Automation WHERE Location=?', (location, )):
        try:

            device_connect(row[0])
            for capability in m.server_capabilities:
                continue

            d.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?",(time.strftime("%H:%M:%S +00"), date.today(), status_1, row[0],))
            mydb.commit()

        except AttributeError:
            d.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?",(time.strftime("%H:%M:%S +00"), date.today(), status_2, row[0],))
</code>```

Title: For-loop exiting prematurely

Body:
I'm having an issue where a python for loop is exiting prematurely. The loop iterates over SQL database entries by location.

If location is found, it will grab the IP address of those entries and send a configuration. If the job fails, or throws an exception in my case, within the exception it will go to a function to update the status, date/time. The expected result currently is an exception.

When it comes back to the original function, it exits the loop and doesn't go to the next DB entry (which I know is there.) If I remove the function from within the exception then everything works fine.

Current results. It shows the loop working from function to function. I should see twice, or 6 lines:

Return to Function,
Back to function,
Finished,

Return to Function,
Back to function,
Finished,

Here's what I'm getting

1. IP
2. Status
3. Location
4. Main

Selection: 3

Location: Test

Return to Function,
Back to function,
Finished,

Code shown below:

def db_entry(Device, status):

    int = 0

    while int < 1:

        c.execute('SELECT * FROM Automation WHERE Device=?', (Device,))

        if bool(c.fetchone()) == True:
            c.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?"(time.strftime("%H:%M:%S +0000"), date.today(), status, Device))
            mydb.commit()
            int = int + 1
        else:
            c.execute("INSERT INTO Automation VALUES ('%s','NETCONF','POC', '%s', '%s', '%s')" % (Device, status, date.today(), time.strftime("%H:%M:%S +0000")))
            mydb.commit()
            int = int + 1
    else:
        print("Return to Function")

def send_single_configuration(file):

    status_1 = "Success"
    status_2 = "Fail"

    print("\n")
    view_database()
    print("\n")
    retries = 0

    print("1. IP")
    print("2. Status")
    print("3. Location")
    print("4. Main")
    print("\n")

    input_selection = input("Selection: ")
    print("\n")

    if input_selection == "3":

        location = input("Location: ")

        for row in c.execute('SELECT * FROM Automation WHERE Location=?', (location, )):
            try:
                m = manager.connect(row[0], 830, "cisco", "cisco", {'name': 'csr'})
                config_file = open(file=file).read()
                m.edit_config(config_file, target="running")
                db_entry(row[0], status_1)
                print("\n")
                print("Configuration Complete!")
                print("\n")

            except AttributeError:
                db_entry(row[0], status_2)
                print("Back to function")

        else:
            print("Finished")

Traceback (most recent call last):
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 412, in <module>
    main()
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 82, in main
    snmp_configuration()
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 326, in snmp_configuration
    send_single_configuration(SNMP_file)
  File "C:/Users/chris.oberdalhoff/PycharmProjects/Automation/venv/SQL.py", line 395, in send_single_configuration
    m.edit_config(config_file, target="running")
AttributeError: 'NoneType' object has no attribute 'edit_config'

More Testing:

If i remove everything but a print statement from the db_entry function which gave the expected result.

I'm thinking something withing this line of code or something with the module/progam interaction.

    c.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE
    Device=?",(time.strftime("%H:%M:%S +0000"), date.today(), status,
    Device))

Body:
It was the sqlite3 module. I found an old answer from 8 years ago here, python sqlite3 for loop update.

sqllitle3 module doesn't allow for multi-threading.

I created another connection object and used it to update the DB entry

    c = mydb.cursor() # Find the location
    d = mydb.cursor() # Update the entry

            for row in c.execute('SELECT * FROM Automation WHERE Location=?', (location, )):
        try:

            device_connect(row[0])
            for capability in m.server_capabilities:
                continue

            d.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?",(time.strftime("%H:%M:%S +00"), date.today(), status_1, row[0],))
            mydb.commit()

        except AttributeError:
            d.execute("UPDATE Automation SET Time=?, DateTime=?, Status=? WHERE Device=?",(time.strftime("%H:%M:%S +00"), date.today(), status_2, row[0],))


问:
While making Plot in pandas python I am getting Error: EOL
df

```<code>import pandas as pd
df = pd.DataFrame({
    'SKU': ['BIKES','MATS', 'BLANKETS', 'CREAMS'],'Col1': [1,3,6,10],'Col2': [4,5, 6,16],'Month':[1,2,3,4],'Year':['2015','2010','2011','2012']})
</code>```

Code tried which doesnt work

```<code>    import matplotlib.pyplot as plt

#Visualisations

fig, ax = plt.subplots()
for col in ['Col1', 'Col2']:
    ax.plot(df[col], label=col)
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)
</code>```

I need tickers for months and values for years. But before I can proceed with tickers etc., I am getting error:

```<code>File "<ipython-input-14-136f7818ccc7>", line 6
    for col in ['Col1', 'Col2']:
                                ^
SyntaxError: EOL while scanning string literal
</code>```

答:
You are getting error because you have not given dates in the for loop. For which dates do you need the plot?

```<code>import matplotlib.pyplot as plt
from matplotlib import dates as mdates

# The new column to be used as x axis
df['Date'] = pd.to_datetime(df[['Year', 'Month']].assign(Day=1))

# Plot the data
fig, ax = plt.subplots(figsize=(10, 2))
for col in ['Col1', 'Col2']:
    ax.plot(df['Date'], df[col], label=col)  #Note I have inserted df['Date'] before df[col] in the code
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)
</code>```

Adding tickers as required by you in the second edit:

```<code>years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y')

ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
</code>```

Body:
df

import pandas as pd
df = pd.DataFrame({
    'SKU': ['BIKES','MATS', 'BLANKETS', 'CREAMS'],'Col1': [1,3,6,10],'Col2': [4,5, 6,16],'Month':[1,2,3,4],'Year':['2015','2010','2011','2012']})

Code tried which doesnt work

    import matplotlib.pyplot as plt

#Visualisations

fig, ax = plt.subplots()
for col in ['Col1', 'Col2']:
    ax.plot(df[col], label=col)
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)

I need tickers for months and values for years. But before I can proceed with tickers etc., I am getting error:

File "<ipython-input-14-136f7818ccc7>", line 6
    for col in ['Col1', 'Col2']:
                                ^
SyntaxError: EOL while scanning string literal

Body:
You are getting error because you have not given dates in the for loop. For which dates do you need the plot?

import matplotlib.pyplot as plt
from matplotlib import dates as mdates

# The new column to be used as x axis
df['Date'] = pd.to_datetime(df[['Year', 'Month']].assign(Day=1))

# Plot the data
fig, ax = plt.subplots(figsize=(10, 2))
for col in ['Col1', 'Col2']:
    ax.plot(df['Date'], df[col], label=col)  #Note I have inserted df['Date'] before df[col] in the code
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)

Adding tickers as required by you in the second edit:

years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y')

ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))


问:
Grep with regex expression
I need the content between the fourth and fifth "|" on all lines starting with FHEAD. The goal is to apply the regular expression in grep to read files.

I have this expression that returns all content between "|"

```<code>(?<=\|)(.*?)(?=\|)
</code>```

The goal in the example below would be to return

1047

  8401-

```<code>FHEAD|1|PRMPC|20200217103050|1047|S
TMBPE|FHEAD|2|MOD
FHEAD|3|8401|230008|8401-|8401-Dcto|8401-Dcto 10FHEAD|1|235211|20190206000001|20190402235959|2||1||8||
TPGRP|4|240184
TGLIST|5|235213||||FHEAD
TLITM|6|101029605
TLITM|7|FHEAD101052978
</code>```

Someone can help me?

Thanks in advance

答:
```<code>awk -F '|' '$5=="1047" || $5=="8401-"{ print $0 }"  inputfile.txt
</code>```

Above will find "1047" or "8401" in the fifth column of the inputfile "inputfile.txt"

```<code>grep -E "\|1047\||\|8401-\|" inputfile.txt
</code>```

Above will do the same with grep (but this will not be restricted to column 5.

EDIT:
I must have missed the 'starting with FHEAD'....

```<code>awk -F\| '/^FHEAD/{ print $5 }'  inputfile.txt
</code>```

or with grep

```<code>grep -e '^FHEAD|\(.[^|]*|\)\{3\}\(.[^|]*\)' -o inputfile.txt | grep  '.[^|]*|*' -o | grep -v '|$'
</code>```

a combination of grep and cut:

```<code>grep -e '^FHEAD' inputfile.txt | cut -d'|' -f 5
</code>```

Title: Grep with regex expression

Body:
I need the content between the fourth and fifth "|" on all lines starting with FHEAD. The goal is to apply the regular expression in grep to read files.

I have this expression that returns all content between "|"

(?<=\|)(.*?)(?=\|)

The goal in the example below would be to return

1047

  8401-

FHEAD|1|PRMPC|20200217103050|1047|S
TMBPE|FHEAD|2|MOD
FHEAD|3|8401|230008|8401-|8401-Dcto|8401-Dcto 10FHEAD|1|235211|20190206000001|20190402235959|2||1||8||
TPGRP|4|240184
TGLIST|5|235213||||FHEAD
TLITM|6|101029605
TLITM|7|FHEAD101052978

Someone can help me?

Thanks in advance

Body:
awk -F '|' '$5=="1047" || $5=="8401-"{ print $0 }"  inputfile.txt

Above will find "1047" or "8401" in the fifth column of the inputfile "inputfile.txt"

grep -E "\|1047\||\|8401-\|" inputfile.txt

Above will do the same with grep (but this will not be restricted to column 5.

EDIT:
I must have missed the 'starting with FHEAD'....

awk -F\| '/^FHEAD/{ print $5 }'  inputfile.txt

or with grep

grep -e '^FHEAD|\(.[^|]*|\)\{3\}\(.[^|]*\)' -o inputfile.txt | grep  '.[^|]*|*' -o | grep -v '|$'

a combination of grep and cut:

grep -e '^FHEAD' inputfile.txt | cut -d'|' -f 5


问:
How to get the callback event outside the scope of object?
I'm using Chart.js with a plugin to drag data points. The chart needs a options object to be passed to customize it and triggers a callback passed along with options when there is a dragEnd event. I want to modify the options object's dataset when there is a event triggered. How do I get the event outside its scope so that I can do manupulations.

```<code>@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {

  @ViewChild('myChart') myChart: BaseChartDirective;

  public chartInstance: Chart;
  public context: CanvasRenderingContext2D;

  public options: any = {
    type: 'line',
    data: {
      labels: [2010, 2011, 2012, 2013, 2014],
      datasets: [
        {
          label: 'Marks',
          data: [120, 90, 30, 50, 20, 30],
          borderWidth: 3,
          borderColor: "#00a2e8",
          fill: false
        }
      ]
    },
    options: {
      dragDataRound: 0,
      dragData: true,
      scales: {
        yAxes: [{
          ticks: {
            reverse: false
          }
        }]
      },
      onDragEnd: function (e, datasetIndex, index, value) {
          console.log('Event Triggered'); // This works fine.
          //Here I want to trigger a function outside its scope.
          this.dragEndEvent(e, datasetIndex, index, value);
      }
    }
  };

  dragEndEvent(e, datasetIndex, index, value) {
    //Do some manipulations on the myChartOptions object.
    // When this event is triggered, I cannot acccess options object.
    // console.log(this.options);
    //Error: Cannot read property 'options' of undefined
  }

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    this.chartInstance = new Chart(this.myChart.ctx, this.options);
  }
}
</code>```

答:
You have to use arrow functon to refer this context

Try this:

```<code>public myChartOptions = {
  type: 'line',
  data: {...},
  options: {
    dragData: true,
    dragX: false,
    dragDataRound: 0,
    dragOptions: {
      magnet: {
        to: Math.round
      }
    },
    onDragEnd: (e, datasetIndex, index, value) => {
      console.log('Event Triggered'); // This works fine.
      //Here I want to trigger a function outside its scope.
      this.dragEndEvent(e, datasetIndex, index, value);
    }
  }
}

dragEndEvent(e, datasetIndex, index, value) {
    //Do some manipulations on the myChartOptions object.
    // This is not getting triggered.
}
</code>```

Body:
I'm using Chart.js with a plugin to drag data points. The chart needs a options object to be passed to customize it and triggers a callback passed along with options when there is a dragEnd event. I want to modify the options object's dataset when there is a event triggered. How do I get the event outside its scope so that I can do manupulations.

@Component({
  selector: 'app-line-chart',
  templateUrl: './line-chart.component.html',
  styleUrls: ['./line-chart.component.css']
})
export class LineChartComponent implements OnInit {

  @ViewChild('myChart') myChart: BaseChartDirective;

  public chartInstance: Chart;
  public context: CanvasRenderingContext2D;

  public options: any = {
    type: 'line',
    data: {
      labels: [2010, 2011, 2012, 2013, 2014],
      datasets: [
        {
          label: 'Marks',
          data: [120, 90, 30, 50, 20, 30],
          borderWidth: 3,
          borderColor: "#00a2e8",
          fill: false
        }
      ]
    },
    options: {
      dragDataRound: 0,
      dragData: true,
      scales: {
        yAxes: [{
          ticks: {
            reverse: false
          }
        }]
      },
      onDragEnd: function (e, datasetIndex, index, value) {
          console.log('Event Triggered'); // This works fine.
          //Here I want to trigger a function outside its scope.
          this.dragEndEvent(e, datasetIndex, index, value);
      }
    }
  };

  dragEndEvent(e, datasetIndex, index, value) {
    //Do some manipulations on the myChartOptions object.
    // When this event is triggered, I cannot acccess options object.
    // console.log(this.options);
    //Error: Cannot read property 'options' of undefined
  }

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit(): void {
    this.chartInstance = new Chart(this.myChart.ctx, this.options);
  }
}

Body:
You have to use arrow functon to refer this context

Try this:

public myChartOptions = {
  type: 'line',
  data: {...},
  options: {
    dragData: true,
    dragX: false,
    dragDataRound: 0,
    dragOptions: {
      magnet: {
        to: Math.round
      }
    },
    onDragEnd: (e, datasetIndex, index, value) => {
      console.log('Event Triggered'); // This works fine.
      //Here I want to trigger a function outside its scope.
      this.dragEndEvent(e, datasetIndex, index, value);
    }
  }
}

dragEndEvent(e, datasetIndex, index, value) {
    //Do some manipulations on the myChartOptions object.
    // This is not getting triggered.
}


问:
How to get a ID in a modal coming by dataTable?
My question is, I'm posting an ID into a modal, but when I click in a datepicker inside modal, it gives me as an undefined value, it seems that I'm losing the ID somewhere, could you help me? Here is my code:

Here is my modal HTML:

```<code><div class="modal fade" id="modalUpdatePeriodico" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered " role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Prontuário médico</h4>
          <!-- para pegar o id do meu campo -->
          <input type="hidden" id="hiddenIdPeriodic"/>
        </div>
        <div class="modal-body">
          <div class="row">
            <!-- left column -->
            <div class="col-md-12">
                <!-- Inicio do Formulario de Pesquisa -->
                <form id="formUpdatePeriodico" enctype="multipart/form-data" action="#" method="POST">
                <!-- Form Data e Qtde dias -->
                <div class="form-row">
                  <div class="form-group col-md-6">
                    <label for="dateExam">Data da Realização</label>
                    <input type="text" class="form-control datepicker-calendar" id="dateExam" name="dateExam">
                  </div>
                  <div class="form-group col-md-6">
                    <label for="statusExam">Status</label>
                    <select class="form-control select2" id="statusExam" name="statusExam">
                      <option value="1">Inapto</option>
                      <option value="2">Apto</option>
                    </select>
                  </div>
                </div>
              </form>
              <!-- Fim do Formulario de Pesquisa -->
            </div>
            <!--/.col (right) -->
          </div>
          <!-- /.row -->
        </div>
        <div class="modal-footer">
          <button
            type="button"
            id="btnSavePeriodic"
            class="btn btn-success"
            data-dismiss="modal"
            onclick="saveEmpRestrictions('periodics', inputMatriculaAtes, dateExam, statusExam, hiddenIdPeriodic, examType);">
            Salvar
          </button>
          <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
        </div>
      </div>
    </div>
</code>```

Here is my DataTable JS code:

```<code>function tbPeriodic() {

    // Definição do id da tabela como um dataTable
      $("#tbPeriodico").DataTable({
          "ajax": "webservices/ws_medicalRecord/tables/tb_medicalRecords.php?action=per&matriculaOp=" + <?php echo $matricula; ?>,
          sorting: false,
          "columns":
          [
              { "data": "id" ,
                render: function(data, type, row) { // Função para link de download dos arquivos que foram "upados" no formulário.
                  data = '<a href="#" data-toggle="modal" data-target="#modalUpdatePeriodico" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';
                  return data;
                }
              },
              { "data": "ult_exame" },
              { "data": "tipo_exame" },
              { "data": "status_exame" },
              { "data": "prox_exame" }
          ]
      });
    }
</code>```

Here is my function to post my id into a input hidden:

```<code>$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
        var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
        var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
        console.log(id);
        var modal = $(this);
        modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
    });
</code>```

Here is my datepicker function:

```<code>$('.datepicker-calendar').datepicker({
      autoclose: true
    });
</code>```

So, when I input a date from my datepicker the console shows me undefined, could you help me?

Thanks a lot!

答:
I think you are confused here and there are 2 things happening. Or I should say there is one thing happening and the other step is missing. I am going to try and clarify this for you.

#1

The undefined is happening because you are not getting the value of id correctly. Add a class clickme to your dataTable  like below and get rid of the modal call.

dataTable

```<code>data = '<a class="clickme" href="#" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';
</code>```

Then get rid of

```<code>$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
    var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
    var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
    console.log(id);
    var modal = $(this);
    modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
</code>```

and change it to

```<code>$(document).on('click', '.clickme', function() {
    var id = $(this).data('id');
    $('#modalUpdatePeriodico').modal('show');
    $('#modalUpdatePeriodico').find('#hiddenIdPeriodic').val(id);
    console.log(id);
})
</code>```

#2

The date thing is a different event so add this to get the date

```<code>$('.datepicker-calendar').datepicker({
    autoclose: true,
    onSelect: function(date) {
        console.log(date)
    }
})
</code>```

Body:
My question is, I'm posting an ID into a modal, but when I click in a datepicker inside modal, it gives me as an undefined value, it seems that I'm losing the ID somewhere, could you help me? Here is my code:

Here is my modal HTML:

Prontuário médico

          <input type="hidden" id="hiddenIdPeriodic"/>

                <form id="formUpdatePeriodico" enctype="multipart/form-data" action="#" method="POST">

                    Data da Realização
                    <input type="text" class="form-control datepicker-calendar" id="dateExam" name="dateExam">

                    Status
                    <select class="form-control select2" id="statusExam" name="statusExam">
                      <option value="1">Inapto</option>
                      <option value="2">Apto</option>
                    </select>

              </form>

          <button
            type="button"
            id="btnSavePeriodic"
            class="btn btn-success"
            data-dismiss="modal"
            onclick="saveEmpRestrictions('periodics', inputMatriculaAtes, dateExam, statusExam, hiddenIdPeriodic, examType);">
            Salvar
          </button>
          <button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>

Here is my DataTable JS code:

function tbPeriodic() {

    // Definição do id da tabela como um dataTable
      $("#tbPeriodico").DataTable({
          "ajax": "webservices/ws_medicalRecord/tables/tb_medicalRecords.php?action=per&matriculaOp=" + <?php echo $matricula; ?>,
          sorting: false,
          "columns":
          [
              { "data": "id" ,
                render: function(data, type, row) { // Função para link de download dos arquivos que foram "upados" no formulário.
                  data = '' + row.id + '';
                  return data;
                }
              },
              { "data": "ult_exame" },
              { "data": "tipo_exame" },
              { "data": "status_exame" },
              { "data": "prox_exame" }
          ]
      });
    }

Here is my function to post my id into a input hidden:

$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
        var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
        var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
        console.log(id);
        var modal = $(this);
        modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
    });

Here is my datepicker function:

$('.datepicker-calendar').datepicker({
      autoclose: true
    });

So, when I input a date from my datepicker the console shows me undefined, could you help me?

Thanks a lot!

Body:
I think you are confused here and there are 2 things happening. Or I should say there is one thing happening and the other step is missing. I am going to try and clarify this for you.

#1

The undefined is happening because you are not getting the value of id correctly. Add a class clickme to your dataTable <a> like below and get rid of the modal call.

dataTable

data = '<a class="clickme" href="#" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';

Then get rid of

$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
    var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
    var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
    console.log(id);
    var modal = $(this);
    modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});

and change it to

$(document).on('click', '.clickme', function() {
    var id = $(this).data('id');
    $('#modalUpdatePeriodico').modal('show');
    $('#modalUpdatePeriodico').find('#hiddenIdPeriodic').val(id);
    console.log(id);
})

#2

The date thing is a different event so add this to get the date

$('.datepicker-calendar').datepicker({
    autoclose: true,
    onSelect: function(date) {
        console.log(date)
    }
})


问:
Storing Images in DB - Yea or Nay?
So I'm using an app that stores images heavily in the DB. What's your outlook on this? I'm more of a type to store the location in the filesystem, than store it directly in the DB.

What do you think are the pros/cons?

答:
For a large number of small images, the database might be better.

I had an application with many small thumbnails (2Kb each). When I put them on the filesystem, they each consumed 8kb, due to the filesystem's blocksize. A 400% increase in space!

See this post for more information on block size:
What is the block size of the iphone filesystem?

ContentLicense: CC BY-SA 2.5

Title: Storing Images in DB - Yea or Nay?

LastEditorDisplayName: nickf

ContentLicense: CC BY-SA 3.0


问:
Calculate maximum of column values with common value in another column in PostgreSQL
I am trying to calculalate maximum of column values with common id.

I have following table as input

```<code>TABLE 1:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA502 | abcdef | 2.2   |
| UA504 | yzab   | 8.8   |
| UA504 | lmnop  | 2.8   |
| UA503 | uvwx   | 8.6   |
| UA503 | ghijk  | 2.6   |

</code>```

The desired output is:

```<code>| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA504 | yzab   | 8.8   |
| UA503 | uvwx   | 8.6   |
</code>```

I am running following WITH query (max_calc) with groupby and max function on the output of another WITH query (union_data; TABLE 1).

```<code>max_calc as(

  select id, seq, max(score)
  from union_data
  GROUP BY id

  )

select * from max_calc
;

</code>```

The error I am getting is:

```<code> Query Error: error: column "union_data.seq" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

I do not understand this error. I am grouping the data based on common id not seq. Why I should include column "union_data.seq" in GROUPBY.

Thanks

答:
The answers previously given show how to correct/circumvent the original error. However they do not address the actual inquiry as to the cause of the error. So lets return to the original query.

```<code>  select id, seq, max(score)
  from union_data
  GROUP BY id
</code>```

This query results in the error. The cause being that the non-aggregate column seq is omitted from the grouping. SQL syntax rules require all non-aggregate columns in the select list be in the "group by" clause when aggregate function(s) are also in the column list. That is why Postgres has the "distinct by" extension. It essentially permits bypassing the SQL syntax rule, but it's not a free lunch. Distinct By imposes its own requirements.

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of
  each set of rows where the given expressions evaluate to equal. The
  DISTINCT ON expressions are interpreted using the same rules as for
  ORDER BY (see above). Note that the “first row” of each set is
  unpredictable unless ORDER BY is used to ensure that the desired row
  appears first. ... The DISTINCT ON expression(s) must match the
  leftmost ORDER BY expression(s). The ORDER BY clause will normally
  contain additional expression(s) that determine the desired precedence
  of rows within each DISTINCT ON group.]

Body:
I am trying to calculalate maximum of column values with common id.

I have following table as input

TABLE 1:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA502 | abcdef | 2.2   |
| UA504 | yzab   | 8.8   |
| UA504 | lmnop  | 2.8   |
| UA503 | uvwx   | 8.6   |
| UA503 | ghijk  | 2.6   |

The desired output is:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA504 | yzab   | 8.8   |
| UA503 | uvwx   | 8.6   |

I am running following WITH query (max_calc) with groupby and max function on the output of another WITH query (union_data; TABLE 1).

max_calc as(

  select id, seq, max(score)
  from union_data
  GROUP BY id

  )

select * from max_calc
;

The error I am getting is:

 Query Error: error: column "union_data.seq" must appear in the GROUP BY clause or be used in an aggregate function

I do not understand this error. I am grouping the data based on common id not seq. Why I should include column "union_data.seq" in GROUPBY.

Thanks

Body:
The answers previously given show how to correct/circumvent the original error. However they do not address the actual inquiry as to the cause of the error. So lets return to the original query.

  select id, seq, max(score)
  from union_data
  GROUP BY id

This query results in the error. The cause being that the non-aggregate column seq is omitted from the grouping. SQL syntax rules require all non-aggregate columns in the select list be in the "group by" clause when aggregate function(s) are also in the column list. That is why Postgres has the "distinct by" extension. It essentially permits bypassing the SQL syntax rule, but it's not a free lunch. Distinct By imposes its own requirements.

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of
  each set of rows where the given expressions evaluate to equal. The
  DISTINCT ON expressions are interpreted using the same rules as for
  ORDER BY (see above). Note that the “first row” of each set is
  unpredictable unless ORDER BY is used to ensure that the desired row
  appears first. ... The DISTINCT ON expression(s) must match the
  leftmost ORDER BY expression(s). The ORDER BY clause will normally
  contain additional expression(s) that determine the desired precedence
  of rows within each DISTINCT ON group.]


问:
How to set circle button with background image on right navigation bar item
I have tried to put circle button on right navigation bar of iOS but unfortunately When I use button background it doesn't round the image it shows square shape background image but When I remove image and put background colour it round the button with background colour.
Code that I tried:</p>

```<code>        let button = UIButton()
        button.frame = CGRectMake(0, 0, 40, 40)
        button.layer.cornerRadius = 0.5 * button.bounds.size.width
        button.setImage(self.myPic, forState: .Normal)
        let barButton = UIBarButtonItem()
        barButton.customView = button
        self.navigationItem.rightBarButtonItem = barButton
</code>```

答:
Swift 5 - You can simply do that, and make sure you make clipstobounds to true</p>

```<code>teacherImage.setImage(UIImage(named: "icon_profile"), for: .normal)
teacherImage.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
teacherImage.addTarget(self, action: #selector(addPressed), for: .touchUpInside)
teacherImage.layer.cornerRadius = 0.5 * teacherImage.bounds.size.width
teacherImage.clipsToBounds = true
let rightNavBarButton = UIBarButtonItem(customView: teacherImage)
let currWidth = rightNavBarButton.customView?.widthAnchor.constraint(equalToConstant: 40)
currWidth?.isActive = true
let currHeight = rightNavBarButton.customView?.heightAnchor.constraint(equalToConstant: 40)
currHeight?.isActive = true
self.navigationItem.rightBarButtonItem = rightNavBarButton
</code>```

Body:
I have tried to put circle button on right navigation bar of iOS but unfortunately When I use button background it doesn't round the image it shows square shape background image but When I remove image and put background colour it round the button with background colour.
Code that I tried:

        let button = UIButton()
        button.frame = CGRectMake(0, 0, 40, 40)
        button.layer.cornerRadius = 0.5 * button.bounds.size.width
        button.setImage(self.myPic, forState: .Normal)
        let barButton = UIBarButtonItem()
        barButton.customView = button
        self.navigationItem.rightBarButtonItem = barButton

Body:
Swift 5 - You can simply do that, and make sure you make clipstobounds to true

teacherImage.setImage(UIImage(named: "icon_profile"), for: .normal)
teacherImage.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
teacherImage.addTarget(self, action: #selector(addPressed), for: .touchUpInside)
teacherImage.layer.cornerRadius = 0.5 * teacherImage.bounds.size.width
teacherImage.clipsToBounds = true
let rightNavBarButton = UIBarButtonItem(customView: teacherImage)
let currWidth = rightNavBarButton.customView?.widthAnchor.constraint(equalToConstant: 40)
currWidth?.isActive = true
let currHeight = rightNavBarButton.customView?.heightAnchor.constraint(equalToConstant: 40)
currHeight?.isActive = true
self.navigationItem.rightBarButtonItem = rightNavBarButton


问:
How do I tell when a NetworkImage has finished loading?
I have a NetworkImage and I'd like to know when it's finished loading. How do I do that?</p>

答:
thank you for your comment thats help to resolve the situation that how to know if the image is loaded or not hope that help

I use a StatefulWidget need a editing depend on your AffichScreen

situation :

```<code>-i have an url that i enter
 -if url is correct affich the image if not affich an icon
 -if empty affich a Text()
 -precacheImage check if the url is correct if not give an error
 -and change _loadingimage(bool) to false to affich the icon eror
 -i use a NetworkImage to check with precacheImage and before
 -affich use a Image.network

bool _loadingimage;
ImageProvider _image;
Image _imagescreen;

@override
  void initState() {
    _loadingimage = true;
    _imageUrlfocusNode.addListener(_updateImageUrl);
    super.initState();
  }

   @override
  void dispose() {
    _imageUrlfocusNode.removeListener(_updateImageUrl);
    _quantityfocusNode.dispose();
    _imageUrlConroller.dispose();
    _imageUrlfocusNode.dispose();
    super.dispose();
  }

  void _updateImageUrl() {
    setState(() {
      _image = NetworkImage(_imageUrlConroller.text);
    });
    if (!_imageUrlfocusNode.hasFocus) {
      if (_imageUrlConroller.text.isNotEmpty) {
        setState(() {
          loadimage();
        });
      }
    }
  }

  void loadimage() {
    _loadingimage = true;
    precacheImage(_image, context, onError: (e, stackTrace) {
      // log.fine('Image ${widget.url} failed to load with error $e.');
      print('error $e');
      setState(() {
        _loadingimage = false;
        print(_loadingimage);
      });
    });
    if (_loadingimage == true) {
      _imagescreen = Image.network(
        _imageUrlConroller.text,
        fit: BoxFit.fill,
      );
    }
  }

  Container(
                              width: 100,
                              height: 100,
                              margin: EdgeInsets.only(top: 13, right: 11),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  width: 1,
                                  color: Colors.grey,
                                ),
                              ),
                              child:_imageUrlConroller.text.isEmpty
                                      ? Text('enter an url')
                                      : !_loadingimage
                                          ? Container(
                                              child: Icon(Icons.add_a_photo),
                                            )
                                          : Container(
                                              child: _imagescreen,
                                            ),
                            ),
</code>```

Body:
thank you for your comment thats help to resolve the situation that how to know if the image is loaded or not hope that help

I use a StatefulWidget need a editing depend on your AffichScreen

situation :

-i have an url that i enter
 -if url is correct affich the image if not affich an icon
 -if empty affich a Text()
 -precacheImage check if the url is correct if not give an error
 -and change _loadingimage(bool) to false to affich the icon eror
 -i use a NetworkImage to check with precacheImage and before
 -affich use a Image.network

bool _loadingimage;
ImageProvider _image;
Image _imagescreen;

@override
  void initState() {
    _loadingimage = true;
    _imageUrlfocusNode.addListener(_updateImageUrl);
    super.initState();
  }

   @override
  void dispose() {
    _imageUrlfocusNode.removeListener(_updateImageUrl);
    _quantityfocusNode.dispose();
    _imageUrlConroller.dispose();
    _imageUrlfocusNode.dispose();
    super.dispose();
  }

  void _updateImageUrl() {
    setState(() {
      _image = NetworkImage(_imageUrlConroller.text);
    });
    if (!_imageUrlfocusNode.hasFocus) {
      if (_imageUrlConroller.text.isNotEmpty) {
        setState(() {
          loadimage();
        });
      }
    }
  }

  void loadimage() {
    _loadingimage = true;
    precacheImage(_image, context, onError: (e, stackTrace) {
      // log.fine('Image ${widget.url} failed to load with error $e.');
      print('error $e');
      setState(() {
        _loadingimage = false;
        print(_loadingimage);
      });
    });
    if (_loadingimage == true) {
      _imagescreen = Image.network(
        _imageUrlConroller.text,
        fit: BoxFit.fill,
      );
    }
  }

  Container(
                              width: 100,
                              height: 100,
                              margin: EdgeInsets.only(top: 13, right: 11),
                              decoration: BoxDecoration(
                                border: Border.all(
                                  width: 1,
                                  color: Colors.grey,
                                ),
                              ),
                              child:_imageUrlConroller.text.isEmpty
                                      ? Text('enter an url')
                                      : !_loadingimage
                                          ? Container(
                                              child: Icon(Icons.add_a_photo),
                                            )
                                          : Container(
                                              child: _imagescreen,
                                            ),
                            ),


问:
Adding descriptions to items of a list in R
Is there a way to add descriptions to items in a list in R? I want to combine four dataframes into a list, but along with the name of each dataframe in the list, I want the list to contain a brief description of the dataframe as well.

For example, I want a line to do something like what my last line in the below code (pseudocoded) would do.

```<code>a <- matrix(rnorm(9), nrow=3, ncol=3)
b <- matrix(rnorm(9), nrow=3, ncol=3)
c <- matrix(rnorm(9), nrow=3, ncol=3)
d <- matrix(rnorm(9), nrow=3, ncol=3)
dat <- list(a, b, c, d)
names(dat) <- c("subject_info", "sample_info", "study_info", "test_info")
# description(dat$subject_info) <- "Subject-by-subject summary of results from the clinical trial"
</code>```

答:
Borrowing from @akrun's comment, the natural way of doing this is to use R's concept of help("attributes"). See also Advanced R by Hadley Wickham.

If you want to automate the task of getting and setting a special attribute, in this case the attribute "description", define getter and setter functions.

```<code>description <- function(x){
  attr(x, "description")
}
`description<-` <- function(x, value){
  attr(x, "description") <- value
  x
}

description(dat$subject_info) <- "Subject-by-subject summary of results from the clinical trial"
</code>```

Now see if it worked.

```<code>description(dat$subject_info)
#[1] "Subject-by-subject summary of results from the clinical trial"
</code>```

Note.

Some base R functions with long names that are used many times have short name forms. An example is coefficients and the equivalent coef. If you plan to use these functions, you could define short name aliases.

```<code># aliases
descr <- description
`descr<-` <- `description<-`

descr(dat$sample_info) <- "A test"
descr(dat$sample_info)
#[1] "A test"

lapply(dat, descr)
</code>```

Body:
Is there a way to add descriptions to items in a list in R? I want to combine four dataframes into a list, but along with the name of each dataframe in the list, I want the list to contain a brief description of the dataframe as well.

For example, I want a line to do something like what my last line in the below code (pseudocoded) would do.

a <- matrix(rnorm(9), nrow=3, ncol=3)
b <- matrix(rnorm(9), nrow=3, ncol=3)
c <- matrix(rnorm(9), nrow=3, ncol=3)
d <- matrix(rnorm(9), nrow=3, ncol=3)
dat <- list(a, b, c, d)
names(dat) <- c("subject_info", "sample_info", "study_info", "test_info")
# description(dat$subject_info) <- "Subject-by-subject summary of results from the clinical trial"

Body:
Borrowing from @akrun's comment, the natural way of doing this is to use R's concept of help("attributes"). See also Advanced R by Hadley Wickham.

If you want to automate the task of getting and setting a special attribute, in this case the attribute "description", define getter and setter functions.

description <- function(x){
  attr(x, "description")
}
`description<-` <- function(x, value){
  attr(x, "description") <- value
  x
}

description(dat$subject_info) <- "Subject-by-subject summary of results from the clinical trial"

Now see if it worked.

description(dat$subject_info)
#[1] "Subject-by-subject summary of results from the clinical trial"

Note.

Some base R functions with long names that are used many times have short name forms. An example is coefficients and the equivalent coef. If you plan to use these functions, you could define short name aliases.

# aliases
descr <- description
`descr<-` <- `description<-`

descr(dat$sample_info) <- "A test"
descr(dat$sample_info)
#[1] "A test"

lapply(dat, descr)


问:
Should I return an array or a collection from a function?
What's the preferred container type when returning multiple objects of the same type from a function?

Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)?

Thanks!

答:
Always return an interface type that presents the greatest amount of functionality to the caller.  So in your case ICollection<YourType> ought to be used.

Something interesting to note is that the BCL developers actually got this wrong in some place of the .NET framework - see this Eric Lippert blog post for that story.

OwnerDisplayName: Pwninstein

OwnerDisplayName: Andrew Hare

LastEditorDisplayName: Richard E


问:
Spring Keycloak - How to set principal from JWT access token
I've been at this for about a week now.

I have a use case where I recieve an auth token through the body instead of the header, and because of that Keycloak and Spring don't automatically set the user. (The reason being, with websockets, I can only send the auth token through the body with the initial connection)

I've tried intercepting the call before keycloak and copying the token from the body to the header, but that did not work.

So now I would like to manually authenticate through keycloak (or just manually set the principal user). I have access to the JWT Access Token, but from here I'm not sure how to authenticate with keycloak.

Anyone have any input?

答:
Since there are two Keycloak pieces that could be in play here, I'll start with a clarification:

Keycloak - This is the authorization server that a client will use to obtain a JWT

Keycloak Adapter - This is the thing that configures a Resource Server to integrate Keycloak with Spring Security

I have a use case where I recieve an auth token through the body instead of the header, and because of that Keycloak and Spring don't automatically set the user.

Spring Security 5.1 ships with built-in support for JWT-based access tokens, so you may not need to use the Keycloak Adapter for what you are wanting to do.

When using Spring Security's built-in support, you can configure the DefaultBearerTokenResolver to look in the body:

@Bean
public BearerTokenResolver bearerTokenResolver() {
    DefaultBearerTokenResolver resolver =
            new DefaultBearerTokenResolver();
    resolver.setAllowFormEncodedBodyParameter(true);
    return resolver;
}
```


问:
Filter with terniary operator
I have a method

```<code>AddOrUpdateList(this List<T> list, T scope, Func<T, bool>, Func<T, bool> when = null){
    T item = default;
    if (when == null)
        list.SingleOrDefault(t => t.Equals(scope)); //Check Single
    else
        item = list.SingleOrDefault(when);
    .
    .
    .
}
</code>```

When I'm going to use it I have two possible starts:

I receive an element which element.Title is something, so I use the Title as filter

I receive an element which has no title, so I need to get the last one from a List

I was thinking to use terniary operator and lambda to create a filter that contemplates both cases.

What I came up with is:

```<code>var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e = list.Select(ele => ele).Last());
</code>```

But that gives me: Error CS0030  Cannot convert type 'T' to 'System.Func<T, bool>'

Any idea or help you can give me??

Im pretty new to C# and Linq so I don't understand to well how some things should work

Thanks in advance.

答:
Your current filter is

```<code>var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e = list.Select(ele => ele).Last());
</code>```

But e = list.Select(ele => ele).Last() is not a Func<T, bool>. In fact, it is not a function at all. As @canton7 said, you need to use the arrow notation (=>)to create a lambda. Moreover, even if that line was a lambda, it would be of type Func<T, T>,
since it simply returns the last item in a list of items of type T; it does not return a bool at all!

Is this more what you want?

```<code>var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e => e.Title == list.Last().Title);
</code>```

Title: Filter with terniary operator

Body:
I have a method

AddOrUpdateList(this List<T> list, T scope, Func<T, bool>, Func<T, bool> when = null){
    T item = default;
    if (when == null)
        list.SingleOrDefault(t => t.Equals(scope)); //Check Single
    else
        item = list.SingleOrDefault(when);
    .
    .
    .
}

When I'm going to use it I have two possible starts:

I receive an element which element.Title is something, so I use the Title as filter

I receive an element which has no title, so I need to get the last one from a List

I was thinking to use terniary operator and lambda to create a filter that contemplates both cases.

What I came up with is:

var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e = list.Select(ele => ele).Last());

But that gives me: Error CS0030  Cannot convert type 'T' to 'System.Func<T, bool>'

Any idea or help you can give me??

Im pretty new to C# and Linq so I don't understand to well how some things should work

Thanks in advance.

Body:
Your current filter is

var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e = list.Select(ele => ele).Last());

But e = list.Select(ele => ele).Last() is not a Func<T, bool>. In fact, it is not a function at all. As @canton7 said, you need to use the arrow notation (=>)to create a lambda. Moreover, even if that line was a lambda, it would be of type Func<T, T>,
since it simply returns the last item in a list of items of type T; it does not return a bool at all!

Is this more what you want?

var filter = (element.Title != "")
   ? (Func<T, bool>)(e => e.Title == element.Title)
   : (Func<T, bool>)(e => e.Title == list.Last().Title);


问:
Display headers in Excel only when the range has values

I am trying to Display in Column A (A23:A29) the header of a table only when it has values on either column B (Current Pay) or C (Year to Date).

I am able to display it when both have values, or when B has a value (positive or negative). But I am not able to display the header when only C has a value (but not B). (Also could I remove #N/A when there is no values or both are zero?)

I have attached a picture to show the layout and added some dummy values to show when it works and when it doesn't.

I am using the following formula in column A:

```<code>=IF(COUNTA($B23:$C23)=0,"",INDEX(PP[[#Headers],[Column1]],MATCH(TRUE,INDEX($B23:$C23<>0,0),0)))
</code>```

答:
MATCH(TRUE,INDEX($B23:$C23<>0,0),0)

gives value 2 and then it searches for header in row 2. Thats why Reference Error

If you want only headers from row number 1 then try replace above with 1 as below. Then it will take header in case both the columns are filled or any one column is filled

try this

=IF(COUNTA($B23:$C23)=0,"",INDEX(Table2[[#Headers],[Column1]],1))

Body:
I am trying to Display in Column A (A23:A29) the header of a table only when it has values on either column B (Current Pay) or C (Year to Date).

I am able to display it when both have values, or when B has a value (positive or negative). But I am not able to display the header when only C has a value (but not B). (Also could I remove #N/A when there is no values or both are zero?)

I have attached a picture to show the layout and added some dummy values to show when it works and when it doesn't.

I am using the following formula in column A:

=IF(COUNTA($B23:$C23)=0,"",INDEX(PP[[#Headers],[Column1]],MATCH(TRUE,INDEX($B23:$C23<>0,0),0)))


问:
EF Code First DBContext and Transactions
I would like know what is the best possible way to implement transactions with DBContext. In particular,

Does DbContext.SaveChanges implement transaction internall if i change multiple entities?

If i want to call DbContext.SaveChanges multiple times(same contxet/different contxets), how transaction can be achieved?

答:
Yes. SaveChanges uses transaction internally.

Use TransactionScope to wrap multiple calls to SaveChanges

Example:

```<code>using(var scope = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    // Do something
    context.SaveChanges();
    // Do something else
    context.SaveChanges();

    scope.Complete();
}
</code>```

Body:
Yes. SaveChanges uses transaction internally.

Use TransactionScope to wrap multiple calls to SaveChanges

Example:

using(var scope = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    // Do something
    context.SaveChanges();
    // Do something else
    context.SaveChanges();

    scope.Complete();
}


问:
bootstrap-vue : how to recognize hover event over b-tab
I'm trying to change the active tab of a bootstrap-vue b-tabs when the tab title is hovered over, not only when clicked on. I'm having trouble isolating this event.

In the following Codepen example, I can isolate the event when the image is being hovered over, however I want to isolate the event when the title ('Tubes and Vials' for example) is being hovered over.

I'm fairly new to Vue so I apologize if this is a simple answer, but I haven't struggled with this for a while now and haven't been able to figure this out. Thanks!

Component File

```<code><template>
    <b-container class="px-3" fluid>
        <div>
            <h3>Range Of Glass Products We Inspect</h3>
            <p>Anything formed from tubular glass</p>
        </div>
        <div>
            <b-tabs content-class="mt-3" align="left" class="vial-types" vertical>
                <b-tab
                        v-for="glassItem in productRange"
                        v-bind:key="glassItem.type"
                        v-bind:ref="glassItem"
                        v-bind:title="glassItem.type"
                        @mouseover.native="greet()"
                        @mouseleave.native="greet()"
                >
                    <b-img
                            v-bind:src="glassItem.image"
                            alt="Factory Image">
                    </b-img>
                </b-tab>
            </b-tabs>
        </div>
    </b-container>
</template>

<script>
    export default {
        name: "ProductRange",
        data() {
            return {
                productRange: [
                    {type: "Screw & Flanged Head", image:"https://picsum.photos/600/400/", hover: false},
                    {type: "Tubes and Vials", image:"https://picsum.photos/600/400/", hover: false},
                    {type: "Pipettes, Syringes, Filling Needles", image:"https://picsum.photos/400/400/",hover: false},
                    {type: "Ampoules", image:"https://picsum.photos/600/400/", hover: false},
                    {type: "Custom Geometries Per Customer Specification", image:"https://picsum.photos/600/400/", hover: false}
                ]
            }
        },
        methods: {
            greet: function () {
                console.log("Hovering");
            }
        }
    }
</script>

<style lang="sass">

</style>
</code>```

答:
Sadly I don't think there's a built-in way to easily do this.

However, you can still solve this by hiding the standard tabs and instead reconstruct the structure yourself using b-nav and binding to the b-tabs v-model.

You can then add your events the b-nav-item as they'll be working as your tabs.

new Vue({
  el: "#app",
  data: {
    selectedTab: 0,
    productRange: [
      {
        type: "Screw & Flanged Head",
        image: "https://picsum.photos/600/400/"
      },
      {
       type: "Tubes and Vials",
       mage: "https://picsum.photos/640/400/"
      },
      {
        type: "Pipettes, Syringes, Filling Needles",
        image: "https://picsum.photos/400/400/"
      },
      {
        type: "Ampoules",
        image: "https://picsum.photos/600/400/"
      },
      {
        type: "Custom Geometries Per Customer Specification",
        image: "https://picsum.photos/700/400/"
      }
    ]
  },
  methods: {
    greet: function() {
      console.log("hovering");
    },
    onTabHover(glassItem) {
      console.log("Tab hovered", glassItem)
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.2/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.4.2/dist/bootstrap-vue.min.js"></script>

<b-container id="app" class="px-3"fluid>
  <div>
    <h3>Range Of Glass Products We Inspect</h3>
    <p>Anything formed from tubular glass</p>
  </div>
  <div>
    <b-row>
      <b-col cols="auto">
        <b-nav pills vertical>
          <b-nav-item v-for="(glassItem, index) in productRange"
                      :active="selectedTab === index"
                      @click="selectedTab = index"
                      @mouseenter="onTabHover(glassItem)">
            {{ glassItem.type }}
          </b-nav-item>
        </b-nav>
      </b-col>
      <b-col>
        <b-tabs v-model="selectedTab"
                content-class="mt-3"
                class="vial-types"
                nav-class="d-none">
         <b-tab
                v-for="glassItem in productRange"
                :key="glassItem.type"
                :ref="glassItem"
                :title="glassItem.type"
                @mouseover.native="greet()"
                @mouseleave.native="greet()"
                >
            <b-img
                   :src="glassItem.image"
                   alt="Factory Image">
            </b-img>
          </b-tab>
        </b-tabs>
      </b-col>
    </b-row>
  </div>
</b-container></code>```

Body:
I'm trying to change the active tab of a bootstrap-vue b-tabs when the tab title is hovered over, not only when clicked on. I'm having trouble isolating this event.

In the following Codepen example, I can isolate the event when the image is being hovered over, however I want to isolate the event when the title ('Tubes and Vials' for example) is being hovered over.

I'm fairly new to Vue so I apologize if this is a simple answer, but I haven't struggled with this for a while now and haven't been able to figure this out. Thanks!

Component File

<template>

Range Of Glass Products We Inspect

Anything formed from tubular glass

</template>

Body:
Sadly I don't think there's a built-in way to easily do this.

However, you can still solve this by hiding the standard tabs and instead reconstruct the structure yourself using b-nav and binding to the b-tabs v-model.

You can then add your events the b-nav-item as they'll be working as your tabs.

new Vue({
  el: "#app",
  data: {
    selectedTab: 0,
    productRange: [
      {
        type: "Screw & Flanged Head",
        image: "https://picsum.photos/600/400/"
      },
      {
       type: "Tubes and Vials",
       mage: "https://picsum.photos/640/400/"
      },
      {
        type: "Pipettes, Syringes, Filling Needles",
        image: "https://picsum.photos/400/400/"
      },
      {
        type: "Ampoules",
        image: "https://picsum.photos/600/400/"
      },
      {
        type: "Custom Geometries Per Customer Specification",
        image: "https://picsum.photos/700/400/"
      }
    ]
  },
  methods: {
    greet: function() {
      console.log("hovering");
    },
    onTabHover(glassItem) {
      console.log("Tab hovered", glassItem)
    }
  }
});

<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/bootstrap-vue@2.4.2/dist/bootstrap-vue.css" rel="stylesheet"/>

<script src="https://unpkg.com/vue@2.6.10/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.4.2/dist/bootstrap-vue.min.js"></script>

<b-container id="app" class="px-3"fluid>
  <div>
    <h3>Range Of Glass Products We Inspect</h3>
    <p>Anything formed from tubular glass</p>
  </div>
  <div>
    <b-row>
      <b-col cols="auto">
        <b-nav pills vertical>
          <b-nav-item v-for="(glassItem, index) in productRange"
                      :active="selectedTab === index"
                      @click="selectedTab = index"
                      @mouseenter="onTabHover(glassItem)">
            {{ glassItem.type }}
          </b-nav-item>
        </b-nav>
      </b-col>
      <b-col>
        <b-tabs v-model="selectedTab"
                content-class="mt-3"
                class="vial-types"
                nav-class="d-none">
         <b-tab
                v-for="glassItem in productRange"
                :key="glassItem.type"
                :ref="glassItem"
                :title="glassItem.type"
                @mouseover.native="greet()"
                @mouseleave.native="greet()"
                >
            <b-img
                   :src="glassItem.image"
                   alt="Factory Image">
            </b-img>
          </b-tab>
        </b-tabs>
      </b-col>
    </b-row>
  </div>
</b-container>


问:
How can I call a method as background worker by adding it into Startup in .netcore 2.1?
I am creating a simple logging system by using Nest and C#. I have a log producer for collecting logs inside of blockingcollection. Also I have a consumer. But I stumpled upon with an issue. How can I use my comsumer in startup or is there any way to create background servise which was listening queue of blockingcollection? What is best practice of it? I am confusing how to call AsyncConsumer or consumer when application startup.</p>

```<code> public class SimpleLog
    {
        public string Header { get; set; }
        public string LogDate { get; set; }
        public string Sessionid { get; set; }
        public string Userid { get; set; }
        public string Correlationid { get; set; }
        public int Status { get; set; }
        public string UrlQueryString { get; set; }
        public string UrlPath { get; set; }
        public string UrlMethod { get; set; }
        public string Environment { get; set; }
        public string IndexName { get; set; }
        public string IndexType { get; set; }

    }
    public class QuickLog
    {
        private static BlockingCollection<SimpleLog> data = new BlockingCollection<SimpleLog>();

        public static void Producer(SimpleLog pageviewLog)
        {
            data.TryAdd(pageviewLog, TimeSpan.FromSeconds(10));
        }

        public static void Consumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }

            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();

            var response = _client.IndexMany(logs, log.IndexName, log.IndexType);

            if (!response.IsValid)
                throw response.OriginalException;

        }

        public async Task AsyncConsumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }
            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();
            var response = await _client.IndexManyAsync(logs, log.IndexName, log.IndexType).ConfigureAwait(false);

            if (!response.IsValid)
                throw response.OriginalException;

            await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
        }
    }
    public static class ElasticConfig
    {
        private static IElasticClient _client;
        static ElasticConfig()
        {
            var esurl = LogSettings.Url;
            string[] urls = esurl.Split(',');
            var nodes = new Uri[2];

            for (int i = 0; i < urls.Length; i++)
            {
                nodes.SetValue(new Uri(urls[i]), i);
            }

            var connectionPool = new SniffingConnectionPool(nodes);
            var connectionSettings = new ConnectionSettings(connectionPool).RequestTimeout(
                TimeSpan.FromSeconds(60))
                .PingTimeout(TimeSpan.FromSeconds(60))
                .MaxRetryTimeout(TimeSpan.FromSeconds(60))
                .MaxDeadTimeout(TimeSpan.FromSeconds(60))
                .DeadTimeout(TimeSpan.FromSeconds(60)).DisablePing()
                                .SniffOnConnectionFault(false)
                                .SniffOnStartup(false)
                                .SniffLifeSpan(TimeSpan.FromMinutes(1));
            _client = new ElasticClient(connectionSettings);
        }
        public static IElasticClient GetClient()
        {
            return _client;
        }
    }
</code>```

答:
Not sure how many times and which method exactly you want to call. If you want to run some asynchronous background jobs you can use IHostedService. You will need to install  Microsoft.Extensions.Hosting NuGet package or Microsoft.AspNetCore.App metapackage.

Usage:

Add this line to your Startup.cs

```<code>services.AddHostedService<LogBackgroundService>(); //service is instance of IServiceCollection
</code>```

And this is the implementation of your background service:

```<code>public class LogBackgroundService : IHostedService
{

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await QuickLog.AsyncConsumer(); // or whatever you want to call
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}
</code>```

Behavior:

It will run once(but IHostedService still will be running. If you want to reduce resource consumption just call StopAsync() when it's done). If you want to run something in a loop, you can implement this:

```<code>while (!cancellationToken.IsCancellationRequested)
{
    await QuickLog.AsyncConsumer();
    await Task.Delay(250, cancellationToken); // you can add this if you want to throttle
}
</code>```

PS. If you need to run multiple IHostedServices in your application without blocking each other you will need to wrap your methods into Tasks:

```<code>public Task StartAsync(CancellationToken cancellationToken)
{
    Task.Run(() =>  QuickLog.AsyncConsumer(), cancellationToken);
 }
</code>```

Body:
I am creating a simple logging system by using Nest and C#. I have a log producer for collecting logs inside of blockingcollection. Also I have a consumer. But I stumpled upon with an issue. How can I use my comsumer in startup or is there any way to create background servise which was listening queue of blockingcollection? What is best practice of it? I am confusing how to call AsyncConsumer or consumer when application startup.

 public class SimpleLog
    {
        public string Header { get; set; }
        public string LogDate { get; set; }
        public string Sessionid { get; set; }
        public string Userid { get; set; }
        public string Correlationid { get; set; }
        public int Status { get; set; }
        public string UrlQueryString { get; set; }
        public string UrlPath { get; set; }
        public string UrlMethod { get; set; }
        public string Environment { get; set; }
        public string IndexName { get; set; }
        public string IndexType { get; set; }

    }
    public class QuickLog
    {
        private static BlockingCollection<SimpleLog> data = new BlockingCollection<SimpleLog>();

        public static void Producer(SimpleLog pageviewLog)
        {
            data.TryAdd(pageviewLog, TimeSpan.FromSeconds(10));
        }

        public static void Consumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }

            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();

            var response = _client.IndexMany(logs, log.IndexName, log.IndexType);

            if (!response.IsValid)
                throw response.OriginalException;

        }

        public async Task AsyncConsumer()
        {
            var _client = ElasticConfig.GetClient();
            var logs = new List<SimpleLog>();

            foreach (var item in data.GetConsumingEnumerable())
            {
                logs.Add(item);
            }
            if (logs == null && logs.Count <= 0)
                return;
            var log = logs.FirstOrDefault();
            var response = await _client.IndexManyAsync(logs, log.IndexName, log.IndexType).ConfigureAwait(false);

            if (!response.IsValid)
                throw response.OriginalException;

            await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
        }
    }
    public static class ElasticConfig
    {
        private static IElasticClient _client;
        static ElasticConfig()
        {
            var esurl = LogSettings.Url;
            string[] urls = esurl.Split(',');
            var nodes = new Uri[2];

            for (int i = 0; i < urls.Length; i++)
            {
                nodes.SetValue(new Uri(urls[i]), i);
            }

            var connectionPool = new SniffingConnectionPool(nodes);
            var connectionSettings = new ConnectionSettings(connectionPool).RequestTimeout(
                TimeSpan.FromSeconds(60))
                .PingTimeout(TimeSpan.FromSeconds(60))
                .MaxRetryTimeout(TimeSpan.FromSeconds(60))
                .MaxDeadTimeout(TimeSpan.FromSeconds(60))
                .DeadTimeout(TimeSpan.FromSeconds(60)).DisablePing()
                                .SniffOnConnectionFault(false)
                                .SniffOnStartup(false)
                                .SniffLifeSpan(TimeSpan.FromMinutes(1));
            _client = new ElasticClient(connectionSettings);
        }
        public static IElasticClient GetClient()
        {
            return _client;
        }
    }

Body:
Not sure how many times and which method exactly you want to call. If you want to run some asynchronous background jobs you can use IHostedService. You will need to install  Microsoft.Extensions.Hosting NuGet package or Microsoft.AspNetCore.App metapackage.

Usage:

Add this line to your Startup.cs

services.AddHostedService<LogBackgroundService>(); //service is instance of IServiceCollection

And this is the implementation of your background service:

public class LogBackgroundService : IHostedService
{

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        await QuickLog.AsyncConsumer(); // or whatever you want to call
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

Behavior:

It will run once(but IHostedService still will be running. If you want to reduce resource consumption just call StopAsync() when it's done). If you want to run something in a loop, you can implement this:

while (!cancellationToken.IsCancellationRequested)
{
    await QuickLog.AsyncConsumer();
    await Task.Delay(250, cancellationToken); // you can add this if you want to throttle
}

PS. If you need to run multiple IHostedServices in your application without blocking each other you will need to wrap your methods into Tasks:

public Task StartAsync(CancellationToken cancellationToken)
{
    Task.Run(() =>  QuickLog.AsyncConsumer(), cancellationToken);
 }


问:
java xpath should show subnodes only without attributes, but shows all
I have a simple example xml file:

```<code><?xml version="1.0" ?>
<testCars>
    <cars id="0">
        <color id="0">Black</color>
        <color id="1">Orange</color>
    </cars>
    <cars id="1">
        <color id="0">Blue</color>
        <color id="1">Grey</color>
    </cars>
    <cars>
        <color id="0>">Red</color>
        <color id="1>">Green</color>
    </cars>
 </testCars>
</code>```

First I use DocumentBuilder to parse that file, and then I use xpath to get the things I want.
I would use the expression and xpath to get the color 0 of car 1:

```<code>String expression = String.format("/testCars/cars[@id=\"%s\"]/color[@id=\"%s\"]",1,0);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
System.out.println(nodeList.item(0).getTextContent());
</code>```

And I get Blue, as I should. But lets say I want the color 0 of a card without an ID, it should be Red.

So I change the expression to

```<code>String expression = String.format("/testCars/cars/color[@id=\"%s\"]",0);
</code>```

But now the result is Black. It just takes the first node, although I want it to take the one without any attributes on it.

Does Xpath have some specific command to explicitly select nodes without an attribute? Or do I need to restructe the xml file?

Thx.

答: To select the cars element with no attributes, use cars[not(@*)]. To select a cars element with no @id attribute, use cars[not(@id)].

Body:
I have a simple example xml file:

<?xml version="1.0" ?>
<testCars>
    <cars id="0">
        <color id="0">Black</color>
        <color id="1">Orange</color>
    </cars>
    <cars id="1">
        <color id="0">Blue</color>
        <color id="1">Grey</color>
    </cars>
    <cars>
        <color id="0>">Red</color>
        <color id="1>">Green</color>
    </cars>
 </testCars>

First I use DocumentBuilder to parse that file, and then I use xpath to get the things I want.
I would use the expression and xpath to get the color 0 of car 1:

String expression = String.format("/testCars/cars[@id=\"%s\"]/color[@id=\"%s\"]",1,0);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
System.out.println(nodeList.item(0).getTextContent());

And I get Blue, as I should. But lets say I want the color 0 of a card without an ID, it should be Red.

So I change the expression to

String expression = String.format("/testCars/cars/color[@id=\"%s\"]",0);

But now the result is Black. It just takes the first node, although I want it to take the one without any attributes on it.

Does Xpath have some specific command to explicitly select nodes without an attribute? Or do I need to restructe the xml file?

Thx.


问:
distcc - are there cases it requires a synchronized network filesystem
Two simplified makefiles

makefile1

```<code>a.txt:
    echo “123144234” > a.txt

t2: a.txt
    cat a.txt > b.txt
</code>```

makefile2

```<code>t1:
    echo “123144234” > a.txt

t2: t1
    cat a.txt > b.txt
</code>```

Both makefiles have the same functionality.

Both makefiles can be run in parallel because the dependency of t2 on t1.

However, there is a critical difference which might?/does? make a difference when it comes to distributed builds.

In makefile1, t2 depends directly on the artifact a.txt which is also the same as the name of the target itself a.txt. However, in makefile2, while the recipe and artifact of t1 is same as for a.txt, the name of the target is not a.txt.

This difference is key because gnu make (and I assume distcc) does NOT parse the recipe - nor analyze the filesystem at runtime - to determine all the artifacts for a given target. In makefile2, gnu make does NOT create ANY relationship between a.txt and t1.

When the build is done as make -j i.e. parallel but not distributed, this difference is irrelevant because all make targets are run on the same machine i.e. all the make instances access the same filesystem.

But let's consider what could?/does? happen during a distributed build if the two targets are built on two separate machines

In both makefiles, the recipe for t2 would be run AFTER the recipe for a.txt/t1.

However, in makefile1 the dependency of t2 on a.txt is explicit i.e. distcc knows that to make t2 on a separate machine, it must send the file a.txt to that separate machine.

QUESTION

If makefile2 is run using distcc, without a synchronized distributed filesystem, and t2 is maked on another machine, will there be a build error because a.txt is not present on the other machine?

What are the options for a distributed Linux filesystem?

答:
distcc is merely a replacement for gcc. It uses local gcc to preprocess the source file, then sends it for compilation to another machine, receives back the object file and saves it into the local filesystem. distcc doesn't require a shared network filesystem or clock synchronization between the participating hosts.

There is alse new "pump" functionality that preprocesses on remote servers, but it doesn't require a shared network filesystem or clock synchronization either.

Your make always runs locally.

Answering your questions:

distcc doesn't run make. make runs distc instead of gcc. make examines dependencies and their timestamps locally.

make runs locally and it doesn't care whether the filesystem it uses is local or networked.

Body:
Two simplified makefiles

makefile1

a.txt:
    echo “123144234” > a.txt

t2: a.txt
    cat a.txt > b.txt

makefile2

t1:
    echo “123144234” > a.txt

t2: t1
    cat a.txt > b.txt

Both makefiles have the same functionality.

Both makefiles can be run in parallel because the dependency of t2 on t1.

However, there is a critical difference which might?/does? make a difference when it comes to distributed builds.

In makefile1, t2 depends directly on the artifact a.txt which is also the same as the name of the target itself a.txt. However, in makefile2, while the recipe and artifact of t1 is same as for a.txt, the name of the target is not a.txt.

This difference is key because gnu make (and I assume distcc) does NOT parse the recipe - nor analyze the filesystem at runtime - to determine all the artifacts for a given target. In makefile2, gnu make does NOT create ANY relationship between a.txt and t1.

When the build is done as make -j i.e. parallel but not distributed, this difference is irrelevant because all make targets are run on the same machine i.e. all the make instances access the same filesystem.

But let's consider what could?/does? happen during a distributed build if the two targets are built on two separate machines

In both makefiles, the recipe for t2 would be run AFTER the recipe for a.txt/t1.

However, in makefile1 the dependency of t2 on a.txt is explicit i.e. distcc knows that to make t2 on a separate machine, it must send the file a.txt to that separate machine.

QUESTION

If makefile2 is run using distcc, without a synchronized distributed filesystem, and t2 is maked on another machine, will there be a build error because a.txt is not present on the other machine?

What are the options for a distributed Linux filesystem?


问:
When sorting a Angular Material table can you view the data without modifying it?
Angular Material table utilizes a MatTableDataSource method called sortData() to sort the table's data source. (https://material.angular.io/components/table/api#MatTableDataSource). It is an arrow function:

```<code>sortData: ((data: T[], sort: MatSort) => T[])
</code>```

I need to view the sorted data without actually changing the sort. For example,

```<code>this.dataSource.sortData = (sortData) => {
    console.log(sortData);
    return sortData;
};
</code>```

The problem here is that I am overriding the native sort functionality. return sortData returns the original data, without any sorting. All I want to do is observe the sorted data without modifying it. Is it possible to do this?

答:
You could overwrite sortData function:

```<code>this.dataSource.sortData = this.sortData;

...

sortData = function(data: any, sort: MatSort) {
  const active = sort.active;
  const direction = sort.direction;
  if (!active || direction == '') { return data; }

  const sorted = data.sort((a, b) => {
    let valueA = this.sortingDataAccessor(a, active);
    let valueB = this.sortingDataAccessor(b, active);

    // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if
    // one value exists while the other doesn't. In this case, existing value should come last.
    // This avoids inconsistent results when comparing values to undefined/null.
    // If neither value exists, return 0 (equal).
    let comparatorResult = 0;
    if (valueA != null && valueB != null) {
      // Check if one value is greater than the other; if equal, comparatorResult should remain 0.
      if (valueA > valueB) {
        comparatorResult = 1;
      } else if (valueA < valueB) {
        comparatorResult = -1;
      }
    } else if (valueA != null) {
      comparatorResult = 1;
    } else if (valueB != null) {
      comparatorResult = -1;
    }

    return comparatorResult * (direction == 'asc' ? 1 : -1);
  });

  console.log(sorted)
  return sorted;
}
</code>```

As you can see, I barely changed the original function. Add removed types as per your needs.

p.s. overwriting some of the functions inside MatTableDataSource is a common practise:

May be overridden for a custom implementation of data ordering.

Body:
Angular Material table utilizes a MatTableDataSource method called sortData() to sort the table's data source. (https://material.angular.io/components/table/api#MatTableDataSource). It is an arrow function:

sortData: ((data: T[], sort: MatSort) => T[])

I need to view the sorted data without actually changing the sort. For example,

this.dataSource.sortData = (sortData) => {
    console.log(sortData);
    return sortData;
};

The problem here is that I am overriding the native sort functionality. return sortData returns the original data, without any sorting. All I want to do is observe the sorted data without modifying it. Is it possible to do this?

Body:
You could overwrite sortData function:

this.dataSource.sortData = this.sortData;

...

sortData = function(data: any, sort: MatSort) {
  const active = sort.active;
  const direction = sort.direction;
  if (!active || direction == '') { return data; }

  const sorted = data.sort((a, b) => {
    let valueA = this.sortingDataAccessor(a, active);
    let valueB = this.sortingDataAccessor(b, active);

    // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if
    // one value exists while the other doesn't. In this case, existing value should come last.
    // This avoids inconsistent results when comparing values to undefined/null.
    // If neither value exists, return 0 (equal).
    let comparatorResult = 0;
    if (valueA != null && valueB != null) {
      // Check if one value is greater than the other; if equal, comparatorResult should remain 0.
      if (valueA > valueB) {
        comparatorResult = 1;
      } else if (valueA < valueB) {
        comparatorResult = -1;
      }
    } else if (valueA != null) {
      comparatorResult = 1;
    } else if (valueB != null) {
      comparatorResult = -1;
    }

    return comparatorResult * (direction == 'asc' ? 1 : -1);
  });

  console.log(sorted)
  return sorted;
}

As you can see, I barely changed the original function. Add removed types as per your needs.

p.s. overwriting some of the functions inside MatTableDataSource is a common practise:

May be overridden for a custom implementation of data ordering.


问:
Differences between Agile, Incremental and Waterfall development model?
What is the key difference between agile and Incremental and waterfall models?
As a beginner software developer what model should I follow?
I need to be clear.  </p>

答:
Waterfall is sequential while agile is an incremental approach.

Waterfall: Conception, initiation, analysis, design, construction, testing, implementation and maintenance. All eight steps will be done in sequential manner (one after another). Once a step is completed, you can’t go back to the previous step. If you make a little change, the whole project will start from zero. So, there's no room for error or change.

When to use waterfall:

If the client has complete knowledge of what they want (size, cost & timeline of project), then go for waterfall.

Advantages:

If any employer leaves the job, the new employer will suddenly grip down the project as all the steps are sequential, so new resources will easily understand the current situation of the project.

Client knows what the final product will look like.

Disadvantages:

If one step is completed, you cannot go back.

Waterfalls demand heavy initial requirements, false requirements will lead your project to somewhere else, not to destination.

If any error is found or any change needs to be made, the project has to start from the beginning.

The whole project is only tested at the end, if bugs are written early but discovered late, their existence may have affected how other code was written.

Agile: Developers start with simple design and then begin to work on small modules. The work on these modules is done on a weekly or monthly basis. After completion of a module, module sent to testing phase, and if any bug comes, then developer first removes that bug and then result is deployed in order to take client review, if client demands any change then first developer has to implement that change.  At the end of each module, project priorities are evaluated, on which module we should start work.

When to use agile:

When rapid production is more important than the quality of the product.

When there's no clear picture of what the final product looks like.

Advantages:

Each module is tested after its completion that trains developers not to make such mistakes in the next module.

Agile allows developers and clients to add change at any time.

After each module, the client reviews the application, so the client knows about the progress of the project after each module.

Disadvantages:

It highly demands the successful project manager. As making modules, prioritizing them and setting time period of a module really requires a lot of experience.

As no one has initial requirements, so the final product can be grossly different than what was initially intended.


问:
Expo in-app-purchases: ReferenceError: Can't find variable: connectAsync
I'm trying to follow along with expo's in app purchases documentation.. I have the android developer account and set up my in-app-purchase on that account for the same app. I'm just trying to get started with the documentation and receive an error immediately.

If you look at the documentation, I'm just trying to enter in what's in the first example. I call this function at the beginning of the render method of my app.

```<code>import * as InAppPurchases from 'expo-in-app-purchases';
...

const getHistory = async function(){
  const history = await connectAsync();
    if (history.responseCode === IAPResponseCode.OK) {
      history.results.forEach(result => {
        console.log(result)
      });
    }
}
</code>```

And I receive these errors

```<code>[Unhandled promise rejection: ReferenceError: Can't find variable: connectAsync]
* App.js:57:19 in getHistory
- node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:271:30 in invoke
- node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:135:28 in invoke
- node_modules/regenerator-runtime/runtime.js:170:17 in Promise$argument_0
- node_modules/promise/setimmediate/core.js:45:7 in tryCallTwo

...
</code>```

答:
Since you used:

```<code>import * as InAppPurchases from 'expo-in-app-purchases';
</code>```

That means your code should look like:
...

```<code>const getHistory = async function(){
  const history = await InAppPurchases.connectAsync();
    if (history.responseCode === InAppPurchases.IAPResponseCode.OK) {
      history.results.forEach(result => {
        console.log(result)
      });
    }
}
</code>```

Body:
I'm trying to follow along with expo's in app purchases documentation.. I have the android developer account and set up my in-app-purchase on that account for the same app. I'm just trying to get started with the documentation and receive an error immediately.

If you look at the documentation, I'm just trying to enter in what's in the first example. I call this function at the beginning of the render method of my app.

import * as InAppPurchases from 'expo-in-app-purchases';
...

const getHistory = async function(){
  const history = await connectAsync();
    if (history.responseCode === IAPResponseCode.OK) {
      history.results.forEach(result => {
        console.log(result)
      });
    }
}

And I receive these errors

[Unhandled promise rejection: ReferenceError: Can't find variable: connectAsync]
* App.js:57:19 in getHistory
- node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:271:30 in invoke
- node_modules/regenerator-runtime/runtime.js:45:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:135:28 in invoke
- node_modules/regenerator-runtime/runtime.js:170:17 in Promise$argument_0
- node_modules/promise/setimmediate/core.js:45:7 in tryCallTwo

...

Body:
Since you used:

import * as InAppPurchases from 'expo-in-app-purchases';

That means your code should look like:
...

const getHistory = async function(){
  const history = await InAppPurchases.connectAsync();
    if (history.responseCode === InAppPurchases.IAPResponseCode.OK) {
      history.results.forEach(result => {
        console.log(result)
      });
    }
}