问:
Quarkus RestEasy reactive InputStream response using wrong writer
I tried to optimize a reactive endpoint streaming input of an audio file based on  Quarkus REST Score Console. I replaced generic Response with Reactive RestResponse. It increased the score to 100 but it is using ServerStringMessageBodyHandler instead of ServerInputStreamMessageBodyHandler now. Is there a way to tell Quarkus what MessageBodyHandler to use? Now it is calling .toString() method on inputStream object. I tried to return directly ByteArray, but the issue is the same. Any idea what is going on wrong here?</p>
```<code>@GET
@Path("/{lectureId}/stream")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
fun getLectureStreamById(
    @RestHeader("Range") rangeParam: String?,
    @RestPath lectureId: LectureId
): Uni<RestResponse<InputStream>> {
    return lectureAudioService.getAudioFile(lectureId).map { lectureStream ->
            downloadResponse(ByteArrayInputStream(lectureStream.data), filename = "$lectureId.mp3").build()
    }
}

fun downloadResponse(
    data: InputStream,
    filename: String,
): ResponseBuilder<InputStream> {
    return ResponseBuilder.ok(data)
        .header("Content-Disposition", "attachment;filename=$filename")
}
</code>```

答:
Based on answer in github issue it should be fixed in upcoming releases but original approach was not good as well because it blocked event loop. Better approach will be:

```<code>@Path("/{filename}/async-file")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
fun getAsyncFile(filename: String): Uni<RestResponse<AsyncFile>> {
    return Uni.createFrom().emitter { emitter: UniEmitter<in RestResponse<AsyncFile>> ->
        vertx.fileSystem().open(
            "$filename.mp3", OpenOptions()
        ) { result: AsyncResult<AsyncFile> ->
            if (result.succeeded()) emitter.complete(
                ResponseBuilder.ok(result.result()).header("Content-Disposition", "attachment;filename=$filename.mp3").build()
            ) else emitter.fail(result.cause())
        }
    }
}
</code>```

Thanks to @geoand

Body:
I tried to optimize a reactive endpoint streaming input of an audio file based on  Quarkus REST Score Console. I replaced generic Response with Reactive RestResponse. It increased the score to 100 but it is using ServerStringMessageBodyHandler instead of ServerInputStreamMessageBodyHandler now. Is there a way to tell Quarkus what MessageBodyHandler to use? Now it is calling .toString() method on inputStream object. I tried to return directly ByteArray, but the issue is the same. Any idea what is going on wrong here?

@GET
@Path("/{lectureId}/stream")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
fun getLectureStreamById(
    @RestHeader("Range") rangeParam: String?,
    @RestPath lectureId: LectureId
): Uni<RestResponse<InputStream>> {
    return lectureAudioService.getAudioFile(lectureId).map { lectureStream ->
            downloadResponse(ByteArrayInputStream(lectureStream.data), filename = "$lectureId.mp3").build()
    }
}

fun downloadResponse(
    data: InputStream,
    filename: String,
): ResponseBuilder<InputStream> {
    return ResponseBuilder.ok(data)
        .header("Content-Disposition", "attachment;filename=$filename")
}

Body:
Based on answer in github issue it should be fixed in upcoming releases but original approach was not good as well because it blocked event loop. Better approach will be:

@Path("/{filename}/async-file")
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
fun getAsyncFile(filename: String): Uni<RestResponse<AsyncFile>> {
    return Uni.createFrom().emitter { emitter: UniEmitter<in RestResponse<AsyncFile>> ->
        vertx.fileSystem().open(
            "$filename.mp3", OpenOptions()
        ) { result: AsyncResult<AsyncFile> ->
            if (result.succeeded()) emitter.complete(
                ResponseBuilder.ok(result.result()).header("Content-Disposition", "attachment;filename=$filename.mp3").build()
            ) else emitter.fail(result.cause())
        }
    }
}

Thanks to @geoand


来源: stackexchange

问:
Strange +99 in @Order Spring
Anyone can explain what is the reason for +99 in @Order(Ordered.HIGHEST_PRECEDENCE + 99) I've seen in some spring documentation?

Ordered.HIGHEST_PRECEDENCE means that some interceptor will have the maximum priority in the chain executed by spring, but for spring, the lower the number the higher the priority.
So if you look at Ordered class, you'll see

```<code>HIGHEST_PRECEDENCE = Integer.MIN_VALUE;
</code>```

Therefore adding +99 will in fact DECREASE the priority.

What is the reason for this, so?

For example, in the end of the section:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket-stomp-authentication-token-based

答: The reason for @Order(Ordered.HIGHEST_PRECEDENCE + 99) is @Order(Ordered.HIGHEST_PRECEDENCE + 100) in AbstractSecurityWebSocketMessageBrokerConfigurer. @Order(Ordered.HIGHEST_PRECEDENCE + 99) is only needed if you want to implement authorization described in the next section of your link (So that the class with +99 do logic which is needed for authorization +100). Authorization will be done by extending AbstractSecurityWebSocketMessageBrokerConfigurer as described.

ContentLicense: CC BY-SA 4.0

Title: Strange +99 in @Order Spring

Body:
Anyone can explain what is the reason for +99 in @Order(Ordered.HIGHEST_PRECEDENCE + 99) I've seen in some spring documentation?

Ordered.HIGHEST_PRECEDENCE means that some interceptor will have the maximum priority in the chain executed by spring, but for spring, the lower the number the higher the priority.
So if you look at Ordered class, you'll see

HIGHEST_PRECEDENCE = Integer.MIN_VALUE;

Therefore adding +99 will in fact DECREASE the priority.

What is the reason for this, so?

For example, in the end of the section:
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#websocket-stomp-authentication-token-based


问:
How to get total sum of nested list's total value in a while loop?
I am trying to get buy and sell orders from binance api(python-binance) which has a limit of 500 values.(500 ask,500 buy). I already can get this with creating 500 variables with index numbers but it seems to me there has to be a better way than to write 500 lines of code.
This is the code I am trying to make it happen.

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-
from binance.client import Client

user_key = ''
secret_key = ''
binance_client = Client(user_key, secret_key)

while True:
    alis = binance_client.futures_order_book(symbol='XRPUSDT')

    binance_buy = alis['bids'][0]
    binance_buy1 = alis['bids'][1]
    binance_buy2 = alis['bids'][2]
    binance_buy3 = alis['bids'][3]
    binance_buy4 = alis['bids'][4]
    binance_buy5 = alis['bids'][5]
    binance_buy6 = alis['bids'][6]
    binance_buy7 = alis['bids'][7]
    binance_buy8 = alis['bids'][8]
    binance_buy9 = alis['bids'][9]
    binance_buy10 = alis['bids'][10]
    binance_buy11 = alis['bids'][11]
    binance_buy12 = alis['bids'][12]
    binance_buy13 = alis['bids'][13]
    binance_buy14 = alis['bids'][14]
    binance_buy15 = alis['bids'][15]
    binance_buy16 = alis['bids'][16]
    binance_buy17 = alis['bids'][17]
    binance_buy18 = alis['bids'][18]
    binance_buy19 = alis['bids'][19]
    binance_buy20 = alis['bids'][20]
    binance_sell = alis['asks'][0]
    binance_sell1 = alis['asks'][1]
    binance_sell2 = alis['asks'][2]
    binance_sell3 = alis['asks'][3]
    binance_sell4 = alis['asks'][4]
    binance_sell5 = alis['asks'][5]
    binance_sell6 = alis['asks'][6]
    binance_sell7 = alis['asks'][7]
    binance_sell8 = alis['asks'][8]
    binance_sell9 = alis['asks'][9]
    binance_sell10 = alis['asks'][10]
    binance_sell11 = alis['asks'][11]
    binance_sell12 = alis['asks'][12]
    binance_sell13 = alis['asks'][13]
    binance_sell14 = alis['asks'][14]
    binance_sell15 = alis['asks'][15]
    binance_sell16 = alis['asks'][16]
    binance_sell17 = alis['asks'][17]
    binance_sell18 = alis['asks'][18]
    binance_sell19 = alis['asks'][19]
    binance_sell20 = alis['asks'][20]

    binance_buy_demand = float(binance_buy[1]) + float(binance_buy1[1]) \
        + float(binance_buy2[1]) + float(binance_buy3[1]) \
        + float(binance_buy4[1]) + float(binance_buy5[1]) \
        + float(binance_buy6[1]) + float(binance_buy7[1]) \
        + float(binance_buy8[1]) + float(binance_buy9[1]) \
        + float(binance_buy10[1]) + float(binance_buy11[1]) \
        + float(binance_buy12[1]) + float(binance_buy13[1]) \
        + float(binance_buy14[1]) + float(binance_buy15[1]) \
        + float(binance_buy16[1]) + float(binance_buy17[1]) \
        + float(binance_buy18[1]) + float(binance_buy19[1]) \
        + float(binance_buy20[1])

    for i in range(0, 500):
        print (alis['asks'][i][0], alis['asks'][i][1])

    binance_sell_demand = float(binance_sell[1]) \
        + float(binance_sell1[1]) + float(binance_sell2[1]) \
        + float(binance_sell3[1]) + float(binance_sell4[1]) \
        + float(binance_sell5[1]) + float(binance_sell6[1]) \
        + float(binance_sell7[1]) + float(binance_sell8[1]) \
        + float(binance_sell9[1]) + float(binance_sell10[1]) \
        + float(binance_sell11[1]) + float(binance_sell12[1]) \
        + float(binance_sell13[1]) + float(binance_sell14[1]) \
        + float(binance_sell15[1]) + float(binance_sell16[1]) \
        + float(binance_sell17[1]) + float(binance_sell18[1]) \
        + float(binance_sell19[1]) + float(binance_sell20[1])
</code>```

there is 500 bids and 500 asks
after getting data I sum bids  ands asks like this

I tried to make for loop but only could print this values cant sum it in for loop this is the code I tried:
sample output:

```<code>0.9315 18328.6
0.9316 18201.2
0.9317 23544.0
0.9318 260.4
0.9319 689.5
0.9320 20410.5
0.9321 47.7
0.9322 294.2
0.9323 446.6
0.9324 104.0
0.9325 3802.3
0.9326 100.1
0.9327 20122.9
0.9328 1410.0
0.9329 7745.1
0.9330 9094.4
0.9331 10389.9
0.9332 248.5
0.9333 71559.7
0.9334 18024.1
0.9335 7404.5
0.9336 1366.6
0.9337 21972.4
0.9338 1224.8
0.9339 49.9
0.9340 17590.5
0.9341 17967.1
0.9342 272.3
0.9343 704.4
0.9344 3581.7
0.9345 3896.8
</code>```

the first items are price second is quantity

I am trying to make a function that sum and divide avg.price and also want to know how many bids total and asks total.

答:
Use the sum() function with a generator that gets the appropriate element of each list item.

```<code>binance_buy_demand = sum(float(x[1]) for x in alis['bids'])
binance_sell_demand = sum(float(x[1]) for x in alis['asks'])
</code>```

Body:
I am trying to get buy and sell orders from binance api(python-binance) which has a limit of 500 values.(500 ask,500 buy). I already can get this with creating 500 variables with index numbers but it seems to me there has to be a better way than to write 500 lines of code.
This is the code I am trying to make it happen.

#!/usr/bin/python
# -*- coding: utf-8 -*-
from binance.client import Client

user_key = ''
secret_key = ''
binance_client = Client(user_key, secret_key)

while True:
    alis = binance_client.futures_order_book(symbol='XRPUSDT')

    binance_buy = alis['bids'][0]
    binance_buy1 = alis['bids'][1]
    binance_buy2 = alis['bids'][2]
    binance_buy3 = alis['bids'][3]
    binance_buy4 = alis['bids'][4]
    binance_buy5 = alis['bids'][5]
    binance_buy6 = alis['bids'][6]
    binance_buy7 = alis['bids'][7]
    binance_buy8 = alis['bids'][8]
    binance_buy9 = alis['bids'][9]
    binance_buy10 = alis['bids'][10]
    binance_buy11 = alis['bids'][11]
    binance_buy12 = alis['bids'][12]
    binance_buy13 = alis['bids'][13]
    binance_buy14 = alis['bids'][14]
    binance_buy15 = alis['bids'][15]
    binance_buy16 = alis['bids'][16]
    binance_buy17 = alis['bids'][17]
    binance_buy18 = alis['bids'][18]
    binance_buy19 = alis['bids'][19]
    binance_buy20 = alis['bids'][20]
    binance_sell = alis['asks'][0]
    binance_sell1 = alis['asks'][1]
    binance_sell2 = alis['asks'][2]
    binance_sell3 = alis['asks'][3]
    binance_sell4 = alis['asks'][4]
    binance_sell5 = alis['asks'][5]
    binance_sell6 = alis['asks'][6]
    binance_sell7 = alis['asks'][7]
    binance_sell8 = alis['asks'][8]
    binance_sell9 = alis['asks'][9]
    binance_sell10 = alis['asks'][10]
    binance_sell11 = alis['asks'][11]
    binance_sell12 = alis['asks'][12]
    binance_sell13 = alis['asks'][13]
    binance_sell14 = alis['asks'][14]
    binance_sell15 = alis['asks'][15]
    binance_sell16 = alis['asks'][16]
    binance_sell17 = alis['asks'][17]
    binance_sell18 = alis['asks'][18]
    binance_sell19 = alis['asks'][19]
    binance_sell20 = alis['asks'][20]

    binance_buy_demand = float(binance_buy[1]) + float(binance_buy1[1]) \
        + float(binance_buy2[1]) + float(binance_buy3[1]) \
        + float(binance_buy4[1]) + float(binance_buy5[1]) \
        + float(binance_buy6[1]) + float(binance_buy7[1]) \
        + float(binance_buy8[1]) + float(binance_buy9[1]) \
        + float(binance_buy10[1]) + float(binance_buy11[1]) \
        + float(binance_buy12[1]) + float(binance_buy13[1]) \
        + float(binance_buy14[1]) + float(binance_buy15[1]) \
        + float(binance_buy16[1]) + float(binance_buy17[1]) \
        + float(binance_buy18[1]) + float(binance_buy19[1]) \
        + float(binance_buy20[1])

    for i in range(0, 500):
        print (alis['asks'][i][0], alis['asks'][i][1])

    binance_sell_demand = float(binance_sell[1]) \
        + float(binance_sell1[1]) + float(binance_sell2[1]) \
        + float(binance_sell3[1]) + float(binance_sell4[1]) \
        + float(binance_sell5[1]) + float(binance_sell6[1]) \
        + float(binance_sell7[1]) + float(binance_sell8[1]) \
        + float(binance_sell9[1]) + float(binance_sell10[1]) \
        + float(binance_sell11[1]) + float(binance_sell12[1]) \
        + float(binance_sell13[1]) + float(binance_sell14[1]) \
        + float(binance_sell15[1]) + float(binance_sell16[1]) \
        + float(binance_sell17[1]) + float(binance_sell18[1]) \
        + float(binance_sell19[1]) + float(binance_sell20[1])

there is 500 bids and 500 asks
after getting data I sum bids  ands asks like this

I tried to make for loop but only could print this values cant sum it in for loop this is the code I tried:
sample output:

0.9315 18328.6
0.9316 18201.2
0.9317 23544.0
0.9318 260.4
0.9319 689.5
0.9320 20410.5
0.9321 47.7
0.9322 294.2
0.9323 446.6
0.9324 104.0
0.9325 3802.3
0.9326 100.1
0.9327 20122.9
0.9328 1410.0
0.9329 7745.1
0.9330 9094.4
0.9331 10389.9
0.9332 248.5
0.9333 71559.7
0.9334 18024.1
0.9335 7404.5
0.9336 1366.6
0.9337 21972.4
0.9338 1224.8
0.9339 49.9
0.9340 17590.5
0.9341 17967.1
0.9342 272.3
0.9343 704.4
0.9344 3581.7
0.9345 3896.8

the first items are price second is quantity

I am trying to make a function that sum and divide avg.price and also want to know how many bids total and asks total.

Body:
Use the sum() function with a generator that gets the appropriate element of each list item.

binance_buy_demand = sum(float(x[1]) for x in alis['bids'])
binance_sell_demand = sum(float(x[1]) for x in alis['asks'])


问:
How to Seed created Laravel Field
Hello Everyone I have a question:  I am a new lo Laravel and I'm wondering is there is a way to seed a newly created column?
I created a new column using migration command:

php artisan migration:make --table Authors

I created a new field image, now I want to populate it with www.thispersondoesntexists.com images. Is there a way to do that for every existing record in my database?

答:
```<code>Add the following fields in your seeders file which is located in database -> seeders -> DatabaseSeeder.

DB::table('users')->insert([
    'name' => Str::random(10),
    'email' => Str::random(10).'@gmail.com',
    'password' => Hash::make('password'),
]);

here add your table name and table fields.Then use the following command.
php artisan make:seeder DatabaseSeeder
</code>```

Title: How to Seed created Laravel Field


问:
Excel - How to convert US date string (dd-mmm-yyyy) to European date
How can date in the US format dd-mmm-yyyy be converted to a date in European format.

When importing text based data with US Dates, some dates will import as a date, some import as a string.

A US date like 11-Jun-2021 is equal to NL format, so it will import as a date.
A US date like 11-Oct-2021 should be converted to 10-okt-2021, but it's imported as a string.

Is there a way to convert this string to a date format?

答:
Found something. It's kinda dirty, but it works:</p>
```<code>=IF(C3=0;"";IF(IFERROR(FIND("Oct";C3;1);FALSE);REPLACE(C3;FIND("Oct";C3;1);3;"Okt");IF(IFERROR(FIND("May";C3;1);FALSE);REPLACE(C3;FIND("May";C3;1);3;"Mei");IF(IFERROR(FIND("Mar";C3;1);FALSE);REPLACE(C3;FIND("Mar";C3;1);3;"Mrt");C3))))
</code>```

Body:
Found something. It's kinda dirty, but it works:

=IF(C3=0;"";IF(IFERROR(FIND("Oct";C3;1);FALSE);REPLACE(C3;FIND("Oct";C3;1);3;"Okt");IF(IFERROR(FIND("May";C3;1);FALSE);REPLACE(C3;FIND("May";C3;1);3;"Mei");IF(IFERROR(FIND("Mar";C3;1);FALSE);REPLACE(C3;FIND("Mar";C3;1);3;"Mrt");C3))))


问:
How to change the function parameters (visualize_topics_over_time) in BERTopic?
I am using BERTopic to perform the topic modelling, everything works perfectly fine. However, since I am forcing the algorithm to give me 10 topics using nr_topics=10 as output, and when I visualize the topics overtime using
topic_model.visualize_topics_over_time(topics_over_time, top_n_topics=10, width=1250, height=450), some colors are repeated for topics as there are only 7 colors mentioned in the function visualize_topics_over_time. I tried executing the same function in my python notebook with additional color values, but it gives me the following error:

 Can someone please help me update the function with additional four colors?

答:
To add colors to the function, you will indeed have to copy the function and change it to include more colors:

import pandas as pd
from typing import List
import plotly.graph_objects as go
from sklearn.preprocessing import normalize

def visualize_topics_over_time(topic_model,
                               topics_over_time: pd.DataFrame,
                               top_n_topics: int = None,
                               topics: List[int] = None,
                               normalize_frequency: bool = False,
                               width: int = 1250,
                               height: int = 450) -> go.Figure:
    """ Visualize topics over time
    Arguments:
        topic_model: A fitted BERTopic instance.
        topics_over_time: The topics you would like to be visualized with the
                          corresponding topic representation
        top_n_topics: To visualize the most frequent topics instead of all
        topics: Select which topics you would like to be visualized
        normalize_frequency: Whether to normalize each topic's frequency individually
        width: The width of the figure.
        height: The height of the figure.
    Returns:
        A plotly.graph_objects.Figure including all traces
    Usage:
    To visualize the topics over time, simply run:
    ```python
    topics_over_time = topic_model.topics_over_time(docs, topics, timestamps)
    topic_model.visualize_topics_over_time(topics_over_time)
    ```
    Or if you want to save the resulting figure:
    ```python
    fig = topic_model.visualize_topics_over_time(topics_over_time)
    fig.write_html("path/to/file.html")
    ```

    """
    colors = ["#E69F00", "#56B4E9", "#009E73", "#F0E442", "#D55E00", "#0072B2", "#CC79A7"]  # DEFINE MORE COLORS HERE

    # Select topics
    if topics:
        selected_topics = topics
    elif top_n_topics:
        selected_topics = topic_model.get_topic_freq().head(top_n_topics + 1)[1:].Topic.values
    else:
        selected_topics = topic_model.get_topic_freq().Topic.values

    # Prepare data
    topic_names = {key: value[:40] + "..." if len(value) > 40 else value
                   for key, value in topic_model.topic_names.items()}
    topics_over_time["Name"] = topics_over_time.Topic.map(topic_names)
    data = topics_over_time.loc[topics_over_time.Topic.isin(selected_topics), :]

    # Add traces
    fig = go.Figure()
    for index, topic in enumerate(data.Topic.unique()):
        trace_data = data.loc[data.Topic == topic, :]
        topic_name = trace_data.Name.values[0]
        words = trace_data.Words.values
        if normalize_frequency:
            y = normalize(trace_data.Frequency.values.reshape(1, -1))[0]
        else:
            y = trace_data.Frequency
        fig.add_trace(go.Scatter(x=trace_data.Timestamp, y=y,
                                 mode='lines',
                                 marker_color=colors[index % 7],
                                 hoverinfo="text",
                                 name=topic_name,
                                 hovertext=[f'Topic {topic}
Words: {word}' for word in words]))

    # Styling of the visualization
    fig.update_xaxes(showgrid=True)
    fig.update_yaxes(showgrid=True)
    fig.update_layout(
        yaxis_title="Normalized Frequency" if normalize_frequency else "Frequency",
        title={
            'text': "Topics over Time",
            'y': .95,
            'x': 0.40,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': dict(
                size=22,
                color="Black")
        },
        template="simple_white",
        width=width,
        height=height,
        hoverlabel=dict(
            bgcolor="white",
            font_size=16,
            font_family="Rockwell"
        ),
        legend=dict(
            title="Global Topic Representation",
        )
    )
    return fig
```
<p>Then, you can use the function as follows:</p>
<pre class="lang-py prettyprint-override"><code>import re
import pandas as pd
from bertopic import BERTopic

# Prepare data
trump = pd.read_csv('https://drive.google.com/uc?export=download&id=1xRKHaP-QwACMydlDnyFPEaFdtskJuBa6')
trump.text = trump.apply(lambda row: re.sub(r"http\S+", "", row.text).lower(), 1)
trump.text = trump.apply(lambda row: " ".join(filter(lambda x:x[0]!="@", row.text.split())), 1)
trump.text = trump.apply(lambda row: " ".join(re.sub("[^a-zA-Z]+", " ", row.text).split()), 1)
trump = trump.loc[(trump.isRetweet == "f") & (trump.text != ""), :]
timestamps = trump.date.to_list()
tweets = trump.text.to_list()

# Create topics over time
model = BERTopic(verbose=True)
topics, probs = model.fit_transform(tweets)
topics_over_time = model.topics_over_time(tweets, topics, timestamps)

# Visualize topics over time with the updated colors
visualize_topics_over_time(model, topics_over_time)
</code>```

Body:
To add colors to the function, you will indeed have to copy the function and change it to include more colors:

import pandas as pd
from typing import List
import plotly.graph_objects as go
from sklearn.preprocessing import normalize

def visualize_topics_over_time(topic_model,
                               topics_over_time: pd.DataFrame,
                               top_n_topics: int = None,
                               topics: List[int] = None,
                               normalize_frequency: bool = False,
                               width: int = 1250,
                               height: int = 450) -> go.Figure:
    """ Visualize topics over time
    Arguments:
        topic_model: A fitted BERTopic instance.
        topics_over_time: The topics you would like to be visualized with the
                          corresponding topic representation
        top_n_topics: To visualize the most frequent topics instead of all
        topics: Select which topics you would like to be visualized
        normalize_frequency: Whether to normalize each topic's frequency individually
        width: The width of the figure.
        height: The height of the figure.
    Returns:
        A plotly.graph_objects.Figure including all traces
    Usage:
    To visualize the topics over time, simply run:
    ```python
    topics_over_time = topic_model.topics_over_time(docs, topics, timestamps)
    topic_model.visualize_topics_over_time(topics_over_time)
    ```
    Or if you want to save the resulting figure:
    ```python
    fig = topic_model.visualize_topics_over_time(topics_over_time)
    fig.write_html("path/to/file.html")
    ```
    <iframe src="../../getting_started/visualization/trump.html"
    style="width:1000px; height: 680px; border: 0px;""></iframe>
    """
    colors = ["#E69F00", "#56B4E9", "#009E73", "#F0E442", "#D55E00", "#0072B2", "#CC79A7"]  # DEFINE MORE COLORS HERE

    # Select topics
    if topics:
        selected_topics = topics
    elif top_n_topics:
        selected_topics = topic_model.get_topic_freq().head(top_n_topics + 1)[1:].Topic.values
    else:
        selected_topics = topic_model.get_topic_freq().Topic.values

    # Prepare data
    topic_names = {key: value[:40] + "..." if len(value) > 40 else value
                   for key, value in topic_model.topic_names.items()}
    topics_over_time["Name"] = topics_over_time.Topic.map(topic_names)
    data = topics_over_time.loc[topics_over_time.Topic.isin(selected_topics), :]

    # Add traces
    fig = go.Figure()
    for index, topic in enumerate(data.Topic.unique()):
        trace_data = data.loc[data.Topic == topic, :]
        topic_name = trace_data.Name.values[0]
        words = trace_data.Words.values
        if normalize_frequency:
            y = normalize(trace_data.Frequency.values.reshape(1, -1))[0]
        else:
            y = trace_data.Frequency
        fig.add_trace(go.Scatter(x=trace_data.Timestamp, y=y,
                                 mode='lines',
                                 marker_color=colors[index % 7],
                                 hoverinfo="text",
                                 name=topic_name,
                                 hovertext=[f'<b>Topic {topic}</b><br>Words: {word}' for word in words]))

    # Styling of the visualization
    fig.update_xaxes(showgrid=True)
    fig.update_yaxes(showgrid=True)
    fig.update_layout(
        yaxis_title="Normalized Frequency" if normalize_frequency else "Frequency",
        title={
            'text': "<b>Topics over Time",
            'y': .95,
            'x': 0.40,
            'xanchor': 'center',
            'yanchor': 'top',
            'font': dict(
                size=22,
                color="Black")
        },
        template="simple_white",
        width=width,
        height=height,
        hoverlabel=dict(
            bgcolor="white",
            font_size=16,
            font_family="Rockwell"
        ),
        legend=dict(
            title="<b>Global Topic Representation",
        )
    )
    return fig

Then, you can use the function as follows:

import re
import pandas as pd
from bertopic import BERTopic

# Prepare data
trump = pd.read_csv('https://drive.google.com/uc?export=download&id=1xRKHaP-QwACMydlDnyFPEaFdtskJuBa6')
trump.text = trump.apply(lambda row: re.sub(r"http\S+", "", row.text).lower(), 1)
trump.text = trump.apply(lambda row: " ".join(filter(lambda x:x[0]!="@", row.text.split())), 1)
trump.text = trump.apply(lambda row: " ".join(re.sub("[^a-zA-Z]+", " ", row.text).split()), 1)
trump = trump.loc[(trump.isRetweet == "f") & (trump.text != ""), :]
timestamps = trump.date.to_list()
tweets = trump.text.to_list()

# Create topics over time
model = BERTopic(verbose=True)
topics, probs = model.fit_transform(tweets)
topics_over_time = model.topics_over_time(tweets, topics, timestamps)

# Visualize topics over time with the updated colors
visualize_topics_over_time(model, topics_over_time)


问:
Git: can't undo local changes (error: path ... is unmerged)
I have following working tree state

```<code>$ git status foo/bar.txt
# On branch master
# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#       deleted by us:      foo/bar.txt
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

File foo/bar.txt is there and I want to get it to the "unchanged state" again (similar to 'svn revert'):

```<code>$ git checkout HEAD foo/bar.txt
error: path 'foo/bar.txt' is unmerged
$ git reset HEAD foo/bar.txt
Unstaged changes after reset:
M       foo/bar.txt
</code>```

Now it is getting confusing:

```<code>$ git status foo/bar.txt
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   foo/bar.txt
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   foo/bar.txt
#
</code>```

The same file in both sections, new and modified? What should I do?

答:
If the above answers didn't work try:</p>
```<code>git reset -–merge
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have following working tree state

$ git status foo/bar.txt
# On branch master
# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add/rm <file>..." as appropriate to mark resolution)
#
#       deleted by us:      foo/bar.txt
#
no changes added to commit (use "git add" and/or "git commit -a")

File foo/bar.txt is there and I want to get it to the "unchanged state" again (similar to 'svn revert'):

$ git checkout HEAD foo/bar.txt
error: path 'foo/bar.txt' is unmerged
$ git reset HEAD foo/bar.txt
Unstaged changes after reset:
M       foo/bar.txt

Now it is getting confusing:

$ git status foo/bar.txt
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   foo/bar.txt
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   foo/bar.txt
#

The same file in both sections, new and modified? What should I do?

Body:
If the above answers didn't work try:

git reset -–merge


问:
MDX query: How to compare year to date figures from the current year with year to date figures from the previous year?
With the below MDX queries I am attempting to return a comparison of sales figures.

I want to compare YTD with LYTD, defined as follows:

YTD: 01 Jan this year (01/Jan/2011) until today (17/Aug/2011)

LYTD: 01 Jan last year (01/Jan/2010) until today's date last year (17/Aug/2010)

Both periods should contain the same number of days (give or take one day for leap years).

So far I have tried using the YTD() function to get this year's data but I have not had much success with wrapping the YTD() function in something to get it to return the same dates from last year. I have employed LAG(1) and ParallelPeriod (see both examples below):

```<code>WITH
MEMBER [Measures].[Sales YTD] AS
    'SUM(YTD(),[Measures].[Sales])'
MEMBER [Measures].[Sales LYTD] AS
    'SUM((YTD(),[Measures].[Sales]).LAG(1))'
SELECT
    {[Sales YTD], [Sales LYTD]} ON COLUMNS
    ...
</code>```

Or

```<code>WITH
MEMBER [Measures].[Sales YTD] AS
    'SUM(YTD(),[Measures].[Sales])'
MEMBER [Measures].[Sales LYTD] AS
    'SUM(ParallelPeriod(YTD(),1),[Measures].[Sales])'
SELECT
    {[Sales YTD], [Sales LYTD]} ON COLUMNS
    ...
</code>```

The resulting data when using either ParallelPeriod or LAG always returns a column of nulls for Last Year's sales:

```<code>Customer    Sales YTD  Sales LYTD
ABC Screws      $1024       (Null)
ABC Bolts       $2392       (Null)
ABC Nuts        $3735       (Null)
</code>```

Can anybody suggest changes to the query which will return the correct data, or perhaps offer an alternative strategy to using LAG or ParallelPeriod?

答:
Not long after posting the question and further experimentation the following construction seemed to return the results I was looking for:

```<code>WITH
MEMBER [Measures].[Sales YTD] AS
    'SUM(YTD(),[Measures].[Sales])'
MEMBER [Measures].[Sales LYTD] AS
    'SUM(YTD(ParallelPeriod([Time].[Year],1,[Time].CURRENTMEMBER)),[Measures].[Sales])'
SELECT
    {[Sales YTD], [Sales LYTD]} ON COLUMNS
    ...
</code>```

I would have posted my answer yesterday evening but users with less than 100 points have to wait 8 hours before they can answer their own questions.

@Max Thanks for your input, looks like you had the same idea. Therefore you get the accepted answer even though I'm using my own for the implementation.

Body:
With the below MDX queries I am attempting to return a comparison of sales figures.

I want to compare YTD with LYTD, defined as follows:

YTD: 01 Jan this year (01/Jan/2011) until today (17/Aug/2011)

LYTD: 01 Jan last year (01/Jan/2010) until today's date last year (17/Aug/2010)

Both periods should contain the same number of days (give or take one day for leap years).

So far I have tried using the YTD() function to get this year's data but I have not had much success with wrapping the YTD() function in something to get it to return the same dates from last year. I have employed LAG(1) and ParallelPeriod (see both examples below):

WITH
MEMBER [Measures].[Sales YTD] AS
    'SUM(YTD(),[Measures].[Sales])'
MEMBER [Measures].[Sales LYTD] AS
    'SUM((YTD(),[Measures].[Sales]).LAG(1))'
SELECT
    {[Sales YTD], [Sales LYTD]} ON COLUMNS
    ...

Or

WITH
MEMBER [Measures].[Sales YTD] AS
    'SUM(YTD(),[Measures].[Sales])'
MEMBER [Measures].[Sales LYTD] AS
    'SUM(ParallelPeriod(YTD(),1),[Measures].[Sales])'
SELECT
    {[Sales YTD], [Sales LYTD]} ON COLUMNS
    ...

The resulting data when using either ParallelPeriod or LAG always returns a column of nulls for Last Year's sales:

Customer    Sales YTD  Sales LYTD
ABC Screws      $1024       (Null)
ABC Bolts       $2392       (Null)
ABC Nuts        $3735       (Null)

Can anybody suggest changes to the query which will return the correct data, or perhaps offer an alternative strategy to using LAG or ParallelPeriod?

Body:
Not long after posting the question and further experimentation the following construction seemed to return the results I was looking for:

WITH
MEMBER [Measures].[Sales YTD] AS
    'SUM(YTD(),[Measures].[Sales])'
MEMBER [Measures].[Sales LYTD] AS
    'SUM(YTD(ParallelPeriod([Time].[Year],1,[Time].CURRENTMEMBER)),[Measures].[Sales])'
SELECT
    {[Sales YTD], [Sales LYTD]} ON COLUMNS
    ...

I would have posted my answer yesterday evening but users with less than 100 points have to wait 8 hours before they can answer their own questions.

@Max Thanks for your input, looks like you had the same idea. Therefore you get the accepted answer even though I'm using my own for the implementation.


问:
please rebuild precompiled header error when building inet project
I'm working with inet and veins in omnet++, when I build inet project, there is always an error like the following in the console:

```<code>please rebuild precompiled header 'inet/common/precompiled_debug.h.pch'
</code>```

I can not understand how to solve the error. I tried to run ./configure then make clean and make. However the error still exists. I appreciate if anyone can guid me.

答: make cleanall should solve that, but simply deleting the inet/common/precompiled_debug.h.pch file will also solve the problem.

Body:
I'm working with inet and veins in omnet++, when I build inet project, there is always an error like the following in the console:

please rebuild precompiled header 'inet/common/precompiled_debug.h.pch'

I can not understand how to solve the error. I tried to run ./configure then make clean and make. However the error still exists. I appreciate if anyone can guid me.


问:
Calling super method from interface
I want to call a super method from overriden method with the same name from an interface thats extending another interface

Example:

```<code>    default private interface A {
        void foo() {
            System.out.println("B");
        }
    }

    private interface B extends A {
        @Override
        default void foo() {
            System.out.println("B");
        }
    }
</code>```

I want to call classC(implements interface B).foo() ending with output

```<code>B
A.foo() call
</code>```

How can i achive this?

In my case i dont want to implement interface B, because it's a interface thats extending JpaRepository, and I'm just calling repository methods using only this interface.

UPDATE:

I gave the wrong example, thats not describing my problem. Below is the description of my specific problem.

Before saving object to db i want to make some actoions on this object. I'm using interface repositories. I want to override a Repository.save(Object o) method, and make changes there, but im just not able to call a super method from extended repository.

Example:

```<code>public interface FooRepository extends MongoRepository<Foo, String> {

    @Override
    default <S extends Foo> S save(S s) {
        s.doSth();
        return MongoRepository.super.save(s);   //This doesn't compile
    }
}
</code>```

I know i can do this by creating the class and injecting FooRepository in there, but is there any way to do this by overriding a save() method in FooRepository?

答: I don't think you can call that method without implementing interface B. JPA creates a framework-made implementation of JpaRepository interface under the hood, an implementation that you cannot access in order to call the foo method.</p>

Title: Calling super method from interface

Body:
I want to call a super method from overriden method with the same name from an interface thats extending another interface

Example:

    default private interface A {
        void foo() {
            System.out.println("B");
        }
    }

    private interface B extends A {
        @Override
        default void foo() {
            System.out.println("B");
        }
    }

I want to call classC(implements interface B).foo() ending with output

B
A.foo() call

How can i achive this?

In my case i dont want to implement interface B, because it's a interface thats extending JpaRepository, and I'm just calling repository methods using only this interface.

UPDATE:

I gave the wrong example, thats not describing my problem. Below is the description of my specific problem.

Before saving object to db i want to make some actoions on this object. I'm using interface repositories. I want to override a Repository.save(Object o) method, and make changes there, but im just not able to call a super method from extended repository.

Example:

public interface FooRepository extends MongoRepository<Foo, String> {

    @Override
    default <S extends Foo> S save(S s) {
        s.doSth();
        return MongoRepository.super.save(s);   //This doesn't compile
    }
}

I know i can do this by creating the class and injecting FooRepository in there, but is there any way to do this by overriding a save() method in FooRepository?


问:
How to create an HttpResponse object with dummy values in ktor Kotlin?
I am using ktor for developing a microservice in Kotlin. For testing a method, I need to create a dummy HttpResponse (io.ktor.client.statement.HttpResponse to be specific) object with status = 200 and body = some json data.

Any idea how I can create it?

答:
You can use mockk or a similar kind of library to mock an HttpResponse. Unfortunately, this is complicated because HttpRequest, HttpResponse, and HttpClient objects are tightly coupled with the HttpClientCall. Here is an example of how you can do that:

```<code>val call = mockk<HttpClientCall> {
    every { client } returns mockk {}
    coEvery { receive(io.ktor.util.reflect.typeInfo<String>()) } returns "body"
    every { coroutineContext } returns EmptyCoroutineContext
    every { attributes } returns Attributes()
    every { request } returns object : HttpRequest {
        override val call: HttpClientCall = this@mockk
        override val attributes: Attributes = Attributes()
        override val content: OutgoingContent = object : OutgoingContent.NoContent() {}
        override val headers: Headers = Headers.Empty
        override val method: HttpMethod = HttpMethod.Get
        override val url: Url = Url("/")
    }

    every { response } returns object : HttpResponse() {
        override val call: HttpClientCall = this@mockk
        override val content: ByteReadChannel = ByteReadChannel("body")
        override val coroutineContext: CoroutineContext = EmptyCoroutineContext
        override val headers: Headers = Headers.Empty
        override val requestTime: GMTDate = GMTDate.START
        override val responseTime: GMTDate = GMTDate.START
        override val status: HttpStatusCode = HttpStatusCode.OK
        override val version: HttpProtocolVersion = HttpProtocolVersion.HTTP_1_1
    }
}

val response = call.response
</code>```

Body:
You can use mockk or a similar kind of library to mock an HttpResponse. Unfortunately, this is complicated because HttpRequest, HttpResponse, and HttpClient objects are tightly coupled with the HttpClientCall. Here is an example of how you can do that:

val call = mockk<HttpClientCall> {
    every { client } returns mockk {}
    coEvery { receive(io.ktor.util.reflect.typeInfo<String>()) } returns "body"
    every { coroutineContext } returns EmptyCoroutineContext
    every { attributes } returns Attributes()
    every { request } returns object : HttpRequest {
        override val call: HttpClientCall = this@mockk
        override val attributes: Attributes = Attributes()
        override val content: OutgoingContent = object : OutgoingContent.NoContent() {}
        override val headers: Headers = Headers.Empty
        override val method: HttpMethod = HttpMethod.Get
        override val url: Url = Url("/")
    }

    every { response } returns object : HttpResponse() {
        override val call: HttpClientCall = this@mockk
        override val content: ByteReadChannel = ByteReadChannel("body")
        override val coroutineContext: CoroutineContext = EmptyCoroutineContext
        override val headers: Headers = Headers.Empty
        override val requestTime: GMTDate = GMTDate.START
        override val responseTime: GMTDate = GMTDate.START
        override val status: HttpStatusCode = HttpStatusCode.OK
        override val version: HttpProtocolVersion = HttpProtocolVersion.HTTP_1_1
    }
}

val response = call.response


问:
Changing Color of Text Based on Variable
Trying to make a simple increase/decrease counter. When var n is < 0 it changes to red, and same for ==, but when its greater than it stays black..am i missing something?

```<code>var n = 0

function increase() {
    n = n + 1
    document.getElementById('num').innerHTML = n
    if (n > 0) {
        document.getElementById('num').style.color = '#013220'
    }
    else if (n < 0) {
        document.getElementById('num').style.color = '#ff0000'
    }
    else if (n == 0) {
        document.getElementById('num').style.color = '#000000'
    }
}
</code>```

no error messages.

答:
this is a way to do it:

var n = -2. // let me start with a negative number so we can see that color too

function increase() {
    n = n + 1;
    let color = '#000000'; // default color is black
    if (n > 0){
        color = '#CC0'; // yellow when n > 0
    }
    if (n < 0){
        color = '#ff0000'; // red when n < 0
    }
    const elem = document.getElementById('numWrapper')
    elem.innerHTML = n
    elem.style.color = color

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='numWrapper'>-2</div>
<button onClick='increase()'>Increase</button></code>```

Body:
Trying to make a simple increase/decrease counter. When var n is < 0 it changes to red, and same for ==, but when its greater than it stays black..am i missing something?

var n = 0

function increase() {
    n = n + 1
    document.getElementById('num').innerHTML = n
    if (n > 0) {
        document.getElementById('num').style.color = '#013220'
    }
    else if (n < 0) {
        document.getElementById('num').style.color = '#ff0000'
    }
    else if (n == 0) {
        document.getElementById('num').style.color = '#000000'
    }
}

no error messages.

Body:
this is a way to do it:

var n = -2. // let me start with a negative number so we can see that color too

function increase() {
    n = n + 1;
    let color = '#000000'; // default color is black
    if (n > 0){
        color = '#CC0'; // yellow when n > 0
    }
    if (n < 0){
        color = '#ff0000'; // red when n < 0
    }
    const elem = document.getElementById('numWrapper')
    elem.innerHTML = n
    elem.style.color = color

}

<div id='numWrapper'>-2</div>
<button onClick='increase()'>Increase</button>


问:
when using dcc.Store(), TypeError: Object of type DataFrame is not JSON serializable
I am using dcc.Store() to share dataframe data between callback. and I got an error of
TypeError: Object of type DataFrame is not JSON serializable.  Thanks for your help.</p>
```<code>
@app.callback(
    [
    Output("well-table", "data"),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State("select-area-dropdown", "value"),
     State('read-existing-data-radio','value'),
    ],

    prevent_initial_call=True,   # disable output in the first load
)
def change_area_data(n_clicks,area,read_existing_radio):

...
    s=json.dumps(df_timedata)
    return (datatable_thisarea,
            s,
           )
TypeError: Object of type DataFrame is not JSON serializable

</code>```

答:
This is usually due to collecting/passing/returning a raw dataframe rather than a JSON-compatible version of it which can be serialised. You haven't provided an in-depth error log for this issue, but I highly suspect that you are returning the df_timedata incorrectly back to a dash datatable.

In any case, make sure you convert the dataframe using something like pandas.DataFrame.to_dict() which can be serialised and then storing that in a dcc.Store. you can reconvert back to a dataframe using pandas.DataFrame.from_dict()

Body:
I am using dcc.Store() to share dataframe data between callback. and I got an error of
TypeError: Object of type DataFrame is not JSON serializable.  Thanks for your help.

@app.callback(
    [
    Output("well-table", "data"),
    ],
    [
    Input('load-area-data','n_clicks'),
    ],
    [
     State("select-area-dropdown", "value"),
     State('read-existing-data-radio','value'),
    ],

    prevent_initial_call=True,   # disable output in the first load
)
def change_area_data(n_clicks,area,read_existing_radio):

...
    s=json.dumps(df_timedata)
    return (datatable_thisarea,
            s,
           )
TypeError: Object of type DataFrame is not JSON serializable


问:
Clicking content below image with higher z-index
I have created a slider using jquery and the slides plugin. I wanted to create an effect where it looks like the slider is circular shaped, so I positioned an image with a transparent circular center absolutely above the slider, with a higher z-index. You can see a working example here:  http://vitaminjdesign.com/example/examples/Standard/index.html

The problem I have having is that you cannot click on anything within the slider, because of the "mask image" which has a higher z-index than the rest of the content. I want to be able to click on the links within the caption area, as well as the entire slide. Does anybody have any good ideas on how to solve this issue?

I cannot give .caption a higher z-index than the mask because then you would see the background pass above the circular mask. BUT I need to be able to click within the transparent area of the image mask. Any ideas?

答:
It seems, that your slider returns false, when a click on a link occurs. So give much attention to the next line in the code window.location.href = myLink.attr('href');

```<code>$('#slides #mask').click(function (e) {

    // user click coordinates
    var cursorPosX = e.pageX;
    var cursorPosY = e.pageY;

    $('#slides .caption a').each(function () {
        var myLink = $(this);

        // coordinates of the link at the moment
        var linkPosLeft = myLink.offset().left;
        var linkPosTop = myLink.offset().top;

        // parameters of the link
        var linkWidth = myLink.width() + linkPosLeft;
        var linkHeight = myLink.height() + linkPosTop;

        // compare...
        if ( cursorPosX >= linkPosLeft && cursorPosX <= linkWidth ) {
            if ( cursorPosY >= linkPosTop && cursorPosY <= linkHeight ) {
                window.location.href = myLink.attr('href');
            }
        }
    });

});
</code>```

Body:
It seems, that your slider returns false, when a click on a link occurs. So give much attention to the next line in the code window.location.href = myLink.attr('href');

$('#slides #mask').click(function (e) {

    // user click coordinates
    var cursorPosX = e.pageX;
    var cursorPosY = e.pageY;

    $('#slides .caption a').each(function () {
        var myLink = $(this);

        // coordinates of the link at the moment
        var linkPosLeft = myLink.offset().left;
        var linkPosTop = myLink.offset().top;

        // parameters of the link
        var linkWidth = myLink.width() + linkPosLeft;
        var linkHeight = myLink.height() + linkPosTop;

        // compare...
        if ( cursorPosX >= linkPosLeft && cursorPosX <= linkWidth ) {
            if ( cursorPosY >= linkPosTop && cursorPosY <= linkHeight ) {
                window.location.href = myLink.attr('href');
            }
        }
    });

});


问:
How to add y bar in ggplot2() annotate?
I'm trying to add an annotation in my ggplot using annotate, but I was wondering if I can add the expression x bar (in latex it should be $\bar{x}$) in there.</p>

答:
Another option is to use unicode with bquote. However, when plotting directly in R, the bar may be slightly to the right (though this is probably device dependent). To get a high resolution image with the correct placement, you can use a combination of ggsave and ragg. Then, when the file is read back into R, it will plot correctly.

```<code>library(ggplot2)
library(magick)
library(ragg)

p <- ggplot(data.frame(x = 50, y = 25), aes(x, y)) +
  annotate(
    geom = "text",
    x = 50,
    y = 25,
    label = bquote("x\u0305") ,
    size = 10
  )

ggsave("agg_png-ggsave.png", p, device = agg_png)
ggs <- image_read("agg_png-ggsave.png")
</code>```

Title: How to add y bar in ggplot2() annotate?

Body:
Another option is to use unicode with bquote. However, when plotting directly in R, the bar may be slightly to the right (though this is probably device dependent). To get a high resolution image with the correct placement, you can use a combination of ggsave and ragg. Then, when the file is read back into R, it will plot correctly.

library(ggplot2)
library(magick)
library(ragg)

p <- ggplot(data.frame(x = 50, y = 25), aes(x, y)) +
  annotate(
    geom = "text",
    x = 50,
    y = 25,
    label = bquote("x\u0305") ,
    size = 10
  )

ggsave("agg_png-ggsave.png", p, device = agg_png)
ggs <- image_read("agg_png-ggsave.png")


问:
Inner join three tables out of which one is not connected with other
I have three tables client_invoices ,contract_additional_info and contract out of which
client_invoices is connected with contract_additional_info  and contract_additional_info is connected with contract table .

contract table and client_invoices table don't have any relations.

Now I am running following query

```<code>SELECT   client_invoices.markup_type,
         client_invoices.supplier_invoice_number,
         client_invoices.client_payment_req_id,
         client_invoices.net_amount,
         client_invoices.markup_value,
         client_invoices.net_qty,
         client_invoices.markup_value,
         contract.clientId as buyerClientId,
         contract_additional_info.buyer_contract_id as contract_id
FROM client_invoices
INNER JOIN contract_additional_info ON contract_additional_info.contract_id =client_invoices.contract_id
INNER JOIN contract ON contract_additional_info.buyer_contract_id = contract.id
WHERE  client_invoices.status=3 ;
</code>```

It is giving me duplicate records ,how to fix the query such that it only gives unique records (unique client_invoice.supplier_invoice_number)

答: Have you tried using SELECT DISTINCT? This should give you only unique records.

Body:
I have three tables client_invoices ,contract_additional_info and contract out of which
client_invoices is connected with contract_additional_info  and contract_additional_info is connected with contract table .

contract table and client_invoices table don't have any relations.

Now I am running following query

SELECT   client_invoices.markup_type,
         client_invoices.supplier_invoice_number,
         client_invoices.client_payment_req_id,
         client_invoices.net_amount,
         client_invoices.markup_value,
         client_invoices.net_qty,
         client_invoices.markup_value,
         contract.clientId as buyerClientId,
         contract_additional_info.buyer_contract_id as contract_id
FROM client_invoices
INNER JOIN contract_additional_info ON contract_additional_info.contract_id =client_invoices.contract_id
INNER JOIN contract ON contract_additional_info.buyer_contract_id = contract.id
WHERE  client_invoices.status=3 ;

It is giving me duplicate records ,how to fix the query such that it only gives unique records (unique client_invoice.supplier_invoice_number)


问:
Need help understanding an event being assigned "delegate { }"
While looking at an UWP example app, I came across this code. What I don't understand and can't seem to find in google is line 40:

```<code>        public event PropertyChangedEventHandler PropertyChanged = delegate { };
</code>```

Says in the comments that it is a multicast event. What does assigning delegate { } do? Does it have anything to do with the comment saying the event is multicast?

答:
What does assigning delegate { } do?

That is simply adding an anonymous function to the event, with an empty body. Since C#3, one would generally use a lambda expression instead:

```<code>public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };
</code>```

However, lambda expressions require each parameter to be elicited, whereas using delegate does not. So if you don't need to use the arguments, then delegate may be more concise.

Microsoft highlight this as the single remaining use case of the delegate syntax for defining an anonymous function:

When you use the delegate operator, you might omit the parameter list. If you do that, the created anonymous method can be converted to a delegate type with any list of parameters. That's the only functionality of anonymous methods that is not supported by lambda expressions. In all other cases, a lambda expression is a preferred way to write inline code.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/delegate-operator

Does it have anything to do with the comment saying the event is multicast?

No; multicast means that you can add more than one handling function to the event, and when the event is raised, each one is invoked.

For example:

```<code>class Example
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaiseEvent()
    {
        PropertyChanged?.Invoke(default, default);
    }
}

var example = new Example();

// Use the += operator to add a new handler (rather than = which overwrites)
example += delegate { Console.Writeline("Handler 1"); };
example += delegate { Console.Writeline("Handler 2"); };

example.RaiseEvent();

// Output:
// Handler 1
// Handler 2
</code>```

Follow up question: What is the purpose of assigning an anonymous function to the event?

If no handler has been added, invoking the event can cause a NullReferenceException, so assigning an empty handler could remove the necessity to handle null.

So the event can be raised like this:

```<code>PropertyChanged.Invoke(default, default);
</code>```

Or this:

```<code>PropertyChanged(default, default);
</code>```

Rather than this:

```<code>PropertyChanged?.Invoke(default, default);
</code>```

Body:
While looking at an UWP example app, I came across this code. What I don't understand and can't seem to find in google is line 40:

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

Says in the comments that it is a multicast event. What does assigning delegate { } do? Does it have anything to do with the comment saying the event is multicast?

Body:
What does assigning delegate { } do?

That is simply adding an anonymous function to the event, with an empty body. Since C#3, one would generally use a lambda expression instead:

public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

However, lambda expressions require each parameter to be elicited, whereas using delegate does not. So if you don't need to use the arguments, then delegate may be more concise.

Microsoft highlight this as the single remaining use case of the delegate syntax for defining an anonymous function:

When you use the delegate operator, you might omit the parameter list. If you do that, the created anonymous method can be converted to a delegate type with any list of parameters. That's the only functionality of anonymous methods that is not supported by lambda expressions. In all other cases, a lambda expression is a preferred way to write inline code.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/delegate-operator

Does it have anything to do with the comment saying the event is multicast?

No; multicast means that you can add more than one handling function to the event, and when the event is raised, each one is invoked.

For example:

class Example
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaiseEvent()
    {
        PropertyChanged?.Invoke(default, default);
    }
}

var example = new Example();

// Use the += operator to add a new handler (rather than = which overwrites)
example += delegate { Console.Writeline("Handler 1"); };
example += delegate { Console.Writeline("Handler 2"); };

example.RaiseEvent();

// Output:
// Handler 1
// Handler 2

Follow up question: What is the purpose of assigning an anonymous function to the event?

If no handler has been added, invoking the event can cause a NullReferenceException, so assigning an empty handler could remove the necessity to handle null.

So the event can be raised like this:

PropertyChanged.Invoke(default, default);

Or this:

PropertyChanged(default, default);

Rather than this:

PropertyChanged?.Invoke(default, default);


问:
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?
I'm trying to migrate some Java library from 'normal' JVM to android and stuck with some Java11 APIs used in the code.

The first thing I already got - Java11 language features seems to work only with Canary build of Android Studio, see answer here

Now I need to get understanding about which APIs can be really used. Here are two use-cases which do not work for me and I can't get if I'm doing something wrong or it never should work:

List.copyOf() - introduced in Java11, method copyOf is not available on android. Methods 'List.of()', introduced with Java 9, work OK.

class java.lang.invoke.LambdaMetafactory - introduced with Java 1.8 - to be used for programmatic creation of lambdas for usage instead for reflection, is not visible on Android.

I see both of them in sources of desugar_jdk_libs here:

https://github.com/google/desugar_jdk_libs/blob/master/jdk11/src/java.base/share/classes/java/lang/invoke/LambdaMetafactory.java

https://github.com/google/desugar_jdk_libs/blob/master/src/share/classes/java/util/List.java

So - the question is: how can I identify if some Java API is supposed to be available in 'desugared' android build or no? What really can be expected from 'desugaring'?

Steps to reproduce:

Using Android Studio Canary generate a dummy "Basic Activity" project

Make sure following is provided in build.gradle

```<code>android {
    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
}
dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}
</code>```

Add following lines somewhere in code

```<code>        List<Integer> ints1 = List.of(1, 2, 3);
        Supplier<List<Object>> listSupplier = () -> new ArrayList<>();
        List<Object> alist = listSupplier.get();

        List<Integer> ints2 = List.copyOf(ints1);
        LambdaMetafactory.metafactory(null,null,null,null,null,null);
</code>```

Last 2 lines fail to compile for me.

PS: final application is supposed to work on Android 10+.

答:
Desugaring lib is considered unofficial. We can't expect an exact answer. We get the feature when it is ready. Now List.copyOf() method now working with the latest Gradle version.

About the LambdaMetafactory class, It is not included in Android Javadoc.  This means we assume we don't have LambdaMetafactory at all. Google stripped down some java API for being lightweight.

In general, We should check android Javadoc first. If android Javadoc has no mention about some API. We can be sure we won't get that feature anytime soon.

Body:
I'm trying to migrate some Java library from 'normal' JVM to android and stuck with some Java11 APIs used in the code.

The first thing I already got - Java11 language features seems to work only with Canary build of Android Studio, see answer here

Now I need to get understanding about which APIs can be really used. Here are two use-cases which do not work for me and I can't get if I'm doing something wrong or it never should work:

List.copyOf() - introduced in Java11, method copyOf is not available on android. Methods 'List.of()', introduced with Java 9, work OK.

class java.lang.invoke.LambdaMetafactory - introduced with Java 1.8 - to be used for programmatic creation of lambdas for usage instead for reflection, is not visible on Android.

I see both of them in sources of desugar_jdk_libs here:

https://github.com/google/desugar_jdk_libs/blob/master/jdk11/src/java.base/share/classes/java/lang/invoke/LambdaMetafactory.java

https://github.com/google/desugar_jdk_libs/blob/master/src/share/classes/java/util/List.java

So - the question is: how can I identify if some Java API is supposed to be available in 'desugared' android build or no? What really can be expected from 'desugaring'?

Steps to reproduce:

Using Android Studio Canary generate a dummy "Basic Activity" project

Make sure following is provided in build.gradle

android {
    compileOptions {
        coreLibraryDesugaringEnabled true
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
}
dependencies {
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

Add following lines somewhere in code

        List<Integer> ints1 = List.of(1, 2, 3);
        Supplier<List<Object>> listSupplier = () -> new ArrayList<>();
        List<Object> alist = listSupplier.get();

        List<Integer> ints2 = List.copyOf(ints1);
        LambdaMetafactory.metafactory(null,null,null,null,null,null);

Last 2 lines fail to compile for me.

PS: final application is supposed to work on Android 10+.


问:
nginx: load 404 page if location is not matched with given url
in nginx.conf I have used this

try_files $uri $uri/ /index.php;

so that when user type any url the index.php will load.

but now I have some list of url. like [blog, contact, faq]

so when user hit anything out of that url. for example, /test I want to display the 404 page.

how can I achieve that?

here is the location block

```<code>location / {
             auth_basic "Restricted Content";
             auth_basic_user_file /etc/nginx/.htpasswd;
             try_files $uri $uri/ /index.php;

         }
</code>```

答:
If it's a long list, use a map, but if its a short list, add extra location rules:

```<code>location = /test { return 404; }
</code>```

If you want these rules to be subject to your auth_basic, either nest them within the location / block, or if possible, move the auth_basic statements into the outer block.

Body:
in nginx.conf I have used this

try_files $uri $uri/ /index.php;

so that when user type any url the index.php will load.

but now I have some list of url. like [blog, contact, faq]

so when user hit anything out of that url. for example, /test I want to display the 404 page.

how can I achieve that?

here is the location block

location / {
             auth_basic "Restricted Content";
             auth_basic_user_file /etc/nginx/.htpasswd;
             try_files $uri $uri/ /index.php;

         }

Body:
If it's a long list, use a map, but if its a short list, add extra location rules:

location = /test { return 404; }

If you want these rules to be subject to your auth_basic, either nest them within the location / block, or if possible, move the auth_basic statements into the outer block.


问:
One-to-One relationship in Entity Framework Core
I have been playing around with .NET Core for the past couple of weeks and decided to try EF Core (coming from ASP.NET MVC with NHibernate). After a bit of digging I found a nice extensions called EF Visual Designer. It allows me to visually create the model and generate code.

I have defined a simple one-to-one relationship shown in the diagram:
Simple one-to-one relationship

After generating the code I get the following as Fluent API code:

```<code>modelBuilder.Entity<Authentication>()
   .ToTable("Authentications")
   .HasKey(t => t.Id);

modelBuilder.Entity<Authentication>()
    .Property(t => t.Id)
    .IsRequired()
    .ValueGeneratedOnAdd();

modelBuilder.Entity<User>()
     .ToTable("Users")
     .HasKey(t => t.Id);

modelBuilder.Entity<User>()
     .Property(t => t.Id)
     .IsRequired()
     .ValueGeneratedOnAdd();

modelBuilder.Entity<User>()
    .HasOne(x => x.Authentication)
    .WithOne()
    .HasForeignKey("Authentication_Id")
    .IsRequired();
</code>```

The user class has the following (relevant) properties:

```<code>public Class User {
    [Key]
    [Required]
    public Guid Id { get; set; }
    ...
    public virtual Authentication Authentication { get; set; }
}
</code>```

Authentication has the following (relevant) property:

```<code>public class Authentication  {
    [Key]
    [Required]
    public Guid Id { get; set; }
}
</code>```

However when I try to generate a migration I get the following error:

You are configuring a relationship between 'User' and 'Authentication'
but have specified a foreign key on
'Authentication_Id'. The foreign key
must be defined on a type that is part of the relationship.

I tried switching to a many-to-one relationship and that works without any problems. That could be a work-around but not a very clean one. Is this perhaps due to naming issues like both entities having "Id" as primary key?

If that's the case, what is the "best practice"? Do I give every entity a unique ID-column name? How do I go about an abstract entity with derived classes all inheriting the ID column?

答:
All who have responded thus far are right. You were missing a foreign key in your dependent entity, so you need to add one. According to your code, it has to be "Authentication_Id" as that is the name that you referenced -- yet you had not actually declared one!

Secondly, Vladislav Vazhenin is right:

Got an error when tried to build on .HasForeignKey(x => x.AuthenticationId);
But .HasForeignKey <User> (x => x.AuthenticationId); worked for me

Just make sure that you point to the navigation properties and not the associated entity key properties (Authentication vs AuthenticationId). So, consider that.

In fact, someone needs to push for the documentation (which seems to be user edited) to include these subtle differences. For example; .HasOne also has a variation of

```<code>.HasOne(x=>x.Authentication)
</code>```

and

```<code>.HasOne<Authentication>()
</code>```

Include, a note on if they differ by the versions of Entity Framework Core. The compiler sometimes blocks and or ignores some of these nice to haves or deprecated command variations. But we need to know which will work for which version and how the overriding of data annotations by fluent api works (put emphasis on which one takes precedence).

Body:
I have been playing around with .NET Core for the past couple of weeks and decided to try EF Core (coming from ASP.NET MVC with NHibernate). After a bit of digging I found a nice extensions called EF Visual Designer. It allows me to visually create the model and generate code.

I have defined a simple one-to-one relationship shown in the diagram:
Simple one-to-one relationship

After generating the code I get the following as Fluent API code:

modelBuilder.Entity<Authentication>()
   .ToTable("Authentications")
   .HasKey(t => t.Id);

modelBuilder.Entity<Authentication>()
    .Property(t => t.Id)
    .IsRequired()
    .ValueGeneratedOnAdd();

modelBuilder.Entity<User>()
     .ToTable("Users")
     .HasKey(t => t.Id);

modelBuilder.Entity<User>()
     .Property(t => t.Id)
     .IsRequired()
     .ValueGeneratedOnAdd();

modelBuilder.Entity<User>()
    .HasOne(x => x.Authentication)
    .WithOne()
    .HasForeignKey("Authentication_Id")
    .IsRequired();

The user class has the following (relevant) properties:

public Class User {
    [Key]
    [Required]
    public Guid Id { get; set; }
    ...
    public virtual Authentication Authentication { get; set; }
}

Authentication has the following (relevant) property:

public class Authentication  {
    [Key]
    [Required]
    public Guid Id { get; set; }
}

However when I try to generate a migration I get the following error:

You are configuring a relationship between 'User' and 'Authentication'
but have specified a foreign key on
'Authentication_Id'. The foreign key
must be defined on a type that is part of the relationship.

I tried switching to a many-to-one relationship and that works without any problems. That could be a work-around but not a very clean one. Is this perhaps due to naming issues like both entities having "Id" as primary key?

If that's the case, what is the "best practice"? Do I give every entity a unique ID-column name? How do I go about an abstract entity with derived classes all inheriting the ID column?

Body:
All who have responded thus far are right. You were missing a foreign key in your dependent entity, so you need to add one. According to your code, it has to be "Authentication_Id" as that is the name that you referenced -- yet you had not actually declared one!

Secondly, Vladislav Vazhenin is right:

Got an error when tried to build on .HasForeignKey(x => x.AuthenticationId);
But .HasForeignKey <User> (x => x.AuthenticationId); worked for me

Just make sure that you point to the navigation properties and not the associated entity key properties (Authentication vs AuthenticationId). So, consider that.

In fact, someone needs to push for the documentation (which seems to be user edited) to include these subtle differences. For example; .HasOne also has a variation of

.HasOne(x=>x.Authentication)

and

.HasOne<Authentication>()

Include, a note on if they differ by the versions of Entity Framework Core. The compiler sometimes blocks and or ignores some of these nice to haves or deprecated command variations. But we need to know which will work for which version and how the overriding of data annotations by fluent api works (put emphasis on which one takes precedence).


问:
Cannot remove OneNote from Greenshot
Something pretty strange is happening.

In %appdata%\greenshot\Greenshot.ini

I have :

```<code>ExcludeDestinations=OneNote
</code>```

and OneNote still shows on the list?

I also tried with a
 C:\Program Files\Greenshot\greenshot-fixed.ini

containing this line, nothing works. OneNote always shows. It's crucial for me to disable it since it doesn't work at the moment even with latest Greenshot release (1.2.9.129 or new 1.2.10.3-RC1)

If i add for example :

```<code>ExcludeDestinations=OneNote,Outlook,Word
</code>```

Outlook and Word disappear from the destination list but OneNote still shows...however i'm clearly using the proper name as listed here :

http://getgreenshot.org/faq/how-remove-plugins-or-destinations-from-greenshot/

Thank you for you time!

答:
Open the Greenshot "Preferences..." in the icons menu.

Go to the "Plugins" tab in the "Settings" window.

Read the DLL Path of the Office Plugin (it is the same for all the default installations)

Close the Greenshot application via "Exit" in the icons menu.

Navigate to the (c:) drive location/path of the Plugin

Mine was C:\Program Files\Greenshot\Plugins

With the Applicaiton closed, you can delete the Plugin folder for "Office" and for save keeps, create a copy of it and save a zipped version in your Documents/Downlaods folder etc.

When you return the plugins will be removed as you active screen capturing options

Title: Cannot remove OneNote from Greenshot

Body:
Something pretty strange is happening.

In %appdata%\greenshot\Greenshot.ini

I have :

ExcludeDestinations=OneNote

and OneNote still shows on the list?

I also tried with a
 C:\Program Files\Greenshot\greenshot-fixed.ini

containing this line, nothing works. OneNote always shows. It's crucial for me to disable it since it doesn't work at the moment even with latest Greenshot release (1.2.9.129 or new 1.2.10.3-RC1)

If i add for example :

ExcludeDestinations=OneNote,Outlook,Word

Outlook and Word disappear from the destination list but OneNote still shows...however i'm clearly using the proper name as listed here :

http://getgreenshot.org/faq/how-remove-plugins-or-destinations-from-greenshot/

Thank you for you time!


问:
case sensitive in select2.js dropdown list
I am currently using select2.js 4.0.3

Scenario

let's say the dropdown list has these options

JavaScript

javascript

Javascript

javaScript

so... when user types java as of now... the list shows all the options (because case doesn't matter as of now)

Example 1

What I want to is... when user types Java only these options should show up

JavaScript

Javascript

Example 2

If user types script ... these options should show up

javascript

Javascript

Example 3

for aS

JavaScript

javaScript

答:
I was looking for the same issue for a long time, but everywhere I found the opposite questions (how to make select2 case-insensitive), so I was very surprised when I found already working solution in the documentation.

function matchCustom(params, data) {
    if ($.trim(params.term) === '') {
      return data;
    }

    if (typeof data.text === 'undefined') {
      return null;
    }

    if (data.text.indexOf(params.term) > -1) {
      var modifiedData = $.extend({}, data, true);

      return modifiedData;
    }

    return null;
}

$(document).ready(function () {
    $("select").select2({
         tags: true,
         matcher: matchCustom
    });
});```
<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>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>

<select>
  <option>javascript</option>
  <option>Javascript</option>
  <option>JavaScript</option>
  <option>javaScript</option>
</select></code>```

Body:
I was looking for the same issue for a long time, but everywhere I found the opposite questions (how to make select2 case-insensitive), so I was very surprised when I found already working solution in the documentation.

function matchCustom(params, data) {
    if ($.trim(params.term) === '') {
      return data;
    }

    if (typeof data.text === 'undefined') {
      return null;
    }

    if (data.text.indexOf(params.term) > -1) {
      var modifiedData = $.extend({}, data, true);

      return modifiedData;
    }

    return null;
}

$(document).ready(function () {
    $("select").select2({
         tags: true,
         matcher: matchCustom
    });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>

<select>
  <option>javascript</option>
  <option>Javascript</option>
  <option>JavaScript</option>
  <option>javaScript</option>
</select>


问:
Vulkan Invalid attribAddress alignment for vertex attribute 0
I really do not understand what the validation error means. There is no alignment requirement for vertex shader attributes in VkPhysicalDeviceLimits.

Here is the full error:
[2022-02-07.20:42:38]: Validation Error: [ VUID-vkCmdDrawIndexed-None-02721 ] Object 0: handle = 0xfef35a00000000a0, type = VK_OBJECT_TYPE_BUFFER; Object 1: handle = 0xa56ac00000000d4, type = VK_OBJECT_TYPE_PIPELINE; | MessageID = 0x24afafc5 | vkCmdDrawIndexed: Invalid attribAddress alignment for vertex attribute 0, VK_FORMAT_R32G32B32_SFLOAT,from of VkPipeline 0xa56ac00000000d4[] and vertex VkBuffer 0xfef35a00000000a0[]. The Vulkan spec states: For a given vertex buffer binding, any attribute data fetched must be entirely contained within the corresponding vertex buffer binding, as described in Vertex Input Description (https://vulkan.lunarg.com/doc/view/1.2.198.1/windows/1.2-extensions/vkspec.html#VUID-vkCmdDrawIndexed-None-02721)

Here is my shader.

```<code>#version 450 core

layout (location = 0) in vec3 inPosition;
layout (location = 1) in vec3 inNormal;
layout (location = 2) in vec2 inTexCoord;

// Instancing Data
//layout (location = 3) in vec2 XYOffset;

layout (binding = 0) uniform View_Projection {
    mat4 u_View;
    mat4 u_Projection;
};

layout (binding = 1) uniform Model {
    mat4 u_Model;
    mat4 u_NormalModel; // transpose(inverse(u_Model))
};

layout (location = 0) out vec3 Normal;
layout (location = 1) out vec2 TexCoord;

void main() {
    Normal = mat3(u_NormalModel) * inNormal;
    TexCoord = inTexCoord;
    //vec4 InstancePosition = vec4(inPosition.xy + XYOffset, inPosition.z, 1.0);
    //gl_Position = u_Projection * u_View * u_Model * InstancePosition;
    gl_Position = u_Projection * u_View * u_Model * vec4(inPosition, 1.0);
}
</code>```

UPDATE 1:

```<code>struct VulkanPipelineVertexInput
{
    VkPipelineVertexInputStateCreateInfo createInfo;
    std::vector<VkVertexInputBindingDescription> binding_descriptions;
    std::vector<VkVertexInputAttributeDescription> attribute_descriptions;
    std::vector<VkVertexInputBindingDivisorDescriptionEXT> divisor_description;
    VkPipelineVertexInputDivisorStateCreateInfoEXT divisorCreateInfo;
};

static VulkanPipelineVertexInput Vulkan_Internal_PipelineState_InitalizeVertexInput(IPipelineLayout layout)
{
    VulkanPipelineVertexInput input_state;

    PipelineVertexInputDescription &input_description = layout->m_vertex_input_description;
    if(input_description.m_input_elements.size() > 0)
    {
        int lastBinding = -1;
        for(const auto& element : input_description.m_input_elements)
        {
            VkVertexInputAttributeDescription attribute;
            attribute.binding = element.m_binding_id;
            attribute.format = element.m_vk_format;
            attribute.location = element.m_location;
            attribute.offset = element.m_offset;
            input_state.attribute_descriptions.push_back(attribute);
            if(lastBinding != element.m_binding_id)
            {
                lastBinding = element.m_binding_id;
                VkVertexInputBindingDescription binding_description;
                binding_description.binding = element.m_binding_id;
                binding_description.inputRate = element.m_per_instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
                binding_description.stride = element.m_stride;
                if(element.m_per_instance)
                {
                    VkVertexInputBindingDivisorDescriptionEXT divisor_description;
                    divisor_description.binding = element.m_binding_id;
                    divisor_description.divisor = element.m_divisor_rate;
                    input_state.divisor_description.push_back(divisor_description);
                }
                input_state.binding_descriptions.push_back(binding_description);
            }
        }
    }

    input_state.createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    input_state.createInfo.pNext = input_state.divisor_description.size() > 0 ? &input_state.divisorCreateInfo : nullptr;
    input_state.createInfo.flags = 0;
    input_state.createInfo.vertexBindingDescriptionCount = input_state.binding_descriptions.size();
    input_state.createInfo.pVertexBindingDescriptions = input_state.binding_descriptions.data();
    input_state.createInfo.vertexAttributeDescriptionCount = input_state.attribute_descriptions.size();
    input_state.createInfo.pVertexAttributeDescriptions = input_state.attribute_descriptions.data();
    return input_state;
}
</code>```

UPDATE 2:
This code does render, however some geometry is shifted.

Render Output

答:
Vertex attributes must be naturally aligned on the primitive type. For VK_FORMAT_R32G32B32_SFLOAT this means a 4 byte boundary.

Section 22.4.1 in the Vulkan 1.3 spec:

For each attribute, raw data is extracted starting at attribAddress and is converted from the
VkVertexInputAttributeDescription’s format to either floating-point, unsigned integer, or signed
integer based on the base type of the format; the base type of the format must match the base type
of the input variable in the shader. The input variable in the shader must be declared as a 64-bit
data type if and only if format is a 64-bit data type. If format is a packed format, attribAddress must
be a multiple of the size in bytes of the whole attribute data type as described in Packed Formats.
Otherwise, attribAddress must be a multiple of the size in bytes of the component type indicated by
format (see Formats).

Body:
I really do not understand what the validation error means. There is no alignment requirement for vertex shader attributes in VkPhysicalDeviceLimits.

Here is the full error:
[2022-02-07.20:42:38]: Validation Error: [ VUID-vkCmdDrawIndexed-None-02721 ] Object 0: handle = 0xfef35a00000000a0, type = VK_OBJECT_TYPE_BUFFER; Object 1: handle = 0xa56ac00000000d4, type = VK_OBJECT_TYPE_PIPELINE; | MessageID = 0x24afafc5 | vkCmdDrawIndexed: Invalid attribAddress alignment for vertex attribute 0, VK_FORMAT_R32G32B32_SFLOAT,from of VkPipeline 0xa56ac00000000d4[] and vertex VkBuffer 0xfef35a00000000a0[]. The Vulkan spec states: For a given vertex buffer binding, any attribute data fetched must be entirely contained within the corresponding vertex buffer binding, as described in Vertex Input Description (https://vulkan.lunarg.com/doc/view/1.2.198.1/windows/1.2-extensions/vkspec.html#VUID-vkCmdDrawIndexed-None-02721)

Here is my shader.

#version 450 core

layout (location = 0) in vec3 inPosition;
layout (location = 1) in vec3 inNormal;
layout (location = 2) in vec2 inTexCoord;

// Instancing Data
//layout (location = 3) in vec2 XYOffset;

layout (binding = 0) uniform View_Projection {
    mat4 u_View;
    mat4 u_Projection;
};

layout (binding = 1) uniform Model {
    mat4 u_Model;
    mat4 u_NormalModel; // transpose(inverse(u_Model))
};

layout (location = 0) out vec3 Normal;
layout (location = 1) out vec2 TexCoord;

void main() {
    Normal = mat3(u_NormalModel) * inNormal;
    TexCoord = inTexCoord;
    //vec4 InstancePosition = vec4(inPosition.xy + XYOffset, inPosition.z, 1.0);
    //gl_Position = u_Projection * u_View * u_Model * InstancePosition;
    gl_Position = u_Projection * u_View * u_Model * vec4(inPosition, 1.0);
}

UPDATE 1:

struct VulkanPipelineVertexInput
{
    VkPipelineVertexInputStateCreateInfo createInfo;
    std::vector<VkVertexInputBindingDescription> binding_descriptions;
    std::vector<VkVertexInputAttributeDescription> attribute_descriptions;
    std::vector<VkVertexInputBindingDivisorDescriptionEXT> divisor_description;
    VkPipelineVertexInputDivisorStateCreateInfoEXT divisorCreateInfo;
};

static VulkanPipelineVertexInput Vulkan_Internal_PipelineState_InitalizeVertexInput(IPipelineLayout layout)
{
    VulkanPipelineVertexInput input_state;

    PipelineVertexInputDescription &input_description = layout->m_vertex_input_description;
    if(input_description.m_input_elements.size() > 0)
    {
        int lastBinding = -1;
        for(const auto& element : input_description.m_input_elements)
        {
            VkVertexInputAttributeDescription attribute;
            attribute.binding = element.m_binding_id;
            attribute.format = element.m_vk_format;
            attribute.location = element.m_location;
            attribute.offset = element.m_offset;
            input_state.attribute_descriptions.push_back(attribute);
            if(lastBinding != element.m_binding_id)
            {
                lastBinding = element.m_binding_id;
                VkVertexInputBindingDescription binding_description;
                binding_description.binding = element.m_binding_id;
                binding_description.inputRate = element.m_per_instance ? VK_VERTEX_INPUT_RATE_INSTANCE : VK_VERTEX_INPUT_RATE_VERTEX;
                binding_description.stride = element.m_stride;
                if(element.m_per_instance)
                {
                    VkVertexInputBindingDivisorDescriptionEXT divisor_description;
                    divisor_description.binding = element.m_binding_id;
                    divisor_description.divisor = element.m_divisor_rate;
                    input_state.divisor_description.push_back(divisor_description);
                }
                input_state.binding_descriptions.push_back(binding_description);
            }
        }
    }

    input_state.createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    input_state.createInfo.pNext = input_state.divisor_description.size() > 0 ? &input_state.divisorCreateInfo : nullptr;
    input_state.createInfo.flags = 0;
    input_state.createInfo.vertexBindingDescriptionCount = input_state.binding_descriptions.size();
    input_state.createInfo.pVertexBindingDescriptions = input_state.binding_descriptions.data();
    input_state.createInfo.vertexAttributeDescriptionCount = input_state.attribute_descriptions.size();
    input_state.createInfo.pVertexAttributeDescriptions = input_state.attribute_descriptions.data();
    return input_state;
}

UPDATE 2:
This code does render, however some geometry is shifted.

Render Output


问:
Java regex for image filename?
I have to filter filenames to match only image (png,jpg,gif,bmp) files, is possible to make a such regex or do I have to have different regex for every file type? It also cannot contain path like ../../ or /var/app/filename.exe etc.</p>

答:
Pretty easy:

```<code>re = ".*\\.(png|jpg|gif|bmp)"
</code>```

as long as you don't need UPPERCASE and jpeg. :)

Title: Java regex for image filename?

Body:
Pretty easy:

re = ".*\\.(png|jpg|gif|bmp)"

as long as you don't need UPPERCASE and jpeg. :)


问:
when i installing the "cronie" the system mentioned me that ths cronie require the "dailyjobs"
when i installing the "cronie" the system mentioned me that ths cronie require the "dailyjobs" like the following shows:

Error: Package: cronie-1.4.4-7.2.alios6.x86_64
             Requires: dailyjobs

I have searched it online but no tip works.

thanks

答:
Install cronie and cronie-anacron at same time.

rpm -i cronie-xxxx.rpm cronie-anacron-xxxx.rpm


问:
Map or reduce with index in Swift
Is there a way to get the index of the array in map or reduce in Swift? I'm looking for something like each_with_index in Ruby.

```<code>func lunhCheck(number : String) -> Bool
{
    var odd = true;
    return reverse(number).map { String($0).toInt()! }.reduce(0) {
        odd = !odd
        return $0 + (odd ? ($1 == 9 ? 9 : ($1 * 2) % 9) : $1)
    }  % 10 == 0
}

lunhCheck("49927398716")
lunhCheck("49927398717")
</code>```

I would like to get rid of the odd variable above.

答:
reduce in swift :

```<code>let numbers = [7,3,10]

let sum = numbers.reduce(0) {

$0 + $1

}

print(sum) // 20
</code>```

Map in swift:

Convert the model to the model that we need

We want array of names change to array of names with uppercase letters,

means every thing that I want

```<code>let names = ["John", "Paul", "George", "Ringo"]

let uppercased = names.map {

    $0.uppercased()
}

print(uppercased) // ["JOHN", "PAUL", "GEORGE", "RINGO"]
</code>```

I hope you understand what I mean :).

Title: Map or reduce with index in Swift

Body:
Is there a way to get the index of the array in map or reduce in Swift? I'm looking for something like each_with_index in Ruby.

func lunhCheck(number : String) -> Bool
{
    var odd = true;
    return reverse(number).map { String($0).toInt()! }.reduce(0) {
        odd = !odd
        return $0 + (odd ? ($1 == 9 ? 9 : ($1 * 2) % 9) : $1)
    }  % 10 == 0
}

lunhCheck("49927398716")
lunhCheck("49927398717")

I would like to get rid of the odd variable above.

Body:
reduce in swift :

let numbers = [7,3,10]

let sum = numbers.reduce(0) {

$0 + $1

}

print(sum) // 20

Map in swift:

Convert the model to the model that we need

We want array of names change to array of names with uppercase letters,

means every thing that I want

let names = ["John", "Paul", "George", "Ringo"]

let uppercased = names.map {

    $0.uppercased()
}

print(uppercased) // ["JOHN", "PAUL", "GEORGE", "RINGO"]

I hope you understand what I mean :).