问:
Font awesome icon not changing in response to the slider change
I'm trying to change the icon in response to the volume control (range) element and can't make it work.

My html is:

```<code><div class="slidercontainer fs-4" id="slider-container">
    <span style="color:white;">    </span>
    <span class="badge rounded-pill bg-warning">Audio Volume</span>
    <span style="color:white;">    </span>

    <i id="volume_low" class="fa fa-volume-down fa-2x"></i>
    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">
    <i id="volume-up" class="fa fa-volume-up fa-2x"></i>

  </div>
</code>```

... and it is shown correctly in a browser

My javascript is:

```<code>// for slider
const slider = document.querySelector("#myRange");

$("#myRange").on("input change", function()
{
  const sliderValue = slider.value;
  if(sliderValue==0){
    console.log('zero', sliderValue );
    $('#volume_low').find("i").toggleClass("fa fa-volume-off fa-2x fa fa-volume-down fa-2x");
  }else
  {
    console.log('nonzero', sliderValue);
    $('#volume_low').find("i").toggleClass("fa fa-volume-down fa-2x fa fa-volume-off fa-2x");
  }

});

// end of for slider
</code>```

Doesn't work (icon not changing in the leftmost position as required), not showing any errors

答:
You did mistake targeting the i.

No need .find("i") because you already did it with $('#volume_low')

// for slider
const slider = document.querySelector("#myRange");

$("#myRange").on("input change", function() {
  const sliderValue = slider.value;
  if (sliderValue == 0) {
    console.log('zero', sliderValue );
    $('#volume_low').removeClass('fa-volume-down').addClass("fa-volume-off");
  } else {
    console.log('nonzero', sliderValue);
    $('#volume_low').removeClass('fa-volume-off').addClass("fa-volume-down");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="slidercontainer fs-4" id="slider-container">
    <span style="color:white;">    </span>
    <span class="badge rounded-pill bg-warning">Audio Volume</span>
    <span style="color:white;">    </span>

    <i id="volume_low" class="fa fa-volume-down fa-2x"></i>
    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">
    <i id="volume-up" class="fa fa-volume-up fa-2x"></i>

  </div></code>```

Body:
I'm trying to change the icon in response to the volume control (range) element and can't make it work.

My html is:

    Audio Volume

    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">

... and it is shown correctly in a browser

My javascript is:

// for slider
const slider = document.querySelector("#myRange");

$("#myRange").on("input change", function()
{
  const sliderValue = slider.value;
  if(sliderValue==0){
    console.log('zero', sliderValue );
    $('#volume_low').find("i").toggleClass("fa fa-volume-off fa-2x fa fa-volume-down fa-2x");
  }else
  {
    console.log('nonzero', sliderValue);
    $('#volume_low').find("i").toggleClass("fa fa-volume-down fa-2x fa fa-volume-off fa-2x");
  }

});

// end of for slider

Doesn't work (icon not changing in the leftmost position as required), not showing any errors

Body:
You did mistake targeting the i.

No need .find("i") because you already did it with $('#volume_low')

// for slider
const slider = document.querySelector("#myRange");

$("#myRange").on("input change", function() {
  const sliderValue = slider.value;
  if (sliderValue == 0) {
    console.log('zero', sliderValue );
    $('#volume_low').removeClass('fa-volume-down').addClass("fa-volume-off");
  } else {
    console.log('nonzero', sliderValue);
    $('#volume_low').removeClass('fa-volume-off').addClass("fa-volume-down");
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class="slidercontainer fs-4" id="slider-container">
    <span style="color:white;">&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <span class="badge rounded-pill bg-warning">Audio Volume</span>
    <span style="color:white;">&nbsp;&nbsp;&nbsp;&nbsp;</span>

    <i id="volume_low" class="fa fa-volume-down fa-2x"></i>
    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">
    <i id="volume-up" class="fa fa-volume-up fa-2x"></i>

  </div>


来源: stackexchange

问:
dbExpress design question
Does anybody know (or care to make a suppostion as to) why TSqlDataset has a commandtext property (string) whereas TSqlQuery has a sql property (tstrings)?

Consider the sql statement

```<code>select id, name from
table
order by name
</code>```

If I use a TSqlQuery, then I can change the table name in the query dynamically by accessing sql[1], but if I am using a TSqlDataset (as I have to if I need a bidrectional dataset, the dataset is connected to a provider and thence to a tclientdataset), I have to set the commandtext string literally. Whilst the above example is trivial, it can be a problem when the sql statement is much more involved.

Update:
Judging by the comments and answers so far, it seems that I was misunderstood. I don't care very much for improving the runtime performance of the components (what does one millisecond matter when the query takes one second) but I do care about the programmer (ie me) and the ability to maintain the program. In real life, I have the following query which is stored in a TSqlQuery:

```<code>select dockets.id, dockets.opendate, customers.name, statuses.statname,
dockets.totalcost, dockets.whopays, dockets.expected, dockets.urgent,
(dockets.totalcost - dockets.billed) as openbill,
(dockets.totalcost - dockets.paid) as opencost,
location.name as locname, dockets.attention,
statuses.colour, statuses.disporder, statuses.future, dockets.urgcomment
from location, statuses, dockets left join customers
on dockets.customer = customers.id
where dockets.location = location.id
and dockets.status = statuses.id
</code>```

I haven't counted the number of characters in the string, but I'm sure that there are more than 255, thus precluding storing the query in a simple string. In certain circumstances, I want to filter the amount of data being displayed by adding the line 'and statuses.id = 3' or 'and customers.id = 249'. If the query were stored as TStrings, then I could add to the basic query the dummy line 'and 1 = 1', and then update this line as needed. But the query is one long string and I can't easily access the end of it.

What I am currently doing (in lieu of a better solution) is creating another TSqlDataSet, and setting its commandtext to the default TSqlDataSet's commandtext whilst appending the extra condition.

答:
1) TSQLQuery is rather for compatibility with BDE TQuery. And BDE TQuery has SQL: TStrings property. TSQLDataSet is what supposed to be used for new applications.

2) Although SQL: TStrings is usefull for some tasks, it is also error prone. Often programmers forget to clear SQL property before filling again. Also if your query is a big one, the filling of SQL may lead to performance degradation. Because on each SQL.Add(...) call dbExpress code parses query when ParamCheck is True. That may be solved by using BeginUpdate / EndUpdate or setting ParamCheck to False. But note, setting ParamCheck to False stops automatic parameters creation.

```<code>SQLQuery1.SQL.BeginUpdate;
try
  SQLQuery1.SQL.Clear;
  SQLQuery1.SQL.Add('SELECT * FROM');
  SQLQuery1.SQL.Add('Orders');
finally
  SQLQuery1.SQL.EndUpdate;
end;
</code>```

CommandText does not have such issues.

3) You can use Format function for building a dynamic SQL string:

```<code>var
  sTableName: String;
...
sTableName := 'Orders';
SQLDataSet1.CommandText := Format('select * from %s', [sTableName]);
</code>```

4) Other data access libraries, like AnyDAC, have macro variables, simplifying dynamic query text building. For example:

```<code>ADQuery1.SQL.Text := 'SELECT * FROM &TabName';
ADQuery1.Macros[0].AsRaw := 'Orders';
ADQuery1.Open;
</code>```

ContentLicense: CC BY-SA 3.0

Title: dbExpress design question

Body:
Does anybody know (or care to make a suppostion as to) why TSqlDataset has a commandtext property (string) whereas TSqlQuery has a sql property (tstrings)?

Consider the sql statement

select id, name from
table
order by name

If I use a TSqlQuery, then I can change the table name in the query dynamically by accessing sql[1], but if I am using a TSqlDataset (as I have to if I need a bidrectional dataset, the dataset is connected to a provider and thence to a tclientdataset), I have to set the commandtext string literally. Whilst the above example is trivial, it can be a problem when the sql statement is much more involved.

Update:
Judging by the comments and answers so far, it seems that I was misunderstood. I don't care very much for improving the runtime performance of the components (what does one millisecond matter when the query takes one second) but I do care about the programmer (ie me) and the ability to maintain the program. In real life, I have the following query which is stored in a TSqlQuery:

select dockets.id, dockets.opendate, customers.name, statuses.statname,
dockets.totalcost, dockets.whopays, dockets.expected, dockets.urgent,
(dockets.totalcost - dockets.billed) as openbill,
(dockets.totalcost - dockets.paid) as opencost,
location.name as locname, dockets.attention,
statuses.colour, statuses.disporder, statuses.future, dockets.urgcomment
from location, statuses, dockets left join customers
on dockets.customer = customers.id
where dockets.location = location.id
and dockets.status = statuses.id

I haven't counted the number of characters in the string, but I'm sure that there are more than 255, thus precluding storing the query in a simple string. In certain circumstances, I want to filter the amount of data being displayed by adding the line 'and statuses.id = 3' or 'and customers.id = 249'. If the query were stored as TStrings, then I could add to the basic query the dummy line 'and 1 = 1', and then update this line as needed. But the query is one long string and I can't easily access the end of it.

What I am currently doing (in lieu of a better solution) is creating another TSqlDataSet, and setting its commandtext to the default TSqlDataSet's commandtext whilst appending the extra condition.

Body:
1) TSQLQuery is rather for compatibility with BDE TQuery. And BDE TQuery has SQL: TStrings property. TSQLDataSet is what supposed to be used for new applications.

2) Although SQL: TStrings is usefull for some tasks, it is also error prone. Often programmers forget to clear SQL property before filling again. Also if your query is a big one, the filling of SQL may lead to performance degradation. Because on each SQL.Add(...) call dbExpress code parses query when ParamCheck is True. That may be solved by using BeginUpdate / EndUpdate or setting ParamCheck to False. But note, setting ParamCheck to False stops automatic parameters creation.

SQLQuery1.SQL.BeginUpdate;
try
  SQLQuery1.SQL.Clear;
  SQLQuery1.SQL.Add('SELECT * FROM');
  SQLQuery1.SQL.Add('Orders');
finally
  SQLQuery1.SQL.EndUpdate;
end;

CommandText does not have such issues.

3) You can use Format function for building a dynamic SQL string:

var
  sTableName: String;
...
sTableName := 'Orders';
SQLDataSet1.CommandText := Format('select * from %s', [sTableName]);

4) Other data access libraries, like AnyDAC, have macro variables, simplifying dynamic query text building. For example:

ADQuery1.SQL.Text := 'SELECT * FROM &TabName';
ADQuery1.Macros[0].AsRaw := 'Orders';
ADQuery1.Open;


问:
Store files on mongodb database or server
I have a website built on MongoDB which has files to be downloaded by users other than images ( it can be a software installer or .exe file .msi file or .blender file ) I mean different file formats.

How can you store such files on the server so that users can download them? As an example software companies have their software on servers that we as users can download. How do they store the on server if they use MongoDB?

答: MongoDB is in general document store , and it is best practice to store just a link in mongoDB , but keep the file content in file system,  ftp , sftp, s3 , cloud object storage  etc. If you anyway want to store files in mongoDB you can still do it , but you are facing the default max document size limit of 16MB so you need to use the special file storage API -> gridFS to overcome this limit for files bigger than 16MB.</p>

ContentLicense: CC BY-SA 4.0


问:
Getting unique values from an Array for use in ListItem
I have an array of objects that contains the location of each user.  I'm trying to group them by location and use that as the title in my react native component but I'm having difficulty filtering on the location property and could use a push in the right direction.

Here's a sample of the array:

```<code>const Users = [
    {
        id: 1,
        name: "user1",
        image: require("../assets/1.jpeg"),
        location: "Portland"
    },
    {
        id: 2,
        name: "user2",
        image: require("../assets/2.jpeg"),
        location: "Portland"
    },
    {
        id: 3,
        name: "user3",
        image: require("../assets/3.jpeg"),
        location: "New York"
    },
    {
        id: 4,
        name: "user4",
        image: require("../assets/4.jpeg"),
        location: "Pullman"
    },
    {
        id: 5,
        name: "user5",
        image: require("../assets/5.jpeg"),
        location: "Portland"
    },
    {
        id: 6,
        name: "user6",
        image: require("../assets/6.jpeg"),
        location: "San Francisco"
    },
    {
        id: 7,
        name: "user7",
        image: require("../assets/7.jpeg"),
        location: "Pullman"
    },
];
</code>```

This is the component. I've tried both filter and reduce methods but I get the same duplicate results because it's evaluating the entire object. I want to return only the unique values of the location property.

```<code>const userItems = ({ item }) => {
    return (
        <>
            <ThemeProvider theme={ListItemTheme}>
                <View>
                    {Users.filter(
                        (currentValue, index, arr) => arr.indexOf(currentValue) === index
                    ).map((user) => (
                        <View style={styles.userContainer}>
                            <ListItem.Title key={user.id}>{user.location}</ListItem.Title>
                        </View>
                    ))}
                </View>
            </ThemeProvider>
        </>
    );
};
</code>```

try with reduce method.

```<code>const userItems = ({ item }) => {
    return (
        <>
            <ThemeProvider theme={ListItemTheme}>
                <View>
                    {Users.reduce(
                        (acc, currentValue) =>
                            acc.includes(currentValue.location)
                                ? acc
                                : [...acc, currentValue],
                        []
                    ).map((user) => (
                        <View style={styles.userContainer}>
                            <ListItem.Title key={user.id}>{user.location}</ListItem.Title>
                        </View>
                    ))}
                </View>
            </ThemeProvider>
        </>
    );
};
</code>```

答:
Edit I misunderstood the question, I would suggest using reduce.

note I made all require statements a string for this example to run

const Users = [{
    id: 1,
    name: "user1",
    image: 'require("../assets/1.jpeg")',
    location: "Portland"
  },
  {
    id: 2,
    name: "user2",
    image: 'require("../assets/2.jpeg")',
    location: "Portland"
  },
  {
    id: 3,
    name: "user3",
    image: 'require("../assets/3.jpeg")',
    location: "New York"
  },
  {
    id: 4,
    name: "user4",
    image: 'require("../assets/4.jpeg")',
    location: "Pullman"
  },
  {
    id: 5,
    name: "user5",
    image: 'require("../assets/5.jpeg")',
    location: "Portland"
  },
  {
    id: 6,
    name: "user6",
    image: 'require("../assets/6.jpeg")',
    location: "San Francisco"
  },
  {
    id: 7,
    name: "user7",
    image: 'require("../assets/7.jpeg")',
    location: "Pullman"
  },
];

console.log(Users.reduce((acc, val) => {
  acc[val.location] = acc[val.location] ? [...acc[val.location], val] : [val];
  return acc
}, {}))```
</div>
</div>
</p>
<p>And something like this in the component?</p>
```const userItems = ({ item }) => {
 const users = Users.reduce((acc, val) => {
      acc[val.location] = acc[val.location] ? [...acc[val.location], val] : [val];
      return acc
    }, {})

    return (
     <>
      <ThemeProvider theme={ListItemTheme}>
         <View>
          {Object.keys(users).map((key) => (
           <View style={styles.userContainer}>
             {users[key].map((user) => (
             <ListItem.Title key={user.id}>{key}</ListItem.Title>
             // >>>.....more user info stuff
             ))}
           </View>
           ))}
         </View>
      </ThemeProvider>
    </>
    );
};
```

Body:
I have an array of objects that contains the location of each user.  I'm trying to group them by location and use that as the title in my react native component but I'm having difficulty filtering on the location property and could use a push in the right direction.

Here's a sample of the array:

const Users = [
    {
        id: 1,
        name: "user1",
        image: require("../assets/1.jpeg"),
        location: "Portland"
    },
    {
        id: 2,
        name: "user2",
        image: require("../assets/2.jpeg"),
        location: "Portland"
    },
    {
        id: 3,
        name: "user3",
        image: require("../assets/3.jpeg"),
        location: "New York"
    },
    {
        id: 4,
        name: "user4",
        image: require("../assets/4.jpeg"),
        location: "Pullman"
    },
    {
        id: 5,
        name: "user5",
        image: require("../assets/5.jpeg"),
        location: "Portland"
    },
    {
        id: 6,
        name: "user6",
        image: require("../assets/6.jpeg"),
        location: "San Francisco"
    },
    {
        id: 7,
        name: "user7",
        image: require("../assets/7.jpeg"),
        location: "Pullman"
    },
];

This is the component. I've tried both filter and reduce methods but I get the same duplicate results because it's evaluating the entire object. I want to return only the unique values of the location property.

const userItems = ({ item }) => {
    return (
        <>
            <ThemeProvider theme={ListItemTheme}>
                <View>
                    {Users.filter(
                        (currentValue, index, arr) => arr.indexOf(currentValue) === index
                    ).map((user) => (
                        <View style={styles.userContainer}>
                            <ListItem.Title key={user.id}>{user.location}</ListItem.Title>
                        </View>
                    ))}
                </View>
            </ThemeProvider>
        </>
    );
};

try with reduce method.

const userItems = ({ item }) => {
    return (
        <>
            <ThemeProvider theme={ListItemTheme}>
                <View>
                    {Users.reduce(
                        (acc, currentValue) =>
                            acc.includes(currentValue.location)
                                ? acc
                                : [...acc, currentValue],
                        []
                    ).map((user) => (
                        <View style={styles.userContainer}>
                            <ListItem.Title key={user.id}>{user.location}</ListItem.Title>
                        </View>
                    ))}
                </View>
            </ThemeProvider>
        </>
    );
};

Body:
Edit I misunderstood the question, I would suggest using reduce.

note I made all require statements a string for this example to run

const Users = [{
    id: 1,
    name: "user1",
    image: 'require("../assets/1.jpeg")',
    location: "Portland"
  },
  {
    id: 2,
    name: "user2",
    image: 'require("../assets/2.jpeg")',
    location: "Portland"
  },
  {
    id: 3,
    name: "user3",
    image: 'require("../assets/3.jpeg")',
    location: "New York"
  },
  {
    id: 4,
    name: "user4",
    image: 'require("../assets/4.jpeg")',
    location: "Pullman"
  },
  {
    id: 5,
    name: "user5",
    image: 'require("../assets/5.jpeg")',
    location: "Portland"
  },
  {
    id: 6,
    name: "user6",
    image: 'require("../assets/6.jpeg")',
    location: "San Francisco"
  },
  {
    id: 7,
    name: "user7",
    image: 'require("../assets/7.jpeg")',
    location: "Pullman"
  },
];

console.log(Users.reduce((acc, val) => {
  acc[val.location] = acc[val.location] ? [...acc[val.location], val] : [val];
  return acc
}, {}))

And something like this in the component?

const userItems = ({ item }) => {
 const users = Users.reduce((acc, val) => {
      acc[val.location] = acc[val.location] ? [...acc[val.location], val] : [val];
      return acc
    }, {})

    return (
     <>
      <ThemeProvider theme={ListItemTheme}>
         <View>
          {Object.keys(users).map((key) => (
           <View style={styles.userContainer}>
             {users[key].map((user) => (
             <ListItem.Title key={user.id}>{key}</ListItem.Title>
             // >>>.....more user info stuff
             ))}
           </View>
           ))}
         </View>
      </ThemeProvider>
    </>
    );
};


问:
Calculate date & time difference between two cells (DD.MM.YYYY HH:MM:SS)

I am trying to find the difference in datetime between two cells from an imported data file.

I cannot seem to find the correct formula with the formatting.

DD.MM.YYYY HH:MM:SS

Is there anything I can do to help calculate without getting a #VALUE error? Attached below is a sample - the imported files often contain hundreds of entries.

答:
As You have DD.MM.YYYY format,</p>
```<code>=DATEDIF(SUBSTITUTE( A2,".","/"), SUBSTITUTE(B2,".","/"),"y")&" years, "&DATEDIF(SUBSTITUTE(A2,".","/"),SUBSTITUTE(B2,".","/"),"ym")&" months, "&DATEDIF(SUBSTITUTE(A2,".","/"),SUBSTITUTE(B2,".","/"),"md")&" days, "&HOUR(SUBSTITUTE(B2,".","/") -SUBSTITUTE(A2,".","/") )&" hours, "&MINUTE(SUBSTITUTE(B2,".","/") -SUBSTITUTE(A2,".","/") )&" minutes and "&SECOND(SUBSTITUTE(B2,".","/") -SUBSTITUTE(A2,".","/") )&" seconds"
</code>```

Body:
As You have DD.MM.YYYY format,

=DATEDIF(SUBSTITUTE( A2,".","/"), SUBSTITUTE(B2,".","/"),"y")&" years, "&DATEDIF(SUBSTITUTE(A2,".","/"),SUBSTITUTE(B2,".","/"),"ym")&" months, "&DATEDIF(SUBSTITUTE(A2,".","/"),SUBSTITUTE(B2,".","/"),"md")&" days, "&HOUR(SUBSTITUTE(B2,".","/") -SUBSTITUTE(A2,".","/") )&" hours, "&MINUTE(SUBSTITUTE(B2,".","/") -SUBSTITUTE(A2,".","/") )&" minutes and "&SECOND(SUBSTITUTE(B2,".","/") -SUBSTITUTE(A2,".","/") )&" seconds"


问:
How to change JFreeChart vertical bar to a solid color?
I have the following sample code for a JFreeChart, how to change the vertical bars to a solid color [ right now it has some white color in each bar ] ?

```<code>import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.date.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;

public class Price_Volume_Chart_Demo extends JPanel                                       // A demonstration application showing how to create a price-volume chart.
{
  static boolean EXIT_ON_CLOSE_B=true;

  public Price_Volume_Chart_Demo(String title)
  {
    JFreeChart chart=createChart();
    ChartPanel panel=new ChartPanel(chart,true,true,true,false,true);
    panel.setPreferredSize(new java.awt.Dimension(1000,500));
    add(panel);
  }

  private JFreeChart createChart()
  {
    XYDataset priceData=createPriceDataset();
    String title="Eurodollar Futures Contract (MAR03)";
    JFreeChart chart=ChartFactory.createTimeSeriesChart(title,
                                                        "Date",
                                                        getYLabel("Price ( $ )"),
                                                        priceData,
                                                        true,
                                                        true,
                                                        true
                                                       );
    XYPlot plot=chart.getXYPlot();
    NumberAxis rangeAxis1=(NumberAxis)plot.getRangeAxis();
    rangeAxis1.setLowerMargin(0.40);  // to leave room for volume bars
    DecimalFormat format=new DecimalFormat("00.00");
    rangeAxis1.setNumberFormatOverride(format);

    XYItemRenderer renderer1=plot.getRenderer();
    /*
            renderer1.setToolTipGenerator(
                new StandardXYToolTipGenerator(
                    StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")
                )
            );
     */
    NumberAxis rangeAxis2=new NumberAxis("Volume");
    rangeAxis2.setUpperMargin(1.00);  // to leave room for price line
    plot.setRangeAxis(1,rangeAxis2);
    plot.setDataset(1,createVolumeDataset());
    plot.setRangeAxis(1,rangeAxis2);
    plot.mapDatasetToRangeAxis(1,1);
    XYBarRenderer renderer2=new XYBarRenderer(0.20);
    renderer2.setShadowVisible(false);
    /*
            renderer2.setToolTipGenerator(
                new StandardXYToolTipGenerator(
                    StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0,000.00")
                )
            );
     */
    plot.setRenderer(1,renderer2);
    return chart;
  }

  private static XYDataset createPriceDataset()
  {
    // create dataset 1...
    TimeSeries series1=new TimeSeries("Price");

    series1.add(new Day(2,MonthConstants.JANUARY,2002),95.565);
    series1.add(new Day(3,MonthConstants.JANUARY,2002),95.640);
    series1.add(new Day(4,MonthConstants.JANUARY,2002),95.710);

    series1.add(new Day(7,MonthConstants.JANUARY,2002),95.930);
    series1.add(new Day(8,MonthConstants.JANUARY,2002),95.930);
    series1.add(new Day(9,MonthConstants.JANUARY,2002),95.960);
    series1.add(new Day(10,MonthConstants.JANUARY,2002),96.055);
    series1.add(new Day(11,MonthConstants.JANUARY,2002),96.335);

    series1.add(new Day(14,MonthConstants.JANUARY,2002),96.290);
    series1.add(new Day(15,MonthConstants.JANUARY,2002),96.275);
    series1.add(new Day(16,MonthConstants.JANUARY,2002),96.240);
    series1.add(new Day(17,MonthConstants.JANUARY,2002),96.080);
    series1.add(new Day(18,MonthConstants.JANUARY,2002),96.145);

    return new TimeSeriesCollection(series1);
  }

  private static IntervalXYDataset createVolumeDataset()
  {
    // create dataset 2...
    TimeSeries series1=new TimeSeries("Volume");

    series1.add(new Day(2,MonthConstants.JANUARY,2002),41020);
    series1.add(new Day(3,MonthConstants.JANUARY,2002),45586);
    series1.add(new Day(4,MonthConstants.JANUARY,2002),81672);

    series1.add(new Day(7,MonthConstants.JANUARY,2002),81975);
    series1.add(new Day(8,MonthConstants.JANUARY,2002),79692);
    series1.add(new Day(9,MonthConstants.JANUARY,2002),53187);
    series1.add(new Day(10,MonthConstants.JANUARY,2002),87929);
    series1.add(new Day(11,MonthConstants.JANUARY,2002),107047);

    series1.add(new Day(14,MonthConstants.JANUARY,2002),86276);
    series1.add(new Day(15,MonthConstants.JANUARY,2002),79005);
    series1.add(new Day(16,MonthConstants.JANUARY,2002),80632);
    series1.add(new Day(17,MonthConstants.JANUARY,2002),88797);
    series1.add(new Day(18,MonthConstants.JANUARY,2002),57179);

    return new TimeSeriesCollection(series1);
  }

  String getYLabel(String Text)
  {
    String Result="";

    for (int i=0;i<Text.length();i++) Result+=Text.charAt(i)+(i<Text.length()-1?"\u2009":"");
//    Out(Result);
    return Result;
  }

  private static void out(String message) { System.out.print(message); }
  private static void Out(String message) { System.out.println(message); }

  // Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
  static void Create_And_Show_GUI()
  {
    final Price_Volume_Chart_Demo demo=new Price_Volume_Chart_Demo("Price Volume Chart Demo");

    JFrame frame=new JFrame("Time_Series_Chart Frame");
    frame.add(demo);
    frame.addWindowListener( new WindowAdapter()
    {
      public void windowActivated(WindowEvent e) { }
      public void windowClosed(WindowEvent e) { }
      public void windowClosing(WindowEvent e) { if (EXIT_ON_CLOSE_B) System.exit(0); }
      public void windowDeactivated(WindowEvent e) { }
      public void windowDeiconified(WindowEvent e) { demo.repaint(); }
      public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
      public void windowIconified(WindowEvent e) { }
      public void windowLostFocus(WindowEvent e) { }
      public void windowOpening(WindowEvent e) { demo.repaint(); }
      public void windowOpened(WindowEvent e) { }
      public void windowResized(WindowEvent e) { demo.repaint(); }
      public void windowStateChanged(WindowEvent e) { demo.repaint(); }
    });
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  public static void main(String[] args)
  {
    // Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } });
  }
}
</code>```

答:
As shown here, use a StandardXYBarPainter to get a flat effect instead of the default gradient.

```<code>XYBarRenderer renderer2=new XYBarRenderer(0.20);
renderer2.setBarPainter(new StandardXYBarPainter());
renderer2.setShadowVisible(false);
</code>```

I tried, but didn't work: renderer2.setDefaultBarPainter(new StandardXYBarPainter()).

Note that XYBarRenderer.setDefaultBarPainter() is a static method. It should be called before instantiating the renderer.

```<code>XYBarRenderer.setDefaultBarPainter(new StandardXYBarPainter());
XYBarRenderer renderer2=new XYBarRenderer(0.20);
</code>```

Either formulation produces the desired result:

As an aside, plot.setRangeAxis(1,rangeAxis2) needs to be called only once.

Body:
I have the following sample code for a JFreeChart, how to change the vertical bars to a solid color [ right now it has some white color in each bar ] ?

import java.awt.event.*;
import java.text.DecimalFormat;
import javax.swing.*;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.date.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;

public class Price_Volume_Chart_Demo extends JPanel                                       // A demonstration application showing how to create a price-volume chart.
{
  static boolean EXIT_ON_CLOSE_B=true;

  public Price_Volume_Chart_Demo(String title)
  {
    JFreeChart chart=createChart();
    ChartPanel panel=new ChartPanel(chart,true,true,true,false,true);
    panel.setPreferredSize(new java.awt.Dimension(1000,500));
    add(panel);
  }

  private JFreeChart createChart()
  {
    XYDataset priceData=createPriceDataset();
    String title="Eurodollar Futures Contract (MAR03)";
    JFreeChart chart=ChartFactory.createTimeSeriesChart(title,
                                                        "Date",
                                                        getYLabel("Price ( $ )"),
                                                        priceData,
                                                        true,
                                                        true,
                                                        true
                                                       );
    XYPlot plot=chart.getXYPlot();
    NumberAxis rangeAxis1=(NumberAxis)plot.getRangeAxis();
    rangeAxis1.setLowerMargin(0.40);  // to leave room for volume bars
    DecimalFormat format=new DecimalFormat("00.00");
    rangeAxis1.setNumberFormatOverride(format);

    XYItemRenderer renderer1=plot.getRenderer();
    /*
            renderer1.setToolTipGenerator(
                new StandardXYToolTipGenerator(
                    StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")
                )
            );
     */
    NumberAxis rangeAxis2=new NumberAxis("Volume");
    rangeAxis2.setUpperMargin(1.00);  // to leave room for price line
    plot.setRangeAxis(1,rangeAxis2);
    plot.setDataset(1,createVolumeDataset());
    plot.setRangeAxis(1,rangeAxis2);
    plot.mapDatasetToRangeAxis(1,1);
    XYBarRenderer renderer2=new XYBarRenderer(0.20);
    renderer2.setShadowVisible(false);
    /*
            renderer2.setToolTipGenerator(
                new StandardXYToolTipGenerator(
                    StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0,000.00")
                )
            );
     */
    plot.setRenderer(1,renderer2);
    return chart;
  }

  private static XYDataset createPriceDataset()
  {
    // create dataset 1...
    TimeSeries series1=new TimeSeries("Price");

    series1.add(new Day(2,MonthConstants.JANUARY,2002),95.565);
    series1.add(new Day(3,MonthConstants.JANUARY,2002),95.640);
    series1.add(new Day(4,MonthConstants.JANUARY,2002),95.710);

    series1.add(new Day(7,MonthConstants.JANUARY,2002),95.930);
    series1.add(new Day(8,MonthConstants.JANUARY,2002),95.930);
    series1.add(new Day(9,MonthConstants.JANUARY,2002),95.960);
    series1.add(new Day(10,MonthConstants.JANUARY,2002),96.055);
    series1.add(new Day(11,MonthConstants.JANUARY,2002),96.335);

    series1.add(new Day(14,MonthConstants.JANUARY,2002),96.290);
    series1.add(new Day(15,MonthConstants.JANUARY,2002),96.275);
    series1.add(new Day(16,MonthConstants.JANUARY,2002),96.240);
    series1.add(new Day(17,MonthConstants.JANUARY,2002),96.080);
    series1.add(new Day(18,MonthConstants.JANUARY,2002),96.145);

    return new TimeSeriesCollection(series1);
  }

  private static IntervalXYDataset createVolumeDataset()
  {
    // create dataset 2...
    TimeSeries series1=new TimeSeries("Volume");

    series1.add(new Day(2,MonthConstants.JANUARY,2002),41020);
    series1.add(new Day(3,MonthConstants.JANUARY,2002),45586);
    series1.add(new Day(4,MonthConstants.JANUARY,2002),81672);

    series1.add(new Day(7,MonthConstants.JANUARY,2002),81975);
    series1.add(new Day(8,MonthConstants.JANUARY,2002),79692);
    series1.add(new Day(9,MonthConstants.JANUARY,2002),53187);
    series1.add(new Day(10,MonthConstants.JANUARY,2002),87929);
    series1.add(new Day(11,MonthConstants.JANUARY,2002),107047);

    series1.add(new Day(14,MonthConstants.JANUARY,2002),86276);
    series1.add(new Day(15,MonthConstants.JANUARY,2002),79005);
    series1.add(new Day(16,MonthConstants.JANUARY,2002),80632);
    series1.add(new Day(17,MonthConstants.JANUARY,2002),88797);
    series1.add(new Day(18,MonthConstants.JANUARY,2002),57179);

    return new TimeSeriesCollection(series1);
  }

  String getYLabel(String Text)
  {
    String Result="";

    for (int i=0;i<Text.length();i++) Result+=Text.charAt(i)+(i<Text.length()-1?"\u2009":"");
//    Out(Result);
    return Result;
  }

  private static void out(String message) { System.out.print(message); }
  private static void Out(String message) { System.out.println(message); }

  // Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
  static void Create_And_Show_GUI()
  {
    final Price_Volume_Chart_Demo demo=new Price_Volume_Chart_Demo("Price Volume Chart Demo");

    JFrame frame=new JFrame("Time_Series_Chart Frame");
    frame.add(demo);
    frame.addWindowListener( new WindowAdapter()
    {
      public void windowActivated(WindowEvent e) { }
      public void windowClosed(WindowEvent e) { }
      public void windowClosing(WindowEvent e) { if (EXIT_ON_CLOSE_B) System.exit(0); }
      public void windowDeactivated(WindowEvent e) { }
      public void windowDeiconified(WindowEvent e) { demo.repaint(); }
      public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
      public void windowIconified(WindowEvent e) { }
      public void windowLostFocus(WindowEvent e) { }
      public void windowOpening(WindowEvent e) { demo.repaint(); }
      public void windowOpened(WindowEvent e) { }
      public void windowResized(WindowEvent e) { demo.repaint(); }
      public void windowStateChanged(WindowEvent e) { demo.repaint(); }
    });
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  public static void main(String[] args)
  {
    // Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
    SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } });
  }
}

Body:
As shown here, use a StandardXYBarPainter to get a flat effect instead of the default gradient.

XYBarRenderer renderer2=new XYBarRenderer(0.20);
renderer2.setBarPainter(new StandardXYBarPainter());
renderer2.setShadowVisible(false);

I tried, but didn't work: renderer2.setDefaultBarPainter(new StandardXYBarPainter()).

Note that XYBarRenderer.setDefaultBarPainter() is a static method. It should be called before instantiating the renderer.

XYBarRenderer.setDefaultBarPainter(new StandardXYBarPainter());
XYBarRenderer renderer2=new XYBarRenderer(0.20);

Either formulation produces the desired result:

As an aside, plot.setRangeAxis(1,rangeAxis2) needs to be called only once.


问:
ROR: Mapping array to get value
I need a small help on ROR.

I have a return from a query and when I do puts result.to_a, I have got:

```<code>{"clazz_id"=>1, "staff_id"=>1}
{"clazz_id"=>2, "staff_id"=>1}
{"clazz_id"=>3, "staff_id"=>1}
</code>```

I have like to convert it to an array of [1, 2, 3] from clazz_id and how can I achieve that?

答:
if use Active record query can make this direct pluck

```<code>results.pluck(:clazz_id)
</code>```

if you need deal with array of hash can use map or map! like

```<code>p results.to_a.map{|e| e["clazz_id"] }
</code>```

or can use collect

```<code>p results.to_a.collect{|e| e["clazz_id"] }
</code>```

Title: ROR: Mapping array to get value

Body:
I need a small help on ROR.

I have a return from a query and when I do puts result.to_a, I have got:

{"clazz_id"=>1, "staff_id"=>1}
{"clazz_id"=>2, "staff_id"=>1}
{"clazz_id"=>3, "staff_id"=>1}

I have like to convert it to an array of [1, 2, 3] from clazz_id and how can I achieve that?

Body:
if use Active record query can make this direct pluck

results.pluck(:clazz_id)

if you need deal with array of hash can use map or map! like

p results.to_a.map{|e| e["clazz_id"] }

or can use collect

p results.to_a.collect{|e| e["clazz_id"] }


问:
Change color of bootstrap navbar on hover link?
I want to know how to change the color of the links when you hover over them in the nav bar, as currently they are an ugly color.

Thanks for any suggestions?

HTML:

```<code><div class="container">
    <div class="navbar">
        <div class="navbar-inner">
            <ul class="nav">
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#">Link One</a></li>
                <li><a href="#">Link Two</a></li>
                <li><a href="#">Link Three</a></li>
            </ul>
        </div>
    </div>
</div>
</code>```

答:
This helped me!</p>
```<code>.navbar-light .navbar-nav > li > a:hover,
.navbar-light .navbar-nav > li > a:focus {
    color:  black;
}
</code>```

Body:
I want to know how to change the color of the links when you hover over them in the nav bar, as currently they are an ugly color.

Thanks for any suggestions?

HTML:

Home

Link One

Link Two

Link Three

Body:
This helped me!

.navbar-light .navbar-nav > li > a:hover,
.navbar-light .navbar-nav > li > a:focus {
    color:  black;
}


问:
processing an audio wav file with C
I'm working on processing the amplitude of a wav file and scaling it by some decimal factor. I'm trying to wrap my head around how to read and re-write the file in a memory-efficient way while also trying to tackle the nuances of the language (I'm new to C). The file can be in either an 8- or 16-bit format.  The way I thought of doing this is by first reading the header data into some pre-defined struct, and then processing the actual data in a loop where I'll read a chunk of data into a buffer, do whatever is needed to it, and then write it to the output.

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

typedef struct header
{
    char chunk_id[4];
    int chunk_size;
    char format[4];
    char subchunk1_id[4];
    int subchunk1_size;
    short int audio_format;
    short int num_channels;
    int sample_rate;
    int byte_rate;
    short int block_align;
    short int bits_per_sample;
    short int extra_param_size;
    char subchunk2_id[4];
    int subchunk2_size;
} header;

typedef struct header* header_p;

void scale_wav_file(char * input, float factor, int is_8bit)
{
    FILE * infile = fopen(input, "rb");
    FILE * outfile = fopen("outfile.wav", "wb");

    int BUFSIZE = 4000, i, MAX_8BIT_AMP = 255, MAX_16BIT_AMP = 32678;

    // used for processing 8-bit file
    unsigned char inbuff8[BUFSIZE], outbuff8[BUFSIZE];

    // used for processing 16-bit file
    short int inbuff16[BUFSIZE], outbuff16[BUFSIZE];

    // header_p points to a header struct that contains the file's metadata fields
    header_p meta = (header_p)malloc(sizeof(header));

    if (infile)
    {

        // read and write header data
        fread(meta, 1, sizeof(header), infile);
        fwrite(meta, 1, sizeof(meta), outfile);

        while (!feof(infile))
        {
            if (is_8bit)
            {
                fread(inbuff8, 1, BUFSIZE, infile);
            } else {
                fread(inbuff16, 1, BUFSIZE, infile);
            }

            // scale amplitude for 8/16 bits
            for (i=0; i < BUFSIZE; ++i)
            {
                if (is_8bit)
                {
                    outbuff8[i] = factor * inbuff8[i];
                    if ((int)outbuff8[i] > MAX_8BIT_AMP)
                    {
                        outbuff8[i] = MAX_8BIT_AMP;
                    }
                } else {
                    outbuff16[i] = factor * inbuff16[i];
                    if ((int)outbuff16[i] > MAX_16BIT_AMP)
                    {
                        outbuff16[i] = MAX_16BIT_AMP;
                    } else if ((int)outbuff16[i] < -MAX_16BIT_AMP) {
                        outbuff16[i] = -MAX_16BIT_AMP;
                    }
                }
            }

            // write to output file for 8/16 bit
            if (is_8bit)
            {
                fwrite(outbuff8, 1, BUFSIZE, outfile);
            } else {
                fwrite(outbuff16, 1, BUFSIZE, outfile);
            }
        }
    }

    // cleanup
    if (infile) { fclose(infile); }
    if (outfile) { fclose(outfile); }
    if (meta) { free(meta); }
}

int main (int argc, char const *argv[])
{
    char infile[] = "file.wav";
    float factor = 0.5;
    scale_wav_file(infile, factor, 0);
    return 0;
}
</code>```

I'm getting differing file sizes at the end (by 1k or so, for a 40Mb file), and I suspect this is due to the fact that I'm writing an entire buffer to the output, even though the file may have terminated before filling the entire buffer size. Also, the output file is messed up - won't play or open - so I'm probably doing the whole thing wrong. Any tips on where I'm messing up will be great. Thanks!

答:
If possible you may want to look at a different language than C unless it is specifically for a C application.

For example python has a good wav package that reads & writes wav files easily.

For more professional or academic use, the first go-to is MATLAB which also reads wav files very easily (directly into vectors which are then operated on as single expressions).

ContentLicense: CC BY-SA 2.5

Title: processing an audio wav file with C

Body:
I'm working on processing the amplitude of a wav file and scaling it by some decimal factor. I'm trying to wrap my head around how to read and re-write the file in a memory-efficient way while also trying to tackle the nuances of the language (I'm new to C). The file can be in either an 8- or 16-bit format.  The way I thought of doing this is by first reading the header data into some pre-defined struct, and then processing the actual data in a loop where I'll read a chunk of data into a buffer, do whatever is needed to it, and then write it to the output.

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

typedef struct header
{
    char chunk_id[4];
    int chunk_size;
    char format[4];
    char subchunk1_id[4];
    int subchunk1_size;
    short int audio_format;
    short int num_channels;
    int sample_rate;
    int byte_rate;
    short int block_align;
    short int bits_per_sample;
    short int extra_param_size;
    char subchunk2_id[4];
    int subchunk2_size;
} header;

typedef struct header* header_p;

void scale_wav_file(char * input, float factor, int is_8bit)
{
    FILE * infile = fopen(input, "rb");
    FILE * outfile = fopen("outfile.wav", "wb");

    int BUFSIZE = 4000, i, MAX_8BIT_AMP = 255, MAX_16BIT_AMP = 32678;

    // used for processing 8-bit file
    unsigned char inbuff8[BUFSIZE], outbuff8[BUFSIZE];

    // used for processing 16-bit file
    short int inbuff16[BUFSIZE], outbuff16[BUFSIZE];

    // header_p points to a header struct that contains the file's metadata fields
    header_p meta = (header_p)malloc(sizeof(header));

    if (infile)
    {

        // read and write header data
        fread(meta, 1, sizeof(header), infile);
        fwrite(meta, 1, sizeof(meta), outfile);

        while (!feof(infile))
        {
            if (is_8bit)
            {
                fread(inbuff8, 1, BUFSIZE, infile);
            } else {
                fread(inbuff16, 1, BUFSIZE, infile);
            }

            // scale amplitude for 8/16 bits
            for (i=0; i < BUFSIZE; ++i)
            {
                if (is_8bit)
                {
                    outbuff8[i] = factor * inbuff8[i];
                    if ((int)outbuff8[i] > MAX_8BIT_AMP)
                    {
                        outbuff8[i] = MAX_8BIT_AMP;
                    }
                } else {
                    outbuff16[i] = factor * inbuff16[i];
                    if ((int)outbuff16[i] > MAX_16BIT_AMP)
                    {
                        outbuff16[i] = MAX_16BIT_AMP;
                    } else if ((int)outbuff16[i] < -MAX_16BIT_AMP) {
                        outbuff16[i] = -MAX_16BIT_AMP;
                    }
                }
            }

            // write to output file for 8/16 bit
            if (is_8bit)
            {
                fwrite(outbuff8, 1, BUFSIZE, outfile);
            } else {
                fwrite(outbuff16, 1, BUFSIZE, outfile);
            }
        }
    }

    // cleanup
    if (infile) { fclose(infile); }
    if (outfile) { fclose(outfile); }
    if (meta) { free(meta); }
}

int main (int argc, char const *argv[])
{
    char infile[] = "file.wav";
    float factor = 0.5;
    scale_wav_file(infile, factor, 0);
    return 0;
}

I'm getting differing file sizes at the end (by 1k or so, for a 40Mb file), and I suspect this is due to the fact that I'm writing an entire buffer to the output, even though the file may have terminated before filling the entire buffer size. Also, the output file is messed up - won't play or open - so I'm probably doing the whole thing wrong. Any tips on where I'm messing up will be great. Thanks!


问:
Creating a fill animation in flutter
I need find a way to create an animation that will fill and dispense a liquid inside a tube. I will need some kind of variables, such as percentages where as the percentage goes up and down the liquid rises and falls. I'm not quite sure how to do such an animation in flutter, so any help is appreciated.

I have a few pictures posted below for when the tube is empty and when it is at 180 micro liters.

答:
I had some time so I made this implementation of it:

https://dartpad.dev/?id=4e595e1950c21582dd33b4d55427a561

Title: Creating a fill animation in flutter


问:
Scala - what is this map + case syntax?
I can't seem to find further information on this language feature where you can put a case inside a map like this:

```<code>   val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { case (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""
</code>```

I've been starting to use this syntax, but what is it called and where can I find more information on it?

答:
This is usually called "destructuring" or "destructuring bind" (ex: in Clojure https://clojure.org/guides/destructuring). Scala uses pattern matching to achieve this.

In your example, you use shortened pattern matching to destructure the Option which contains the version. You could also skip the explicit Long type declaration.

Good reads on this topic:

https://www.oreilly.com/library/view/programming-scala-2nd/9781491950135/ch04.html
https://docs.scala-lang.org/cheatsheets/index.html

Title: Scala - what is this map + case syntax?

Body:
I can't seem to find further information on this language feature where you can put a case inside a map like this:

   val sVersion = CrossVersion.partialVersion(scalaVersion)
      .map { case (major:Long, minor: Long) => s"_$major.$minor" } getOrElse ""

I've been starting to use this syntax, but what is it called and where can I find more information on it?


问:
Replace a set of html br elements with another in jQuery -- parsing HTML with jQuery
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

```<code><br><br clear=all><br>
</code>```

with

```<code><br />
</code>```

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

答:
Use the Next Adjacent Selector (+):

```<code>$("br+br").remove(); //Removes all <br> tags in front of another
</code>```

jsFiddle demo

Body:
So here's my problem. I have a little third-party service on my site that generates a bunch of HTML from an RSS feed and sticks it in my webpage when the page is loaded. However, when it generates the HTML, it inserts a bunch of totally unnecessary break tags. Unfortunately, the source file that generates this code is on the third party's server and not mine, so I can't tweak it.

Thus, I'm trying to tweak the HTML right before the page is loaded by using a little jQuery inside the onLoad="" property in the body tag. However, I can't simply use something like $('br').remove(); because then there aren't ANY break tags, and I need one per each spot where there are currently three.

So ultimately, what I need to do is come up with a jQuery statement that replaces

with

I'm rather new to jQuery, but I couldn't seem to find anything that would help me do this. Any ideas?

Thanks in advance for any help!

Body:
Use the Next Adjacent Selector (+):

$("br+br").remove(); //Removes all <br> tags in front of another

jsFiddle demo


问:
Using current user when running container in docker-compose
Is there a way to execute or login as current user to a bash of specific container . I tried running docker-compose exec -u $USER phoenix bash but it says unable to find user raz: no matching entries in passwd file

I tried another way by adding a useradd command in a dockerfile.

```<code>FROM elixir:latest

ARG USER_ID
ARG GROUP_ID

RUN addgroup --gid $GROUP_ID raz
RUN adduser --disabled-password --gecos '' --uid $USER_ID --gid $GROUP_ID raz
USER raz

RUN apt-get update && \
    apt-get install -y postgresql-client && \
    apt-get install -y inotify-tools && \
    apt-get install -y nodejs && \
    curl -L https://npmjs.org/install.sh | sh && \
    mix local.hex --force && \
    mix archive.install hex phx_new 1.5.3 --force && \
    mix local.rebar --force

COPY . /app
WORKDIR /app

COPY ./entrypoint.sh /entrypoint.sh
RUN ["chmod", "+x", "/entrypoint.sh"]
ENTRYPOINT ["/entrypoint.sh"]
</code>```

but when I run docker-compose build I get a permission denied error when running the apt-get commands.
I also look for gosu as a step down root user but it seems complicated.

Is it possible for added user in Dockerfile command to have same permission as my current user?
I'm running WSL2 btw.

答:
Building on top of the answer by Joepreludian, focusing on docker-compose:

You can use the user: and volumes: options in the compose file. For example:

  my-service:
    image: ubuntu:latest
    user: ${MY_UID}:${MY_GID}
    volumes:
      - /etc/passwd:/etc/passwd:ro
      - /etc/group:/etc/group:ro
```
<p>and define these variables where you are starting your compose:</p>
<pre class="lang-sh prettyprint-override"><code>MY_UID="$(id -u)" MY_GID="$(id -g)" docker-compose up
</code>```

Body:
Is there a way to execute or login as current user to a bash of specific container . I tried running docker-compose exec -u $USER phoenix bash but it says unable to find user raz: no matching entries in passwd file

I tried another way by adding a useradd command in a dockerfile.

FROM elixir:latest

ARG USER_ID
ARG GROUP_ID

RUN addgroup --gid $GROUP_ID raz
RUN adduser --disabled-password --gecos '' --uid $USER_ID --gid $GROUP_ID raz
USER raz

RUN apt-get update && \
    apt-get install -y postgresql-client && \
    apt-get install -y inotify-tools && \
    apt-get install -y nodejs && \
    curl -L https://npmjs.org/install.sh | sh && \
    mix local.hex --force && \
    mix archive.install hex phx_new 1.5.3 --force && \
    mix local.rebar --force

COPY . /app
WORKDIR /app

COPY ./entrypoint.sh /entrypoint.sh
RUN ["chmod", "+x", "/entrypoint.sh"]
ENTRYPOINT ["/entrypoint.sh"]

but when I run docker-compose build I get a permission denied error when running the apt-get commands.
I also look for gosu as a step down root user but it seems complicated.

Is it possible for added user in Dockerfile command to have same permission as my current user?
I'm running WSL2 btw.

Body:
Building on top of the answer by Joepreludian, focusing on docker-compose:

You can use the user: and volumes: options in the compose file. For example:

  my-service:
    image: ubuntu:latest
    user: ${MY_UID}:${MY_GID}
    volumes:
      - /etc/passwd:/etc/passwd:ro
      - /etc/group:/etc/group:ro

and define these variables where you are starting your compose:

MY_UID="$(id -u)" MY_GID="$(id -g)" docker-compose up


问:
Bottom-left screen positioning CSS
I am trying to make the Card as i call it attached to the screen so when it is resized, the card will go along with it.

Css code:

```<code>    #wrapper {
    position: relative;
    max-width: 1920px;
    max-width: 100%;
    padding-right: 10px;
    padding-left: 10px;
}
#introduction-container {
    position: relative;
}
#introduction-textposition {
    position: absolute;
    bottom: 100%;
    left: 10%;
}
#introduction-paragraph {
    width: 500px;
    height: 150px;
    background-color: rgba(18, 18, 18, 0.7);
    padding: 40px 25px;
    margin-top: 0;
}
</code>```

html code

```<code> <div id="wrapper">
    <div id="introduction-container">
        <div id="introduction-textposition">
      <div id="introduction-paragraph">
        <h3>RTX 2080Ti Available Now!</h3>
        <h1>RAY-TRACE</h1>
        <p><span style="color: rgb(118, 185, 0);">NVIDIA RTX</span> is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create</p>
        <div>
            <a href="#" class="introduction-button hover-color">SHOP NOW!</a>
        </div>
      </div>
    </div>
    </div>
</code>```

ps: the introduction-textposition percentaged is me playing around with it, wont work tho.
problem is, when i used the relative position on #introduction-container it the properties wont show here;
html image

What it should look like: illustration

答:
Let me help my bro, maybe my css can help you

#wrapper{
background-image: linear-gradient(#1391ff,#0145ff);
    width: 200px;
    height: 160px;
    position: absolute;
    top: 100%;
    left: 100%;
    text-align: center;
    border-radius: 16px;
    padding: 120px 50px;
    box-shadow: 2px 2px 8px #000000ab;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="wrapper">
    <div id="introduction-container">
        <div id="introduction-textposition">
      <div id="introduction-paragraph">
        <h3>RTX 2080Ti Available Now!</h3>
        <h1>RAY-TRACE</h1>
        <p><span style="color: rgb(118, 185, 0);">NVIDIA RTX</span> is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create</p>
        <div>
            SHOP NOW!
        </div>
      </div>
    </div>
    </div></code>```

Title: Bottom-left screen positioning CSS

Body:
I am trying to make the Card as i call it attached to the screen so when it is resized, the card will go along with it.

Css code:

    #wrapper {
    position: relative;
    max-width: 1920px;
    max-width: 100%;
    padding-right: 10px;
    padding-left: 10px;
}
#introduction-container {
    position: relative;
}
#introduction-textposition {
    position: absolute;
    bottom: 100%;
    left: 10%;
}
#introduction-paragraph {
    width: 500px;
    height: 150px;
    background-color: rgba(18, 18, 18, 0.7);
    padding: 40px 25px;
    margin-top: 0;
}

html code

RTX 2080Ti Available Now!

RAY-TRACE

NVIDIA RTX is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create

            SHOP NOW!

ps: the introduction-textposition percentaged is me playing around with it, wont work tho.
problem is, when i used the relative position on #introduction-container it the properties wont show here;
html image

What it should look like: illustration

Body:
Let me help my bro, maybe my css can help you

#wrapper{
background-image: linear-gradient(#1391ff,#0145ff);
    width: 200px;
    height: 160px;
    position: absolute;
    top: 100%;
    left: 100%;
    text-align: center;
    border-radius: 16px;
    padding: 120px 50px;
    box-shadow: 2px 2px 8px #000000ab;
}

 <div id="wrapper">
    <div id="introduction-container">
        <div id="introduction-textposition">
      <div id="introduction-paragraph">
        <h3>RTX 2080Ti Available Now!</h3>
        <h1>RAY-TRACE</h1>
        <p><span style="color: rgb(118, 185, 0);">NVIDIA RTX</span> is the most advanced platform for ray tracing and AI technologies that are revolutionizing the ways we play and create</p>
        <div>
            <a href="#" class="introduction-button hover-color">SHOP NOW!</a>
        </div>
      </div>
    </div>
    </div>


问:
Parse String to Jason C# - can't access due to protection level -JObject
Hey i want to parse a String to a Jason Object in C#.

I have found this code but i alltimes get the problem that it means for JObject:
"can't access due to protection level c#"
Its because JObject is Internal in this Framework i think. But i found online so much solution and they tell all to make it like below. I dont know what i make wrong.

```<code>        string APIUrlRandomNameGenerator = "https://api.parser.name/api";
        var json = new WebClient().DownloadString(APIUrlRandomNameGenerator);

        var jobj = new JObject();
        dynamic data = JObject.Parse(json);
        Console.WriteLine(data.id);
        Console.WriteLine(data.first_name);
        Console.WriteLine(data.last_name);
        Console.WriteLine(data.gender);
</code>```

答:
You don'nt need to install any extra packages. Try this</p>
```<code>    var jsonParsed = JObject.Parse(json);
    Console.WriteLine(jsonParsed["id"]);
    Console.WriteLine(jsonParsed["first_name"]);
    Console.WriteLine(jsonParsed["last_name"]);
    Console.WriteLine(jsonParsed["gender"]);
</code>```

Body:
Hey i want to parse a String to a Jason Object in C#.

I have found this code but i alltimes get the problem that it means for JObject:
"can't access due to protection level c#"
Its because JObject is Internal in this Framework i think. But i found online so much solution and they tell all to make it like below. I dont know what i make wrong.

        string APIUrlRandomNameGenerator = "https://api.parser.name/api";
        var json = new WebClient().DownloadString(APIUrlRandomNameGenerator);

        var jobj = new JObject();
        dynamic data = JObject.Parse(json);
        Console.WriteLine(data.id);
        Console.WriteLine(data.first_name);
        Console.WriteLine(data.last_name);
        Console.WriteLine(data.gender);

Body:
You don'nt need to install any extra packages. Try this

    var jsonParsed = JObject.Parse(json);
    Console.WriteLine(jsonParsed["id"]);
    Console.WriteLine(jsonParsed["first_name"]);
    Console.WriteLine(jsonParsed["last_name"]);
    Console.WriteLine(jsonParsed["gender"]);


问:
CSS transition of div on hover over only part of div?
Let me see how well I can explain this. I am working on an index on a website that is in a div that is pushed off of the page via css margin with only part of it showing. When you hover over the part that is showing, the rest slides down into view. This works fine. I already have the transition effect in place for the margin change slide and also a background color change with rgba. It looks very nice.

My question is, the index is around 500px wide and the visible part before hovering is 70px high. So that is a fairly large area of the screen for people to accidentally catch with their mouse hover if they are not trying to display the index div. Is there some way that I can only make part of the initially visible portion of the div activate the hover transition animation to bring the full div into view? Or perhaps someway I can attach a smaller div to this one as a sort of tab, that will bring down the larger div and itself via transition on hover?

I hope this makes sense. Thank you.

Here is the basic idea of the current code:

```<code>#index {
    position:fixed;
    background:rgba(0,0,0,0.3);
    width:500px;
    height:500px;
    top:0;
    left:50%;
    margin:-430px 0 0 -500px;
    transition:0.5s;
    -moz-transition:0.5s;
    -webkit-transition:0.5s;
    -o-transition:0.5s;}

#index:hover {
    background:rgba(0,0,0,0.8);
    margin:0 0 0 -500px;}
</code>```

答: This comes from the position:relative property. I strongly feel that your current div tag has position relative property. Please remove that.</p>

Body:
Let me see how well I can explain this. I am working on an index on a website that is in a div that is pushed off of the page via css margin with only part of it showing. When you hover over the part that is showing, the rest slides down into view. This works fine. I already have the transition effect in place for the margin change slide and also a background color change with rgba. It looks very nice.

My question is, the index is around 500px wide and the visible part before hovering is 70px high. So that is a fairly large area of the screen for people to accidentally catch with their mouse hover if they are not trying to display the index div. Is there some way that I can only make part of the initially visible portion of the div activate the hover transition animation to bring the full div into view? Or perhaps someway I can attach a smaller div to this one as a sort of tab, that will bring down the larger div and itself via transition on hover?

I hope this makes sense. Thank you.

Here is the basic idea of the current code:

#index {
    position:fixed;
    background:rgba(0,0,0,0.3);
    width:500px;
    height:500px;
    top:0;
    left:50%;
    margin:-430px 0 0 -500px;
    transition:0.5s;
    -moz-transition:0.5s;
    -webkit-transition:0.5s;
    -o-transition:0.5s;}

#index:hover {
    background:rgba(0,0,0,0.8);
    margin:0 0 0 -500px;}


问:
plotly hoverlabel color transparency
Is it possible to format hoverlabel so that the background color is transparent & it's possible to see the plot through the labels?

I can set it to a solid color by e.g. hoverlabel = list(bgcolor = '#fff') but looks like if I try to add transparency, that part of the color string gets ignored. Same with bgcolor = 'rgba(255,255,255,0.05)', doesn't work either. Looks like for markers there is opacity setting, but not for hoverlabels.

Thanks!!

答:
Another approach is using CSS selector with css file in www folder and included the css in ui.R file like this

This approach allow you to have color variable set for each label compare to hard code in the accepted answer.

 dashboardBody(
   # use the css to set opacity of hover label - here I use tag$head in shinydashboard
   tags$head(
     tags$link(rel = "stylesheet", type = "text/css", href = "styles.css")
   )
   # more code here ...
)
```
<pre class="lang-css prettyprint-override"><code># this file located in www/styles.css
g.hovertext > path {
  opacity: .6;
}
</code>```

This approach will result that every hover text on the page got the opacity setting not one specific plot. For specific plot it would require some extra work on the selector.

Edit: a reproducible example:

```<code>library(shiny)
library(plotly)

ui <- fluidPage(
  tags$style(HTML("g.hovertext > path {opacity: .6;}")),
  plotlyOutput("myPlot")
)

server <- function(input, output, session) {
  output$myPlot <- renderPlotly({
    plot_ly(x = 1:10, y = 1:10, type = "scatter", mode = "lines")
  })
}

shinyApp(ui, server)
</code>```

Title: plotly hoverlabel color transparency

Body:
Another approach is using CSS selector with css file in www folder and included the css in ui.R file like this

This approach allow you to have color variable set for each label compare to hard code in the accepted answer.

 dashboardBody(
   # use the css to set opacity of hover label - here I use tag$head in shinydashboard
   tags$head(
     tags$link(rel = "stylesheet", type = "text/css", href = "styles.css")
   )
   # more code here ...
)

# this file located in www/styles.css
g.hovertext > path {
  opacity: .6;
}

This approach will result that every hover text on the page got the opacity setting not one specific plot. For specific plot it would require some extra work on the selector.

Edit: a reproducible example:

library(shiny)
library(plotly)

ui <- fluidPage(
  tags$style(HTML("g.hovertext > path {opacity: .6;}")),
  plotlyOutput("myPlot")
)

server <- function(input, output, session) {
  output$myPlot <- renderPlotly({
    plot_ly(x = 1:10, y = 1:10, type = "scatter", mode = "lines")
  })
}

shinyApp(ui, server)


问:
Creating several roles definition and assignment with Bicep template for Azure Cosmos DB
I try to create two role definitions and two role assignments to one Azure CosmosDB SQL API account using Bicep template.

I decompiled below arm template with az bicep decompile:
https://github.com/Azure/azure-quickstart-templates/blob/master/101-cosmosdb-sql-rbac/azuredeploy.json

and I got below:

```<code>resource accountName_readOnlyRoleDefinitionId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readOnlyRoleDefinitionId}'
  properties: {
    roleName: readOnlyRoleDefinitionName
    type: 'CustomRole'
    assignableScopes: [
      accountName_resource.id
    ]
    permissions: [
      {
        dataActions: readOnlyRoleDataActions
      }
    ]
  }
}

resource accountName_readOnlyRoleAssignmentId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readOnlyRoleAssignmentId}'
  properties: {
    roleDefinitionId: accountName_readOnlyRoleDefinitionId.id
    principalId: readOnlyPrincipalId
    scope: accountName_resource.id
  }
}
</code>```

which works, but only when I have one role definition and assignment.

When I try deploy it together with below:

```<code>resource accountName_readWriteRoleDefinitionId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readWriteRoleDefinitionId}'
  properties: {
    roleName: readWriteRoleDefinitionName
    type: 'CustomRole'
    assignableScopes: [
      accountName_resource.id
    ]
    permissions: [
      {
        dataActions: readWriteRoleDataActions
      }
    ]
  }
}

resource accountName_readWriteRoleAssignmentId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readWriteRoleAssignmentId}'
  properties: {
    roleDefinitionId: accountName_readWriteRoleDefinitionId.id
    principalId: readWritePrincipalId
    scope: accountName_resource.id
  }
}
</code>```

I have got below error:

```<code>Deployment failed. Correlation ID: 8fe92bd6-6db6-4d9a-98b5-5f78811cc741. {
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "DeploymentFailed",
        "message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.",
        "details": [
          {
            "code": "PreconditionFailed",
            "message": "{\r\n  \"code\": \"PreconditionFailed\",\r\n  \"message\": \"There is another user operation in progress which requires an exclusive lock on [cosmossqlapibiceptest]. Please retry after sometime.\\r\\nActivityId: 7d56ef38-85ee-490e-9819-cc74afc142d3, Microsoft.Azure.Documents.Common/2.14.0\"\r\n}"
          }
        ]
      }
    ]
  }
}
</code>```

I tried also iterating instead of having separated resources, using nested modules for each role, but it does not help.

UPDATE 2021-06-02

I tried also deployed json file, but result the same. I attached arm template:

```<code>{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.3.539.46024",
      "templateHash": "54838909324108202"
    }
  },
  "functions": [],
  "resources": [
    {
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2019-10-01",
      "name": "cosmos_deployment",
      "properties": {
        "expressionEvaluationOptions": {
          "scope": "inner"
        },
        "mode": "Incremental",
        "parameters": {
          "accountName": {
            "value": "add_yours_input"
          },
          "databaseName": {
            "value": "add_yours_input"
          },
          "containerName": {
            "value": "add_yours_input"
          },
          "timeToLive": {
            "value": 2592000
          },
          "readOnlyPrincipalId": {
            "value": "add_yours_input"
          },
          "readWritePrincipalId": {
            "value": "add_yours_input"
          }
        },
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
          "contentVersion": "1.0.0.0",
          "metadata": {
            "_generator": {
              "name": "bicep",
              "version": "0.3.539.46024",
              "templateHash": "10083279953983831862"
            }
          },
          "parameters": {
            "location": {
              "type": "string",
              "defaultValue": "[resourceGroup().location]"
            },
            "accountName": {
              "type": "string"
            },
            "databaseName": {
              "type": "string"
            },
            "containerName": {
              "type": "string"
            },
            "timeToLive": {
              "type": "int"
            },
            "throughput": {
              "type": "int",
              "defaultValue": 400,
              "metadata": {
                "description": "The throughput for the container"
              },
              "maxValue": 1000000,
              "minValue": 400
            },
            "publicNetworkAccess": {
              "type": "string",
              "defaultValue": "Enabled",
              "allowedValues": [
                "Enabled",
                "Disabled"
              ]
            },
            "readOnlyPrincipalId": {
              "type": "string",
              "metadata": {
                "description": "Object ID of the AAD identity. Must be a GUID."
              }
            },
            "readOnlyRoleDefinitionName": {
              "type": "string",
              "defaultValue": "Read Only Role"
            },
            "readOnlyRoleDataActions": {
              "type": "array",
              "defaultValue": [
                "Microsoft.DocumentDB/databaseAccounts/readMetadata",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/read",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/executeQuery",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/readChangeFeed"
              ],
              "metadata": {
                "description": "Data actions permitted by the ReadOnlyRole Role Definition"
              }
            },
            "readWritePrincipalId": {
              "type": "string",
              "metadata": {
                "description": "Object ID of the AAD identity. Must be a GUID."
              }
            },
            "readWriteRoleDefinitionName": {
              "type": "string",
              "defaultValue": "Read Write Role"
            },
            "readWriteRoleDataActions": {
              "type": "array",
              "defaultValue": [
                "Microsoft.DocumentDB/databaseAccounts/readMetadata",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*"
              ],
              "metadata": {
                "description": "Data actions permitted by the ReadWriteOnlyRole Role Definition"
              }
            }
          },
          "functions": [],
          "variables": {
            "readOnlyRoleDefinitionId": "[guid('sql-read-role-definition-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]",
            "readOnlyRoleAssignmentId": "[guid('sql-read-role-assignment-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]",
            "readWriteRoleDefinitionId": "[guid('sql-write-role-definition-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]",
            "readWriteRoleAssignmentId": "[guid('sql-write-role-assignment-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]"
          },
          "resources": [
            {
              "type": "Microsoft.DocumentDB/databaseAccounts",
              "apiVersion": "2021-03-01-preview",
              "name": "[parameters('accountName')]",
              "location": "[parameters('location')]",
              "kind": "GlobalDocumentDB",
              "properties": {
                "createMode": "Default",
                "consistencyPolicy": {
                  "defaultConsistencyLevel": "Strong"
                },
                "locations": [
                  {
                    "locationName": "[parameters('location')]",
                    "failoverPriority": 0,
                    "isZoneRedundant": false
                  }
                ],
                "databaseAccountOfferType": "Standard",
                "enableAutomaticFailover": false,
                "enableMultipleWriteLocations": false,
                "publicNetworkAccess": "[parameters('publicNetworkAccess')]"
              }
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases",
              "apiVersion": "2021-03-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), parameters('databaseName'))]",
              "properties": {
                "resource": {
                  "id": "[parameters('databaseName')]"
                }
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers",
              "apiVersion": "2021-03-01-preview",
              "name": "[format('{0}/{1}/{2}', parameters('accountName'), parameters('databaseName'), parameters('containerName'))]",
              "location": "[parameters('location')]",
              "tags": {},
              "properties": {
                "resource": {
                  "id": "[parameters('containerName')]",
                  "partitionKey": {
                    "paths": [
                      "/partitionKey"
                    ],
                    "kind": "Hash"
                  },
                  "indexingPolicy": {
                    "indexingMode": "consistent",
                    "includedPaths": [
                      {
                        "path": "/a/b/?",
                        "indexes": [
                          {
                            "kind": "Hash",
                            "dataType": "String",
                            "precision": -1
                          }
                        ]
                      }
                    ],
                    "excludedPaths": [
                      {
                        "path": "/*"
                      }
                    ]
                  },
                  "defaultTtl": 1
                },
                "options": {
                  "throughput": "[parameters('throughput')]"
                }
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlDatabases', parameters('accountName'), parameters('databaseName'))]",
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readOnlyRoleDefinitionId'))]",
              "properties": {
                "roleName": "[parameters('readOnlyRoleDefinitionName')]",
                "type": "CustomRole",
                "assignableScopes": [
                  "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
                ],
                "permissions": [
                  {
                    "dataActions": "[parameters('readOnlyRoleDataActions')]"
                  }
                ]
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readOnlyRoleAssignmentId'))]",
              "properties": {
                "roleDefinitionId": "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readOnlyRoleDefinitionId'))]",
                "principalId": "[parameters('readOnlyPrincipalId')]",
                "scope": "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readOnlyRoleDefinitionId'))]",
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readWriteRoleDefinitionId'))]",
              "properties": {
                "roleName": "[parameters('readWriteRoleDefinitionName')]",
                "type": "CustomRole",
                "assignableScopes": [
                  "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
                ],
                "permissions": [
                  {
                    "dataActions": "[parameters('readWriteRoleDataActions')]"
                  }
                ]
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readWriteRoleAssignmentId'))]",
              "properties": {
                "roleDefinitionId": "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readWriteRoleDefinitionId'))]",
                "principalId": "[parameters('readWritePrincipalId')]",
                "scope": "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readWriteRoleDefinitionId'))]",
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            }
          ]
        }
      }
    }
  ]
}
</code>```

答: Try using dependsOn:[] - https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/resource-dependencies#explicit-dependency between each of the assignments.</p>

Body:
I try to create two role definitions and two role assignments to one Azure CosmosDB SQL API account using Bicep template.

I decompiled below arm template with az bicep decompile:
https://github.com/Azure/azure-quickstart-templates/blob/master/101-cosmosdb-sql-rbac/azuredeploy.json

and I got below:

resource accountName_readOnlyRoleDefinitionId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readOnlyRoleDefinitionId}'
  properties: {
    roleName: readOnlyRoleDefinitionName
    type: 'CustomRole'
    assignableScopes: [
      accountName_resource.id
    ]
    permissions: [
      {
        dataActions: readOnlyRoleDataActions
      }
    ]
  }
}

resource accountName_readOnlyRoleAssignmentId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readOnlyRoleAssignmentId}'
  properties: {
    roleDefinitionId: accountName_readOnlyRoleDefinitionId.id
    principalId: readOnlyPrincipalId
    scope: accountName_resource.id
  }
}

which works, but only when I have one role definition and assignment.

When I try deploy it together with below:

resource accountName_readWriteRoleDefinitionId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readWriteRoleDefinitionId}'
  properties: {
    roleName: readWriteRoleDefinitionName
    type: 'CustomRole'
    assignableScopes: [
      accountName_resource.id
    ]
    permissions: [
      {
        dataActions: readWriteRoleDataActions
      }
    ]
  }
}

resource accountName_readWriteRoleAssignmentId 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2020-06-01-preview' = {
  parent: accountName_resource
  name: '${readWriteRoleAssignmentId}'
  properties: {
    roleDefinitionId: accountName_readWriteRoleDefinitionId.id
    principalId: readWritePrincipalId
    scope: accountName_resource.id
  }
}

I have got below error:

Deployment failed. Correlation ID: 8fe92bd6-6db6-4d9a-98b5-5f78811cc741. {
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "DeploymentFailed",
        "message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/DeployOperations for usage details.",
        "details": [
          {
            "code": "PreconditionFailed",
            "message": "{\r\n  \"code\": \"PreconditionFailed\",\r\n  \"message\": \"There is another user operation in progress which requires an exclusive lock on [cosmossqlapibiceptest]. Please retry after sometime.\\r\\nActivityId: 7d56ef38-85ee-490e-9819-cc74afc142d3, Microsoft.Azure.Documents.Common/2.14.0\"\r\n}"
          }
        ]
      }
    ]
  }
}

I tried also iterating instead of having separated resources, using nested modules for each role, but it does not help.

UPDATE 2021-06-02

I tried also deployed json file, but result the same. I attached arm template:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.3.539.46024",
      "templateHash": "54838909324108202"
    }
  },
  "functions": [],
  "resources": [
    {
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2019-10-01",
      "name": "cosmos_deployment",
      "properties": {
        "expressionEvaluationOptions": {
          "scope": "inner"
        },
        "mode": "Incremental",
        "parameters": {
          "accountName": {
            "value": "add_yours_input"
          },
          "databaseName": {
            "value": "add_yours_input"
          },
          "containerName": {
            "value": "add_yours_input"
          },
          "timeToLive": {
            "value": 2592000
          },
          "readOnlyPrincipalId": {
            "value": "add_yours_input"
          },
          "readWritePrincipalId": {
            "value": "add_yours_input"
          }
        },
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
          "contentVersion": "1.0.0.0",
          "metadata": {
            "_generator": {
              "name": "bicep",
              "version": "0.3.539.46024",
              "templateHash": "10083279953983831862"
            }
          },
          "parameters": {
            "location": {
              "type": "string",
              "defaultValue": "[resourceGroup().location]"
            },
            "accountName": {
              "type": "string"
            },
            "databaseName": {
              "type": "string"
            },
            "containerName": {
              "type": "string"
            },
            "timeToLive": {
              "type": "int"
            },
            "throughput": {
              "type": "int",
              "defaultValue": 400,
              "metadata": {
                "description": "The throughput for the container"
              },
              "maxValue": 1000000,
              "minValue": 400
            },
            "publicNetworkAccess": {
              "type": "string",
              "defaultValue": "Enabled",
              "allowedValues": [
                "Enabled",
                "Disabled"
              ]
            },
            "readOnlyPrincipalId": {
              "type": "string",
              "metadata": {
                "description": "Object ID of the AAD identity. Must be a GUID."
              }
            },
            "readOnlyRoleDefinitionName": {
              "type": "string",
              "defaultValue": "Read Only Role"
            },
            "readOnlyRoleDataActions": {
              "type": "array",
              "defaultValue": [
                "Microsoft.DocumentDB/databaseAccounts/readMetadata",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/read",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/executeQuery",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/readChangeFeed"
              ],
              "metadata": {
                "description": "Data actions permitted by the ReadOnlyRole Role Definition"
              }
            },
            "readWritePrincipalId": {
              "type": "string",
              "metadata": {
                "description": "Object ID of the AAD identity. Must be a GUID."
              }
            },
            "readWriteRoleDefinitionName": {
              "type": "string",
              "defaultValue": "Read Write Role"
            },
            "readWriteRoleDataActions": {
              "type": "array",
              "defaultValue": [
                "Microsoft.DocumentDB/databaseAccounts/readMetadata",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*",
                "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*"
              ],
              "metadata": {
                "description": "Data actions permitted by the ReadWriteOnlyRole Role Definition"
              }
            }
          },
          "functions": [],
          "variables": {
            "readOnlyRoleDefinitionId": "[guid('sql-read-role-definition-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]",
            "readOnlyRoleAssignmentId": "[guid('sql-read-role-assignment-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]",
            "readWriteRoleDefinitionId": "[guid('sql-write-role-definition-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]",
            "readWriteRoleAssignmentId": "[guid('sql-write-role-assignment-', resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName')))]"
          },
          "resources": [
            {
              "type": "Microsoft.DocumentDB/databaseAccounts",
              "apiVersion": "2021-03-01-preview",
              "name": "[parameters('accountName')]",
              "location": "[parameters('location')]",
              "kind": "GlobalDocumentDB",
              "properties": {
                "createMode": "Default",
                "consistencyPolicy": {
                  "defaultConsistencyLevel": "Strong"
                },
                "locations": [
                  {
                    "locationName": "[parameters('location')]",
                    "failoverPriority": 0,
                    "isZoneRedundant": false
                  }
                ],
                "databaseAccountOfferType": "Standard",
                "enableAutomaticFailover": false,
                "enableMultipleWriteLocations": false,
                "publicNetworkAccess": "[parameters('publicNetworkAccess')]"
              }
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases",
              "apiVersion": "2021-03-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), parameters('databaseName'))]",
              "properties": {
                "resource": {
                  "id": "[parameters('databaseName')]"
                }
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers",
              "apiVersion": "2021-03-01-preview",
              "name": "[format('{0}/{1}/{2}', parameters('accountName'), parameters('databaseName'), parameters('containerName'))]",
              "location": "[parameters('location')]",
              "tags": {},
              "properties": {
                "resource": {
                  "id": "[parameters('containerName')]",
                  "partitionKey": {
                    "paths": [
                      "/partitionKey"
                    ],
                    "kind": "Hash"
                  },
                  "indexingPolicy": {
                    "indexingMode": "consistent",
                    "includedPaths": [
                      {
                        "path": "/a/b/?",
                        "indexes": [
                          {
                            "kind": "Hash",
                            "dataType": "String",
                            "precision": -1
                          }
                        ]
                      }
                    ],
                    "excludedPaths": [
                      {
                        "path": "/*"
                      }
                    ]
                  },
                  "defaultTtl": 1
                },
                "options": {
                  "throughput": "[parameters('throughput')]"
                }
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlDatabases', parameters('accountName'), parameters('databaseName'))]",
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readOnlyRoleDefinitionId'))]",
              "properties": {
                "roleName": "[parameters('readOnlyRoleDefinitionName')]",
                "type": "CustomRole",
                "assignableScopes": [
                  "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
                ],
                "permissions": [
                  {
                    "dataActions": "[parameters('readOnlyRoleDataActions')]"
                  }
                ]
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readOnlyRoleAssignmentId'))]",
              "properties": {
                "roleDefinitionId": "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readOnlyRoleDefinitionId'))]",
                "principalId": "[parameters('readOnlyPrincipalId')]",
                "scope": "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readOnlyRoleDefinitionId'))]",
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readWriteRoleDefinitionId'))]",
              "properties": {
                "roleName": "[parameters('readWriteRoleDefinitionName')]",
                "type": "CustomRole",
                "assignableScopes": [
                  "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
                ],
                "permissions": [
                  {
                    "dataActions": "[parameters('readWriteRoleDataActions')]"
                  }
                ]
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            },
            {
              "type": "Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments",
              "apiVersion": "2020-06-01-preview",
              "name": "[format('{0}/{1}', parameters('accountName'), variables('readWriteRoleAssignmentId'))]",
              "properties": {
                "roleDefinitionId": "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readWriteRoleDefinitionId'))]",
                "principalId": "[parameters('readWritePrincipalId')]",
                "scope": "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              },
              "dependsOn": [
                "[resourceId('Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions', parameters('accountName'), variables('readWriteRoleDefinitionId'))]",
                "[resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('accountName'))]"
              ]
            }
          ]
        }
      }
    }
  ]
}