问:
Convert "15 Dec 2022" to 2022-12-15" using XSLT
I am trying to transform the following XML using XSLT

```<code><?xml version="1.0" encoding="UTF-8"?>
<root>
   <CandidateId>863</CandidateId>
   <CaseId>2762833</CaseId>
   <Status>Completed</Status>
   <InitiatedDate>01 Dec 2022</InitiatedDate>
   <CompletionDate>15 Jan 2022</CompletionDate>
   <Comments />
</root>
</code>```

My XSLT code is as follows:

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="node()">
      <xsl:apply-templates/>
  </xsl:template>

<xsl:template match="/">

<JobApplication>
<xsl:for-each select="root">
<JobApplication>

<xsl:variable name="month" select="substring(InitiatedDate,4,3)" />

<xsl:if test="$month = 'Dec'">
     <xsl:variable name="m">12</xsl:variable>
     </xsl:if>
<xsl:if test="$month = 'Nov'">
     <xsl:variable name="m">11</xsl:variable>
     </xsl:if>
<xsl:if test="$month = 'Oct'">
     <xsl:variable name="m">10</xsl:variable>
     </xsl:if>

<Bbgvdate><xsl:value-of select="concat(substring(InitiatedDate,8,4),'-',$m,'-',substring(InitiatedDate,1,2),'T00:00:00')"/></Bbgvdate>
<applicationId><xsl:value-of select="CandidateID"/></applicationId>

</JobApplication>
</xsl:for-each>
</JobApplication>

</xsl:template>

</xsl:stylesheet>

</code>```

Now, I am unable to call the variable "m" for some reason in "Bbgvdate"
I am looking for a converted date that looks like "2022-12-15" (in yyyy-mm-dd format)

I get the error:
Unable to generate the XML document using the provided XML/XSL input. Errors were reported during stylesheet compilation

Need help with this.

Thanks

Body:
I am trying to transform the following XML using XSLT

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <CandidateId>863</CandidateId>
   <CaseId>2762833</CaseId>
   <Status>Completed</Status>
   <InitiatedDate>01 Dec 2022</InitiatedDate>
   <CompletionDate>15 Jan 2022</CompletionDate>
   <Comments />
</root>

My XSLT code is as follows:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="node()">
      <xsl:apply-templates/>
  </xsl:template>

<xsl:template match="/">

<JobApplication>
<xsl:for-each select="root">
<JobApplication>

<xsl:variable name="month" select="substring(InitiatedDate,4,3)" />

<xsl:if test="$month = 'Dec'">
     <xsl:variable name="m">12</xsl:variable>
     </xsl:if>
<xsl:if test="$month = 'Nov'">
     <xsl:variable name="m">11</xsl:variable>
     </xsl:if>
<xsl:if test="$month = 'Oct'">
     <xsl:variable name="m">10</xsl:variable>
     </xsl:if>

<Bbgvdate><xsl:value-of select="concat(substring(InitiatedDate,8,4),'-',$m,'-',substring(InitiatedDate,1,2),'T00:00:00')"/></Bbgvdate>
<applicationId><xsl:value-of select="CandidateID"/></applicationId>

</JobApplication>
</xsl:for-each>
</JobApplication>

</xsl:template>

</xsl:stylesheet>

Now, I am unable to call the variable "m" for some reason in "Bbgvdate"
I am looking for a converted date that looks like "2022-12-15" (in yyyy-mm-dd format)

I get the error:
Unable to generate the XML document using the provided XML/XSL input. Errors were reported during stylesheet compilation

Need help with this.

Thanks


来源: stackexchange

问:
The search feature in the drop-down lists does not work (add option 2)
I am trying to activate the search feature in the dynamically generated drop-down lists by using select 2 plugin, but unfortunately the plugin does not work at all.

Any solution would be appreciated.

This is the source code for all the page this plugin is on which I can't get it to work

      الحساب
      مدين
      دائن
      وصف

        <select
          class="form-control select_acount js-example-basic-single"
          name="account[]"
          required
        >
          <option value="1">--1--</option>
          <option value="2">--2--</option>
          <option value="3">--3--</option>
          <option value="4">--4--</option>
          <option value="5">--5--</option>
          <option value="6">--6--</option>
        </select>

        <input
          type="number"
          name="debtor[]"
          id="fname"
          class="form-control debtor arabicNumbers"
          onkeydown="return event.keyCode !== 69"
          required
        />

        <input
          type="number"
          name="creditor[]"
          id="james"
          class="form-control creditor arabicNumbers"
          onkeydown="return event.keyCode !== 69"
          required
        />

        <input type="text" name="description[]" class="form-control" required />

        <input type="text" name="mount[]" class="form-control mount" required />

        <button type="button" name="add" id="add-btn" class="btn btn-success">

        </button>

```
<p>jquery code:</p>
<pre class="lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script></script>
<script>
  $(document).ready(function() {
    $('.js-example-basic-single').select2();
});
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to activate the search feature in the dynamically generated drop-down lists by using select 2 plugin, but unfortunately the plugin does not work at all.

Any solution would be appreciated.

This is the source code for all the page this plugin is on which I can't get it to work

      الحساب
      مدين
      دائن
      وصف

        <select
          class="form-control select_acount js-example-basic-single"
          name="account[]"
          required
        >
          <option value="1">--1--</option>
          <option value="2">--2--</option>
          <option value="3">--3--</option>
          <option value="4">--4--</option>
          <option value="5">--5--</option>
          <option value="6">--6--</option>
        </select>

        <input
          type="number"
          name="debtor[]"
          id="fname"
          class="form-control debtor arabicNumbers"
          onkeydown="return event.keyCode !== 69"
          required
        />

        <input
          type="number"
          name="creditor[]"
          id="james"
          class="form-control creditor arabicNumbers"
          onkeydown="return event.keyCode !== 69"
          required
        />

        <input type="text" name="description[]" class="form-control" required />

        <input type="text" name="mount[]" class="form-control mount" required />

        <button type="button" name="add" id="add-btn" class="btn btn-success">

        </button>

jquery code:

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


问:
Close quickinfo Template programatically in synfusion
I am using https://www.syncfusion.com/ to create popup quick info template in the calendar view.I have referred to this forum https://www.syncfusion.com/forums/157722/close-quickinfo-template-programatically but not suitable for me because I am using React. May I know how to close the quick info template programmatically in react? Below is my existing coding:

 const handleCloseQuickInfoTemplate = e => {
    this.CloseQuickInfoPopup(); // To programmatically close the quick popup
  };

  const headerTemplate = props => {
    console.log('headerTemplate', props);
    return (

          <button
            class="e-edit e-control e-btn e-lib e-flat e-round e-small e-icon-btn"
            title="Edit"
          >

          </button>
          <button
            class="e-delete e-control e-btn e-lib e-flat e-round e-small e-icon-btn"
            title="Delete"
            onClick={() => setOpenDeletePopup(true)}
          >

          </button>
          <button
            class="e-close e-control e-btn e-lib e-flat e-round e-small e-icon-btn"
            title="Close"
            onClick={handleCloseQuickInfoTemplate}
          >

          </button>

            {props.Subject}

    );
  };

  const contentTemplate = props => {
    let startDateConvert = moment(props.StartTime.toString()).format(
      'MMMM DD, YYYY'
    );
    let startTimeConvert = moment(props.StartTime.toString()).format('h:mm A');
    let endTimeConvert = moment(props.EndTime.toString()).format('h:mm A');

    return (

              {startDateConvert} ({startTimeConvert} -
              {endTimeConvert})

{props.Location}

            {props.DoctorList}

{props.Type}

            {props.Status}

    );
  };

  <ScheduleComponent
            cssClass="virtual-scrolling schedule-header-bar"
            width="100%"
            height="100%"
            resizeStop={rescheduleDrag.bind()}
            dragStop={rescheduleDrag.bind()}
            locale={checkLocal()}
            currentView={schedularView}
            eventSettings={{
              dataSource: list.concat(organizerList),
              eventTemplate: eventTemplate.bind(),
            }}
            quickInfoTemplates={{
              header: headerTemplate.bind(),
              content: contentTemplate.bind(),
            }}
            renderCell={onCellRender.bind()}
            eventRendered={onEventRendered.bind()}
            ref={schedular_element}
            actionComplete={onActionComplete.bind()}
            headerIndentTemplate={headerIndentTemplate.bind()}
            rowAutoHeight={true}
            timeScale={{
              enable: true,
              interval: 60,
              slotCount: 60 / timeInterval,
              majorSlotTemplate: majorSlotTemplate.bind(),
              minorSlotTemplate: minorSlotTemplate.bind(),
            }}
            popupOpen={popUpHandler.bind()}
            group={{ byDate: true, resources: ['Doctors'] }}
            selectedDate={startDate}
          >
            <ResourcesDirective>
              <ResourceDirective
                field="Doctor"
                name="Doctors"
                dataSource={
                  selectedDoctorList.length > 0
                    ? filteredDoctorListSchedulerOrDefault()
                    : doctorListScheduler
                }
                textField={'resource'}
                idField={'resource'}
                allowMultiple={true}
              ></ResourceDirective>
            </ResourcesDirective>

            <Inject
              services={[
                Day,
                Week,
                WorkWeek,
                Month,
                TimelineMonth,
                Year,
                Resize,
                DragAndDrop,
              ]}
            />
            <ViewsDirective>
              <ViewDirective
                option="Day"
                endHour="24:00"
                startHour="08:00"
                interval={dateInterval}
                eventTemplate={eventTemplate.bind()}
              />
              <ViewDirective option="Week" startHour="08:00" endHour="24:00" />
              <ViewDirective
                option="WorkWeek"
                startHour="08:00"
                endHour="24:00"
              />
              <ViewDirective option="Month" />
              <ViewDirective option="TimelineMonth" />
              <ViewDirective option="Year" />
            </ViewsDirective>
          </ScheduleComponent>
```

Below the picture X button doesn't work:

Body:
I am using https://www.syncfusion.com/ to create popup quick info template in the calendar view.I have referred to this forum https://www.syncfusion.com/forums/157722/close-quickinfo-template-programatically but not suitable for me because I am using React. May I know how to close the quick info template programmatically in react? Below is my existing coding:

 const handleCloseQuickInfoTemplate = e => {
    this.CloseQuickInfoPopup(); // To programmatically close the quick popup
  };

  const headerTemplate = props => {
    console.log('headerTemplate', props);
    return (

          <button
            class="e-edit e-control e-btn e-lib e-flat e-round e-small e-icon-btn"
            title="Edit"
          >

          </button>
          <button
            class="e-delete e-control e-btn e-lib e-flat e-round e-small e-icon-btn"
            title="Delete"
            onClick={() => setOpenDeletePopup(true)}
          >

          </button>
          <button
            class="e-close e-control e-btn e-lib e-flat e-round e-small e-icon-btn"
            title="Close"
            onClick={handleCloseQuickInfoTemplate}
          >

          </button>

            {props.Subject}

    );
  };

  const contentTemplate = props => {
    let startDateConvert = moment(props.StartTime.toString()).format(
      'MMMM DD, YYYY'
    );
    let startTimeConvert = moment(props.StartTime.toString()).format('h:mm A');
    let endTimeConvert = moment(props.EndTime.toString()).format('h:mm A');

    return (

              {startDateConvert} ({startTimeConvert} -
              {endTimeConvert})

{props.Location}

            {props.DoctorList}

{props.Type}

            {props.Status}

    );
  };

  <ScheduleComponent
            cssClass="virtual-scrolling schedule-header-bar"
            width="100%"
            height="100%"
            resizeStop={rescheduleDrag.bind()}
            dragStop={rescheduleDrag.bind()}
            locale={checkLocal()}
            currentView={schedularView}
            eventSettings={{
              dataSource: list.concat(organizerList),
              eventTemplate: eventTemplate.bind(),
            }}
            quickInfoTemplates={{
              header: headerTemplate.bind(),
              content: contentTemplate.bind(),
            }}
            renderCell={onCellRender.bind()}
            eventRendered={onEventRendered.bind()}
            ref={schedular_element}
            actionComplete={onActionComplete.bind()}
            headerIndentTemplate={headerIndentTemplate.bind()}
            rowAutoHeight={true}
            timeScale={{
              enable: true,
              interval: 60,
              slotCount: 60 / timeInterval,
              majorSlotTemplate: majorSlotTemplate.bind(),
              minorSlotTemplate: minorSlotTemplate.bind(),
            }}
            popupOpen={popUpHandler.bind()}
            group={{ byDate: true, resources: ['Doctors'] }}
            selectedDate={startDate}
          >
            <ResourcesDirective>
              <ResourceDirective
                field="Doctor"
                name="Doctors"
                dataSource={
                  selectedDoctorList.length > 0
                    ? filteredDoctorListSchedulerOrDefault()
                    : doctorListScheduler
                }
                textField={'resource'}
                idField={'resource'}
                allowMultiple={true}
              ></ResourceDirective>
            </ResourcesDirective>

            <Inject
              services={[
                Day,
                Week,
                WorkWeek,
                Month,
                TimelineMonth,
                Year,
                Resize,
                DragAndDrop,
              ]}
            />
            <ViewsDirective>
              <ViewDirective
                option="Day"
                endHour="24:00"
                startHour="08:00"
                interval={dateInterval}
                eventTemplate={eventTemplate.bind()}
              />
              <ViewDirective option="Week" startHour="08:00" endHour="24:00" />
              <ViewDirective
                option="WorkWeek"
                startHour="08:00"
                endHour="24:00"
              />
              <ViewDirective option="Month" />
              <ViewDirective option="TimelineMonth" />
              <ViewDirective option="Year" />
            </ViewsDirective>
          </ScheduleComponent>

Below the picture X button doesn't work:


问:
CSS: How to have several fixed background videos on same page
Ever since the property "background-attachment: fixed" has been introduced, we've been able to put several fixed backgrounds at different places of the same page, which gives really cool effects.

However, as far as I know, video backgrounds don't have this wonderful property, and instead rely on the old school "position: fixed" in order to be fixed relative to the screen. But I can't have two full-screen "position: fixed" elements on the same page, can I? Whoever's z-index is higher, will be the only one visible.

Is there any way to overcome this? (Maybe jquery solution, if CSS doesn't allow it?)

Here is my HTML:

```<code><video autoplay muted loop id="video_1">
  <source src="video-1.mp4" type="video/mp4">
</video>

<div class="textbox">
  Here's some content
</div>

<video autoplay muted loop id="video_2">
  <source src="video-2.mp4" type="video/mp4">
</video>
</code>```

and the CSS:

```<code>video {
  position: fixed;
  right: 0;
  top: 0;
  min-width: 100%;
  min-height: 100%;
}
</code>```

Thank you so much.

Body:
Ever since the property "background-attachment: fixed" has been introduced, we've been able to put several fixed backgrounds at different places of the same page, which gives really cool effects.

However, as far as I know, video backgrounds don't have this wonderful property, and instead rely on the old school "position: fixed" in order to be fixed relative to the screen. But I can't have two full-screen "position: fixed" elements on the same page, can I? Whoever's z-index is higher, will be the only one visible.

Is there any way to overcome this? (Maybe jquery solution, if CSS doesn't allow it?)

Here is my HTML:

<video autoplay muted loop id="video_1">
  <source src="video-1.mp4" type="video/mp4">
</video>

  Here's some content

<video autoplay muted loop id="video_2">
  <source src="video-2.mp4" type="video/mp4">
</video>

and the CSS:

video {
  position: fixed;
  right: 0;
  top: 0;
  min-width: 100%;
  min-height: 100%;
}

Thank you so much.


问:
How to apply new config files in .elasticbeanstalk folder to my Elastic Beanstalk Environment
I have a Symfony App with an Elastic Beanstalk environment.
Composer is outdated on the EC2 Instance and I need to update it.

I followed the steps in this doc article: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-configuration-composerupdate.html

I tried to apply the config composer.config with the eb deploy command.

The composer.config is ignored as I can see in the logs.

I am wondering if eb deploy is the correct command to update my EBS environment with the config in my .elasticbeanstalk folder.


问:
Identity Db communicating with Entity Database
I have two databases, the first database is the identity database which I use to register and share user tokens.
My second database is DateDatabase which is a regular database with DbContext. These two databases are in different projects, in the project with DateDatabase there is a reference to the project where the identity database is located. I have some questions related to this configuration

let's say the identity database contains all the data needed to log in, e.g. e-mail, password, etc., and the DateDatabase contains the basic user data, such as the user's first name, last name, profile picture, and so on.

where to create database models?
(in project 1 which has a reference to the IdentityDatabase or where is the Identity database?)

how to properly add data to two databases, for example in the Identity database Email, username, password. And in DateDatabase name, surname ...

(I use swagger for this, so after clicking the execute button, I would like these operations to be performed, unless someone has a better way to proceed)

How to get specific users for example let's say I want to get users named Tom from Identity database

UserModel (DateDatabase)

```<code>public class UserModel
    {
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? PhotoUrl { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
    }
</code>```

UserIdentityModel (identity database )
standard identitytables

Body:
I have two databases, the first database is the identity database which I use to register and share user tokens.
My second database is DateDatabase which is a regular database with DbContext. These two databases are in different projects, in the project with DateDatabase there is a reference to the project where the identity database is located. I have some questions related to this configuration

let's say the identity database contains all the data needed to log in, e.g. e-mail, password, etc., and the DateDatabase contains the basic user data, such as the user's first name, last name, profile picture, and so on.

where to create database models?
(in project 1 which has a reference to the IdentityDatabase or where is the Identity database?)

how to properly add data to two databases, for example in the Identity database Email, username, password. And in DateDatabase name, surname ...

(I use swagger for this, so after clicking the execute button, I would like these operations to be performed, unless someone has a better way to proceed)

How to get specific users for example let's say I want to get users named Tom from Identity database

UserModel (DateDatabase)

public class UserModel
    {
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? PhotoUrl { get; set; }
        public DateTime CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
    }

UserIdentityModel (identity database )
standard identitytables


问:
How container name atribution works in docker
I'm new docker learner, and could someone explain to me why whenever we start a new container it's give to us random names (and where they come from, it's the last column), as shown in the image bellow


问:
a class to store value
I want to store data by using class but it so I write a .h and .C file :

```<code>#ifndef MY_lepton_collection
#define MY_lepton_collection

#include<iostream>
#include<vector>

using namespace std;

class data_collection {

public:
  data_collection(float, float, float,float );
  ~data_collection();
  float pt;
  float eta;
  float phi;
  float en;

private:

};

#endif

</code>```
```<code>#include "data_collection.h"

Lepton_collection::Lepton_collection(float pt1, float eta1, float phi1, float energy1){pt= pt1;eta = eta1;phi = phi1;en=energy1;

}data_collection::~data_collection(){}

 and use it in the main code as:

std::vector<data_collection*>*Selecteddata;

       for(int i=0; i<100; i++){

             Selecteddata->push_back( new data_collection(Pt[i],Eta[i] ,Phi[i], Energy[i]));
                 }

</code>```

but when I get cout of it, there is an error:

invalid memory pointer passed to a callee: cout\<\<(\*Selecteddata)-\>pt;

I don't know what part of it is wrong.

Title: a class to store value

Body:
I want to store data by using class but it so I write a .h and .C file :

#ifndef MY_lepton_collection
#define MY_lepton_collection

#include<iostream>
#include<vector>

using namespace std;

class data_collection {

public:
  data_collection(float, float, float,float );
  ~data_collection();
  float pt;
  float eta;
  float phi;
  float en;

private:

};

#endif

#include "data_collection.h"

Lepton_collection::Lepton_collection(float pt1, float eta1, float phi1, float energy1){pt= pt1;eta = eta1;phi = phi1;en=energy1;

}data_collection::~data_collection(){}

 and use it in the main code as:

std::vector<data_collection*>*Selecteddata;

       for(int i=0; i<100; i++){

             Selecteddata->push_back( new data_collection(Pt[i],Eta[i] ,Phi[i], Energy[i]));
                 }

but when I get cout of it, there is an error:

invalid memory pointer passed to a callee: cout\<\<(\*Selecteddata)-\>pt;

I don't know what part of it is wrong.


问:
Why does Binding with RelativeSource doesn't work from code-behind in design-time?
I am trying to make short version of my binding markup by creating class inherited from Binding and setting all properties in constructor. This is simplified version of how original markup looks like (works as intended):

```<code><Setter Property="Text" Value="{Binding Title, RelativeSource={RelativeSource AncestorType=Window}}"/>
</code>```

I have tried making this expression shorter by creating this class:

```<code>public class TitleExtension : Binding
{
    public TitleExtension()
    {
        Path = new PropertyPath("Title");
        RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Window), 1);
    }
}
</code>```

And using it like this:

```<code><Setter Property="Text" Value="{p:Title}"/>
</code>```

This works in runtime but doesn't in design-time.
But if I add RelativeSource markup to my expression, then it works fine in design-time and runtime. Like this:

```<code><Setter Property="Text" Value="{p:Title, RelativeSource={RelativeSource AncestorType=Window}}"/>
</code>```

I will be glad to hear all your explanations of this behavior, as well as the proposed solutions. Thanks!

Body:
I am trying to make short version of my binding markup by creating class inherited from Binding and setting all properties in constructor. This is simplified version of how original markup looks like (works as intended):

<Setter Property="Text" Value="{Binding Title, RelativeSource={RelativeSource AncestorType=Window}}"/>

I have tried making this expression shorter by creating this class:

public class TitleExtension : Binding
{
    public TitleExtension()
    {
        Path = new PropertyPath("Title");
        RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Window), 1);
    }
}

And using it like this:

<Setter Property="Text" Value="{p:Title}"/>

This works in runtime but doesn't in design-time.
But if I add RelativeSource markup to my expression, then it works fine in design-time and runtime. Like this:

<Setter Property="Text" Value="{p:Title, RelativeSource={RelativeSource AncestorType=Window}}"/>

I will be glad to hear all your explanations of this behavior, as well as the proposed solutions. Thanks!


问:
WSIF Service Failure
When running my application I am getting WSIFException

WSIFMessage outputMessage = execute(
        "listar",
        "listarRequest",
        "listarResponse",
        inputMessage,
        REQUEST_RESPONSE
);
```
```org.apache.wsif.WSIFException: Port 'MenuJCACICSECIPort' is not available and no alternative can be found at org.apache.wsif.base.WSIFServiceImpl.getPort(WSIFServiceImpl.java:599) at
```

I tried to configure the server

Title: WSIF Service Failure

Body:
When running my application I am getting WSIFException

WSIFMessage outputMessage = execute(
        "listar",
        "listarRequest",
        "listarResponse",
        inputMessage,
        REQUEST_RESPONSE
);

org.apache.wsif.WSIFException: Port 'MenuJCACICSECIPort' is not available and no alternative can be found at org.apache.wsif.base.WSIFServiceImpl.getPort(WSIFServiceImpl.java:599) at

I tried to configure the server


问:
How to use highlight.js in a VueJS app with mixed content
I'm currently using highlight.js to hightlight the code in the HTML content being received from my backend. An example of something I might receive from the backend is:

 Check this example of Javascript

```
    <code class="language-javascript">let x = 0;
function hello() {}
    </code>
```
```
<p>As you can see it is a mixed content of HTML and code examples wrapped in <code>pre -> code</code> tags.</p>
<p>I have a component to render WYSIWYG content returned from the backend. In this component, I use <code>highlight.js</code> to highlight the code blocks.</p>
<pre class="lang-js prettyprint-override"><code>import { defineComponent, h, nextTick, onMounted, ref, watch } from 'vue';
// No need to use a third-party component to highlight code
// since the `@tiptap/extension-code-block-lowlight` library has highlight as a dependency
import highlight from 'highlight.js'
import { QNoSsr } from 'quasar';

export const WYSIWYG = defineComponent({
  name: 'WYSIWYG',
  props: {
    content: { type: String, required: true },
  },
  setup(props) {
    const root = ref<HTMLElement>(null);

    const hightlightCodes = async () => {
      if (process.env.CLIENT) {
        await nextTick();

        root.value?.querySelectorAll('pre code').forEach((el: HTMLElement) => {
          highlight.highlightElement(el as HTMLElement);
        });
      }
    }

    onMounted(hightlightCodes);
    watch(() => props.content, hightlightCodes);

    return function render() {
      return h(QNoSsr, {
        placeholder: 'Loading...',
      }, () => h('div', {
        class: 'WYSIWYG',
        ref: root,
        innerHTML: props.content
      }));
    };
  },
});

</code>```

Whenever I visit the page by clicking on a link the page works just fine, but when I hard refresh the page I get the following error:

```<code>`line` must be greater than 0 (lines start at line 1)
</code>```

Currently, I'm not sure precisely why this happens, and tried a couple of different approaches

Aproach 1: try to build the whole content and then replace

const computedHtml = computed(() => {
  if (import.meta.env.SSR) return '';

  console.log(props.content);

  const { value } = highlight.highlightAuto(props.content);

  console.log(value);

  return '';
})

```
<p>With this approach, I get the same error as before</p>
````line` must be greater than 0 (lines start at line 1)
```

I have checked out this error in https://github.com/withastro/astro/issues/3447 and https://github.com/vitejs/vite/issues/11037 but it looks like that this error is more related to Vite than my application - please, correct me if I'm wrong here.

Is there a way for me to highlight the code in the backend that is being returned from the backend in Vue?

Body:
I'm currently using highlight.js to hightlight the code in the HTML content being received from my backend. An example of something I might receive from the backend is:

 Check this example of Javascript

    let x = 0;
function hello() {}

As you can see it is a mixed content of HTML and code examples wrapped in pre -> code tags.

I have a component to render WYSIWYG content returned from the backend. In this component, I use highlight.js to highlight the code blocks.

import { defineComponent, h, nextTick, onMounted, ref, watch } from 'vue';
// No need to use a third-party component to highlight code
// since the `@tiptap/extension-code-block-lowlight` library has highlight as a dependency
import highlight from 'highlight.js'
import { QNoSsr } from 'quasar';

export const WYSIWYG = defineComponent({
  name: 'WYSIWYG',
  props: {
    content: { type: String, required: true },
  },
  setup(props) {
    const root = ref<HTMLElement>(null);

    const hightlightCodes = async () => {
      if (process.env.CLIENT) {
        await nextTick();

        root.value?.querySelectorAll('pre code').forEach((el: HTMLElement) => {
          highlight.highlightElement(el as HTMLElement);
        });
      }
    }

    onMounted(hightlightCodes);
    watch(() => props.content, hightlightCodes);

    return function render() {
      return h(QNoSsr, {
        placeholder: 'Loading...',
      }, () => h('div', {
        class: 'WYSIWYG',
        ref: root,
        innerHTML: props.content
      }));
    };
  },
});

Whenever I visit the page by clicking on a link the page works just fine, but when I hard refresh the page I get the following error:

`line` must be greater than 0 (lines start at line 1)

Currently, I'm not sure precisely why this happens, and tried a couple of different approaches

Aproach 1: try to build the whole content and then replace

const computedHtml = computed(() => {
  if (import.meta.env.SSR) return '';

  console.log(props.content);

  const { value } = highlight.highlightAuto(props.content);

  console.log(value);

  return '';
})

With this approach, I get the same error as before

`line` must be greater than 0 (lines start at line 1)

I have checked out this error in https://github.com/withastro/astro/issues/3447 and https://github.com/vitejs/vite/issues/11037 but it looks like that this error is more related to Vite than my application - please, correct me if I'm wrong here.

Is there a way for me to highlight the code in the backend that is being returned from the backend in Vue?


Title: Getting SignatureDoesNotMatch 403 response when running a GET request in ASW S3 using chilkat

Body:
Getting this error when try to run a GET request on AWS s3. Detailed logs are attached below. Please help

26-Dec-2022 12:26:00 send error: List multipart uploads for key recovery/RÃ©cupÃ©ration_VOL-b001.spf
Unexpected response status code: 403

Error response:

Code: SignatureDoesNotMatch
Message: The request signature we calculated does not match the signature you provided. Check your key and signing method.
AWSAccessKeyId: AKIA4OGRTV42ZXNBHH47
StringToSign: AWS4-HMAC-SHA256
20221226T065419Z
20221226/us-east-2/s3/aws4_request
34482fccab5255ab299ba1a1afe1429ab3b00d25920506f2b26eed3e695d0aaa
SignatureProvided: be3902f4cc91f6263ee88b6c2e90de2ad75858655aa6cb5205fb1950b149677f
StringToSignBytes: 41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 32 32 31 32 32 36 54 30 36 35 34 31 39 5a 0a 32 30 32 32 31 32 32 36 2f 75 73 2d 65 61 73 74 2d 32 2f 73 33 2f 61 77 73 34 5f 72 65 71 75 65 73 74 0a 33 34 34 38 32 66 63 63 61 62 35 32 35 35 61 62 32 39 39 62 61 31 61 31 61 66 65 31 34 32 39 61 62 33 62 30 30 64 32 35 39 32 30 35 30 36 66 32 62 32 36 65 65 64 33 65 36 39 35 64 30 61 61 61
CanonicalRequest: GET
/
prefix=recovery%2FR%C3%83%C2%A9cup%C3%83%C2%A9ration_VOL-b001.spf&uploads=
host:recoverybucket333.s3.us-east-2.amazonaws.com
x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-amz-date:20221226T065419Z

host;x-amz-content-sha256;x-amz-date
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
CanonicalRequestBytes: 47 45 54 0a 2f 0a 70 72 65 66 69 78 3d 72 65 63 6f 76 65 72 79 25 32 46 52 25 43 33 25 38 33 25 43 32 25 41 39 63 75 70 25 43 33 25 38 33 25 43 32 25 41 39 72 61 74 69 6f 6e 5f 56 4f 4c 2d 62 30 30 31 2e 73 70 66 26 75 70 6c 6f 61 64 73 3d 0a 68 6f 73 74 3a 72 65 63 6f 76 65 72 79 62 75 63 6b 65 74 33 33 33 2e 73 33 2e 75 73 2d 65 61 73 74 2d 32 2e 61 6d 61 7a 6f 6e 61 77 73 2e 63 6f 6d 0a 78 2d 61 6d 7a 2d 63 6f 6e 74 65 6e 74 2d 73 68 61 32 35 36 3a 65 33 62 30 63 34 34 32 39 38 66 63 31 63 31 34 39 61 66 62 66 34 63 38 39 39 36 66 62 39 32 34 32 37 61 65 34 31 65 34 36 34 39 62 39 33 34 63 61 34 39 35 39 39 31 62 37 38 35 32 62 38 35 35 0a 78 2d 61 6d 7a 2d 64 61 74 65 3a 32 30 32 32 31 32 32 36 54 30 36 35 34 31 39 5a 0a 0a 68 6f 73 74 3b 78 2d 61 6d 7a 2d 63 6f 6e 74 65 6e 74 2d 73 68 61 32 35 36 3b 78 2d 61 6d 7a 2d 64 61 74 65 0a 65 33 62 30 63 34 34 32 39 38 66 63 31 63 31 34 39 61 66 62 66 34 63 38 39 39 36 66 62 39 32 34 32 37 61 65 34 31 65 34 36 34 39 62 39 33 34 63 61 34 39 35 39 39 31 62 37 38 35 32 62 38 35 35
RequestId: 1SKCZB7ZCJJK4RMC
HostId: qQ/ElU917KLt7vm15qnfCvAZhb8NqL0GXyHt/dCcd6LOL76OhEz7C9bQ5i2zR2B0LO8xpHSvPYc+oe68V/usCA==

26-Dec-2022 12:26:00 Sending RÃ©cupÃ©ration_VOL-b001.spf
26-Dec-2022 12:26:19 send error: List multipart uploads for key recovery/RÃ©cupÃ©ration_VOL-b001.spf
Unexpected response status code: 403

I am trying to upload some files on S3 bucket and it is working for normal file names but not working when the file name contains some ASCII chars or accent marks. It failed with the above error shown in the description.


问:
No 'Access-Control-Allow-Origin' header is present on the requested resource
Hw do i Send Response from a setTimout without having cors throw this error

"Access to XMLHttpRequest at 'https://api.cotton.com/v1/proposed/hash' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource".

Am calling a function inside setTimout and the function is returning a Response, but cors is blocking the response from getting into the header in reactJs. and the setTimeout is called every 10s

Please Can anyone help me with a way i can send res inside setTimeout and it will not be affected by Cors error


问:
How to accommodate image shape according to image view?
I have an ImageView with rounded corners, but when I add the bitmap to it, the image doesn't have rounded corners

I have a module where I capture images, I want these images to always take the shape of the ImageView, in this case, the rounded corners, as seen in the image below.

XML (this is the card)

`

```<code><LinearLayout
    android:layout_width="185dp"
    android:layout_height="185dp"
    android:background="@drawable/bg_rounded_corners"
    android:orientation="vertical">

        <ImageView
            android:id="@+id/im_producto"
            android:layout_weight=".8"
            android:layout_height="0dp"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:scaleType="fitXY"
            android:background="@drawable/bg_rounded_corners_top"
            android:orientation="horizontal"/>

        <Button
            android:id="@+id/btn_eliminar_fotografía"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".2"
            android:text="Eliminar"
            android:background="@drawable/bg_rounded_corners_bottom"
            android:backgroundTint="@color/purple_two"
            android:textSize="17sp"
            android:textStyle="bold"/>

</LinearLayout>
</code>```

`

JAVA
in the java part, I just use the set bitmap method and add the bitmap of the image

Body:
I have an ImageView with rounded corners, but when I add the bitmap to it, the image doesn't have rounded corners

I have a module where I capture images, I want these images to always take the shape of the ImageView, in this case, the rounded corners, as seen in the image below.

XML (this is the card)

`

<LinearLayout
    android:layout_width="185dp"
    android:layout_height="185dp"
    android:background="@drawable/bg_rounded_corners"
    android:orientation="vertical">

        <ImageView
            android:id="@+id/im_producto"
            android:layout_weight=".8"
            android:layout_height="0dp"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:scaleType="fitXY"
            android:background="@drawable/bg_rounded_corners_top"
            android:orientation="horizontal"/>

        <Button
            android:id="@+id/btn_eliminar_fotografía"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".2"
            android:text="Eliminar"
            android:background="@drawable/bg_rounded_corners_bottom"
            android:backgroundTint="@color/purple_two"
            android:textSize="17sp"
            android:textStyle="bold"/>

</LinearLayout>

`

JAVA
in the java part, I just use the set bitmap method and add the bitmap of the image


问:
App built with capacitor, Deeplink opens in browser rather than opening the app in Android 12 device
I am trying to use deep linking in my app, which is built using Capacitor and runs on Android 12 devices. The deep linking works fine in a native Android app, but it is not working in the Capacitor build. I have used the same intent filters in both the Capacitor project and the native Android project, but the deep linking still doesn't work in the Capacitor build.

Intent filter used added in the AndroidManifest.xml

```<code><intent-filter android:autoVerify="true">
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data android:scheme="https" android:host="www.mysite.com" />
</intent-filter>
</code>```

Same intent used for native sample and capacitor sample app. It worked fine with native one. Opened in browser for app build with capacitor. Issue is occuring only in Android 12 + devices only.

Does anyone have any ideas or suggestions for what might be causing the deep linking to fail in the Capacitor build, but not in the native Android app? Any help would be greatly appreciated.

Body:
I am trying to use deep linking in my app, which is built using Capacitor and runs on Android 12 devices. The deep linking works fine in a native Android app, but it is not working in the Capacitor build. I have used the same intent filters in both the Capacitor project and the native Android project, but the deep linking still doesn't work in the Capacitor build.

Intent filter used added in the AndroidManifest.xml

<intent-filter android:autoVerify="true">
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <category android:name="android.intent.category.BROWSABLE" />
     <data android:scheme="https" android:host="www.mysite.com" />
</intent-filter>

Same intent used for native sample and capacitor sample app. It worked fine with native one. Opened in browser for app build with capacitor. Issue is occuring only in Android 12 + devices only.

Does anyone have any ideas or suggestions for what might be causing the deep linking to fail in the Capacitor build, but not in the native Android app? Any help would be greatly appreciated.


问:
Want to mute audio of local participant in Jitsi Android SDK
Is there any feature to disable local audio output in Android SDK ?

Tried to set streamVolume() to 0 of Android AudioManager. But it did not help.


问:
Artillery + Playwright, StatsD data not being ingested in InfluxDB correctly by Telegraf (Template not working)
I have some tests written using Artillery + Playwright and I am using the publish-metrics plugin with type influxdb-statsd.  I then have the following telegraf.config

```<code>[[outputs.influxdb_v2]]
  urls = ["http://${INFLUX_DB2_HOST_ADDRESS}:8086"]
  token = "${INFLUX_DB2_TOKEN}"
  organization = "${INFLUX_DB2_ORGANIZATION}"
  bucket = "${INFLUX_DB2_BUCKET}"

[[inputs.statsd]]
  protocol = "udp"
  max_tcp_connections = 250
  tcp_keep_alive = false
  service_address = ":8125"
  delete_gauges = true
  delete_counters = true
  delete_sets = true
  delete_timings = true
  metric_separator = "_"
  parse_data_dog_tags = true
  datadog_extensions = true
  datadog_distributions = false
</code>```

Data from artillery is sent in this format to statsD

```<code>artillery.browser.page.FID.compliance-hub_dashboard.min:3.2|g
artillery.browser.page.FID.compliance-hub_dashboard.max:3.2|g
artillery.browser.page.FID.compliance-hub_dashboard.count:2|g
artillery.browser.page.FID.compliance-hub_dashboard.p50:3.2|g
</code>```

I would like to set up a telegraf template so that in Influx DB
artillery.browser.page.FID.compliance-hub_dashboard is a measurement and min, max, count and p50 are fields.

How do I do that?

I tried:

```<code> templates = [
     "measurement.measurement.measurement.measurement.measurement.field",
 ]
</code>```

but it's not working. :(

What I see in InfluxDb is a measurement of artillery_browser_page_FID_compliance-hub_dashboard_min with a field of value = 3.2

Body:
I have some tests written using Artillery + Playwright and I am using the publish-metrics plugin with type influxdb-statsd.  I then have the following telegraf.config

[[outputs.influxdb_v2]]
  urls = ["http://${INFLUX_DB2_HOST_ADDRESS}:8086"]
  token = "${INFLUX_DB2_TOKEN}"
  organization = "${INFLUX_DB2_ORGANIZATION}"
  bucket = "${INFLUX_DB2_BUCKET}"

[[inputs.statsd]]
  protocol = "udp"
  max_tcp_connections = 250
  tcp_keep_alive = false
  service_address = ":8125"
  delete_gauges = true
  delete_counters = true
  delete_sets = true
  delete_timings = true
  metric_separator = "_"
  parse_data_dog_tags = true
  datadog_extensions = true
  datadog_distributions = false

Data from artillery is sent in this format to statsD

artillery.browser.page.FID.compliance-hub_dashboard.min:3.2|g
artillery.browser.page.FID.compliance-hub_dashboard.max:3.2|g
artillery.browser.page.FID.compliance-hub_dashboard.count:2|g
artillery.browser.page.FID.compliance-hub_dashboard.p50:3.2|g

I would like to set up a telegraf template so that in Influx DB
artillery.browser.page.FID.compliance-hub_dashboard is a measurement and min, max, count and p50 are fields.

How do I do that?

I tried:

 templates = [
     "measurement.measurement.measurement.measurement.measurement.field",
 ]

but it's not working. :(

What I see in InfluxDb is a measurement of artillery_browser_page_FID_compliance-hub_dashboard_min with a field of value = 3.2


问:
Why do my links on the search bar results not work when clicking on them?
JavaScript

```<code>window.addEventListener("onload", function(e){
    document.querySelector('searchbar').addEventListener('click', search_album()) //adds a listener for the click event, which runs the function search_album()
    document.querySelector('searchbar').addEventListener('blur', hide_results()) //adds a listener for the blur event, where the user loses focus from the input field, running the function hide_results()
});

function search_album() { //function to find the album via search bar
    let input = document.getElementById('searchbar').value //input is the searchbar value
    input = input.toLowerCase(); //turned into lowercase
    let x = document.getElementsByClassName('albums'); // and x is the list of albums with the same class name

    for (i = 0; i < x.length; i++){ //looping around for the number of albums in the list found in the php page
        if (!x[i].innerHTML.toLowerCase().includes(input)) { //checking that the value entered is not found in the list of albums in the php page
            //do not display the list of items that matches
        }
        else{
            x[i].style.display = 'list-item'; //display the list of items that matches
        }
    }
}

function hide_results() { //function to run when the user click anywhere else in the page, not in the input field
    let listItems = document.getElementById('list');
    listItems.style.display = 'none'; //hide the results list
    document.getElementById("searchbar").value = ""; //empty input field
}
</code>```

HTML Code

```<code><input id="searchbar" type="text" name="search" placeholder="Search Something..."
    onkeyup="search_album()" onblur="hide_results()">

    <ol id="list">
        <li class="albums" id="#red"><a href="#red" class="link">Red - Taylor Swift</a></li>
        <li class="albums" id="#allartists"><a href="artists.php" class="link">All Artists</a></li>
        <li class="albums" id="#allalbums"><a href="albums.php" class="link">All Albums of all Artists</a></li>
        <li class="albums" id="#taylor"><a href="taylorswift.php" class="link">About Taylor Swift</a></li>
        <li class="albums" id="#taylor"><a href="tayloralbums.php" class="link">Taylor Swift Albums</a></li>
        <li class="albums" id="#gigs"><a href="gigs.php" class="link">Upcoming GIGS</a></li>
    </ol>
</code>```

I was trying to make a searchbar so the user could enter any key and matching results would start to show up based on if the letter they entered is found in the word, hiding the results when the user clicks outside of the searchbar, showing the results again if inputting letters again, and allowing this process to repeat.

Body:
JavaScript

window.addEventListener("onload", function(e){
    document.querySelector('searchbar').addEventListener('click', search_album()) //adds a listener for the click event, which runs the function search_album()
    document.querySelector('searchbar').addEventListener('blur', hide_results()) //adds a listener for the blur event, where the user loses focus from the input field, running the function hide_results()
});

function search_album() { //function to find the album via search bar
    let input = document.getElementById('searchbar').value //input is the searchbar value
    input = input.toLowerCase(); //turned into lowercase
    let x = document.getElementsByClassName('albums'); // and x is the list of albums with the same class name

    for (i = 0; i < x.length; i++){ //looping around for the number of albums in the list found in the php page
        if (!x[i].innerHTML.toLowerCase().includes(input)) { //checking that the value entered is not found in the list of albums in the php page
            //do not display the list of items that matches
        }
        else{
            x[i].style.display = 'list-item'; //display the list of items that matches
        }
    }
}

function hide_results() { //function to run when the user click anywhere else in the page, not in the input field
    let listItems = document.getElementById('list');
    listItems.style.display = 'none'; //hide the results list
    document.getElementById("searchbar").value = ""; //empty input field
}

HTML Code

<input id="searchbar" type="text" name="search" placeholder="Search Something..."
    onkeyup="search_album()" onblur="hide_results()">

Red - Taylor Swift

All Artists

All Albums of all Artists

About Taylor Swift

Taylor Swift Albums

Upcoming GIGS

I was trying to make a searchbar so the user could enter any key and matching results would start to show up based on if the letter they entered is found in the word, hiding the results when the user clicks outside of the searchbar, showing the results again if inputting letters again, and allowing this process to repeat.


问:
jgit - files not getting added to the github repo
i tried the jgit to add files to the github repo. Commit is getting created, but the files are not added, In addfilepattern - i tried "." as well. I have commented pull as i am  facing error w.r.t branch - saying branch not found. Below is my code snippet:</p>
```<code>   Git.cloneRepository().setURI("https://github.com/"+org+"/"+repo+".git").setCredentialsProvider(credentialsProvider).setDirectory(new File(Gitpath)).setCloneAllBranches(true).call();

Git.init().setDirectory(new File(Gitpath)).setInitialBranch("main").call();

var git = Git.open(new File(Gitpath));

//git.pull().setCredentialsProvider(credentialsProvider).setRemoteBranchName("main").call();

git.add().setUpdate(true).addFilepattern(directoryName+fileName).call();

git.commit().setMessage("Adding files.").call();

git.push().setCredentialsProvider(credentialsProvider).call();
</code>```

Body:
i tried the jgit to add files to the github repo. Commit is getting created, but the files are not added, In addfilepattern - i tried "." as well. I have commented pull as i am  facing error w.r.t branch - saying branch not found. Below is my code snippet:

   Git.cloneRepository().setURI("https://github.com/"+org+"/"+repo+".git").setCredentialsProvider(credentialsProvider).setDirectory(new File(Gitpath)).setCloneAllBranches(true).call();

Git.init().setDirectory(new File(Gitpath)).setInitialBranch("main").call();

var git = Git.open(new File(Gitpath));

//git.pull().setCredentialsProvider(credentialsProvider).setRemoteBranchName("main").call();

git.add().setUpdate(true).addFilepattern(directoryName+fileName).call();

git.commit().setMessage("Adding files.").call();

git.push().setCredentialsProvider(credentialsProvider).call();


问:
Send MQTT from Browser with simple nodejs
just want to test a simple browser application to send mqtt messages to my broker by clicking on a browser button.
I found https://gist.github.com/narutaro/6461c0524f7d7ff01e21c2ecb0be84ca
I am really new to those protocols like HTTP, MQTT, Javascript, HTML and so on.

Using Ubuntu...

But I dont know how to run it. I subscribe the topic "/test" and put in the brokers ip <IP:PORT>
(the x' es are of course changed in my real code 192.xxx.xxx.xxx:1883)
It has no password.

Normally I should receive something.
But i dont receive anything.
What could be the reason?

When subscribing with mosquitto_sub -h  -t /test I can see the normal traffic

```<code>
\<!DOCTYPE html\>
\<html lang="en"\>

\<head\>
\<meta charset="utf-8"\>
\<title\>MQTT DASH\</title\>.
\<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"\>\</script\>
\</head\>

\<body\>

\<script\>
**let client = mqtt.connect('192.xxx.xxx.xxx:1883');**
let topic = "/test"

client.subscribe(topic);

pubLoop = setInterval(() =\> {
const time = Date.now().toString();
const temp = Math.floor( Math.random() \* 11 );
let metric = '{"time":' + time + ', "name": "sensor1", "temp":' + temp + '}'
client.publish(topic, metric);
}, 1000);

client.on('message', function (topic, message) { // message is Buffer
console.log(message.toString());
});

setTimeout(function() { clearInterval( pubLoop ); }, 10000); // stop after 10sec

\</script\>

\</body\>
\</html\>

</code>```

Thank you for advices :)

Body:
just want to test a simple browser application to send mqtt messages to my broker by clicking on a browser button.
I found https://gist.github.com/narutaro/6461c0524f7d7ff01e21c2ecb0be84ca
I am really new to those protocols like HTTP, MQTT, Javascript, HTML and so on.

Using Ubuntu...

But I dont know how to run it. I subscribe the topic "/test" and put in the brokers ip <IP:PORT>
(the x' es are of course changed in my real code 192.xxx.xxx.xxx:1883)
It has no password.

Normally I should receive something.
But i dont receive anything.
What could be the reason?

When subscribing with mosquitto_sub -h  -t /test I can see the normal traffic

\<!DOCTYPE html\>
\

\
\<meta charset="utf-8"\>
\<title\>MQTT DASH\</title\>.
\
\

\

\

\
\

Thank you for advices :)


问:
mypy fails to narrow down generic types in `TypeGuard`-based conditionals
Trying to create a type-pure container in Python, I've stumbled upon type-narrowing failure of generic types by mypy when creating a signature of the __setitem__ method.

Before we dive in, I'm using:

mypy 0.991

python 3.10.6.

First, let's consider a basic example.

Let us define two types, A and B, and a type variable AB that can be either A or B (but not a Union[A, B]):

from __future__ import annotations

import typing as t
from collections import abc
from itertools import tee
from typing_extensions import reveal_type

class A:
    ...

class B:
    ...

AB = t.TypeVar('AB', A, B)  # Strictly A or B
```
<p>Now, suppose we want to define a function or method with the following signature:</p>
<pre class="lang-py prettyprint-override"><code>def fn(arg: AB | abc.Iterable[AB]):
</code>```

The function's body will depend on whether AB or abc.Iterable[AB] are provided.
To check that, let's introduce the following utilities:

T = t.TypeVar('T')

def is_iterable_of(
        s: abc.Iterable[t.Any], _type: t.Type[T]
) -> t.TypeGuard[abc.Iterable[T]]:
    return all(isinstance(x, _type) for x in s)

def is_type(x: t.Any, _type: t.Type[T]) -> t.TypeGuard[T]:
    return isinstance(x, _type)

def is_a_or_b(x: t.Any) -> t.TypeGuard[A | B]:
    return isinstance(x, A) or isinstance(x, B)

def is_iterable_of_ab(s: abc.Iterable[t.Any]) -> t.TypeGuard[abc.Iterable[AB]]:
    ss = tee(s)

    return any(
            is_iterable_of(_s, _t) for _s, _t in zip(ss, [A, B])
        )
```
<p>I think only <code>is_iterable_of_ab</code> might be a little confusing: it checks whether the provided iterable contains all <code>A</code> types or all <code>B</code> types. To view what <code>TypeGuard</code> types are doing, please refer to the mypy docs.</p>
<p>We apply our type-narrowing functions in <code>fn</code> as follows:</p>
<pre class="lang-py prettyprint-override"><code>def fn(arg: A | B | abc.Iterable[AB]):
    if is_a_or_b(arg):
        # Process single instance
        reveal_type(arg)  # A | B
    else:
        # Process multiple instances
        reveal_type(arg)  # (A | B | Iterable[A]) | (A | B | Iterable[B])
        assert is_iterable_of_ab(arg)
</code>```

Mypy produces the following output (you can check the full example's code in mypy playground):

```<code>main.py:46: note: Revealed type is "Union[__main__.A, __main__.B]"
main.py:49: note: Revealed type is "Union[__main__.A, __main__.B, typing.Iterable[__main__.A]]"
main.py:49: note: Revealed type is "Union[__main__.A, __main__.B, typing.Iterable[__main__.B]]"
main.py:50: error: Argument 1 to "is_iterable_of_ab" has incompatible type "Union[A, B, Iterable[A]]"; expected "Iterable[Any]"  [arg-type]
main.py:50: error: Argument 1 to "is_iterable_of_ab" has incompatible type "Union[A, B, Iterable[B]]"; expected "Iterable[Any]"  [arg-type]
</code>```

What is confusing here is that the call to is_a_or_b, while narrows down the type to A | B correctly, doesn't lead to mypy recognizing that if the conditional is False, the provided arg must have the abc.Iterable[AB] type. As a result, any functionality inside the else block that depends on arg being Iterable[AB] will raise an error since mypy thinks arg is can still be A | B.

Note that this also fails:

def fn2(arg: A | B | abc.Iterable[AB]):
    if is_a_or_b(arg):
        # Process single instance
        reveal_type(arg)  # A | B
    elif is_iterable_of_ab(arg):  # error: incompatible type
        # Process multiple instances
        reveal_type(arg)  # wrong type: Iterable[A]
    else:
        raise TypeError()
```
<p><strong>So, how could I correctly use type-narrowing here?</strong></p>
<hr />
<p>For a more realistic example indicated at the beginning, consider making a type pure list class:</p>
<pre class="lang-py prettyprint-override"><code>class TypePureList(t.Generic[AB]):

    def __init__(self, items: abc.Iterable[AB]):
        if not isinstance(items, list):
            items = list(items)
        self._items: list[AB] = items

    @t.overload
    def __setitem__(self, index: t.SupportsIndex, value: AB):
        ...

    @t.overload
    def __setitem__(self, index: slice, value: abc.Iterable[AB]):
        ...

    def __setitem__(self, index: t.SupportsIndex | slice, value: AB | abc.Iterable[AB]):

        if len(self._items) == 0:
            raise ValueError

        if isinstance(index, t.SupportsIndex):
            # Check that the value type is correct by itself
            assert is_a_or_b(value)
            # Check that the value type matches the existing type
            assert is_iterable_of_ab([self._items[0], value])
            reveal_type(value)  # A | B
        else:
            # Index must be slice
            # Value must be Iterable
            reveal_type(index)  # slice
            reveal_type(value)  # (A | Iterable[A]) | (B | Iterable[B])
            # Check that the iterable contains correct types
            value, value1, value2 = tee(value, 3)  # error: incompatible type
            assert is_iterable_of_ab(value1)
            # Check if the iterable types match the existing type
            assert is_iterable_of_ab([self._items[0], next(value2)])

        # error: invalid syntax -- index is Union[SupportsIndex, slice]
        # error: incompatible types in assignment
        self._items.__setitem__(index, value)
</code>```

Firstly, mypy fails to use the overloading information, but that seems to be an ongoing issue (see #7858).
Secondly, same as above, mypy fails to narrow down the types following the assertion that if index has SupportsIndex type, then value must be Iterable[AB] due to assert is_a_or_b(value).

Body:
Trying to create a type-pure container in Python, I've stumbled upon type-narrowing failure of generic types by mypy when creating a signature of the __setitem__ method.

Before we dive in, I'm using:

mypy 0.991

python 3.10.6.

First, let's consider a basic example.

Let us define two types, A and B, and a type variable AB that can be either A or B (but not a Union[A, B]):

from __future__ import annotations

import typing as t
from collections import abc
from itertools import tee
from typing_extensions import reveal_type

class A:
    ...

class B:
    ...

AB = t.TypeVar('AB', A, B)  # Strictly A or B

Now, suppose we want to define a function or method with the following signature:

def fn(arg: AB | abc.Iterable[AB]):

The function's body will depend on whether AB or abc.Iterable[AB] are provided.
To check that, let's introduce the following utilities:

T = t.TypeVar('T')

def is_iterable_of(
        s: abc.Iterable[t.Any], _type: t.Type[T]
) -> t.TypeGuard[abc.Iterable[T]]:
    return all(isinstance(x, _type) for x in s)

def is_type(x: t.Any, _type: t.Type[T]) -> t.TypeGuard[T]:
    return isinstance(x, _type)

def is_a_or_b(x: t.Any) -> t.TypeGuard[A | B]:
    return isinstance(x, A) or isinstance(x, B)

def is_iterable_of_ab(s: abc.Iterable[t.Any]) -> t.TypeGuard[abc.Iterable[AB]]:
    ss = tee(s)

    return any(
            is_iterable_of(_s, _t) for _s, _t in zip(ss, [A, B])
        )

I think only is_iterable_of_ab might be a little confusing: it checks whether the provided iterable contains all A types or all B types. To view what TypeGuard types are doing, please refer to the mypy docs.

We apply our type-narrowing functions in fn as follows:

def fn(arg: A | B | abc.Iterable[AB]):
    if is_a_or_b(arg):
        # Process single instance
        reveal_type(arg)  # A | B
    else:
        # Process multiple instances
        reveal_type(arg)  # (A | B | Iterable[A]) | (A | B | Iterable[B])
        assert is_iterable_of_ab(arg)

Mypy produces the following output (you can check the full example's code in mypy playground):

main.py:46: note: Revealed type is "Union[__main__.A, __main__.B]"
main.py:49: note: Revealed type is "Union[__main__.A, __main__.B, typing.Iterable[__main__.A]]"
main.py:49: note: Revealed type is "Union[__main__.A, __main__.B, typing.Iterable[__main__.B]]"
main.py:50: error: Argument 1 to "is_iterable_of_ab" has incompatible type "Union[A, B, Iterable[A]]"; expected "Iterable[Any]"  [arg-type]
main.py:50: error: Argument 1 to "is_iterable_of_ab" has incompatible type "Union[A, B, Iterable[B]]"; expected "Iterable[Any]"  [arg-type]

What is confusing here is that the call to is_a_or_b, while narrows down the type to A | B correctly, doesn't lead to mypy recognizing that if the conditional is False, the provided arg must have the abc.Iterable[AB] type. As a result, any functionality inside the else block that depends on arg being Iterable[AB] will raise an error since mypy thinks arg is can still be A | B.

Note that this also fails:

def fn2(arg: A | B | abc.Iterable[AB]):
    if is_a_or_b(arg):
        # Process single instance
        reveal_type(arg)  # A | B
    elif is_iterable_of_ab(arg):  # error: incompatible type
        # Process multiple instances
        reveal_type(arg)  # wrong type: Iterable[A]
    else:
        raise TypeError()

So, how could I correctly use type-narrowing here?

For a more realistic example indicated at the beginning, consider making a type pure list class:

class TypePureList(t.Generic[AB]):

    def __init__(self, items: abc.Iterable[AB]):
        if not isinstance(items, list):
            items = list(items)
        self._items: list[AB] = items

    @t.overload
    def __setitem__(self, index: t.SupportsIndex, value: AB):
        ...

    @t.overload
    def __setitem__(self, index: slice, value: abc.Iterable[AB]):
        ...

    def __setitem__(self, index: t.SupportsIndex | slice, value: AB | abc.Iterable[AB]):

        if len(self._items) == 0:
            raise ValueError

        if isinstance(index, t.SupportsIndex):
            # Check that the value type is correct by itself
            assert is_a_or_b(value)
            # Check that the value type matches the existing type
            assert is_iterable_of_ab([self._items[0], value])
            reveal_type(value)  # A | B
        else:
            # Index must be slice
            # Value must be Iterable
            reveal_type(index)  # slice
            reveal_type(value)  # (A | Iterable[A]) | (B | Iterable[B])
            # Check that the iterable contains correct types
            value, value1, value2 = tee(value, 3)  # error: incompatible type
            assert is_iterable_of_ab(value1)
            # Check if the iterable types match the existing type
            assert is_iterable_of_ab([self._items[0], next(value2)])

        # error: invalid syntax -- index is Union[SupportsIndex, slice]
        # error: incompatible types in assignment
        self._items.__setitem__(index, value)

Firstly, mypy fails to use the overloading information, but that seems to be an ongoing issue (see #7858).
Secondly, same as above, mypy fails to narrow down the types following the assertion that if index has SupportsIndex type, then value must be Iterable[AB] due to assert is_a_or_b(value).


问:
Height screen qualifier is not taking the corresponding values
I have a dimens file that has values that will be used for dp >= 615dp (h615dp)

I am testing the following device:

```<code>2055px of height
screen density: xxhdpi
Dp = 2055/(480/160) = 685 dp
</code>```

According to this answer: https://stackoverflow.com/a/43749616/20018861 , I have seen that the real screen height pixels are a little less that the pixels of the device, so I have used the following to see the real height's pixels of the device:

```<code>    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    Log.d("height", "height: " + height);
</code>```

The real height's pixels are: 1911px

Now I am calculating the real dp:

```<code>1911px of height
screen density: xxhdpi
Dp = 1911/(480/160) = 637 dp
</code>```

Even having calculated the real value, we can see that it is still greater than 615dp

The problem is that even 637 > 615 , the values are not taken from the (h615dp) file and they are taken from the default file...

Body:
I have a dimens file that has values that will be used for dp >= 615dp (h615dp)

I am testing the following device:

2055px of height
screen density: xxhdpi
Dp = 2055/(480/160) = 685 dp

According to this answer: https://stackoverflow.com/a/43749616/20018861 , I have seen that the real screen height pixels are a little less that the pixels of the device, so I have used the following to see the real height's pixels of the device:

    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    Log.d("height", "height: " + height);

The real height's pixels are: 1911px

Now I am calculating the real dp:

1911px of height
screen density: xxhdpi
Dp = 1911/(480/160) = 637 dp

Even having calculated the real value, we can see that it is still greater than 615dp

The problem is that even 637 > 615 , the values are not taken from the (h615dp) file and they are taken from the default file...


问:
FluentAssertions cast type to another on the fly when comparing
I'm facing some issues when using FluentAssertions lib to make a equivalency check on two System.Data objects.

I have this scenario:

```<code>Columns.OfType<DataColumn>().Should().BeEquivalentTo(Columns.OfType<DataColumn>(), options => options
                                                                                .Using<double>(ctx => ((double)ctx.Subject).Should().BeApproximately((double)ctx.Expectation, 0.000000001F))
                                                                                .WhenTypeIs<double>());
</code>```

Columns object is of System.Data.DataColumnCollection type

and when I run the test, I got this exception:

```<code>Expected property Columns.OfType<DataColumn>()[8].DataType to be System.Decimal, but found System.Double.
</code>```

And it's of course self explanatory, I have a type missmatch when comparing (the reason why there is a missmatch is because the expected value is being deserialized from base 64 and I canno't affect that deserialization at all. It converts some floating point numbers to decimal and that's why conversion fails.

My question is, can I do some overrides of the comparison on the fly (e. g. can I do cast before comparison, or something like that) in order to achieve that comparison doesn't throw the exception.

I've tried doing this:

```<code>Columns.OfType<DataColumn>()
       .Should()
       .BeEquivalentTo(Columns.OfType<DataColumn>(), options => options
                                                     .RespectingDeclaredTypes()
                                                     .Using<decimal>(ctx => (decimal.ToDouble(ctx.Subject)).Should().BeApproximately(decimal.ToDouble(ctx.Expectation), 0.000000001F))
                                                                                .WhenTypeIs<decimal>()
                                                                                .Using<double>(ctx => ((double)ctx.Subject).Should().BeApproximately((double)ctx.Expectation, 0.000000001F))
                                                                                .WhenTypeIs<double>()); //comparing columns for equivalency
</code>```

but it doesn't do the trick.

Any suggestions how can I overcome this?

Body:
I'm facing some issues when using FluentAssertions lib to make a equivalency check on two System.Data objects.

I have this scenario:

Columns.OfType<DataColumn>().Should().BeEquivalentTo(Columns.OfType<DataColumn>(), options => options
                                                                                .Using<double>(ctx => ((double)ctx.Subject).Should().BeApproximately((double)ctx.Expectation, 0.000000001F))
                                                                                .WhenTypeIs<double>());

Columns object is of System.Data.DataColumnCollection type

and when I run the test, I got this exception:

Expected property Columns.OfType<DataColumn>()[8].DataType to be System.Decimal, but found System.Double.

And it's of course self explanatory, I have a type missmatch when comparing (the reason why there is a missmatch is because the expected value is being deserialized from base 64 and I canno't affect that deserialization at all. It converts some floating point numbers to decimal and that's why conversion fails.

My question is, can I do some overrides of the comparison on the fly (e. g. can I do cast before comparison, or something like that) in order to achieve that comparison doesn't throw the exception.

I've tried doing this:

Columns.OfType<DataColumn>()
       .Should()
       .BeEquivalentTo(Columns.OfType<DataColumn>(), options => options
                                                     .RespectingDeclaredTypes()
                                                     .Using<decimal>(ctx => (decimal.ToDouble(ctx.Subject)).Should().BeApproximately(decimal.ToDouble(ctx.Expectation), 0.000000001F))
                                                                                .WhenTypeIs<decimal>()
                                                                                .Using<double>(ctx => ((double)ctx.Subject).Should().BeApproximately((double)ctx.Expectation, 0.000000001F))
                                                                                .WhenTypeIs<double>()); //comparing columns for equivalency

but it doesn't do the trick.

Any suggestions how can I overcome this?


问:
Wrote a Google script, it seems that everything is correct, an error occurs
Here is the script:

var sheet_id = "1wA0nalVyJ7ilv2pwS0kIWDoXudlPCTVZvEDPgIYviy4";
var sheet_name = "Start_ESP"

function doGet(e) {
  var ss = SpreadsheetApp.openById(sheet_id);
  var sheet = ss.getSheetByName(sheet_name);
  var date = Number(e.parameter.date);
  var sensor = Number(e.parameter.sensor);

  sheet.appendRow([sensor, date]);
}
```

An error occurs on startup:

TypeError: Cannot read properties of undefined (reading 'parameter') doGet @ Код.gs:9

I'm new to this, how can I fix this?

Body:
Here is the script:

var sheet_id = "1wA0nalVyJ7ilv2pwS0kIWDoXudlPCTVZvEDPgIYviy4";
var sheet_name = "Start_ESP"

function doGet(e) {
  var ss = SpreadsheetApp.openById(sheet_id);
  var sheet = ss.getSheetByName(sheet_name);
  var date = Number(e.parameter.date);
  var sensor = Number(e.parameter.sensor);

  sheet.appendRow([sensor, date]);
}

An error occurs on startup:

TypeError: Cannot read properties of undefined (reading 'parameter') doGet @ Код.gs:9

I'm new to this, how can I fix this?


问:
Zipping a folder named "dependencies" in a directory "code_w_dependency" in windows 11 terminal
I want to zip a folder "Dependencies" containing number of packages. This folder "Dependencies" in present in a directory "code_w_dependency".
I want the zip file to be created outside the "dependencies" folder.
I want to do this on Windows 11 terminal.

Can anyone let me know ho to do this?


问:
How To Implement Dynamic Columns in Django models based on POST request
I have created a Django RestFramework with few models like Offers, Dailysubs and Requisitions to which I need add columns dynamically for a POST request.

There should be 1-10 blank columns for a model and a Master table which has fields to configure the new column like name and other properties.

I also need to implement an approach to add these dynamic columns into serializers.

```<code>class Requisition(models.Model):
    skill = models.CharField(max_length=255)
    superClass = models.CharField(max_length=255)
    jobFamily = models.CharField(max_length=255)
    yearOfExp = models.CharField(max_length=255)
    grade = models.CharField(max_length=100)
    ...
    ...
</code>```
```<code>class Offer(models.Model):
    businessGroup = models.CharField(max_length=100)
    status = models.CharField(max_length=20)
    sNo = models.IntegerField()
    recruiter = models.CharField(max_length=100)
    manager = models.CharField(max_length=100)
    dateOfOffer = models.DateField()
    dateOfJoining = models.DateField()
    ...
    ...
</code>```
```<code>class MasterTable(models.Model):
    columnName = models.CharField(max_length=100)
    tableName = models.CharField(max_length=100)
    columnFieldType = models.CharField(max_length=100)
</code>```

I read another post related to this at Django Models (dynamic?) but I don't know if I should create another model to hold these blank columns or if I should add blank columns to each model.

Body:
I have created a Django RestFramework with few models like Offers, Dailysubs and Requisitions to which I need add columns dynamically for a POST request.

There should be 1-10 blank columns for a model and a Master table which has fields to configure the new column like name and other properties.

I also need to implement an approach to add these dynamic columns into serializers.

class Requisition(models.Model):
    skill = models.CharField(max_length=255)
    superClass = models.CharField(max_length=255)
    jobFamily = models.CharField(max_length=255)
    yearOfExp = models.CharField(max_length=255)
    grade = models.CharField(max_length=100)
    ...
    ...

class Offer(models.Model):
    businessGroup = models.CharField(max_length=100)
    status = models.CharField(max_length=20)
    sNo = models.IntegerField()
    recruiter = models.CharField(max_length=100)
    manager = models.CharField(max_length=100)
    dateOfOffer = models.DateField()
    dateOfJoining = models.DateField()
    ...
    ...

class MasterTable(models.Model):
    columnName = models.CharField(max_length=100)
    tableName = models.CharField(max_length=100)
    columnFieldType = models.CharField(max_length=100)

I read another post related to this at Django Models (dynamic?) but I don't know if I should create another model to hold these blank columns or if I should add blank columns to each model.


问:
ML.Net C# read onnx file
I am trying to read an onnx file, and input my parameters as an array, and make a prediction.
this is what my code looks like

```<code>using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.Transforms.Onnx;
using System.Collections.Generic;

namespace MachineLearning
{
    public class MLPrediction
    {
        public static double PredictOutput(string onnxFilePath, float[] inputParameterValues)
        {
            // Set up the MLContext
            var mlContext = new MLContext();

            // Load the ONNX model
            OnnxScoringEstimator estimator = mlContext.Transforms.ApplyOnnxModel(onnxFilePath);

            // Create an instance of InputData
            InputData inputData = new InputData
            {
                FeatureVector = inputParameterValues
            };

            // Create an IEnumerable with a single element: the InputData instance
            IEnumerable<InputData> inputEnumerable = new InputData[] { inputData };

            // Load the data from the IEnumerable
            IDataView prediction = mlContext.Data.LoadFromEnumerable<InputData>(inputEnumerable);

            var model = estimator.Fit(prediction);
            // Return the requested output parameter
            double output = (double)model.GetType().GetProperty("Target").GetValue(model);
            return output;
        }
        class InputData
        {
            [VectorType]
            public float[] FeatureVector { get; set; }
        }

        class OutputData
        {
            public double Target { get; set; }
        }

    }
}

</code>```

however i get the error on "System.ArgumentOutOfRangeException: 'Could not find input column 'Target' '" when I try and create the model.

Would anyone be able to point me where I am going wrong?

Have tried adding a Target to the inputs, but I don't believe it should include this.

Title: ML.Net C# read onnx file

Body:
I am trying to read an onnx file, and input my parameters as an array, and make a prediction.
this is what my code looks like

using Microsoft.ML;
using Microsoft.ML.Data;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.Transforms.Onnx;
using System.Collections.Generic;

namespace MachineLearning
{
    public class MLPrediction
    {
        public static double PredictOutput(string onnxFilePath, float[] inputParameterValues)
        {
            // Set up the MLContext
            var mlContext = new MLContext();

            // Load the ONNX model
            OnnxScoringEstimator estimator = mlContext.Transforms.ApplyOnnxModel(onnxFilePath);

            // Create an instance of InputData
            InputData inputData = new InputData
            {
                FeatureVector = inputParameterValues
            };

            // Create an IEnumerable with a single element: the InputData instance
            IEnumerable<InputData> inputEnumerable = new InputData[] { inputData };

            // Load the data from the IEnumerable
            IDataView prediction = mlContext.Data.LoadFromEnumerable<InputData>(inputEnumerable);

            var model = estimator.Fit(prediction);
            // Return the requested output parameter
            double output = (double)model.GetType().GetProperty("Target").GetValue(model);
            return output;
        }
        class InputData
        {
            [VectorType]
            public float[] FeatureVector { get; set; }
        }

        class OutputData
        {
            public double Target { get; set; }
        }

    }
}

however i get the error on "System.ArgumentOutOfRangeException: 'Could not find input column 'Target' '" when I try and create the model.

Would anyone be able to point me where I am going wrong?

Have tried adding a Target to the inputs, but I don't believe it should include this.


问:
How do ensure that server in droplet does not stop once I discconnect SSH connection from my local machine?
I have created a droplet in digital ocean ( I guess OD  calls Virtual Machines - Droplets) that hosts a server. Droplet has Ubuntu as OS. For setting up the server in the droplet, I have accessed the droplet console through SSH public key from a local ubuntu machine. The server is spun successfully. However, closing the SSH connection kills all live sessions of the server. How Do I ensure that server continues to spin even after I kill the SSH connection?

I have tried accessing from cli - ssh - route and console provided by digitalocean for the virtual machine. Both resulted in stoppage of server when connection with droplet of closed. I guess I  need ensure that the command to spin the server is system wide  command not just the ssh session. How do I do that ?


问:
Failure Compiling nginx 1.22.1 with devtoolset-11
I am trying to make custon nginx rpm for centos:8 docker image.

The source was got here: http://nginx.org/packages/centos/8/SRPMS/nginx-1.22.1-1.el8.ngx.src.rpm

When building:

```<code># rpmbuild -bb nginx.spec
Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.7rNBAj
.....
 + gcc version: 11.2.1 20210728 (Red Hat 11.2.1-1) (GCC)
checking for gcc -pipe switch ... found
checking for --with-ld-opt="-Wl,-z,relro -Wl,-z,now -pie" ... not found
./configure: error: the invalid value in --with-ld-opt="-Wl,-z,relro -Wl,-z,now -pie"

error: Bad exit status from /var/tmp/rpm-tmp.bhezBh (%build)
</code>```

Body:
I am trying to make custon nginx rpm for centos:8 docker image.

The source was got here: http://nginx.org/packages/centos/8/SRPMS/nginx-1.22.1-1.el8.ngx.src.rpm

When building:

# rpmbuild -bb nginx.spec
Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.7rNBAj
.....
 + gcc version: 11.2.1 20210728 (Red Hat 11.2.1-1) (GCC)
checking for gcc -pipe switch ... found
checking for --with-ld-opt="-Wl,-z,relro -Wl,-z,now -pie" ... not found
./configure: error: the invalid value in --with-ld-opt="-Wl,-z,relro -Wl,-z,now -pie"

error: Bad exit status from /var/tmp/rpm-tmp.bhezBh (%build)


问:
Using functions and dart codes in a widget without user interactions
I'm using a state to check what Widget is building; I have a screen with 3 states and I'm using short if to check which screen should be built the code snippet is:

state==state1 ? Container():state==state2 ? Container() : Container

now I want to run a piece of code or a function as one of the containers start to render for example second one.
How can I implement that code? do we have a widget that has no visual component and can be used to run a code without the need of user interaction or even a more useful case; a widget which has a property to run codes or functions and use container as child of that widget?

I don't have a test case so we decided to change the scenario but I'm curious to learn.


问:
File name too long @ rb_sysopen - /app/.env. - Read aws secret manager variable - Ruby on rails
I'm hosting my ruby on rails app on AWS ECS.

For the environment variables, I'm using AWS secrets manager.

The problem is that, when i try to retrieve ENV["RAILS_ENV"], i do not retrieve "production" if I'm in production but a hash map with all the secret variables from aws secrets manager (eg {"RAILS_ENV": "production", "JWT_SECRET":"xxx", ...}.

That triggers the following error when the app is launched.

```<code>File name too long @ rb_sysopen - /app/.env.
{
    "RAILS_ENV": "production",
    "JWT_SECRET":"xxx",
    ...
}
.local (Errno::ENAMETOOLONG)
</code>```

Which is quite problematic.

It happens because one of the env var is used to access a file in the configuration (that's what i guess, i'm not sure)

Anyone has an idea why the env var are coming all together and not separetaly ?

--SOLUTION--

Here is how i solved it.

I try to split the env hash map into all env variables before it was used somewhere

(I tried in config > application.rb but it was not good)

The place where it was fixing the bug was in config > boot.rb

just before that line :

```<code>ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)

</code>```

I added that code :

```<code>require 'aws-sdk-secretsmanager'
if(ENV['RAILS_ENV'] && ENV['RAILS_ENV']!="development")
    secret_hash = JSON.parse(ENV['RAILS_ENV'])
    ENV['JWT_SECRET'] = secret_hash['JWT_SECRET']
    ENV['RAILS_ENV'] = secret_hash['RAILS_ENV']
    ....
end
</code>```

And that fixed the problem

If you have better solution, feel free to share them

I tried to fetch the env variables from aws secret manager.

Body:
I'm hosting my ruby on rails app on AWS ECS.

For the environment variables, I'm using AWS secrets manager.

The problem is that, when i try to retrieve ENV["RAILS_ENV"], i do not retrieve "production" if I'm in production but a hash map with all the secret variables from aws secrets manager (eg {"RAILS_ENV": "production", "JWT_SECRET":"xxx", ...}.

That triggers the following error when the app is launched.

File name too long @ rb_sysopen - /app/.env.
{
    "RAILS_ENV": "production",
    "JWT_SECRET":"xxx",
    ...
}
.local (Errno::ENAMETOOLONG)

Which is quite problematic.

It happens because one of the env var is used to access a file in the configuration (that's what i guess, i'm not sure)

Anyone has an idea why the env var are coming all together and not separetaly ?

--SOLUTION--

Here is how i solved it.

I try to split the env hash map into all env variables before it was used somewhere

(I tried in config > application.rb but it was not good)

The place where it was fixing the bug was in config > boot.rb

just before that line :

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)

I added that code :

require 'aws-sdk-secretsmanager'
if(ENV['RAILS_ENV'] && ENV['RAILS_ENV']!="development")
    secret_hash = JSON.parse(ENV['RAILS_ENV'])
    ENV['JWT_SECRET'] = secret_hash['JWT_SECRET']
    ENV['RAILS_ENV'] = secret_hash['RAILS_ENV']
    ....
end

And that fixed the problem

If you have better solution, feel free to share them

I tried to fetch the env variables from aws secret manager.