问:
Allow multiple markers in leaflet map rails 5
I need to allow users to place multiple markers, the max number of markers must be dynamic, the map is in a form, so when I send the form to the controller I have to get the latitude and longitude of the markers in an Array so I can processes them.

This is what I have for one marker:

```<code>  initialize: ->
    maps = $("*[data-mapanswer]")
    if maps.length > 0
      $.each maps, (index, map) ->
        App.MapAnswer.initializeMap map

    $(".js-toggle-map").on
      click: ->
        App.MapAnswer.toggleMap()

  initializeMap: (element) ->
    mapCenterLatitude        = $(element).data("map-center-latitude")
    mapCenterLongitude       = $(element).data("map-center-longitude")
    markerLatitude           = $(element).data("marker-latitude")
    markerLongitude          = $(element).data("marker-longitude")
    zoom                     = $(element).data("map-zoom")
    mapTilesProvider         = $(element).data("map-tiles-provider")
    mapAttribution           = $(element).data("map-tiles-provider-attribution")
    latitudeInputSelector    = $(element).data("latitude-input-selector")
    longitudeInputSelector   = $(element).data("longitude-input-selector")
    zoomInputSelector        = $(element).data("zoom-input-selector")
    removeMarkerSelector     = $(element).data("marker-remove-selector")
    editable                 = $(element).data("marker-editable")
    markerId                 = $(element).data("marker-id")
    answers                  = $(element).data("answers")
    marker                   = null
    markerIcon               = App.MapAnswer.createMarkerIcon(icon_related: false)
    markerRelatedIcon        = App.MapAnswer.createMarkerIcon(icon_related: true)

    createMarker = (latitude, longitude) ->
      markerLatLng  = new (L.LatLng)(latitude, longitude)
      marker  = L.marker(markerLatLng, { icon: markerIcon, draggable: editable })

      marker.addTo(map)
      return marker

    removeMarker = (e) ->
      e.preventDefault()
      if marker
        map.removeLayer(marker)
        marker = null
      $(latitudeInputSelector).val ""
      $(longitudeInputSelector).val ""
      $(zoomInputSelector).val ""
      return

    moveOrPlaceMarker = (e) ->
      if marker
        marker.setLatLng(e.latlng)
      else
        marker = createMarker(e.latlng.lat, e.latlng.lng)

      $(latitudeInputSelector).val(e.latlng.lat)
      $(longitudeInputSelector).val(e.latlng.lng)
      $(zoomInputSelector).val map.getZoom()
      return
    updateZoom = (e) ->
      $(zoomInputSelector).val map.getZoom()
      return

    if markerLatitude && markerLongitude
      mapCenterLatLng  = new (L.LatLng)(markerLatitude, markerLongitude)
    else
      mapCenterLatLng  = new (L.LatLng)(mapCenterLatitude, mapCenterLongitude)
    map              = L.map(element.id,{zoomControl: false}).setView(mapCenterLatLng, zoom)
    L.control.zoom({position: 'bottomright'}).addTo(map)
    L.tileLayer(mapTilesProvider, attribution: mapAttribution).addTo(map)

    if markerLatitude && markerLongitude
      marker  = createMarker(markerLatitude, markerLongitude)
    else if answers
      answers.forEach (answer) ->
        createMarker(answer[0], answer[1])

    if editable
      $(removeMarkerSelector).on "click", removeMarker
      map.on    "click",   moveOrPlaceMarker
      map.on    "zoomend", updateZoom

  createMarkerIcon: (marker_option) ->
    relatedIconClass = "map-icon-related" if marker_option.icon_related
    L.divIcon(
      className: "map-marker"
      iconSize:     [30, 30]
      iconAnchor:   [15, 40]
      html: "<div class='map-icon #{relatedIconClass}'></div>"
    )
</code>```

I guess I have to modify createMarker but nothing is working

Body:
I need to allow users to place multiple markers, the max number of markers must be dynamic, the map is in a form, so when I send the form to the controller I have to get the latitude and longitude of the markers in an Array so I can processes them.

This is what I have for one marker:

  initialize: ->
    maps = $("*[data-mapanswer]")
    if maps.length > 0
      $.each maps, (index, map) ->
        App.MapAnswer.initializeMap map

    $(".js-toggle-map").on
      click: ->
        App.MapAnswer.toggleMap()

  initializeMap: (element) ->
    mapCenterLatitude        = $(element).data("map-center-latitude")
    mapCenterLongitude       = $(element).data("map-center-longitude")
    markerLatitude           = $(element).data("marker-latitude")
    markerLongitude          = $(element).data("marker-longitude")
    zoom                     = $(element).data("map-zoom")
    mapTilesProvider         = $(element).data("map-tiles-provider")
    mapAttribution           = $(element).data("map-tiles-provider-attribution")
    latitudeInputSelector    = $(element).data("latitude-input-selector")
    longitudeInputSelector   = $(element).data("longitude-input-selector")
    zoomInputSelector        = $(element).data("zoom-input-selector")
    removeMarkerSelector     = $(element).data("marker-remove-selector")
    editable                 = $(element).data("marker-editable")
    markerId                 = $(element).data("marker-id")
    answers                  = $(element).data("answers")
    marker                   = null
    markerIcon               = App.MapAnswer.createMarkerIcon(icon_related: false)
    markerRelatedIcon        = App.MapAnswer.createMarkerIcon(icon_related: true)

    createMarker = (latitude, longitude) ->
      markerLatLng  = new (L.LatLng)(latitude, longitude)
      marker  = L.marker(markerLatLng, { icon: markerIcon, draggable: editable })

      marker.addTo(map)
      return marker

    removeMarker = (e) ->
      e.preventDefault()
      if marker
        map.removeLayer(marker)
        marker = null
      $(latitudeInputSelector).val ""
      $(longitudeInputSelector).val ""
      $(zoomInputSelector).val ""
      return

    moveOrPlaceMarker = (e) ->
      if marker
        marker.setLatLng(e.latlng)
      else
        marker = createMarker(e.latlng.lat, e.latlng.lng)

      $(latitudeInputSelector).val(e.latlng.lat)
      $(longitudeInputSelector).val(e.latlng.lng)
      $(zoomInputSelector).val map.getZoom()
      return
    updateZoom = (e) ->
      $(zoomInputSelector).val map.getZoom()
      return

    if markerLatitude && markerLongitude
      mapCenterLatLng  = new (L.LatLng)(markerLatitude, markerLongitude)
    else
      mapCenterLatLng  = new (L.LatLng)(mapCenterLatitude, mapCenterLongitude)
    map              = L.map(element.id,{zoomControl: false}).setView(mapCenterLatLng, zoom)
    L.control.zoom({position: 'bottomright'}).addTo(map)
    L.tileLayer(mapTilesProvider, attribution: mapAttribution).addTo(map)

    if markerLatitude && markerLongitude
      marker  = createMarker(markerLatitude, markerLongitude)
    else if answers
      answers.forEach (answer) ->
        createMarker(answer[0], answer[1])

    if editable
      $(removeMarkerSelector).on "click", removeMarker
      map.on    "click",   moveOrPlaceMarker
      map.on    "zoomend", updateZoom

  createMarkerIcon: (marker_option) ->
    relatedIconClass = "map-icon-related" if marker_option.icon_related
    L.divIcon(
      className: "map-marker"
      iconSize:     [30, 30]
      iconAnchor:   [15, 40]
      html: "

"
    )

I guess I have to modify createMarker but nothing is working


来源: stackexchange

问:
How to dynamically insert text in Ckeditor5 for Vue 2
My application provides many selectable standard paragraphs which users can insert at any point.  In a previous version insertion was simple: CKEDITOR.instances[editorId].insertHTML(text).

I'm trying to use v5 api with model.insertContent(text) but get error:

```<code>"vue.runtime.esm.js:3020 TypeError: t2.is is not a function
    at bl.rp (converters.js:771:21)
    at bl.fire (emittermixin.js:199:30)
    at <computed> (observablemixin.js:262:16)
    at VueComponent.testInsert (Test.vue:29:1)"
</code>```

Here's the composition file.  I have tried accessing the insertContent method from this.editor and from the apiReference returned from the @ready event;

```<code>
<template>
  <div>
    <button @click="testInsert('abracadabra')">Insert literal content</button>
   <ckeditor tag-name="textarea" :editor="editor" v-model="doc.HTML" @ready="editorReady" :config="editorConfig"></ckeditor>
  </div>
</template>

<script>
  import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
  export default {
    name: 'testEditorInsert',
    mounted() {
    },
    data() {
      return {
        doc: {ID: 0, HTML: "This is a sample text.  Insert  here?  This is the remainder of the sample text"},
        editor: ClassicEditor,
        editorData: 'loading',
        editorConfig:   {
          toolbar: [ 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote' ],
         },
        editorApi:null ,
      }
    },
    methods: {
      testInsert: function(text) {
        console.log(this.editorApi, text);
        //this.editor.model.insertContent(text);
        this.editorApi.model.insertContent(text);
      },
      editorReady: function(editor) {
        this.editorApi = editor;
      }
    },
  }
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My application provides many selectable standard paragraphs which users can insert at any point.  In a previous version insertion was simple: CKEDITOR.instances[editorId].insertHTML(text).

I'm trying to use v5 api with model.insertContent(text) but get error:

"vue.runtime.esm.js:3020 TypeError: t2.is is not a function
    at bl.rp (converters.js:771:21)
    at bl.fire (emittermixin.js:199:30)
    at <computed> (observablemixin.js:262:16)
    at VueComponent.testInsert (Test.vue:29:1)"

Here's the composition file.  I have tried accessing the insertContent method from this.editor and from the apiReference returned from the @ready event;

<template>

    <button @click="testInsert('abracadabra')">Insert literal content</button>
   <ckeditor tag-name="textarea" :editor="editor" v-model="doc.HTML" @ready="editorReady" :config="editorConfig"></ckeditor>

</template>


问:
hangfire: Cancel already running recurring job
I have problem with cancellation recurring job.
When i invoke RecurringJob.RemoveIfExist(myJobId) then job is removed from database, but already ran job is not cancelled.
In my case i have while(!cancellationToken.IsCancellationRequest) background job
And i also use ThrowIfCancellationRequested but job still not cancelling
When i use BackgroundJob instead ofRecurringJob then all woks fine.

I tried to to use BackgroundJob.Delete(myJobId) but is not work too.
Also, i passed my own cancellation token and CancellatioToken.None

can anyone help me?


问:
Delete function using href="action.php" method
im using codeigniter 3 to delete a user, the view file its like this

```<code> <a href="action.php?id=<?=$row[TB_PREFIX.'id']?>"  class="btn btn-sm btn-danger popovers deletar" type="button" data-content="Excluir" data-trigger="hover" data-placement="right" data-toggle="tooltip" >
 <i class="fa fa-trash-o"></i>
</a>
</code>```

it calls a file using href attribute, and the action.php file is a switch case logic, which calls ''deletar'' case to delete the user , the code that does it's

```<code>case 'deletar':

            if(!is_null($id)){

                $id = str_replace("#", "", $id );
                $obj_sql->Query("DELETE FROM ".TB_ATUAL." WHERE ".TB_PREFIX."id =                             '".$id."'");
                $return["status"]   = 'success'; // ['ok', 'info', 'erro']
                $return["message"]  = '<b>Registro deletado com sucesso!</b>';
            }

        break;
</code>```

and its returning to a full blank page with null. i dont know how to make it work.

i expect to delete the user and back to the current page with the user deleted from database and the page. thanks to everyone who try to help me with this.
i know its not mvc pattern and im freelancer to this project.

Body:
im using codeigniter 3 to delete a user, the view file its like this

 <a href="action.php?id=<?=$row[TB_PREFIX.'id']?>"  class="btn btn-sm btn-danger popovers deletar" type="button" data-content="Excluir" data-trigger="hover" data-placement="right" data-toggle="tooltip" >

it calls a file using href attribute, and the action.php file is a switch case logic, which calls ''deletar'' case to delete the user , the code that does it's

case 'deletar':

            if(!is_null($id)){

                $id = str_replace("#", "", $id );
                $obj_sql->Query("DELETE FROM ".TB_ATUAL." WHERE ".TB_PREFIX."id =                             '".$id."'");
                $return["status"]   = 'success'; // ['ok', 'info', 'erro']
                $return["message"]  = 'Registro deletado com sucesso!';
            }

        break;

and its returning to a full blank page with null. i dont know how to make it work.

i expect to delete the user and back to the current page with the user deleted from database and the page. thanks to everyone who try to help me with this.
i know its not mvc pattern and im freelancer to this project.


问:
Setting a specific parameter in JavaScript
I have a function that takes multiple parameters where I give each parameter a default value.  When I call this function I only want to change a specific parameter.  Is this possible to do in JavaScript?  I was unable to find a clear answer in a Google search.

I understand that I can use several 'if' statements within my function however I am able to solve this problem in Python through the example:

```<code>setValues(val2="new")
</code>```

This does not work in JavaScript being that the assignment occurs to the first positional variable in the function rather than the one explicitly chosen.

I have the code:

```<code>function setValues(val1="a", val2="b", val3="c")
{
  /*
    Print the value of each variable.
  */
}

setValues(val2="new");
</code>```

Output:

```<code>val1 = "new"
val2 = "b"
val2 = "c"

Expected:

val1 = "a"
val2 = "new"
val3 - "c"
</code>```

Body:
I have a function that takes multiple parameters where I give each parameter a default value.  When I call this function I only want to change a specific parameter.  Is this possible to do in JavaScript?  I was unable to find a clear answer in a Google search.

I understand that I can use several 'if' statements within my function however I am able to solve this problem in Python through the example:

setValues(val2="new")

This does not work in JavaScript being that the assignment occurs to the first positional variable in the function rather than the one explicitly chosen.

I have the code:

function setValues(val1="a", val2="b", val3="c")
{
  /*
    Print the value of each variable.
  */
}

setValues(val2="new");

Output:

val1 = "new"
val2 = "b"
val2 = "c"

Expected:

val1 = "a"
val2 = "new"
val3 - "c"


问:
inline keyboard handlers in node-telegram-bot-api package
I'm currently build a telegram bot and i have one issue.
In my case has had a few inline keyboard. here are

but all inline keyboard has a one handler

bot.on('callback_query',query=>{
    bot.answerCallbackQuery(query.id,{text:query.data,show_alert:false})
    console.log(query)
})
```
<p>so i will need check with a if else condition for all handler in callback_query event but i don't like this way. Then i will had find one to get rid of 'if else'. In this i will had use a EventEmitter to separate each handler</p>
<pre class="lang-js prettyprint-override"><code>emitter.on('eventOne',(chatId)=>{
    ... business logic of handler
})
emitter.on('eventTwo',(chatId)=>{
    ... business logic of handler
})
bot.on('callback_query',query=>{
    emitter.emit(query.data,query.message.chat.id)
    bot.answerCallbackQuery(query.id,{text:query.data,show_alert:false})
    console.log(query)
})
</code>```

is this way right or not, if not i need a right implementation of this issue.

Sorry for grammar mistakes, my native language is Uzbek ;)

I need a right implamentation of inline_keyboards handler

Body:
I'm currently build a telegram bot and i have one issue.
In my case has had a few inline keyboard. here are

but all inline keyboard has a one handler

bot.on('callback_query',query=>{
    bot.answerCallbackQuery(query.id,{text:query.data,show_alert:false})
    console.log(query)
})

so i will need check with a if else condition for all handler in callback_query event but i don't like this way. Then i will had find one to get rid of 'if else'. In this i will had use a EventEmitter to separate each handler

emitter.on('eventOne',(chatId)=>{
    ... business logic of handler
})
emitter.on('eventTwo',(chatId)=>{
    ... business logic of handler
})
bot.on('callback_query',query=>{
    emitter.emit(query.data,query.message.chat.id)
    bot.answerCallbackQuery(query.id,{text:query.data,show_alert:false})
    console.log(query)
})

is this way right or not, if not i need a right implementation of this issue.

Sorry for grammar mistakes, my native language is Uzbek ;)

I need a right implamentation of inline_keyboards handler


问:
converting a integer code to list in gurobi

obj = gp.quicksum(values[i] * v[i] for i in range(num_blocks))
TypeError                                 Traceback (most recent call last)
Input In [57], in <cell line: 3>()
      1 # define the objective function
      2 # maximize the total value of the ore extracted
----> 3 obj = gp.quicksum(values[i] * v[i] for i in range(num_blocks))
      5 # set the objective function of the model
      6 model.setObjective(obj, gp.GRB.MAXIMIZE)

TypeError: 'list' object cannot be interpreted as an integer
```

how can I solve this error?

Body:
obj = gp.quicksum(values[i] * v[i] for i in range(num_blocks))
TypeError                                 Traceback (most recent call last)
Input In [57], in <cell line: 3>()
      1 # define the objective function
      2 # maximize the total value of the ore extracted
----> 3 obj = gp.quicksum(values[i] * v[i] for i in range(num_blocks))
      5 # set the objective function of the model
      6 model.setObjective(obj, gp.GRB.MAXIMIZE)

TypeError: 'list' object cannot be interpreted as an integer

how can I solve this error?


问:
How to split the code into files in Rust?
There are 5 files in my project. (lib.rs, one.rs, two.rs, three.rs, four.rs)

I'd like:

lib.rs knows about one.rs, two.rs

one.rs knows about three.rs, four.rs

two.rs knows about three.rs, four.rs

But I can't find examples. There is a tree everywhere. I can't use tree, three.rs, four.rs must be common.


问:
Limit a watchOS app to only being available on the Ultra watch
Is there a way to limit the availability of a standalone Apple Watch App, to only being available on the Ultra watches?</p>


问:
Power BI Paginated report using power BI dataset from multiple azure sql servers
Just looking for a pointer as to the best way to go about this.
I'm comfortable with Power BI Report Builder (SSRS experience), but am pretty much a Power BI novice.

Basically, we have to create a Paginated (non-interactive) report for client consumption. It's going to be large, have multiple datasets, and use parameters / presence of data in the data sets to group data and/or turn sections on or off.
Not too much visualisation - some illustrative graphs and tables here and there - and quite a bit of text, some of it with data / text inserted via placeholders from the various datasets.

There are 3 Azure SQL databases I need to combine data from for this, (split roughly into config, data and results).

In SSRS / SQL Server, I would have used one of my databases as the data source, and written a stored procedure per SSRS data set, joining to tables in other databases in the stored procedure query.
Then in Report builder just set up the data sets joining to the stored procs and gone from there.

On Azure SQL Server, I think I've got 2 options:

write elastic queries so I can bring in the data I need from each database, but just query on one database.

Build a Power BI Model / Dataset that joins the relevant tables from the 3 databases together, publish to power bi service and use that as my datasource.

What's the best solution for my reporting scenario?

Cheers


问:
How to animate the height of an element which has children of variable heights
I want to animate a
 in HTML on hover. The element would children of variable heights, so I cannot put the parent's height in px or any fixed unit. I have tried putting values like 100%, initial, auto, etc. but they did not work.

.animator {
  max-height: 100px;
  overflow: hidden;
  border: dashed 3px purple;
  transition: max-height 200ms linear;
}

.animator:hover {
  max-height: 200px; /* this needs to be dynamic */
}

.animator .hover-internal {
  height: 400px; /* this can vary depending on the amount of content */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="animator">
  <div class="hover-internal">
    hover over me
  </div>
</div>

<div class="other">Some other content</div></code>```

A related questions solves it by using a fixed pixel max-height, but that would not work in this case, since the height would be dynamic.

Related:
How can I transition height: 0; to height: auto; using CSS?

Body:
I want to animate a
 in HTML on hover. The element would children of variable heights, so I cannot put the parent's height in px or any fixed unit. I have tried putting values like 100%, initial, auto, etc. but they did not work.

.animator {
  max-height: 100px;
  overflow: hidden;
  border: dashed 3px purple;
  transition: max-height 200ms linear;
}

.animator:hover {
  max-height: 200px; /* this needs to be dynamic */
}

.animator .hover-internal {
  height: 400px; /* this can vary depending on the amount of content */
}

    hover over me

Some other content

A related questions solves it by using a fixed pixel max-height, but that would not work in this case, since the height would be dynamic.

Related:
How can I transition height: 0; to height: auto; using CSS?


问:
Spring Boot dropdown menu with options select validation
I have ENUM where I saved types of Income Categories, than I use that ENUM and map it inside my Entity, later I populate my dropdown list with that ENUM and show to user. I want to create a validation so user cant submit form until he choose one option from the dropdown list. Below is code that I think is useful to solve this and also the way I tried to show a error to the user if he didn't select any option from dropdown menu.

I have this ENUM:

```<code>public enum IncomeCategories {

SALARY("Salary"),
BUSINESS("Business"),
GIFTS("Gifts"),
EXTRA_INCOME("Extra income"),
LOAN("Loan"),
PARENTAL_LEAVE("Parental Leave"),
INSURANCE_PAYOUT("Insurance payout"),
OTHER("Other");

private final String displayName;

IncomeCategories(String displayName) {
    this.displayName = displayName;
}

public String getDisplayName() {
    return displayName;
}
}
</code>```

This is ENUM inside entity:

```<code>@Enumerated(EnumType.STRING)
@NotNull(message = "Please, select option from list.")
@Column(name = "income_categories", columnDefinition = "ENUM('SALARY', 'BUSINESS', 'GIFTS', 'EXTRA_INCOME', 'LOAN', 'PARENTAL_LEAVE', 'INSURANCE_PAYOUT', 'OTHER')")
private IncomeCategories incomeCategories;
</code>```

And this is how I tried to show error if nothing is selected from dropdown menu:

```<code><div class="form-group col-md-8">
                        <select th:field="${transaction.incomeCategories}">
                            <option value="0">Select income category</option>
                            <option
                                    th:each="incomeCategories : ${incomeCategories}"
                                    th:value="${incomeCategories}"
                                    th:text="${incomeCategories.displayName}"

                            ></option>

                        </select>
                        <span
                                th:if="${#fields.hasErrors('${transaction.incomeCategories}')}" th:errors="${transaction.incomeCategories}"
                                class="text-danger"></span>
                    </div>
</code>```

But I'm getting this:

Body:
I have ENUM where I saved types of Income Categories, than I use that ENUM and map it inside my Entity, later I populate my dropdown list with that ENUM and show to user. I want to create a validation so user cant submit form until he choose one option from the dropdown list. Below is code that I think is useful to solve this and also the way I tried to show a error to the user if he didn't select any option from dropdown menu.

I have this ENUM:

public enum IncomeCategories {

SALARY("Salary"),
BUSINESS("Business"),
GIFTS("Gifts"),
EXTRA_INCOME("Extra income"),
LOAN("Loan"),
PARENTAL_LEAVE("Parental Leave"),
INSURANCE_PAYOUT("Insurance payout"),
OTHER("Other");

private final String displayName;

IncomeCategories(String displayName) {
    this.displayName = displayName;
}

public String getDisplayName() {
    return displayName;
}
}

This is ENUM inside entity:

@Enumerated(EnumType.STRING)
@NotNull(message = "Please, select option from list.")
@Column(name = "income_categories", columnDefinition = "ENUM('SALARY', 'BUSINESS', 'GIFTS', 'EXTRA_INCOME', 'LOAN', 'PARENTAL_LEAVE', 'INSURANCE_PAYOUT', 'OTHER')")
private IncomeCategories incomeCategories;

And this is how I tried to show error if nothing is selected from dropdown menu:

                        <select th:field="${transaction.incomeCategories}">
                            <option value="0">Select income category</option>
                            <option
                                    th:each="incomeCategories : ${incomeCategories}"
                                    th:value="${incomeCategories}"
                                    th:text="${incomeCategories.displayName}"

                            ></option>

                        </select>

But I'm getting this:


问:
Nest JS swagger API response body from third party package
I am writing a REST API swagger in Nest JS.

My code snippet looks like this:

  @Get()
  @ApiOperation({
    summary: `Something`,
    description: `Something`,
  })
  @ApiOkResponse({
    description: 'The resources were returned successfully',
    type: VpcV1,
    isArray: true
  })
  @ApiForbiddenResponse({ description: 'Unauthorized Request' })
  list() {
    return this.service.list();
  }
```

As you can see the the this.service.list() is returning ab object of type VpcV1.

I have added it as type in the @ApiOkResponse().

But as the VpcV1 is from third party package which I do not have any control, it's not a DTO.
In such a case how can I see the API response object such that when user will see the swagger, they can be able to see the Response Schema properly?

Body:
I am writing a REST API swagger in Nest JS.

My code snippet looks like this:

  @Get()
  @ApiOperation({
    summary: `Something`,
    description: `Something`,
  })
  @ApiOkResponse({
    description: 'The resources were returned successfully',
    type: VpcV1,
    isArray: true
  })
  @ApiForbiddenResponse({ description: 'Unauthorized Request' })
  list() {
    return this.service.list();
  }

As you can see the the this.service.list() is returning ab object of type VpcV1.

I have added it as type in the @ApiOkResponse().

But as the VpcV1 is from third party package which I do not have any control, it's not a DTO.
In such a case how can I see the API response object such that when user will see the swagger, they can be able to see the Response Schema properly?


问:
Migration to log4j2
I am trying to migrate some code from log4j 1.x to 2.x. Some things are easy to replace, but I cannot find the way to replace this:

```<code>Object obj = event.getMDC("xxx"); //event is org.apache.log4j.spi.LoggingEvent type from log4j 1.x.
</code>```

I know about the method with the bridge but for now I want to skip it and try to do it like this.

MDC can be replace with ThreadContext and I see some people using org.apache.logging.log4j.core.LogEvent but it doesn't contain the same methods as LoggingEvent (examples):

.getRenderMessage()

.getTrowableInformation()

.getMDC();

Title: Migration to log4j2

Body:
I am trying to migrate some code from log4j 1.x to 2.x. Some things are easy to replace, but I cannot find the way to replace this:

Object obj = event.getMDC("xxx"); //event is org.apache.log4j.spi.LoggingEvent type from log4j 1.x.

I know about the method with the bridge but for now I want to skip it and try to do it like this.

MDC can be replace with ThreadContext and I see some people using org.apache.logging.log4j.core.LogEvent but it doesn't contain the same methods as LoggingEvent (examples):

.getRenderMessage()

.getTrowableInformation()

.getMDC();


问:
How to handle duplicate headers in react-native navigation when nesting a stack navigator inside a drawer navigator
I am using react-navigation (v6.x) in a react-native app.

I have a drawer navigator setup which holds different stack navigators.

If I hide the drawer's header, the drawer button gets hidden and it won't be obvious to the app users that the drawer is there.

If I hide the stack screen's header (inside the stack navigator) it hides the back button and the users won't be able to go back unless they're using the hardware button(Android)/gestures (iOS).

How can I achieve the following:

1- Hide the Stack screen's header, and show the drawer's header on the first screen of the stack (reveal the drawer button, since the back button is not needed at this stage).

2- Hide the drawer's header and show the stack screens header on the second screen of the stack (hide the drawer button, reveal the back button so the user can go to the previous screen in the stack)

or is there a cleaner approach?

Thanks!


问:
Realtime quote of SMS and MMS sending in Twilio
I need to know the price to send a SMS or MMS message to a specific country in realtime... having trouble understanding the data returned by the API... also seems to be missing the MMS price quotes.... help?

I have used the API to return the prices for the different countries.

Thanks!


问:
How to manage tracing with Spring WebClient in Reactive way?
I have a method in EventService that calls an API and handle errors if there is any.

```<code>private Mono<ApiResponse> send(String accountId) {
    accountIdBaggageField.updateValue(accountId);
    logger.info("making the call");
    Mono<ApiResponse> res = apiClient.dispatchEvent(accountId);
    return res.doOnError(e -> {
        logger.error("Could not dispatch batch for events");
    });
}
</code>```

Here is the SleuthConfiguration class that defines accountIdBaggageField bean:

```<code>@Configuration
public class SleuthConfiguration {

    @Bean
    public BaggageField accountIdBaggageField() {
        return BaggageField.create(LoggingContextVariables.MDC_ACCOUNT_ID);
    }

    @Bean
    public BaggagePropagationCustomizer baggagePropagationCustomizer(BaggageField accountIdBaggageField) {
        return factoryBuilder -> {
            factoryBuilder.add(remote(accountIdBaggageField));
        };
    }

    @Bean
    public CorrelationScopeCustomizer correlationScopeCustomizer(BaggageField accountIdBaggageField) {
        return builder -> {
            builder.add(createCorrelationScopeConfig(accountIdBaggageField));
        };
    }

    private CorrelationScopeConfig createCorrelationScopeConfig(BaggageField field) {
        return CorrelationScopeConfig.SingleCorrelationField.newBuilder(field)
                .flushOnUpdate()
                .build();
    }
}
</code>```

Here is the ApiClient's dispatchEvents method:

```<code>public Mono<ApiResponse> dispatchEvent(String accountId) {
        return webClient
                .post()
                .uri(properties.getEndpoints().getDispatchEvent(), Map.of("accountId", accountId))
                .retrieve()
                .onStatus(HttpStatus::isError, this::constructException)
                .bodyToMono(ApiResponse.class)
                .onErrorMap(WebClientRequestException.class, e -> new CGWException("Error during dispatching event to Connector Gateway", e));
    }
</code>```

Here is how I call the send method:

```<code>eventService.send("account1");
eventService.send("account2");
</code>```

The problem here is that the accountIdBaggageField is first set to "account1" and then the io process is started when apiClient.dispatchEvents is called. Before the end of the io process (before getting a response from the api), the second call takes place and the accountIdBaggageField is set to "account2".

Then, when the response of the first request is returned, the error log in doOnError adds the accountId to the log as "account2" but needs to add it as "account1".

Here are the logs:

```<code>2023-01-09 11:50:56.791  INFO [account1] [Thread-1] c.t.e.s.impl.EventServiceImpl    making the call

2023-01-09 11:50:56.812  INFO [account2] [Thread-1] c.t.e.s.impl.EventServiceImpl    making the call

2023-01-09 11:50:58.241  INFO [account2] [reactor-http-nio-4] c.t.e.s.impl.EventServiceImpl    Could not dispatch batch for events

2023-01-09 11:50:58.281  INFO [account2] [reactor-http-nio-6] c.t.e.s.impl.EventServiceImpl    Could not dispatch batch for events
</code>```

As can be seen in the logs, the log on line 3 should have been accountId1 instead of accountId2.
How can I fix this situation?

Body:
I have a method in EventService that calls an API and handle errors if there is any.

private Mono<ApiResponse> send(String accountId) {
    accountIdBaggageField.updateValue(accountId);
    logger.info("making the call");
    Mono<ApiResponse> res = apiClient.dispatchEvent(accountId);
    return res.doOnError(e -> {
        logger.error("Could not dispatch batch for events");
    });
}

Here is the SleuthConfiguration class that defines accountIdBaggageField bean:

@Configuration
public class SleuthConfiguration {

    @Bean
    public BaggageField accountIdBaggageField() {
        return BaggageField.create(LoggingContextVariables.MDC_ACCOUNT_ID);
    }

    @Bean
    public BaggagePropagationCustomizer baggagePropagationCustomizer(BaggageField accountIdBaggageField) {
        return factoryBuilder -> {
            factoryBuilder.add(remote(accountIdBaggageField));
        };
    }

    @Bean
    public CorrelationScopeCustomizer correlationScopeCustomizer(BaggageField accountIdBaggageField) {
        return builder -> {
            builder.add(createCorrelationScopeConfig(accountIdBaggageField));
        };
    }

    private CorrelationScopeConfig createCorrelationScopeConfig(BaggageField field) {
        return CorrelationScopeConfig.SingleCorrelationField.newBuilder(field)
                .flushOnUpdate()
                .build();
    }
}

Here is the ApiClient's dispatchEvents method:

public Mono<ApiResponse> dispatchEvent(String accountId) {
        return webClient
                .post()
                .uri(properties.getEndpoints().getDispatchEvent(), Map.of("accountId", accountId))
                .retrieve()
                .onStatus(HttpStatus::isError, this::constructException)
                .bodyToMono(ApiResponse.class)
                .onErrorMap(WebClientRequestException.class, e -> new CGWException("Error during dispatching event to Connector Gateway", e));
    }

Here is how I call the send method:

eventService.send("account1");
eventService.send("account2");

The problem here is that the accountIdBaggageField is first set to "account1" and then the io process is started when apiClient.dispatchEvents is called. Before the end of the io process (before getting a response from the api), the second call takes place and the accountIdBaggageField is set to "account2".

Then, when the response of the first request is returned, the error log in doOnError adds the accountId to the log as "account2" but needs to add it as "account1".

Here are the logs:

2023-01-09 11:50:56.791  INFO [account1] [Thread-1] c.t.e.s.impl.EventServiceImpl    making the call

2023-01-09 11:50:56.812  INFO [account2] [Thread-1] c.t.e.s.impl.EventServiceImpl    making the call

2023-01-09 11:50:58.241  INFO [account2] [reactor-http-nio-4] c.t.e.s.impl.EventServiceImpl    Could not dispatch batch for events

2023-01-09 11:50:58.281  INFO [account2] [reactor-http-nio-6] c.t.e.s.impl.EventServiceImpl    Could not dispatch batch for events

As can be seen in the logs, the log on line 3 should have been accountId1 instead of accountId2.
How can I fix this situation?


问:
Access denied reset Password LDAP .net 6
Good morning, I am developing an application with .net 6 to change and reset passwords through LDAP but it gives me an access denied exception to use "ResetPassword" I tried with the administrator user and it didn't work either, could someone help me or guide me on what may be wrong in code.
excepsion

My code is

```<code>public string cambiarPass(string usuarioAdmin, string adminPass, string usuarioC, string nuevaPass)
{
    try
    {
        DirectoryEntry domainEntry = new DirectoryEntry(path, usuarioAdmin, adminPass);
        domainEntry.AuthenticationType = AuthenticationTypes.Secure;

        DirectorySearcher dirSearcher = new DirectorySearcher(domainEntry);
        //string filter = string.Format("(SAMAccountName={0})", usuarioC);

        //dirSearcher.Filter = "(samaccountname=" + usuarioC + ")";
        dirSearcher.Filter = string.Format("(sAMAccountName={0})", usuarioC);
        dirSearcher.SearchScope = SearchScope.Subtree;
        dirSearcher.CacheResults = false;

        //dirSearcher.Filter = filter;
        SearchResult result = dirSearcher.FindOne();
        if (result != null)
        {
            DirectoryEntry userEntry = result.GetDirectoryEntry();

            //Enable Account if it is disabled
            // userEntry.Properties["userAccountControl"].Value = 0x200;
            //Reset User Password
            userEntry.Invoke("SetPassword", new object[] { nuevaPass });
            //forzar la contraseña al cambio de contraseña en el siguiente inicio de sesion
            userEntry.Properties["LockOutTime"].Value = 0;
            userEntry.Properties["pwdlastset"][0] = 0;
            userEntry.CommitChanges();
           // userEntry.Close();

            guardaError = "a";
        }
        else
        {
            guardaError = "b";
        }
    }
    catch (Exception ex)
    {
        guardaError = ex.ToString();
    }

    return guardaError;
}
</code>```

I hope you can help me, greetings!

Body:
Good morning, I am developing an application with .net 6 to change and reset passwords through LDAP but it gives me an access denied exception to use "ResetPassword" I tried with the administrator user and it didn't work either, could someone help me or guide me on what may be wrong in code.
excepsion

My code is

public string cambiarPass(string usuarioAdmin, string adminPass, string usuarioC, string nuevaPass)
{
    try
    {
        DirectoryEntry domainEntry = new DirectoryEntry(path, usuarioAdmin, adminPass);
        domainEntry.AuthenticationType = AuthenticationTypes.Secure;

        DirectorySearcher dirSearcher = new DirectorySearcher(domainEntry);
        //string filter = string.Format("(SAMAccountName={0})", usuarioC);

        //dirSearcher.Filter = "(samaccountname=" + usuarioC + ")";
        dirSearcher.Filter = string.Format("(sAMAccountName={0})", usuarioC);
        dirSearcher.SearchScope = SearchScope.Subtree;
        dirSearcher.CacheResults = false;

        //dirSearcher.Filter = filter;
        SearchResult result = dirSearcher.FindOne();
        if (result != null)
        {
            DirectoryEntry userEntry = result.GetDirectoryEntry();

            //Enable Account if it is disabled
            // userEntry.Properties["userAccountControl"].Value = 0x200;
            //Reset User Password
            userEntry.Invoke("SetPassword", new object[] { nuevaPass });
            //forzar la contraseña al cambio de contraseña en el siguiente inicio de sesion
            userEntry.Properties["LockOutTime"].Value = 0;
            userEntry.Properties["pwdlastset"][0] = 0;
            userEntry.CommitChanges();
           // userEntry.Close();

            guardaError = "a";
        }
        else
        {
            guardaError = "b";
        }
    }
    catch (Exception ex)
    {
        guardaError = ex.ToString();
    }

    return guardaError;
}

I hope you can help me, greetings!


问:
Validate JSON input against schema in Vue.js
I'm trying to create a JSON input field for my application made in Vue.js. I'm looking for a component/package/library that allows me to:

Lint and format the JSON, displaying any errors (like this)

Have an interface that displays the line numbers (like this)

Validate the resulting JSON against a schema with its rules and regex (like this)

Does anybody know if anything like that exists?

I've tried to implement the solutions shown at point 1) (this) it works but with some tweaks needed.


问:
Video player using qml ,opencv and pyside2
I have a video stream that I want to display as simply as possible (no audio, just a sequence of frames ). my question is how to dynamically pass the emitted image to requestImage, assigning a new image every frame?

Here is the code I'm using:

main.py

```<code>import cv2
import sys
from PySide2 import QtCore
from PySide2 import QtQuick
from PySide2.QtGui import QImage, QPixmap
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QThread, Signal, Slot, QUrl

class VideoThread(QThread):
    changePixmapSignal = Signal(QPixmap)
    def __init__(self):
        QThread.__init__(self)
        self.capturing = True
        self.video_capture = cv2.VideoCapture("video1.mp4")
        self.video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    @Slot()
    def startCapture(self):
        if not self.capturing:
            self.capturing = True
            self.start()
    @Slot()
    def stopCapture(self):
        if self.capturing:
            self.capturing = False
            self.video_capture.release()
            self.quit()
    def run(self):
        while self.capturing:
            _, frame = self.video_capture.read()
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(image)
            self.changePixmapSignal.emit(pixmap)

def qt_message_handler(mode, context, message):
    if mode == QtCore.QtInfoMsg:
        mode = 'Info'
    elif mode == QtCore.QtWarningMsg:
        mode = 'Warning'
    elif mode == QtCore.QtCriticalMsg:
        mode = 'critical'
    elif mode == QtCore.QtFatalMsg:
        mode = 'fatal'
    else:
        mode = 'Debug'
    print("%s: %s (%s:%d, %s)" % (mode, message, context.file, context.line, context.file))

if __name__ == "__main__":
    QtCore.qInstallMessageHandler(qt_message_handler)
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    # Expose the Camera class to QML
    context = engine.rootContext()
    video_thread = VideoThread()
    context.setContextProperty("videoThread", video_thread)
    qml_file = QUrl.fromLocalFile("mainview.qml")
    engine.load(qml_file)
    screen = engine.rootObjects()[0]
    print(screen)
    print(screen.findChild(QtQuick.QQuickItem, "videoFrame"))
    video_thread.changePixmapSignal.connect(screen.findChild(QtQuick.QQuickItem, "videoFrame").updateFrame)
    sys.exit(app.exec_())
</code>```

mainview.qml

```<code>import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    Image {
        id: videoFrame
        anchors.fill: parent
        fillMode: Image.PreserveAspectCrop
        // This is the slot that updates the image source
        function updateFrame(pixmap) {
            videoFrame.source = pixmap
        }
    }
}
</code>```

When I run this program I get this error :

```<code>video_thread.changePixmapSignal.connect(screen.findChild(QtQuick.QQuickItem, "videoFrame").updateFrame)
AttributeError: 'NoneType' object has no attribute 'updateFrame'
</code>```

Body:
I have a video stream that I want to display as simply as possible (no audio, just a sequence of frames ). my question is how to dynamically pass the emitted image to requestImage, assigning a new image every frame?

Here is the code I'm using:

main.py

import cv2
import sys
from PySide2 import QtCore
from PySide2 import QtQuick
from PySide2.QtGui import QImage, QPixmap
from PySide2.QtWidgets import QApplication
from PySide2.QtQml import QQmlApplicationEngine
from PySide2.QtCore import QThread, Signal, Slot, QUrl

class VideoThread(QThread):
    changePixmapSignal = Signal(QPixmap)
    def __init__(self):
        QThread.__init__(self)
        self.capturing = True
        self.video_capture = cv2.VideoCapture("video1.mp4")
        self.video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    @Slot()
    def startCapture(self):
        if not self.capturing:
            self.capturing = True
            self.start()
    @Slot()
    def stopCapture(self):
        if self.capturing:
            self.capturing = False
            self.video_capture.release()
            self.quit()
    def run(self):
        while self.capturing:
            _, frame = self.video_capture.read()
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image = QImage(frame, frame.shape[1], frame.shape[0], QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(image)
            self.changePixmapSignal.emit(pixmap)

def qt_message_handler(mode, context, message):
    if mode == QtCore.QtInfoMsg:
        mode = 'Info'
    elif mode == QtCore.QtWarningMsg:
        mode = 'Warning'
    elif mode == QtCore.QtCriticalMsg:
        mode = 'critical'
    elif mode == QtCore.QtFatalMsg:
        mode = 'fatal'
    else:
        mode = 'Debug'
    print("%s: %s (%s:%d, %s)" % (mode, message, context.file, context.line, context.file))

if __name__ == "__main__":
    QtCore.qInstallMessageHandler(qt_message_handler)
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()
    # Expose the Camera class to QML
    context = engine.rootContext()
    video_thread = VideoThread()
    context.setContextProperty("videoThread", video_thread)
    qml_file = QUrl.fromLocalFile("mainview.qml")
    engine.load(qml_file)
    screen = engine.rootObjects()[0]
    print(screen)
    print(screen.findChild(QtQuick.QQuickItem, "videoFrame"))
    video_thread.changePixmapSignal.connect(screen.findChild(QtQuick.QQuickItem, "videoFrame").updateFrame)
    sys.exit(app.exec_())

mainview.qml

import QtQuick 2.15
import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 640
    height: 480

    Image {
        id: videoFrame
        anchors.fill: parent
        fillMode: Image.PreserveAspectCrop
        // This is the slot that updates the image source
        function updateFrame(pixmap) {
            videoFrame.source = pixmap
        }
    }
}

When I run this program I get this error :

video_thread.changePixmapSignal.connect(screen.findChild(QtQuick.QQuickItem, "videoFrame").updateFrame)
AttributeError: 'NoneType' object has no attribute 'updateFrame'


问:
Programming for Android under Eclipse
I am using Java Eclipse IDE for programming Android application. Recently Google changed requirements for publishing new apk's: it must have targetSdkVersion>=31.
I tried to sign apk inside Eclipse with targetSdkVersion=31 - but now Android says .apk format is corrupted.

I undestand that this way of programming for Android is obsolete, but I really don't like Android Studio.

My question is for guys who may still programming for Android under Eclipse: is there are a way to sign .APK inside Eclipse with targetSdkVersion>31?

Thanks.

Title: Programming for Android under Eclipse


问:
Add Jenkins Shared Libraries with classes reference in a Jenkinsfile dynamically
I have constructed a Shared Library in which I want to have class definitions, below is the example shared lib code.

```<code>package api
class api implements Serializable {

    private final Map data
    private final DSL steps

    api(Map data, DSL steps) {
        this.data = data
        this.steps = steps
    }
}
</code>```

I have placed this class definition in a shared library git repo, with the path api/src/api/api.groovy. I am importing the shared library using the following step at the top of my jenkinsfile, outside any node or pipeline directive:

```<code>library identifier: 'api@master', retriever: modernSCM(
    scm: [
       $class: 'GitSCMSource',
        credentialsId: '<my-credentials-id>',
        remote: '<my-git-remote>',
        traits: [gitBranchDiscovery()]
    ],
    libraryPath: 'api/'
)
import api.*
</code>```

When I use the above class from the shared library it's throwing an exception saying that the class is not found.

```<code>WorkflowScript: 75: unable to resolve class api
 @ line 75, column 29.
               api foo = new api(env.data, steps)
                               ^

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:309)
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:981)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:626)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:575)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:323)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:293)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox$Scope.parse(GroovySandbox.java:163)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:562)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:514)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:336)
    at hudson.model.ResourceController.execute(ResourceController.java:107)
    at hudson.model.Executor.run(Executor.java:449)
Finished: FAILURE
</code>```

As i read in the doccument that loading library dynamically does not import classes directly to the pipeline's classpath.

So need a little help to get this class into my job execution.

Note: I have tested it and it's working when adding the global libraries under jenkins global settings, however i want this library setting to be dynamic from jenkins file.

Body:
I have constructed a Shared Library in which I want to have class definitions, below is the example shared lib code.

package api
class api implements Serializable {

    private final Map data
    private final DSL steps

    api(Map data, DSL steps) {
        this.data = data
        this.steps = steps
    }
}

I have placed this class definition in a shared library git repo, with the path api/src/api/api.groovy. I am importing the shared library using the following step at the top of my jenkinsfile, outside any node or pipeline directive:

library identifier: 'api@master', retriever: modernSCM(
    scm: [
       $class: 'GitSCMSource',
        credentialsId: '<my-credentials-id>',
        remote: '<my-git-remote>',
        traits: [gitBranchDiscovery()]
    ],
    libraryPath: 'api/'
)
import api.*

When I use the above class from the shared library it's throwing an exception saying that the class is not found.

WorkflowScript: 75: unable to resolve class api
 @ line 75, column 29.
               api foo = new api(env.data, steps)
                               ^

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:309)
    at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:981)
    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:626)
    at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:575)
    at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:323)
    at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:293)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox$Scope.parse(GroovySandbox.java:163)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
    at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:562)
    at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:514)
    at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:336)
    at hudson.model.ResourceController.execute(ResourceController.java:107)
    at hudson.model.Executor.run(Executor.java:449)
Finished: FAILURE

As i read in the doccument that loading library dynamically does not import classes directly to the pipeline's classpath.

So need a little help to get this class into my job execution.

Note: I have tested it and it's working when adding the global libraries under jenkins global settings, however i want this library setting to be dynamic from jenkins file.


问:
Some Unicode Characters are not rendered in Emacs
My emacs has a problem in rendering the Unicode character written by \McU (All \Mc* and \Mi* characters) in Agda input mode. (, , , ... etc)

I installed Iosevka and JuliaMono Light fonts,
follwed the instruction in here: https://github.com/rolandwalker/unicode-fonts

Downloaded font-utils.el / list-utils.el / ucs-utils.el / unicode-fonts.el    in my .emacs.d folder

Inserted the following in my .emacs file:
```<code>(require 'font-utils)
(require 'ucs-utils)
(require 'list-utils)
(add-to-list 'load-path "~/.emacs.d/unicode-fonts/")
(require 'unicode-fonts)
(unicode-fonts-setup)
</code>```

And added
```<code>(set-frame-font "Iosevka SS04" nil t)
;; Set a fallback font for mathematical script and fraktur. (It'll mess up monospacing.
(set-fontset-font "fontset-default" '(#x1d49c . #x1d537) "JuliaMono Light")
</code>```
to my .emacs file.

None of these works... What can I do?

I expect that Emacs can render unicode characters such as , ...

Actually, I already tried many fonts, modifying my .emacs file. Especially, JuliaMono certainly has this glyph , but still  is not rendered in Emacs.
JuliaMono font has

Body:
My emacs has a problem in rendering the Unicode character written by \McU (All \Mc* and \Mi* characters) in Agda input mode. (, , , ... etc)

I installed Iosevka and JuliaMono Light fonts,
follwed the instruction in here: https://github.com/rolandwalker/unicode-fonts

Downloaded font-utils.el / list-utils.el / ucs-utils.el / unicode-fonts.el    in my .emacs.d folder

Inserted the following in my .emacs file:

(require 'font-utils)
(require 'ucs-utils)
(require 'list-utils)
(add-to-list 'load-path "~/.emacs.d/unicode-fonts/")
(require 'unicode-fonts)
(unicode-fonts-setup)

And added

(set-frame-font "Iosevka SS04" nil t)
;; Set a fallback font for mathematical script and fraktur. (It'll mess up monospacing.
(set-fontset-font "fontset-default" '(#x1d49c . #x1d537) "JuliaMono Light")

to my .emacs file.

None of these works... What can I do?

I expect that Emacs can render unicode characters such as , ...

Actually, I already tried many fonts, modifying my .emacs file. Especially, JuliaMono certainly has this glyph , but still  is not rendered in Emacs.
JuliaMono font has


问:
How to set affinity for percona mysql helm deployment?
I have a percona mysql cluster deployed in my kubernetes cluster and can't figure it out how to use "pxc.affinity.advanced" parameter to add tolerations.
In the values.yaml file it looks like this:

```<code>affinity:
    antiAffinityTopologyKey: "kubernetes.io/hostname"
    # advanced:
    #   nodeAffinity:
    #     requiredDuringSchedulingIgnoredDuringExecution:
    #       nodeSelectorTerms:
    #       - matchExpressions:
    #         - key: kubernetes.io/e2e-az-name
    #           operator: In
    #           values:
    #           - e2e-az1
    #           - e2e-az2
</code>```

I need to avoid pods being placed on some nodes.
https://github.com/percona/percona-helm-charts/tree/main/charts/pxc-db#installing-the-chart
I'm writing here as a last resort since I couldn't find any information anywhere

My only thought, since I found no documentation ,  was to try a json  format and with my node label being app=pxc  I tried
--set pxc.affinity.advanced={"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [{"matchExpressions": [{"key": "app","operator": "In","values": ["pxc"]}]}]}}}

and got an error:

install.go:192: [debug] Original chart version: "" Error: INSTALLATION
FAILED: expected at most two arguments, unexpected arguments:
{requiredDuringSchedulingIgnoredDuringExecution:, {nodeSelectorTerms:,
[{matchExpressions:, [{key:, app,operator:, In,values:, [pxc]}]}]}}}
helm.go:84: [debug] expected at most two arguments, unexpected
arguments: {requiredDuringSchedulingIgnoredDuringExecution:,
{nodeSelectorTerms:, [{matchExpressions:, [{key:, app,operator:,
In,values:, [pxc]}]}]}}}

Body:
I have a percona mysql cluster deployed in my kubernetes cluster and can't figure it out how to use "pxc.affinity.advanced" parameter to add tolerations.
In the values.yaml file it looks like this:

affinity:
    antiAffinityTopologyKey: "kubernetes.io/hostname"
    # advanced:
    #   nodeAffinity:
    #     requiredDuringSchedulingIgnoredDuringExecution:
    #       nodeSelectorTerms:
    #       - matchExpressions:
    #         - key: kubernetes.io/e2e-az-name
    #           operator: In
    #           values:
    #           - e2e-az1
    #           - e2e-az2

I need to avoid pods being placed on some nodes.
https://github.com/percona/percona-helm-charts/tree/main/charts/pxc-db#installing-the-chart
I'm writing here as a last resort since I couldn't find any information anywhere

My only thought, since I found no documentation ,  was to try a json  format and with my node label being app=pxc  I tried
--set pxc.affinity.advanced={"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": {"nodeSelectorTerms": [{"matchExpressions": [{"key": "app","operator": "In","values": ["pxc"]}]}]}}}

and got an error:

install.go:192: [debug] Original chart version: "" Error: INSTALLATION
FAILED: expected at most two arguments, unexpected arguments:
{requiredDuringSchedulingIgnoredDuringExecution:, {nodeSelectorTerms:,
[{matchExpressions:, [{key:, app,operator:, In,values:, [pxc]}]}]}}}
helm.go:84: [debug] expected at most two arguments, unexpected
arguments: {requiredDuringSchedulingIgnoredDuringExecution:,
{nodeSelectorTerms:, [{matchExpressions:, [{key:, app,operator:,
In,values:, [pxc]}]}]}}}


问:
Form within Partial View - Redirect to different Views
I am using .NET 6 MVC.
Hi, I have a partial View with data, which it gets from the "above" View´s Model.
I want this Form to Redirect to different Actions depending on the "above" View.

ie:
View1.cshtml:

```<code> @await Html.PartialAsync("_Update", Model)
</code>```

View2.cshtml:

```<code> @await Html.PartialAsync("_Update", Model.Data)
</code>```

_Update.cshtml:

```<code>@model MyModel
    <form method="post" asp-action="@(nameof(Controller.update))">
     //...data
     //submit btn
    </form>
</code>```

Currently each Controller has it´s own "update" Action, which is in hindsight not optimal and I will most likely refactor it into one Controller.
The method toupdate Redirects back to the "above" VIew´s Controller on Error or Success. How can I do that with Partials?
My quick fix was to pull the form out of the Partial and add it to the View and define there the correct Update Action and the Partial only has the data and submit btn, but this is kinda ugly.

-> How can I "give" an Partial View from which View it is coming and then Link to the Action from those Controllers?

Body:
I am using .NET 6 MVC.
Hi, I have a partial View with data, which it gets from the "above" View´s Model.
I want this Form to Redirect to different Actions depending on the "above" View.

ie:
View1.cshtml:

 @await Html.PartialAsync("_Update", Model)

View2.cshtml:

 @await Html.PartialAsync("_Update", Model.Data)

_Update.cshtml:

@model MyModel
    <form method="post" asp-action="@(nameof(Controller.update))">
     //...data
     //submit btn
    </form>

Currently each Controller has it´s own "update" Action, which is in hindsight not optimal and I will most likely refactor it into one Controller.
The method toupdate Redirects back to the "above" VIew´s Controller on Error or Success. How can I do that with Partials?
My quick fix was to pull the form out of the Partial and add it to the View and define there the correct Update Action and the Partial only has the data and submit btn, but this is kinda ugly.

-> How can I "give" an Partial View from which View it is coming and then Link to the Action from those Controllers?


问:
Why sometimes with Apache Flink, different keys assigned to the same window
Here I'm feeding the following events to Flink

        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:01.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:02.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:03.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:06.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:07.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:07.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:09.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:10.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:04.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:05.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:12.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:13.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:15.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:16.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:11.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:16.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:17.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:15.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:22.00Z"), 1));

```
<p>And this is my pipeline</p>
<pre class="lang-java prettyprint-override"><code>
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.getConfig().setAutoWatermarkInterval(1000);
        SingleOutputStreamOperator<ClickEvent> output = env.addSource(source).assignTimestampsAndWatermarks
                (WatermarkStrategy.<ClickEvent>forBoundedOutOfOrderness(Duration.ofMillis(1000))
                        .withTimestampAssigner((click, t) -> click.getEventTimeMillis())).keyBy((ClickEvent e) -> e.userId)
                .window(TumblingEventTimeWindows.of(Time.milliseconds(10000)))
                .process(new ProcessWindowFunction<ClickEvent, ClickEvent, Long, TimeWindow>() {
                    @Override
                    public void process(Long aLong, ProcessWindowFunction<ClickEvent, ClickEvent,                                                                                Long, TimeWindow>.Context context, Iterable<ClickEvent> iterable, Collector<ClickEvent> collector) throws Exception {
                                                            // aLong is the key
                                    // context of the window
                                    // iterable is the content of the window (events)
                                    // collector will be used to emit the output of the window

                                System.out.println("[ Window Start: "+context.window().getStart()+" - Current Watermark: "+
                                        context.currentWatermark() + " - Current Key: "+aLong + " - Window End: "+
                                        context.window().getEnd() + " ]");
                                System.out.println("==== Window Elements ====");
                                for(ClickEvent clickEvent : iterable){
                                    System.out.println(clickEvent.toString());
//                                    collector.collect(clickEvent);
                                }
                    }
                });
        output.print();
        return env.execute("Streaming Job with Global Watermark");

</code>```

I think that each window should work on ONE key at a time, so how different keys are assigned to the same window.

The events that I'm use contains late events and out-of-order events as well.

I'm using the ProcessWindowFunction to display the window elements, window start timestamp, window end timestamp, current watermark and the window key.

[ Window Start: 957873600000 - Current Watermark: 957873610999 - Current Key: 2 - Window End: 957873610000 ]
==== Window Elements ====
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:01Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:02Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:03Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:06Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:07Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:04Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:05Z, userId= 2, toSum=1}
[ Window Start: 957873600000 - Current Watermark: 957873610999 - Current Key: 5 - Window End: 957873610000 ]
==== Window Elements ====
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:07Z, userId= 5, toSum=1}
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:09Z, userId= 5, toSum=1}
[ Window Start: 957873610000 - Current Watermark: 9223372036854775807 - Current Key: 5 - Window End: 957873620000 ]
==== Window Elements ====
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:10Z, userId= 5, toSum=1}
[ Window Start: 957873610000 - Current Watermark: 9223372036854775807 - Current Key: 1 - Window End: 957873620000 ]
==== Window Elements ====
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:13Z, userId= 1, toSum=1}
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:12Z, userId= 5, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:15Z, userId= 1, toSum=1}
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:11Z, userId= 5, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:16Z, userId= 1, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:16Z, userId= 1, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:17Z, userId= 1, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:15Z, userId= 1, toSum=1}
[ Window Start: 957873620000 - Current Watermark: 9223372036854775807 - Current Key: 1 - Window End: 957873630000 ]
==== Window Elements ====
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:22Z, userId= 1, toSum=1}

```

Body:
Here I'm feeding the following events to Flink

        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:01.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:02.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:03.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:06.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:07.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:07.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:09.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:10.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:04.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(2, 2, Instant.parse("2000-05-09T12:00:05.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:12.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:13.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:15.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:16.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(5, 5, Instant.parse("2000-05-09T12:00:11.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:16.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:17.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:15.00Z"), 1));
        Thread.sleep(1500);
        ctx.collect(new ClickEvent(1, 1, Instant.parse("2000-05-09T12:00:22.00Z"), 1));

And this is my pipeline

StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.getConfig().setAutoWatermarkInterval(1000);
        SingleOutputStreamOperator<ClickEvent> output = env.addSource(source).assignTimestampsAndWatermarks
                (WatermarkStrategy.<ClickEvent>forBoundedOutOfOrderness(Duration.ofMillis(1000))
                        .withTimestampAssigner((click, t) -> click.getEventTimeMillis())).keyBy((ClickEvent e) -> e.userId)
                .window(TumblingEventTimeWindows.of(Time.milliseconds(10000)))
                .process(new ProcessWindowFunction<ClickEvent, ClickEvent, Long, TimeWindow>() {
                    @Override
                    public void process(Long aLong, ProcessWindowFunction<ClickEvent, ClickEvent,                                                                                Long, TimeWindow>.Context context, Iterable<ClickEvent> iterable, Collector<ClickEvent> collector) throws Exception {
                                                            // aLong is the key
                                    // context of the window
                                    // iterable is the content of the window (events)
                                    // collector will be used to emit the output of the window

                                System.out.println("[ Window Start: "+context.window().getStart()+" - Current Watermark: "+
                                        context.currentWatermark() + " - Current Key: "+aLong + " - Window End: "+
                                        context.window().getEnd() + " ]");
                                System.out.println("==== Window Elements ====");
                                for(ClickEvent clickEvent : iterable){
                                    System.out.println(clickEvent.toString());
//                                    collector.collect(clickEvent);
                                }
                    }
                });
        output.print();
        return env.execute("Streaming Job with Global Watermark");

I think that each window should work on ONE key at a time, so how different keys are assigned to the same window.

The events that I'm use contains late events and out-of-order events as well.

I'm using the ProcessWindowFunction to display the window elements, window start timestamp, window end timestamp, current watermark and the window key.

[ Window Start: 957873600000 - Current Watermark: 957873610999 - Current Key: 2 - Window End: 957873610000 ]
==== Window Elements ====
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:01Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:02Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:03Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:06Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:07Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:04Z, userId= 2, toSum=1}
ClickEvent{ clickId= 2, clickTimestamp= 2000-05-09T12:00:05Z, userId= 2, toSum=1}
[ Window Start: 957873600000 - Current Watermark: 957873610999 - Current Key: 5 - Window End: 957873610000 ]
==== Window Elements ====
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:07Z, userId= 5, toSum=1}
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:09Z, userId= 5, toSum=1}
[ Window Start: 957873610000 - Current Watermark: 9223372036854775807 - Current Key: 5 - Window End: 957873620000 ]
==== Window Elements ====
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:10Z, userId= 5, toSum=1}
[ Window Start: 957873610000 - Current Watermark: 9223372036854775807 - Current Key: 1 - Window End: 957873620000 ]
==== Window Elements ====
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:13Z, userId= 1, toSum=1}
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:12Z, userId= 5, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:15Z, userId= 1, toSum=1}
ClickEvent{ clickId= 5, clickTimestamp= 2000-05-09T12:00:11Z, userId= 5, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:16Z, userId= 1, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:16Z, userId= 1, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:17Z, userId= 1, toSum=1}
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:15Z, userId= 1, toSum=1}
[ Window Start: 957873620000 - Current Watermark: 9223372036854775807 - Current Key: 1 - Window End: 957873630000 ]
==== Window Elements ====
ClickEvent{ clickId= 1, clickTimestamp= 2000-05-09T12:00:22Z, userId= 1, toSum=1}


问:
How to add Cordova plugin in angular library to reuse in multiple ionic apps?
I have created a multi-app ionic project. Also, added angular libraries to be reused in multiple ionic apps.

I managed to setup the libraries to have ionic components and pages and can be reused successfully in multiple ionic applications without any issues.

But I can't figure out how to add a Cordova plugin in angular library to be reused in ionic apps.


问:
Log Files In Active Directory
What is the method to access the log files in Windows Log > Security in Active Directory using Java through an LDAP connection?

So I can filter the deleted users using Event ID

PS: I am using Windows Server 2019

Tried LDAP search on CN=System, the program ran successfully but no output produced.

Title: Log Files In Active Directory


问:
Draging and Droping an object in one script
Hi I'm working on a card game and I started by doing the card movement as it seemed easy for me
I wanted to make the drag and drop code very clean and all in one script but I struggled to make this happen, I need to know if there is an object below the mouse and check it is the right one to drop the card in the right place
I know I can use raycast but I was looking for easier way for doing it, also I wanna keep it in one script as I said before if anyone could help me I would be very thankful

here is the script

```<code>//changing the card parent when Pressing and holding the card
public void OnBeginDrag(PointerEventData eventData)
{
    this.transform.SetParent(GameObject.Find("Game Screen").transform);
    GetComponent<CanvasGroup>().blocksRaycasts = false;
}

// changing the card postion while draging with hamd or mouse
public void OnDrag(PointerEventData eventData)
{
    this.transform.position = eventData.position;
    GetComponent<CanvasGroup>().blocksRaycasts = false;
}

// getting the object below the mouse to know where to palce the card
public void OnDrop(PointerEventData eventData)
{

}

// placing the card in [hand, Monster Area, Spell Area] depending on where it was last
public void OnEndDrag(PointerEventData eventData)
{
    GetComponent<CanvasGroup>().blocksRaycasts = true;

    if ()
    {
        this.transform.position = GameObject.Find("Spell Area").transform.position;
        this.transform.SetParent(GameObject.Find("Spell Area").transform);
    }
    else if ()
    {
        this.transform.position = GameObject.Find("Monster Area").transform.position;
        this.transform.SetParent(GameObject.Find("Monster Area").transform);
    }
    else
    {
        this.transform.position = GameObject.Find("Player Hand").transform.position;
        this.transform.SetParent(GameObject.Find("Player Hand").transform);
    }
}
</code>```

one more thing if I used raycasting should I use 2d or 3d as 2d is in theory will not have the below ray which I need?

Sorry for poor English

Body:
Hi I'm working on a card game and I started by doing the card movement as it seemed easy for me
I wanted to make the drag and drop code very clean and all in one script but I struggled to make this happen, I need to know if there is an object below the mouse and check it is the right one to drop the card in the right place
I know I can use raycast but I was looking for easier way for doing it, also I wanna keep it in one script as I said before if anyone could help me I would be very thankful

here is the script

//changing the card parent when Pressing and holding the card
public void OnBeginDrag(PointerEventData eventData)
{
    this.transform.SetParent(GameObject.Find("Game Screen").transform);
    GetComponent<CanvasGroup>().blocksRaycasts = false;
}

// changing the card postion while draging with hamd or mouse
public void OnDrag(PointerEventData eventData)
{
    this.transform.position = eventData.position;
    GetComponent<CanvasGroup>().blocksRaycasts = false;
}

// getting the object below the mouse to know where to palce the card
public void OnDrop(PointerEventData eventData)
{

}

// placing the card in [hand, Monster Area, Spell Area] depending on where it was last
public void OnEndDrag(PointerEventData eventData)
{
    GetComponent<CanvasGroup>().blocksRaycasts = true;

    if ()
    {
        this.transform.position = GameObject.Find("Spell Area").transform.position;
        this.transform.SetParent(GameObject.Find("Spell Area").transform);
    }
    else if ()
    {
        this.transform.position = GameObject.Find("Monster Area").transform.position;
        this.transform.SetParent(GameObject.Find("Monster Area").transform);
    }
    else
    {
        this.transform.position = GameObject.Find("Player Hand").transform.position;
        this.transform.SetParent(GameObject.Find("Player Hand").transform);
    }
}

one more thing if I used raycasting should I use 2d or 3d as 2d is in theory will not have the below ray which I need?

Sorry for poor English


问:
Rendered sum is displaying as NaN
I am trying to total  a column of numbers by className and have that total displayed. However the result is NaN, and I am not sure where I need to make changes.

Here is the code I currently have that takes hoursCompleted (these are the ones displayed) and I am trying to create a "total" row at the bottom of this with output displaying the totalHoursCompleted.

```<code>let hoursCompleted = document.getElementsByClassName('data-legend-info-part');

let totalHoursCompleted = [];

for (let i = 0; i < hoursCompleted.length; i++) {
const hours = hoursCompleted[i];
totalHoursCompleted.push(Number(hours));
}

let sum = 0;

for (let i = 0; i < totalHoursCompleted.length; i++) {
sum += totalHoursCompleted[i];
}
</code>```

Here is what I have set up for return, and with that the NaN.

```<code>return (
<div className="pie-chart-wrapper">
<div id={`pie-chart-container-${pieChartId}`} className="pie-chart" />
<div>
<div className="pie-chart-legend-header">
<div>Name</div>
<div>{dataLegendHeader}</div>
</div>
{/*Values for Name Header entered here*/}
{Object.keys(dataLegend).map(key => (
<div key={key} className="pie-chart-legend-item">
<div className="data-legend-color" style={{ backgroundColor: color(key)
}} />
<div className="data-legend-info">
{dataLegend[key].map(legendPart => (
<div className="data-legend-info-part">{legendPart}</div>
))}
</div>
</div>
 ))}
{/*Values for Hours Header entered here*/}

<div className="pie-chart-legend-item">
<div className="data-legend-info">
Total Hours Worked:
<div className="data-legend-info-part">{sum}</div>
</div>
</div>
</div>
</div>
);
</code>```

So if there's 3 tasks, all with 4 hoursCompleted. I want the {sum} to display 12. Any help is appreciated!

Title: Rendered sum is displaying as NaN

Body:
I am trying to total  a column of numbers by className and have that total displayed. However the result is NaN, and I am not sure where I need to make changes.

Here is the code I currently have that takes hoursCompleted (these are the ones displayed) and I am trying to create a "total" row at the bottom of this with output displaying the totalHoursCompleted.

let hoursCompleted = document.getElementsByClassName('data-legend-info-part');

let totalHoursCompleted = [];

for (let i = 0; i < hoursCompleted.length; i++) {
const hours = hoursCompleted[i];
totalHoursCompleted.push(Number(hours));
}

let sum = 0;

for (let i = 0; i < totalHoursCompleted.length; i++) {
sum += totalHoursCompleted[i];
}

Here is what I have set up for return, and with that the NaN.

return (

<div id={`pie-chart-container-${pieChartId}`} className="pie-chart" />

Name

{dataLegendHeader}

{/*Values for Name Header entered here*/}
{Object.keys(dataLegend).map(key => (

{dataLegend[key].map(legendPart => (

{legendPart}

))}

 ))}
{/*Values for Hours Header entered here*/}

Total Hours Worked:

{sum}

);

So if there's 3 tasks, all with 4 hoursCompleted. I want the {sum} to display 12. Any help is appreciated!


问:
Not reaching the API after deploying to render
I'm trying to deploy my website on Render.

Locally my code works just fine yet I cannot seem to make it work after deploying it.

I'm getting this error in developer tools on the website

```<code>Had Issues GETing to the backend, endpoint: stay/, with data: [object Object]
http.service.js:35 Error: Network Error
    at e.exports (https://hosty.onrender.com/static/js/main.bbd07398.js:2:70266)
    at y.onerror (https://hosty.onrender.com/static/js/main.bbd07398.js:2:65137)
stay.service.js:28 Cannot get stay Error: Network Error
    at e.exports (createError.js:16:15)
    at y.onerror (xhr.js:117:14)
</code>```

My code in the frontend is

```<code>import Axios from 'axios';

const BASE_URL = process.env.NODE_ENV === 'production' ? '//hosty-backend.onrender.com' : '//localhost:3030/api/';

//http service
var axios = Axios.create({
  withCredentials: true,
});
export const httpService = {
  get(endpoint, data) {
    return ajax(endpoint, 'GET', data);
  },
  post(endpoint, data) {
    return ajax(endpoint, 'POST', data);
  },
  put(endpoint, data) {
    return ajax(endpoint, 'PUT', data);
  },
  delete(endpoint, data) {
    return ajax(endpoint, 'DELETE', data);
  },
};

async function ajax(endpoint, method = 'GET', data = null) {
  try {
    const res = await axios({
      url: `${BASE_URL}${endpoint}`,
      method,
      data,
      params: method === 'GET' ? data : null,
    });
    return res.data;
  } catch (err) {
    console.log(`Had Issues ${method}ing to the backend, endpoint: ${endpoint}, with data: ${data}`);
    console.dir(err);
    if (err.response && err.response.status === 401) {
      sessionStorage.clear();
      window.location.assign('/');
    }
    throw err;
  }
}
</code>```

It's very important to say that my code works properly LOCALLY.
I have also tried to use

const BASE_URL = process.env.NODE_ENV === 'production' ? 'https://hosty-backend.onrender.com' : '//localhost:3030/api/';

but still it doesn't work.

Any help is appreciated!

Body:
I'm trying to deploy my website on Render.

Locally my code works just fine yet I cannot seem to make it work after deploying it.

I'm getting this error in developer tools on the website

Had Issues GETing to the backend, endpoint: stay/, with data: [object Object]
http.service.js:35 Error: Network Error
    at e.exports (https://hosty.onrender.com/static/js/main.bbd07398.js:2:70266)
    at y.onerror (https://hosty.onrender.com/static/js/main.bbd07398.js:2:65137)
stay.service.js:28 Cannot get stay Error: Network Error
    at e.exports (createError.js:16:15)
    at y.onerror (xhr.js:117:14)

My code in the frontend is

import Axios from 'axios';

const BASE_URL = process.env.NODE_ENV === 'production' ? '//hosty-backend.onrender.com' : '//localhost:3030/api/';

//http service
var axios = Axios.create({
  withCredentials: true,
});
export const httpService = {
  get(endpoint, data) {
    return ajax(endpoint, 'GET', data);
  },
  post(endpoint, data) {
    return ajax(endpoint, 'POST', data);
  },
  put(endpoint, data) {
    return ajax(endpoint, 'PUT', data);
  },
  delete(endpoint, data) {
    return ajax(endpoint, 'DELETE', data);
  },
};

async function ajax(endpoint, method = 'GET', data = null) {
  try {
    const res = await axios({
      url: `${BASE_URL}${endpoint}`,
      method,
      data,
      params: method === 'GET' ? data : null,
    });
    return res.data;
  } catch (err) {
    console.log(`Had Issues ${method}ing to the backend, endpoint: ${endpoint}, with data: ${data}`);
    console.dir(err);
    if (err.response && err.response.status === 401) {
      sessionStorage.clear();
      window.location.assign('/');
    }
    throw err;
  }
}

It's very important to say that my code works properly LOCALLY.
I have also tried to use

const BASE_URL = process.env.NODE_ENV === 'production' ? 'https://hosty-backend.onrender.com' : '//localhost:3030/api/';

but still it doesn't work.

Any help is appreciated!


问:
Normalize one (umlaut) character results in two
I assume I didn't fully understand unicodedata.normalize() function in Python.

```<code>from unicodedata import normalize

result = normalize('NFKD', 'Ä')

print(result)  # 'A'

print(len(result))  # 2

print(result == 'A')  # False

print(result[0] == 'A')  # True
</code>```

I'm confused why the len() is 2 instead of 1.

Body:
I assume I didn't fully understand unicodedata.normalize() function in Python.

from unicodedata import normalize

result = normalize('NFKD', 'Ä')

print(result)  # 'A'

print(len(result))  # 2

print(result == 'A')  # False

print(result[0] == 'A')  # True

I'm confused why the len() is 2 instead of 1.


问:
vscode Open Disassembly View is not opened when no opened editor
I'm developing embedded platform, and try to debug via elf file only on Windows,
but when i start debug, with empty opened editor, Open Disassembly View in Call Stack is not working.
enter image description here

when i opened any c file, Open Disassembly View is working fine.
enter image description here
is there any condition or constraint for Open Disassembly View?


问:
passing form parameters from one form to another in the same page
I'm trying to grab values from form1 and form2 post submit respectively.
The only difference is that when i submit form2, I need form1 values as well.

Form 1

```<code><form action="send_value1" method="POST">
      Input1: <input type="text" name="input1">
      Input2: <input type="text" name="input2">
      <input type="submit" name="submit" value="submit_form1">
</form>
</code>```

Form 2

```<code><form action="send_value2" method="POST">
      Input3: <input type="text" name="input3">
      Input4: <input type="text" name="input4">
      <input type="submit" name="submit" value="submit_form2">
</form>
</code>```

In py file, I'm trying to fetch using POST method

```<code>@app.route("/page", methods=["GET", "POST"])
def to_do():

    if request.method == "POST":

        if request.form['submit'] == 'submit_form1':

            data1 = request.form['input1']
            data2 = request.form['input2']

        if request.form['submit'] == 'submit_form2':

            data3 = request.form['input3']
            data4 = request.form['input4']

            # Here I want to grab values of form1 as well

</code>```

I tried a few things to grab form1 values in form2 but to no avail. Any help on how to approach this would be appreciated. Thanks!

Body:
I'm trying to grab values from form1 and form2 post submit respectively.
The only difference is that when i submit form2, I need form1 values as well.

Form 1

<form action="send_value1" method="POST">
      Input1: <input type="text" name="input1">
      Input2: <input type="text" name="input2">
      <input type="submit" name="submit" value="submit_form1">
</form>

Form 2

<form action="send_value2" method="POST">
      Input3: <input type="text" name="input3">
      Input4: <input type="text" name="input4">
      <input type="submit" name="submit" value="submit_form2">
</form>

In py file, I'm trying to fetch using POST method

@app.route("/page", methods=["GET", "POST"])
def to_do():

    if request.method == "POST":

        if request.form['submit'] == 'submit_form1':

            data1 = request.form['input1']
            data2 = request.form['input2']

        if request.form['submit'] == 'submit_form2':

            data3 = request.form['input3']
            data4 = request.form['input4']

            # Here I want to grab values of form1 as well

I tried a few things to grab form1 values in form2 but to no avail. Any help on how to approach this would be appreciated. Thanks!


问:
Flutter and Firebase Filter data
I'am kinda new in Flutter
I would like to know how can I get a snapshot of all messages in all groups where the user is a member of these group

in each users document there is groups array show list of joined group, it contains groupId_groupName

and in groups collections document there is members where it contains userId_userName

each group have messages collections

What is I need is to get the snapshot of all messages collections of a specific user.
I don't know if this is possible

Edited
the code that I made is:

```<code>getAllMessages() async {
    var query = db.collection("groups").where("members",
        arrayContains: 'fKceqEUAhSWGDuV2PxSX6dhxnfI2_Khaldun');
    var rs1 = await query.get();
    var myList = [];
    rs1.docs.forEach((element) {
      myList.add(element.data());
    });
    List myMessages = [];
    for (var element in myList) {
      await db
          .collection('groups')
          .doc(element['groupId'])
          .collection('messages')
          .orderBy("time", descending: true)
          .get()
          .then((value) {
        myMessages.add(value.docs);
      });
    }
    var flat = myMessages.expand((i) => i).toList();
    var realMessages = [];
    for (var i = 0; i < flat.length; i++) {
      realMessages.add(flat[i].data());
    }
    realMessages.sort(((a, b) => b['time'] - a['time']));
     return realMessages[0];
  }
</code>```

this code return a json and I would like to get a snapshot or transform this to Stream I don't know if this is a good practice I would like to know how I could do it other way

This is User Collection

This is Group Collection

Title: Flutter and Firebase Filter data

Body:
I'am kinda new in Flutter
I would like to know how can I get a snapshot of all messages in all groups where the user is a member of these group

in each users document there is groups array show list of joined group, it contains groupId_groupName

and in groups collections document there is members where it contains userId_userName

each group have messages collections

What is I need is to get the snapshot of all messages collections of a specific user.
I don't know if this is possible

Edited
the code that I made is:

getAllMessages() async {
    var query = db.collection("groups").where("members",
        arrayContains: 'fKceqEUAhSWGDuV2PxSX6dhxnfI2_Khaldun');
    var rs1 = await query.get();
    var myList = [];
    rs1.docs.forEach((element) {
      myList.add(element.data());
    });
    List myMessages = [];
    for (var element in myList) {
      await db
          .collection('groups')
          .doc(element['groupId'])
          .collection('messages')
          .orderBy("time", descending: true)
          .get()
          .then((value) {
        myMessages.add(value.docs);
      });
    }
    var flat = myMessages.expand((i) => i).toList();
    var realMessages = [];
    for (var i = 0; i < flat.length; i++) {
      realMessages.add(flat[i].data());
    }
    realMessages.sort(((a, b) => b['time'] - a['time']));
     return realMessages[0];
  }

this code return a json and I would like to get a snapshot or transform this to Stream I don't know if this is a good practice I would like to know how I could do it other way

This is User Collection

This is Group Collection


问:
Map in MapKit snaps back into original span every time firestore query returns
So I know why this happens, but I wanted some suggestions on how to fix this. I save the coordinates of a user's friends in firestore. Everytime a user's coordinates update, the Map View updates and returns the span and centre to the original one. Again, I know why this is happening, but wanted some suggestions to know how to go around this. I'm guessing that some state variable is need. However, that will also reset every time the view reloads.</p>
```<code> @StateObject private var viewModel: LocationViewModel = LocationViewModel()
@State private var addPoint: Bool = false

@EnvironmentObject var authViewModel: AuthViewModel
@EnvironmentObject var friendsViewModel: FriendsViewModel
var region: Binding<MKCoordinateRegion>? {
    guard let location = viewModel.location else {
        return MKCoordinateRegion.goldenGateRegion().getBinding()
    }
    let region = MKCoordinateRegion(center: location.coordinate,span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    return region.getBinding()
}

var points: [Marker] {

    var locations: [Marker] = []
    for friend in friendsViewModel.friends {

        if(friend.location?.latitude != nil && friend.location?.longitude != nil) {
            let coordinate = CLLocationCoordinate2D(latitude: friend.location!.latitude, longitude: friend.location!.longitude)
            let x = Marker(location: coordinate, friendName: friend.name)
            locations.append(x)
        }

    }

    return locations
}

var body: some View {
    ZStack {
        if let region = region {

            Map(coordinateRegion: region, interactionModes: .all, showsUserLocation: true, annotationItems: points) {point in
                MapAnnotation(coordinate: point.location) {
                    PlaceAnnotationView(title: point.friendName)
                }
            }
                .ignoresSafeArea()
                .tint(Color(.systemPink))

        }
</code>```

Body:
So I know why this happens, but I wanted some suggestions on how to fix this. I save the coordinates of a user's friends in firestore. Everytime a user's coordinates update, the Map View updates and returns the span and centre to the original one. Again, I know why this is happening, but wanted some suggestions to know how to go around this. I'm guessing that some state variable is need. However, that will also reset every time the view reloads.

 @StateObject private var viewModel: LocationViewModel = LocationViewModel()
@State private var addPoint: Bool = false

@EnvironmentObject var authViewModel: AuthViewModel
@EnvironmentObject var friendsViewModel: FriendsViewModel
var region: Binding<MKCoordinateRegion>? {
    guard let location = viewModel.location else {
        return MKCoordinateRegion.goldenGateRegion().getBinding()
    }
    let region = MKCoordinateRegion(center: location.coordinate,span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05))
    return region.getBinding()
}

var points: [Marker] {

    var locations: [Marker] = []
    for friend in friendsViewModel.friends {

        if(friend.location?.latitude != nil && friend.location?.longitude != nil) {
            let coordinate = CLLocationCoordinate2D(latitude: friend.location!.latitude, longitude: friend.location!.longitude)
            let x = Marker(location: coordinate, friendName: friend.name)
            locations.append(x)
        }

    }

    return locations
}

var body: some View {
    ZStack {
        if let region = region {

            Map(coordinateRegion: region, interactionModes: .all, showsUserLocation: true, annotationItems: points) {point in
                MapAnnotation(coordinate: point.location) {
                    PlaceAnnotationView(title: point.friendName)
                }
            }
                .ignoresSafeArea()
                .tint(Color(.systemPink))

        }