问:
Dependency injection of events
Could somebody describe how should looks like class Worker with two events which triggers after some action is happened.
I have class Worker with one method ExecuteAsync. Inside this method I'm executing method i.e. DoStuff(). After that I want execute events. Event one and event two has different logic and have independent arguments which should be passed.
What goals I want to achieve.

I want to mock those events and test Worker without side effects.

Class Worker and events is SRP classes.

I can easily inject another realization of events without breaking my code.

I'm not completely understand this thing:

How should look's like realisation with injecting "body" of events.

Could I execute one event but inject inside it file search logic and sending http logic?

```<code>public class Worker
{
    public event EventHandler<FileFoundArgs> FileFound;
    public event EventHandler<SendHttpArgs> SendHttp;

    public async Task ExecuteAsync()
    {
        DoStuff();
        FileFound?.Invoke(this, new FileFoundArgs(file));
        SendHttp?.Invoke(this, new SendHttpArgs(file));
    }
}
</code>```

Title: Dependency injection of events

Body:
Could somebody describe how should looks like class Worker with two events which triggers after some action is happened.
I have class Worker with one method ExecuteAsync. Inside this method I'm executing method i.e. DoStuff(). After that I want execute events. Event one and event two has different logic and have independent arguments which should be passed.
What goals I want to achieve.

I want to mock those events and test Worker without side effects.

Class Worker and events is SRP classes.

I can easily inject another realization of events without breaking my code.

I'm not completely understand this thing:

How should look's like realisation with injecting "body" of events.

Could I execute one event but inject inside it file search logic and sending http logic?

public class Worker
{
    public event EventHandler<FileFoundArgs> FileFound;
    public event EventHandler<SendHttpArgs> SendHttp;

    public async Task ExecuteAsync()
    {
        DoStuff();
        FileFound?.Invoke(this, new FileFoundArgs(file));
        SendHttp?.Invoke(this, new SendHttpArgs(file));
    }
}


来源: stackexchange

问:
Delphi - Button images suddenly not showing
Delphi 11.1 Windows application, suddenly my TButtons with images are not displaying the images.  They normally don't display in debug mode, but now they're not showing in release mode.

These are TButton components with TImageList assigned and ImageIndex value assigned.  I have several TBitBtn components that are displaying properly.

First screenshot shows TButton with miscButtons chosen as images and ImageIndex 16.  The image shows in IDE. Second screenshot is running the application.  I already changed Go To Activity to TSpeedButton, so the image is working.

```<code>        object btnReqNewActivity: TButton
        Left = 141
        Top = 454
        Width = 175
        Height = 40
        Caption = 'Request NEW Activity'
        Font.Charset = DEFAULT_CHARSET
        Font.Color = clWindowText
        Font.Height = -13
        Font.Name = 'Arial'
        Font.Style = []
        ImageIndex = 16
        ImageMargins.Left = 5
        Images = miscButtons
        ParentFont = False
        TabOrder = 1
        OnClick = btnReqNewActivityClick
      end
      object btnExportClassicList: TButton
        Left = 333
        Top = 454
        Width = 78
        Height = 40
        Caption = 'Export'
        Font.Charset = DEFAULT_CHARSET
        Font.Color = clWindowText
        Font.Height = -13
        Font.Name = 'Arial'
        Font.Style = []
        ImageIndex = 4
        ImageMargins.Left = 5
        Images = miscButtons
        ParentFont = False
        TabOrder = 2
        OnClick = btnExportClassicListClick
      end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Delphi 11.1 Windows application, suddenly my TButtons with images are not displaying the images.  They normally don't display in debug mode, but now they're not showing in release mode.

These are TButton components with TImageList assigned and ImageIndex value assigned.  I have several TBitBtn components that are displaying properly.

First screenshot shows TButton with miscButtons chosen as images and ImageIndex 16.  The image shows in IDE. Second screenshot is running the application.  I already changed Go To Activity to TSpeedButton, so the image is working.

        object btnReqNewActivity: TButton
        Left = 141
        Top = 454
        Width = 175
        Height = 40
        Caption = 'Request NEW Activity'
        Font.Charset = DEFAULT_CHARSET
        Font.Color = clWindowText
        Font.Height = -13
        Font.Name = 'Arial'
        Font.Style = []
        ImageIndex = 16
        ImageMargins.Left = 5
        Images = miscButtons
        ParentFont = False
        TabOrder = 1
        OnClick = btnReqNewActivityClick
      end
      object btnExportClassicList: TButton
        Left = 333
        Top = 454
        Width = 78
        Height = 40
        Caption = 'Export'
        Font.Charset = DEFAULT_CHARSET
        Font.Color = clWindowText
        Font.Height = -13
        Font.Name = 'Arial'
        Font.Style = []
        ImageIndex = 4
        ImageMargins.Left = 5
        Images = miscButtons
        ParentFont = False
        TabOrder = 2
        OnClick = btnExportClassicListClick
      end


问:
Angular: How can I intercept the call to a resource on the dev server and send something else back instead?
thank you for your help.

My problem is that in the production environment I have a file on the path

```<code>localhost:8080/content/language.json
</code>```

with all my text that I need for the frontend. But in the development environment I miss some of the text in the file. It is present but useless for me.

I had the idea that I could intercepted the request to this resource and instead call an external api to get the complete file.

The following code was my attempt.

But it didn't work. It just returned the file that is on the filesystem.

function setupProxy({ tls }) {
  const conf = [
    {
      context: ['/content/languages.json'],
      target: `http${tls ? 's' : ''}://localhost:8080`,
      secure: false,
      changeOrigin: tls,
      pathRewrite: { '^/content/languages.json': '/service_path'},
    },
  ];
  return conf;
}

module.exports = setupProxy;
```

Is it possible to interrupt the request to an resource and how can I do it?

Body:
thank you for your help.

My problem is that in the production environment I have a file on the path

localhost:8080/content/language.json

with all my text that I need for the frontend. But in the development environment I miss some of the text in the file. It is present but useless for me.

I had the idea that I could intercepted the request to this resource and instead call an external api to get the complete file.

The following code was my attempt.

But it didn't work. It just returned the file that is on the filesystem.

function setupProxy({ tls }) {
  const conf = [
    {
      context: ['/content/languages.json'],
      target: `http${tls ? 's' : ''}://localhost:8080`,
      secure: false,
      changeOrigin: tls,
      pathRewrite: { '^/content/languages.json': '/service_path'},
    },
  ];
  return conf;
}

module.exports = setupProxy;

Is it possible to interrupt the request to an resource and how can I do it?


问:
Getting Google Doc innerHTML in JavaScript
Good morning! I'm making an extension for Google Chrome. What I need is to get the text from any editable input or div of the element that the user is editing.

For example, if he edits a text input, I must process the information the user types in real time. This is solved with keyup in the doc and then a document.activeElement.

It works well on all websites except Google Docs. The problem is that Google Doc itself is not an input or a div, but a canvas. Does anyone have any idea of how I can access the content of the sheet?

I have tried with a document.querySelector('.kix-canvas-tile-content').innerHTML but it returns an empty string.

Thanks


问:
how can i mock up or adapt a decorator to the test?
I am trying to apply test to decorators, but without success, it seems that it is not executed when jest is compiled (or does experimentalDecorators not work in jest-ts?

how can I effectively test the behavior of my decorator on top of the class?
I would also like to know how I can test if there will be log output in the console, since my decorator is for creating tryCatch logs effectively?

```<code>class ControllerStub {

    @Execpetion({
        methodName: 'Testing a Controller'
    })
    public async running (): Promise<boolean> {
        return false
    }
}

describe('Exeception Logs Test', () => {
  it('Should return a exeception log if running controller to throws', async function () {

    jest.mock('@core/app/decorators', () => {
        Execpetion:  ({ methodName, crached, countryLog = 'pt-BR', execeptionError }: IExecpetion) => {

            return (target: any, nameMethod: string, descriptor: PropertyDescriptor) =>  {
                const originalMethod = descriptor.value /** Original Function */

                descriptor.value = async function (...args: any[]) {
                    const actuallyDateTime = GetLocale(countryLog, 'toLocaleDateString')
                    const actuallyDate = GetLocale(countryLog, 'toLocaleTimeString')
                    const TargetLoggerId = Math.random().toString(36).slice(2, 7) + new Date().getMinutes()

                    const startClock = process.hrtime()
                    console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.blue}EXECUTION RUNNING${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.magenta}RUNNING] ${ColorsLog.white}${methodName}`)
                    try {
                        const executionMethod = await originalMethod.apply(this, args)
                        const endClock = process.hrtime(startClock)
                        const duration = Math.round((endClock[0]*1000) + (endClock[1]/1000000));
                        const taskDuration = Number(duration) / 1000.0
                        console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.green}EXECUTION SUCCESS${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.green}FINALLY${ColorsLog.white}] ${methodName} - [${ColorsLog.yellow}TASK EVENT: ${taskDuration} ms${ColorsLog.white}]`)
                        return executionMethod
                    }  catch (error) {

                      const err = JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
                      const lineError = err.stack.split('at ')[1]
                      const endClock = process.hrtime(startClock)
                      const duration = Math.round((endClock[0]*1000) + (endClock[1]/1000000));
                      const taskDuration = Number(duration) / 1000.0
                      console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.red}EXECUTION FAILED ${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.red}FINALLY] ${ColorsLog.white}${methodName} - [${ColorsLog.yellow}TASK EVENT LOGGER ERROR: ${ColorsLog.white}${err.message ?? 'NOT FOUND'}`)
                      console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.red}EXECUTION FAILED ${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.red}FINALLY] ${ColorsLog.white}${methodName} - [${ColorsLog.yellow}TASK EVENT DEBUG ERROR : ${ColorsLog.white}${lineError?.trim() ?? 'NOT FOUND'}`)
                      console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.red}EXECUTION FAILED ${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.red}FINALLY] ${ColorsLog.white}${methodName} - [${ColorsLog.yellow}TASK EVENT DURATION    : ${ColorsLog.white}${taskDuration} ms]`)

                      const personalizedError = execeptionError ?? new Error('Internal Server Error')
                      return crached ?? personalizedError
                    }

                }
            }
        }
    });

    const myController = new ControllerStub()
    jest.spyOn(myController, 'running').mockReturnValueOnce(new Promise((resolve, reject) => reject('error')))

    const data = await myController.running()

    expect(data).toEqual(new Error('error'))
  })
})
</code>```

Body:
I am trying to apply test to decorators, but without success, it seems that it is not executed when jest is compiled (or does experimentalDecorators not work in jest-ts?

how can I effectively test the behavior of my decorator on top of the class?
I would also like to know how I can test if there will be log output in the console, since my decorator is for creating tryCatch logs effectively?

class ControllerStub {

    @Execpetion({
        methodName: 'Testing a Controller'
    })
    public async running (): Promise<boolean> {
        return false
    }
}

describe('Exeception Logs Test', () => {
  it('Should return a exeception log if running controller to throws', async function () {

    jest.mock('@core/app/decorators', () => {
        Execpetion:  ({ methodName, crached, countryLog = 'pt-BR', execeptionError }: IExecpetion) => {

            return (target: any, nameMethod: string, descriptor: PropertyDescriptor) =>  {
                const originalMethod = descriptor.value /** Original Function */

                descriptor.value = async function (...args: any[]) {
                    const actuallyDateTime = GetLocale(countryLog, 'toLocaleDateString')
                    const actuallyDate = GetLocale(countryLog, 'toLocaleTimeString')
                    const TargetLoggerId = Math.random().toString(36).slice(2, 7) + new Date().getMinutes()

                    const startClock = process.hrtime()
                    console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.blue}EXECUTION RUNNING${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.magenta}RUNNING] ${ColorsLog.white}${methodName}`)
                    try {
                        const executionMethod = await originalMethod.apply(this, args)
                        const endClock = process.hrtime(startClock)
                        const duration = Math.round((endClock[0]*1000) + (endClock[1]/1000000));
                        const taskDuration = Number(duration) / 1000.0
                        console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.green}EXECUTION SUCCESS${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.green}FINALLY${ColorsLog.white}] ${methodName} - [${ColorsLog.yellow}TASK EVENT: ${taskDuration} ms${ColorsLog.white}]`)
                        return executionMethod
                    }  catch (error) {

                      const err = JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
                      const lineError = err.stack.split('at ')[1]
                      const endClock = process.hrtime(startClock)
                      const duration = Math.round((endClock[0]*1000) + (endClock[1]/1000000));
                      const taskDuration = Number(duration) / 1000.0
                      console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.red}EXECUTION FAILED ${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.red}FINALLY] ${ColorsLog.white}${methodName} - [${ColorsLog.yellow}TASK EVENT LOGGER ERROR: ${ColorsLog.white}${err.message ?? 'NOT FOUND'}`)
                      console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.red}EXECUTION FAILED ${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.red}FINALLY] ${ColorsLog.white}${methodName} - [${ColorsLog.yellow}TASK EVENT DEBUG ERROR : ${ColorsLog.white}${lineError?.trim() ?? 'NOT FOUND'}`)
                      console.log(`${ColorsLog.white}[${ColorsLog.cyan}INFO - ${ColorsLog.blue}LOGGER ID: ${ColorsLog.magenta}${TargetLoggerId}${ColorsLog.white}] ${ColorsLog.red}EXECUTION FAILED ${ColorsLog.white} -  ${actuallyDate} - ${actuallyDateTime} | - [${ColorsLog.red}FINALLY] ${ColorsLog.white}${methodName} - [${ColorsLog.yellow}TASK EVENT DURATION    : ${ColorsLog.white}${taskDuration} ms]`)

                      const personalizedError = execeptionError ?? new Error('Internal Server Error')
                      return crached ?? personalizedError
                    }

                }
            }
        }
    });

    const myController = new ControllerStub()
    jest.spyOn(myController, 'running').mockReturnValueOnce(new Promise((resolve, reject) => reject('error')))

    const data = await myController.running()

    expect(data).toEqual(new Error('error'))
  })
})


问:
Issue with rotating the camera vertically
The following piece of code was written in order to rotate the camera by rad radians vertically (on an axis which has the angle of 90 deg on the vector where the camera looks at). However it's only working when the camera looks in Z direction (rotating on X axis) on every other case the code is rotating the camera on X axis when it shouldn't. Can you explain why is this happening? I would highly appreciate your help.

camera.getWorldDirection(direction)
console.log(direction)
/*direction.y or 0 I'm not sure*/
const axis = new THREE.Vector3(-1 * direction.z, 0,direction.x)
camera.rotateOnAxis(axis, rad)
```

I tried searching for similar issues, simulating the program paper. Unfortunately I could not solve it.

Body:
The following piece of code was written in order to rotate the camera by rad radians vertically (on an axis which has the angle of 90 deg on the vector where the camera looks at). However it's only working when the camera looks in Z direction (rotating on X axis) on every other case the code is rotating the camera on X axis when it shouldn't. Can you explain why is this happening? I would highly appreciate your help.

camera.getWorldDirection(direction)
console.log(direction)
/*direction.y or 0 I'm not sure*/
const axis = new THREE.Vector3(-1 * direction.z, 0,direction.x)
camera.rotateOnAxis(axis, rad)

I tried searching for similar issues, simulating the program paper. Unfortunately I could not solve it.


问:
Bootstrap 5 modal button within collapse link
My layout requires a button to open a Modal within a row that opens a Bootstrap Collapse. Although you're not supposed to put a button inside an anchor it seems to work. When I click the button it opens the modal and the collapse. How do I get it to only open the Modal?</p>
```<code><a data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
Some text
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
More text
</a>
<div class="collapse" id="collapseExample">...</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">...</div>
</code>```

Body:
My layout requires a button to open a Modal within a row that opens a Bootstrap Collapse. Although you're not supposed to put a button inside an anchor it seems to work. When I click the button it opens the modal and the collapse. How do I get it to only open the Modal?

Some text
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
More text

...

...


问:
How to Limit Elements on a Screen?
I have 4 boxes, (which will later be 9), in which I want there to be a total of 3 on screen at all times, excluding mobile. The remainder who are not on screen will be moved to the right end of the box line, but be unseen. I have looked around for a method to accomplish this via HTML & CSS and have found none. Is there a way to do this with HTML, CSS, or JS?

.bioSlider {
  position: relative;
  display: flex;
  justify-content: center;
  overflow: hidden;
}

.box {
  position: relative;
  display: inline-block;
  width: 390px;
  padding: 10px;
}

.slideImage {
  position: relative;
  height: 300px;
}

.slideImage img {
  object-fit: cover;
  box-sizing: border-box;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  width: 100%;
  height: 100%;
}

.overlay {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  width: 100%;
  height: 100%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #000000;
  opacity: 0;
  transition: 0.6s ease-in-out;
}

.quoteText {
  position: absolute;
  text-align: left;
  font-style: italic;
  word-break: break-all;
  padding: 30px;
  top: 30px;
  color: #e5e5e5;
  opacity: 0;
  transition: 0.6s ease-in-out;
}

.detailBox {
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  width: 100%;
  padding: 9px;
  background-color: #e8e8e8;
}

.slideImage:hover .overlay {
  opacity: 50%;
}

.slideImage:hover .quoteText {
  opacity: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <!-- Cadet Slider -->
  <ul class='bioSlider'>
    <li class='cadetOne'>
      <div class='box'>
        <div class='slideImage'>
          <img src='/Images/Red_Card.png' alt=''>
          <div class='overlay'> </div>
          <div class='bodyTextContainer'>
            <p class='quoteText'>"Poopoopeepee"</p>
          </div>
        </div>
        <div class='detailBox'>
          <div class='subHeaderTextContainer'>
            <h3 class='subHeaderText_1'>Battalion CDR <br> LTC Chase Hinson</h3>
          </div>
        </div>
      </div>
    </li>

    <li class='cadetTwo'>
      <div class='box'>
        <div class='slideImage'>
          <img src='/Images/Yellow_Card.png' alt=''>
          <div class='overlay'></div>
          <div class='bodyTextContainer'>
            <p class='quoteText'>"Poopoopeepee"</p>
          </div>
        </div>
        <div class='detailBox'>
          <div class='subHeaderTextContainer'>
            <h3 class='subHeaderText_1'>Battalion XO <br> MAJ Grayson Akins</h3>
          </div>
        </div>
      </div>
    </li>

    <li class='cadetThree'>
      <div class='box'>
        <div class='slideImage'>
          <img src='/Images/Blue_Card.png' alt=''>
          <div class='overlay'></div>
          <div class='bodyTextContainer'>
            <p class='quoteText'>"Poopoopeepee"</p>
          </div>
        </div>
        <div class='detailBox'>
          <div class='subHeaderTextContainer'>
            <h3 class='subHeaderText_1'>Battalion NCO <br> CSM Janecia Bass</h3>
          </div>
        </div>
      </div>
    </li>

    <li class='cadetFour'>
      <div class='box'>
        <div class='slideImage'>
          <img src='/Images/Green_Card.png' alt=''>
          <div class='overlay'></div>
          <div class='bodyTextContainer'>
            <p class='quoteText'>"Poopoopeepee"</p>
          </div>
        </div>
        <div class='detailBox'>
          <div class='subHeaderTextContainer'>
            <h3 class='subHeaderText_1'>Battalion S1 <br> CPT Lauren Newton</h3>
          </div>
        </div>
      </div>
    </li>
  </ul>
</div></code>```

Title: How to Limit Elements on a Screen?

Body:
I have 4 boxes, (which will later be 9), in which I want there to be a total of 3 on screen at all times, excluding mobile. The remainder who are not on screen will be moved to the right end of the box line, but be unseen. I have looked around for a method to accomplish this via HTML & CSS and have found none. Is there a way to do this with HTML, CSS, or JS?

.bioSlider {
  position: relative;
  display: flex;
  justify-content: center;
  overflow: hidden;
}

.box {
  position: relative;
  display: inline-block;
  width: 390px;
  padding: 10px;
}

.slideImage {
  position: relative;
  height: 300px;
}

.slideImage img {
  object-fit: cover;
  box-sizing: border-box;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  width: 100%;
  height: 100%;
}

.overlay {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  width: 100%;
  height: 100%;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: #000000;
  opacity: 0;
  transition: 0.6s ease-in-out;
}

.quoteText {
  position: absolute;
  text-align: left;
  font-style: italic;
  word-break: break-all;
  padding: 30px;
  top: 30px;
  color: #e5e5e5;
  opacity: 0;
  transition: 0.6s ease-in-out;
}

.detailBox {
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  width: 100%;
  padding: 9px;
  background-color: #e8e8e8;
}

.slideImage:hover .overlay {
  opacity: 50%;
}

.slideImage:hover .quoteText {
  opacity: 100%;
}

"Poopoopeepee"

Battalion CDR
 LTC Chase Hinson

"Poopoopeepee"

Battalion XO
 MAJ Grayson Akins

"Poopoopeepee"

Battalion NCO
 CSM Janecia Bass

"Poopoopeepee"

Battalion S1
 CPT Lauren Newton


问:
Laravel eager load with groupBy relational data
I want to get the relational data from bdfesidetails by grouping headable type from relation headable of bdfeasibilitydetail

My Modals

```<code>class BdFeasiFessAndCost extends Model
{
    use HasFactory;
    protected $fillable = [
        'location_id',
        'user_id'
    ];

    public function BdFeasiFessAndCostDetail(){
        return $this->hasMany(BdFeasiFessAndCostDetail::class, 'fess_and_cost_id', 'id');
    }
}

 class BdFeasiFessAndCostDetail extends Model
    {
        use HasFactory;

        protected $fillable = [
            'headble_id',
            'headble_type',
            'rate',
            'quantity',
            'remarks'
        ];
        public function headable(){
            return $this->morphTo('','headble_type','headble_id');
        }
    }
</code>```

in headable morphmany class is BdFeasPerticular

```<code>class BdFeasiPerticular extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'unit_id',
        'type',
        'statuts'
    ];
}
</code>```

I want to get relational data using groupBy like this

```<code>$fees_cost = BdFeasiFessAndCost::with(['BdFeasiFessAndCostDetail.headble' => function($query){
           $query->groupBy('headble.type');
        }])
        ->where('id',$id)
        ->get();
</code>```

Body:
I want to get the relational data from bdfesidetails by grouping headable type from relation headable of bdfeasibilitydetail

My Modals

class BdFeasiFessAndCost extends Model
{
    use HasFactory;
    protected $fillable = [
        'location_id',
        'user_id'
    ];

    public function BdFeasiFessAndCostDetail(){
        return $this->hasMany(BdFeasiFessAndCostDetail::class, 'fess_and_cost_id', 'id');
    }
}

 class BdFeasiFessAndCostDetail extends Model
    {
        use HasFactory;

        protected $fillable = [
            'headble_id',
            'headble_type',
            'rate',
            'quantity',
            'remarks'
        ];
        public function headable(){
            return $this->morphTo('','headble_type','headble_id');
        }
    }

in headable morphmany class is BdFeasPerticular

class BdFeasiPerticular extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'unit_id',
        'type',
        'statuts'
    ];
}

I want to get relational data using groupBy like this

$fees_cost = BdFeasiFessAndCost::with(['BdFeasiFessAndCostDetail.headble' => function($query){
           $query->groupBy('headble.type');
        }])
        ->where('id',$id)
        ->get();


问:
Why my app node.js work from my side online, but not for everyone?
I deployed an react app on my website. I use node.js API with static folder to render the index.html file like this:

```<code>//React Endpoint
const root = require("path").join(__dirname, "../../pages/P7-GROUPOMANIA/frontend/build/");
app.use(express.static(root));
app.use("*", (req, res) => {
  res.sendFile("index.html", { root });
});
</code>```

I run the Node.j server on my VPS and everything work fine, no error. I tested multiple browser and device and all was working.
But Yesterday someone tell me my app don't work on Chrome. From my side it still work well on chrome.
But I can see the problem on Edge: ERR_EMPTY_RESPONSE. It look like the API don't send any response.
I didn't do any change so I really don't know where I can find a solution because there is no error, in console from server side or client side.
You can test from your side at : https://minidev.fr:5443/

I already tried to restart the node server and searching if there is error on the console or syntax error.

I hope someone can help to understand why it work from my side with different device but not for everyone.
And hope my explanation is clear, I'm French i do my best to keep it clear.
Thanks in advance for help

Body:
I deployed an react app on my website. I use node.js API with static folder to render the index.html file like this:

//React Endpoint
const root = require("path").join(__dirname, "../../pages/P7-GROUPOMANIA/frontend/build/");
app.use(express.static(root));
app.use("*", (req, res) => {
  res.sendFile("index.html", { root });
});

I run the Node.j server on my VPS and everything work fine, no error. I tested multiple browser and device and all was working.
But Yesterday someone tell me my app don't work on Chrome. From my side it still work well on chrome.
But I can see the problem on Edge: ERR_EMPTY_RESPONSE. It look like the API don't send any response.
I didn't do any change so I really don't know where I can find a solution because there is no error, in console from server side or client side.
You can test from your side at : https://minidev.fr:5443/

I already tried to restart the node server and searching if there is error on the console or syntax error.

I hope someone can help to understand why it work from my side with different device but not for everyone.
And hope my explanation is clear, I'm French i do my best to keep it clear.
Thanks in advance for help


问:
Azure DevOps Build Pipeline : COPY failed file not found in build context or excluded by .dockerignore:
I know, that this problem is discussed a lot of times, but this is because every time the setup is different....
I have an existing pipeline in Azure Dev Ops, in which a yaml file is executed. This yaml file resides in repository in Azure Repos Git.

The content of the yaml file is the following:

```<code>parameters:
- name: 'dockerfilePath'
  default: '$(Build.SourcesDirectory)/.pipelines/dbdump/Dockerfile'
  type: string

- name: 'imageRepository'
  default: 'databasedump'
  type: string

- name: 'dockerRegistryServiceConnection'
  default: 'ServiceConnectionIoTContainerRegistry'
  type: string

steps:
- checkout: self
- task: Docker@2
  displayName: Login to ACR
  inputs:
    command: login
    containerRegistry: ${{ parameters.dockerRegistryServiceConnection }}

- task: Docker@2
  displayName: Build and push an image to container registry
  inputs:
    # Only build on PR, and build and push docker image otherwise
    ${{ if eq(variables['Build.Reason'], 'PullRequest') }}:
      command: build
    ${{ else }}:
      command: buildAndPush
    repository: ${{ parameters.imageRepository }}
    dockerfile: ${{ parameters.dockerfilePath }}
    buildContext: $(Build.Repository.LocalPath)
    containerRegistry: ${{ parameters.dockerRegistryServiceConnection }}
    tag: '$(Build.BuildId)'
</code>```

The yaml file is put into the ".pipelines" directory, in its subdirectory "dbdump" there are two files - "Dockerfile" and "fakedev.dump.sql" i e. i have the following:

```<code>.pipelines/
  build_and_push_docker.yml
  dbdump/
    Dockerfile
    fakedev.dump.sql
</code>```

And the content of the docker file is the following:

```<code>FROM mariadb:10.4.26

ENV MYSQL_ROOT_PASSWORD <some_password>
ENV MARIADB_DATABASE <some_database>
COPY fakedev.dump.sql /docker-entrypoint-initdb.d/

EXPOSE 3306

</code>```

And when i execute the pipeline i get :

```<code>COPY failed: file not found in build context or excluded by .dockerignore: stat fakedev.dump.sql: file does not exist
</code>```

Obviously during the build the search for this file is done in the directory, where the build is executed, and tried by changing the build context, but none of

buildContext: '.'
buildContext: $(Build.Repository.LocalPath)
buildContext: $(Build.SourcesDirectory)

was helpful.
So what i have to change in order the sql file to be found during the build?

Body:
I know, that this problem is discussed a lot of times, but this is because every time the setup is different....
I have an existing pipeline in Azure Dev Ops, in which a yaml file is executed. This yaml file resides in repository in Azure Repos Git.

The content of the yaml file is the following:

parameters:
- name: 'dockerfilePath'
  default: '$(Build.SourcesDirectory)/.pipelines/dbdump/Dockerfile'
  type: string

- name: 'imageRepository'
  default: 'databasedump'
  type: string

- name: 'dockerRegistryServiceConnection'
  default: 'ServiceConnectionIoTContainerRegistry'
  type: string

steps:
- checkout: self
- task: Docker@2
  displayName: Login to ACR
  inputs:
    command: login
    containerRegistry: ${{ parameters.dockerRegistryServiceConnection }}

- task: Docker@2
  displayName: Build and push an image to container registry
  inputs:
    # Only build on PR, and build and push docker image otherwise
    ${{ if eq(variables['Build.Reason'], 'PullRequest') }}:
      command: build
    ${{ else }}:
      command: buildAndPush
    repository: ${{ parameters.imageRepository }}
    dockerfile: ${{ parameters.dockerfilePath }}
    buildContext: $(Build.Repository.LocalPath)
    containerRegistry: ${{ parameters.dockerRegistryServiceConnection }}
    tag: '$(Build.BuildId)'

The yaml file is put into the ".pipelines" directory, in its subdirectory "dbdump" there are two files - "Dockerfile" and "fakedev.dump.sql" i e. i have the following:

.pipelines/
  build_and_push_docker.yml
  dbdump/
    Dockerfile
    fakedev.dump.sql

And the content of the docker file is the following:

FROM mariadb:10.4.26

ENV MYSQL_ROOT_PASSWORD <some_password>
ENV MARIADB_DATABASE <some_database>
COPY fakedev.dump.sql /docker-entrypoint-initdb.d/

EXPOSE 3306

And when i execute the pipeline i get :

COPY failed: file not found in build context or excluded by .dockerignore: stat fakedev.dump.sql: file does not exist

Obviously during the build the search for this file is done in the directory, where the build is executed, and tried by changing the build context, but none of

buildContext: '.'
buildContext: $(Build.Repository.LocalPath)
buildContext: $(Build.SourcesDirectory)

was helpful.
So what i have to change in order the sql file to be found during the build?


问:
SCL3400-D01 Angle conversion
I am using a Murata SCL3400 2 Axis  Inclinometer to do some measurements.
I can talk to unit using a USB-SPI converter chip (as the inclinometer is digital and can only be communicated via SPI Protocol).
One issue that I do have  is that I would like to know how to convert the gravity projection values - ACCx & ACCy(g) to angles in degrees.
I tried using the equation

Angle = Tanh(ACCx/ACCy)

and converted this value in Radians to Degrees by multiplying it with 180/pi.

However this has not worked.
Can anyone help out with my query?

Thanks
LabMat

Title: SCL3400-D01 Angle conversion


问:
Mocking individual methods of external module differently each time in jest
I want to test my service methods which is dependent on the external module azure-devops-extension-api.

Currently I have created __mocks__\azure-devops-extension-sdk.ts and provide the custom implementation which needs to be mocked. It works fine. But there are some issues with unit testing as asked in Methods called on jest mocked response fails with error.

But I don't have to feasibility to change values for each of the unit test. Values that needs to be provided in mock will vary based on the unit test case.

for example, below is my service method which uses the getService() method from SDK of azure-devops-extension-api module.

import * as SDK from 'azure-devops-extension-sdk';
// more stmts

const projectService = await SDK.getService<IProjectPageService>(CommonServiceIds.ProjectPageService);

const project = await projectService.getProject();
```
<p>For first unit test, I want to mock the <code>getProject()</code> method to return a valid value and for the second unit test, I want to be a null.</p>
<p>Most common solution is the below approach, but as requested, I want the flexity to mock differently for each unit test.</p>
<pre class="lang-js prettyprint-override"><code>jest.mock('azure-devops-extension-sdk', () => {
  return { getService: (client: any) => { id: 1, name: 'project' } };
});
</code>```

Body:
I want to test my service methods which is dependent on the external module azure-devops-extension-api.

Currently I have created __mocks__\azure-devops-extension-sdk.ts and provide the custom implementation which needs to be mocked. It works fine. But there are some issues with unit testing as asked in Methods called on jest mocked response fails with error.

But I don't have to feasibility to change values for each of the unit test. Values that needs to be provided in mock will vary based on the unit test case.

for example, below is my service method which uses the getService() method from SDK of azure-devops-extension-api module.

import * as SDK from 'azure-devops-extension-sdk';
// more stmts

const projectService = await SDK.getService<IProjectPageService>(CommonServiceIds.ProjectPageService);

const project = await projectService.getProject();

For first unit test, I want to mock the getProject() method to return a valid value and for the second unit test, I want to be a null.

Most common solution is the below approach, but as requested, I want the flexity to mock differently for each unit test.

jest.mock('azure-devops-extension-sdk', () => {
  return { getService: (client: any) => { id: 1, name: 'project' } };
});


问:
Xamarin Forms/Prism/Shiny Dryly.ContainerException when registering service
I'm having trouble with registering a platform specific service (iOS). This used to work fine, but now when running the app I get the following exception:

```<code>DryIoc.ContainerException: code: Error.UnableToResolveUnknownService;
message: Unable to resolve resolution root PS.Forms.VoiceApp.Base.Interfaces.IInitService
  from container with scope {Name=null}
 with Rules with {TrackingDisposableTransients, UseDynamicRegistrationsAsFallbackOnly, FuncAndLazyWithoutRegistration, SelectLastRegisteredFactory} and without {ThrowOnRegisteringDisposableTransient, UseFastExpressionCompilerIfPlatformSupported}
 with FactorySelector=SelectLastRegisteredFactory
 with Made={FactoryMethod=ConstructorWithResolvableArguments}
Where no service registrations found
  and no dynamic registrations found in 1 of Rules.DynamicServiceProviders
  and nothing found in 0 of Rules.UnknownServiceResolvers
  at DryIoc.Throw.It (System.Int32 error, System.Object arg0, System.Object arg1, System.Object arg2, System.Object arg3) [0x00000] in /_/src/DryIoc/Container.cs:13642
  at DryIoc.Container.TryThrowUnableToResolve (DryIoc.Request request) [0x0006d] in /_/src/DryIoc/Container.cs:1088
  at DryIoc.Container.DryIoc.IContainer.ResolveFactory (DryIoc.Request request) [0x00072] in /_/src/DryIoc/Container.cs:1068
  at DryIoc.Container.ResolveAndCache (System.Int32 serviceTypeHash, System.Type serviceType, DryIoc.IfUnresolved ifUnresolved) [0x00021] in /_/src/DryIoc/Container.cs:367
  at DryIoc.Container.DryIoc.IResolver.Resolve (System.Type serviceType, DryIoc.IfUnresolved ifUnresolved) [0x0011c] in /_/src/DryIoc/Container.cs:356
  at DryIoc.Container.DryIoc.IResolver.Resolve (System.Type serviceType, System.Object serviceKey, DryIoc.IfUnresolved ifUnresolved, System.Type requiredServiceType, DryIoc.Request preResolveParent, System.Object[] args) [0x00039] in /_/src/DryIoc/Container.cs:428
  at DryIoc.Resolver.Resolve (DryIoc.IResolver resolver, System.Type serviceType, System.Object[] args, DryIoc.IfUnresolved ifUnresolved, System.Type requiredServiceType, System.Object serviceKey) [0x00000] in /_/src/DryIoc/Container.cs:8087
  at Prism.DryIoc.DryIocContainerExtension.Resolve (System.Type type, System.ValueTuple`2[System.Type,System.Object][] parameters) [0x0001c] in /_/src/Containers/Prism.DryIoc.Shared/DryIocContainerExtension.cs:294
</code>```

I don't know why this would happen all of a sudden. In my AppDelegate.cs I register the IOSInitService which implements the Interface IInitService like this:

```<code>public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) {
            this.PreventLinkerFromStrippingCommonLocalizationReferences();
            Rg.Plugins.Popup.Popup.Init();
            this.ShinyFinishedLaunching(new VoiceAppStartup {
                RegisterPlatformServices = services =>
                {
                    services.AddSingleton<IInitService, IOSInitService>();
                }
            });
            global::Xamarin.Forms.Forms.Init();
            FormsControls.Touch.Main.Init();
            this.LoadApplication(new App());
            return base.FinishedLaunching(application, launchOptions);
        }
</code>```

I also register some other services in the App.xaml (which I can't do here with platform specific implementations) an they work fine:

```<code>protected override void RegisterTypes(IContainerRegistry containerRegistry) {
            containerRegistry.RegisterPopupNavigationService();
            containerRegistry.RegisterSingleton<IAppInfo, AppInfoImplementation>();
            containerRegistry.RegisterSingleton<IShare, ShareImplementation>();
...}
</code>```

Does anybody have an idea why that could be? The exception implies, that the service is not registered or am I missing something?

Body:
I'm having trouble with registering a platform specific service (iOS). This used to work fine, but now when running the app I get the following exception:

DryIoc.ContainerException: code: Error.UnableToResolveUnknownService;
message: Unable to resolve resolution root PS.Forms.VoiceApp.Base.Interfaces.IInitService
  from container with scope {Name=null}
 with Rules with {TrackingDisposableTransients, UseDynamicRegistrationsAsFallbackOnly, FuncAndLazyWithoutRegistration, SelectLastRegisteredFactory} and without {ThrowOnRegisteringDisposableTransient, UseFastExpressionCompilerIfPlatformSupported}
 with FactorySelector=SelectLastRegisteredFactory
 with Made={FactoryMethod=ConstructorWithResolvableArguments}
Where no service registrations found
  and no dynamic registrations found in 1 of Rules.DynamicServiceProviders
  and nothing found in 0 of Rules.UnknownServiceResolvers
  at DryIoc.Throw.It (System.Int32 error, System.Object arg0, System.Object arg1, System.Object arg2, System.Object arg3) [0x00000] in /_/src/DryIoc/Container.cs:13642
  at DryIoc.Container.TryThrowUnableToResolve (DryIoc.Request request) [0x0006d] in /_/src/DryIoc/Container.cs:1088
  at DryIoc.Container.DryIoc.IContainer.ResolveFactory (DryIoc.Request request) [0x00072] in /_/src/DryIoc/Container.cs:1068
  at DryIoc.Container.ResolveAndCache (System.Int32 serviceTypeHash, System.Type serviceType, DryIoc.IfUnresolved ifUnresolved) [0x00021] in /_/src/DryIoc/Container.cs:367
  at DryIoc.Container.DryIoc.IResolver.Resolve (System.Type serviceType, DryIoc.IfUnresolved ifUnresolved) [0x0011c] in /_/src/DryIoc/Container.cs:356
  at DryIoc.Container.DryIoc.IResolver.Resolve (System.Type serviceType, System.Object serviceKey, DryIoc.IfUnresolved ifUnresolved, System.Type requiredServiceType, DryIoc.Request preResolveParent, System.Object[] args) [0x00039] in /_/src/DryIoc/Container.cs:428
  at DryIoc.Resolver.Resolve (DryIoc.IResolver resolver, System.Type serviceType, System.Object[] args, DryIoc.IfUnresolved ifUnresolved, System.Type requiredServiceType, System.Object serviceKey) [0x00000] in /_/src/DryIoc/Container.cs:8087
  at Prism.DryIoc.DryIocContainerExtension.Resolve (System.Type type, System.ValueTuple`2[System.Type,System.Object][] parameters) [0x0001c] in /_/src/Containers/Prism.DryIoc.Shared/DryIocContainerExtension.cs:294

I don't know why this would happen all of a sudden. In my AppDelegate.cs I register the IOSInitService which implements the Interface IInitService like this:

public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) {
            this.PreventLinkerFromStrippingCommonLocalizationReferences();
            Rg.Plugins.Popup.Popup.Init();
            this.ShinyFinishedLaunching(new VoiceAppStartup {
                RegisterPlatformServices = services =>
                {
                    services.AddSingleton<IInitService, IOSInitService>();
                }
            });
            global::Xamarin.Forms.Forms.Init();
            FormsControls.Touch.Main.Init();
            this.LoadApplication(new App());
            return base.FinishedLaunching(application, launchOptions);
        }

I also register some other services in the App.xaml (which I can't do here with platform specific implementations) an they work fine:

protected override void RegisterTypes(IContainerRegistry containerRegistry) {
            containerRegistry.RegisterPopupNavigationService();
            containerRegistry.RegisterSingleton<IAppInfo, AppInfoImplementation>();
            containerRegistry.RegisterSingleton<IShare, ShareImplementation>();
...}

Does anybody have an idea why that could be? The exception implies, that the service is not registered or am I missing something?


问:
Firebase.Functions.FunctionsException: UNAUTHENTICATED, Can't Call cloud function even after user is authenticated
Unity editor version: 2021.3.9f
Firebase Unity SDK version: 9.6.0
Source you installed the SDK: FirebaseFunctions(.unitypackage or Unity Package Manager)
Problematic Firebase Component: FirebaseFunctions
Other Firebase Components in use: FirebaseFunctions ,Auth
Additional SDKs you are using:
Platform you are using the Unity editor on: Windows
Platform you are targeting:Android
Scripting Runtime: IL2CPP
[REQUIRED] Please describe the issue here:
Firebase.Functions.FunctionsException: UNAUTHENTICATED
at Firebase.Functions.HttpsCallableReference.b__9_0 (System.Threading.Tasks.Task`1[TResult] task) [0x00000] in <00000000000000000000000000000000>:0
I m trying to user firebase functions with unity. I have added firebase auth that is working perfectly. After auth I am calling my firebase function using this code below

`void FirebaseFucntionTest()
{

```<code>var data = new Dictionary<string, object>();
Debug.Log("Calling");
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;
Debug.Log(FirebaseAuth.DefaultInstance.CurrentUser.DisplayName);

var function = functions.GetHttpsCallable("testunity");
function.CallAsync(data).ContinueWith((task) =>
{
   if (task.IsFaulted)
   {
       foreach (var inner in task.Exception.InnerExceptions)
       {
           if (inner is FunctionsException)
           {
               var e = (FunctionsException)inner;
               var code = e.ErrorCode;
               var message = e.ToString();
               Debug.Log(message);
               Debug.Log(code);
           }
       }
   }
   else
   if (task.IsCompleted)
   {
       Debug.Log((string)task.Result.Data);
   }
});
</code>```

}`

I am holding a reference to auth using: auth = FirebaseAuth.DefaultInstance; and after this I am calling my function that runs the cloud function, as you can see in the debug statement at the start of the method I getting the currentusername successfully, but after code moves to cloud function call it is giving me exception of unauthenticated:

Body:
Unity editor version: 2021.3.9f
Firebase Unity SDK version: 9.6.0
Source you installed the SDK: FirebaseFunctions(.unitypackage or Unity Package Manager)
Problematic Firebase Component: FirebaseFunctions
Other Firebase Components in use: FirebaseFunctions ,Auth
Additional SDKs you are using:
Platform you are using the Unity editor on: Windows
Platform you are targeting:Android
Scripting Runtime: IL2CPP
[REQUIRED] Please describe the issue here:
Firebase.Functions.FunctionsException: UNAUTHENTICATED
at Firebase.Functions.HttpsCallableReference.b__9_0 (System.Threading.Tasks.Task`1[TResult] task) [0x00000] in <00000000000000000000000000000000>:0
I m trying to user firebase functions with unity. I have added firebase auth that is working perfectly. After auth I am calling my firebase function using this code below

`void FirebaseFucntionTest()
{

var data = new Dictionary<string, object>();
Debug.Log("Calling");
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;
Debug.Log(FirebaseAuth.DefaultInstance.CurrentUser.DisplayName);

var function = functions.GetHttpsCallable("testunity");
function.CallAsync(data).ContinueWith((task) =>
{
   if (task.IsFaulted)
   {
       foreach (var inner in task.Exception.InnerExceptions)
       {
           if (inner is FunctionsException)
           {
               var e = (FunctionsException)inner;
               var code = e.ErrorCode;
               var message = e.ToString();
               Debug.Log(message);
               Debug.Log(code);
           }
       }
   }
   else
   if (task.IsCompleted)
   {
       Debug.Log((string)task.Result.Data);
   }
});

}`

I am holding a reference to auth using: auth = FirebaseAuth.DefaultInstance; and after this I am calling my function that runs the cloud function, as you can see in the debug statement at the start of the method I getting the currentusername successfully, but after code moves to cloud function call it is giving me exception of unauthenticated:


问:
Error in mocking setState in jest(Argument of type '(init: any) => any[]' is not assignable to parameter of type '() => [unknown, Dispatch<unknown>]')
```<code>const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation((init) => [init, setState]);
</code>```
<p>##Getting error---Argument of type '(init: any) => any[]' is not assignable to parameter of type '() => [unknown, Dispatch]')##</p>

Body:
const useStateSpy = jest.spyOn(React, 'useState');
useStateSpy.mockImplementation((init) => [init, setState]);

##Getting error---Argument of type '(init: any) => any[]' is not assignable to parameter of type '() => [unknown, Dispatch]')##


问:
Puppeteer file form issue
Hi I can't accede to the input field. I have tried with id, class, name, title inserting a delay but without success.

```<code>import puppeteer from 'puppeteer';

//const puppeteer = require('puppeteer')

const preparePageForTests = async (page) => {

    // Pass the User-Agent Test.
    const userAgent = 'Mozilla/5.0 (X11; Linux x86_64)' +
      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36';
    await page.setUserAgent(userAgent);
    }

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await preparePageForTests(page);

  await page.goto('https://serviciosenlinea.bps.gub.uy/ServiciosEnLineaWeb/contenidosEmbebido?id=8782', {
    waitUntil: "networkidle0", //domcontentloaded networkidle0
  });

  await page.screenshot({
    path: 'images/skjdkjkfj.jpg'
  });

  await page.waitForSelector('[title=empresa]');
  await page.typte('[title=empresa]', 'ssddsd');

  await page.waitForSelector('#frmBasico:txtEmpresat');
  await page.typte('#frmBasico:txtEmpresat', 'ssddsd');

  await page.screenshot({
    path: 'images/screenshot11.jpg'
  });

 await page.waitForSelector('.inputAlfanumerico');
 await page.waitForSelector('#frmBasico:txtEmpresat');
 await page.type('.inputAlfanumerico', 'Noseeee');
 await page.type('#frmBasico:txtEmpresat', 'Noseeee');
 await page.screenshot({
    path: 'images/screenshot.jpg'
  });

  await page.focus('.frmBasico:txtDocumento');
  await page.keyboard.type('342323243');

  //await browser.close();
})();
</code>```

I have tried with id, class, name, title inserting a delay but without success. I can't auto complete the inputs.

Any one know how to auto complete the inputs and submit in this case??

Thanks a lot :)

Title: Puppeteer file form issue

Body:
Hi I can't accede to the input field. I have tried with id, class, name, title inserting a delay but without success.

import puppeteer from 'puppeteer';

//const puppeteer = require('puppeteer')

const preparePageForTests = async (page) => {

    // Pass the User-Agent Test.
    const userAgent = 'Mozilla/5.0 (X11; Linux x86_64)' +
      'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36';
    await page.setUserAgent(userAgent);
    }

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await preparePageForTests(page);

  await page.goto('https://serviciosenlinea.bps.gub.uy/ServiciosEnLineaWeb/contenidosEmbebido?id=8782', {
    waitUntil: "networkidle0", //domcontentloaded networkidle0
  });

  await page.screenshot({
    path: 'images/skjdkjkfj.jpg'
  });

  await page.waitForSelector('[title=empresa]');
  await page.typte('[title=empresa]', 'ssddsd');

  await page.waitForSelector('#frmBasico:txtEmpresat');
  await page.typte('#frmBasico:txtEmpresat', 'ssddsd');

  await page.screenshot({
    path: 'images/screenshot11.jpg'
  });

 await page.waitForSelector('.inputAlfanumerico');
 await page.waitForSelector('#frmBasico:txtEmpresat');
 await page.type('.inputAlfanumerico', 'Noseeee');
 await page.type('#frmBasico:txtEmpresat', 'Noseeee');
 await page.screenshot({
    path: 'images/screenshot.jpg'
  });

  await page.focus('.frmBasico:txtDocumento');
  await page.keyboard.type('342323243');

  //await browser.close();
})();

I have tried with id, class, name, title inserting a delay but without success. I can't auto complete the inputs.

Any one know how to auto complete the inputs and submit in this case??

Thanks a lot :)


问:
Clone Spring controller instance for testing purpose
Is it possible to clone an instance of a Spring @Controller in a JUnit 5 test?
I would like to do so for the following reasons :

Mocking pollutes the context for next tests and DirtiesContext has a huge impact on performance. So I don't want to use Mocks unless the modification sticks to the test class.

I would like to run tests in parallel so modifying a shared controller instance at runtime (with ReflectionUtils for example) will produce unpredictable behavior.

I don't want to set a controller as prototype as it is not the case at runtime and Spring is already wiring all dependencies.

I was thinking to inject the controller in the test class with @Autowired as usual and then making a deep copy of it with SerializationUtils like described in this post but I hope there could be a more robust approach than serializing / deserializing in every test class.

What makes tests failing in parallel mode?

The end-to-end tests are using common services. For example, I have a controller used in those two tests.

@RestController
@RequestMapping("/api/public/endpointA/")
public class SomeController {

    @Autowired
    private MyService myService;

    @GetMapping("/{id}")
    public Something getSomethingById(@PathVariable int id) {
        return myService.getSomethingById(id);
    }
}
```
<p>The first test just check the standard usage.</p>
<pre class="lang-java prettyprint-override"><code>class SomeControllerTest {

    @Autowired
    @InjectMocks
    private SomeController someController;

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            // I use some custom wrapper for the HTTP methods calls on
            // the controller like this to ease the mock mvc setup.
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }
}
</code>```

The second case test what happens when error occurs.

class SomeControllerExceptionTest {

    @Autowired
    private SomeController someController;

    @SpyBean
    private MyService myService;

    @BeforeEach
    public void before() {
        // Mock to test error case
        doThrow(RuntimeException.class).when(myService)
                .getSomethingById(anyInt());
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertThrows(
            someController.getAndParse(
                 HttpStatus.OK,
                 Something.class,
                 "/{id}",
                 1
            )
        );
    }
}
```
<p>By mocking in the second test, I'm not sure the first test won't use the mocked instance of the second test when tests are running in parallel.</p>
<hr />
<p><em>Instantiate the controller in the test method yourself, mock the dependencies inside the method and inject them in the controller.</em></p>
<p>Same situation described above but I mock on a new instance of the controller.</p>
<pre class="lang-java prettyprint-override"><code>@RestController
@RequestMapping("/api/public/endpointA/")
public class SomeController {

    @Autowired
    private MyService myService;

    @GetMapping("/{id}")
    public Something getSomethingById(@PathVariable int id) {
        return myService.getSomethingById(id);
    }
}
</code>```

Test both cases in one test.

class SomeControllerTest {

    @Autowired
    private SomeController someController;

    private SomeController someControllerMocked;

    @BeforeEach
    public void before() {
        someControllerMocked = new SomeController();
        MyService mockedService = mock(MyService.class);
        doThrow(RuntimeException.class).when(mockedService)
                .getSomethingById(anyInt());
        ReflectionTestUtils.setField(
            someControllerMocked,
            "myService",
            mockedService
        );
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }

    @Test
    void testGetSomethingByIdException() {
        Assertions.assertThrows(
            someControllerMocked.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            )
        );
    }
}
```
<p>Yes! It's working and the context is not polluted. Ok let's say I have 10 services injected in my controller actually. I will have to do <code>ReflectionUtils#setField</code> 9 times for the legacy services and 1 time for the mock. Looks a bit ugly.</p>
<hr />
<p>With AutowireCapableBeanFactory to the rescue. I've managed to clean this a little bit.</p>
<p>Same situation, but <code>SomeController</code> has 10 autowired services.</p>
<pre class="lang-java prettyprint-override"><code>class SomeControllerTest {

    @Autowired
    private SomeController someController;

    private SomeController someControllerMocked;

    @Autowired
    private AutowireCapableBeanFactory beanFactory;

    @BeforeEach
    public void before() {
        someControllerMocked = new SomeController();

        // Replace the 9 ReflectionUtils#setField calls with this
        beanFactory.autowireBean(someControllerMocked);

        MyService mockedService = mock(MyService.class);
        doThrow(RuntimeException.class).when(mockedService)
                .getSomethingById(anyInt());
        ReflectionTestUtils.setField(
            someControllerMocked,
            "myService",
            mockedService
        );
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }

    @Test
    void testGetSomethingByIdException() {
        Assertions.assertThrows(
            someControllerMocked.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            )
        );
    }
}
</code>```

I think it's the best approach I've found.

Body:
Is it possible to clone an instance of a Spring @Controller in a JUnit 5 test?
I would like to do so for the following reasons :

Mocking pollutes the context for next tests and DirtiesContext has a huge impact on performance. So I don't want to use Mocks unless the modification sticks to the test class.

I would like to run tests in parallel so modifying a shared controller instance at runtime (with ReflectionUtils for example) will produce unpredictable behavior.

I don't want to set a controller as prototype as it is not the case at runtime and Spring is already wiring all dependencies.

I was thinking to inject the controller in the test class with @Autowired as usual and then making a deep copy of it with SerializationUtils like described in this post but I hope there could be a more robust approach than serializing / deserializing in every test class.

What makes tests failing in parallel mode?

The end-to-end tests are using common services. For example, I have a controller used in those two tests.

@RestController
@RequestMapping("/api/public/endpointA/")
public class SomeController {

    @Autowired
    private MyService myService;

    @GetMapping("/{id}")
    public Something getSomethingById(@PathVariable int id) {
        return myService.getSomethingById(id);
    }
}

The first test just check the standard usage.

class SomeControllerTest {

    @Autowired
    @InjectMocks
    private SomeController someController;

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            // I use some custom wrapper for the HTTP methods calls on
            // the controller like this to ease the mock mvc setup.
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }
}

The second case test what happens when error occurs.

class SomeControllerExceptionTest {

    @Autowired
    private SomeController someController;

    @SpyBean
    private MyService myService;

    @BeforeEach
    public void before() {
        // Mock to test error case
        doThrow(RuntimeException.class).when(myService)
                .getSomethingById(anyInt());
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertThrows(
            someController.getAndParse(
                 HttpStatus.OK,
                 Something.class,
                 "/{id}",
                 1
            )
        );
    }
}

By mocking in the second test, I'm not sure the first test won't use the mocked instance of the second test when tests are running in parallel.

Instantiate the controller in the test method yourself, mock the dependencies inside the method and inject them in the controller.

Same situation described above but I mock on a new instance of the controller.

@RestController
@RequestMapping("/api/public/endpointA/")
public class SomeController {

    @Autowired
    private MyService myService;

    @GetMapping("/{id}")
    public Something getSomethingById(@PathVariable int id) {
        return myService.getSomethingById(id);
    }
}

Test both cases in one test.

class SomeControllerTest {

    @Autowired
    private SomeController someController;

    private SomeController someControllerMocked;

    @BeforeEach
    public void before() {
        someControllerMocked = new SomeController();
        MyService mockedService = mock(MyService.class);
        doThrow(RuntimeException.class).when(mockedService)
                .getSomethingById(anyInt());
        ReflectionTestUtils.setField(
            someControllerMocked,
            "myService",
            mockedService
        );
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }

    @Test
    void testGetSomethingByIdException() {
        Assertions.assertThrows(
            someControllerMocked.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            )
        );
    }
}

Yes! It's working and the context is not polluted. Ok let's say I have 10 services injected in my controller actually. I will have to do ReflectionUtils#setField 9 times for the legacy services and 1 time for the mock. Looks a bit ugly.

With AutowireCapableBeanFactory to the rescue. I've managed to clean this a little bit.

Same situation, but SomeController has 10 autowired services.

class SomeControllerTest {

    @Autowired
    private SomeController someController;

    private SomeController someControllerMocked;

    @Autowired
    private AutowireCapableBeanFactory beanFactory;

    @BeforeEach
    public void before() {
        someControllerMocked = new SomeController();

        // Replace the 9 ReflectionUtils#setField calls with this
        beanFactory.autowireBean(someControllerMocked);

        MyService mockedService = mock(MyService.class);
        doThrow(RuntimeException.class).when(mockedService)
                .getSomethingById(anyInt());
        ReflectionTestUtils.setField(
            someControllerMocked,
            "myService",
            mockedService
        );
    }

    @Test
    void testGetSomethingById() {
        Assertions.assertEquals(
            1,
            someController.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            ).getId()
        );
    }

    @Test
    void testGetSomethingByIdException() {
        Assertions.assertThrows(
            someControllerMocked.getAndParse(
                HttpStatus.OK,
                Something.class,
                "/{id}",
                1
            )
        );
    }
}

I think it's the best approach I've found.


问:
python pairing family with scipy
following
Python algorithm with numpy

```<code>import numpy as np
from scipy import sparse
import collections
from scipy.sparse import csgraph

maxdist = 2.
pairings=((1,2),(1,4),(3,2),(3,10),(6,2),(5,8),(5,4),(5,3),(7,10),(7,11),(8,7),(20,21),(20,22))

pairings = np.array(pairings)
node_to_id = np.unique(np.sort(np.ravel(pairings)))
id_to_node = {id_: node for node, id_ in enumerate(node_to_id)}
n_nodes = len(node_to_id)
dok_mat = sparse.dok_matrix((n_nodes, n_nodes), dtype=bool)
for left, right in pairings:
    row, col = id_to_node[left], id_to_node[right]
    dok_mat[row, col] = True
    dok_mat[col, row] = True # undirected graph
csr_mat = dok_mat.tocsr()
del dok_mat
_, components = csgraph.connected_components(csr_mat)
families = collections.defaultdict(list)
for id_, component in zip(node_to_id, components):
    families[component].append(id_)

print("families", list(families.values()))

shortest_paths = csgraph.shortest_path(csr_mat)
for id_, row in zip(node_to_id, shortest_paths):
    immediate_family = node_to_id[row <= maxdist]
    print(id_, "  -  ",immediate_family,"family")
</code>```

Hi again,

I've been running this code now for a while and it works.
But I noticed that there's room for improvement.
Now the maxdist is set to 2, but it will start at pairing (1,2) so the last won't be in this family.

When it is started on 3 pairing they are all family based on the maxdist of 2.

Is there a way to avoid this issue by giving the best possible family combination based on the maxdist?

I ran above code, and I need to get the best family. Based on the pairings and maxdist=2 they should all be family when starting with the 3 pairs.

OUTPUT maxdist=2:

```<code>families [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11], [20, 21, 22]]
1   -   [1 2 3 4 5 6] family
2   -   [ 1  2  3  4  5  6 10] family
3   -   [ 1  2  3  4  5  6  7  8 10] family
4   -   [1 2 3 4 5 8] family
5   -   [ 1  2  3  4  5  7  8 10] family
6   -   [1 2 3 6] family
7   -   [ 3  5  7  8 10 11] family
8   -   [ 3  4  5  7  8 10 11] family
10   -   [ 2  3  5  7  8 10 11] family
11   -   [ 7  8 10 11] family
20   -   [20 21 22] family
21   -   [20 21 22] family
22   -   [20 21 22] family
</code>```

family member 3 has the biggest family based on de maxdist=2, so all other members should have that family.
If the family is equally big take the smallest number.

so number 11 will be lonely sheep.

EXPECTED OUTPUT maxdist=2:

```<code>families [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11], [20, 21, 22]]
1   -   [ 1  2  3  4  5  6  7  8 10] family
2   -   [ 1  2  3  4  5  6  7  8 10] family
3   -   [ 1  2  3  4  5  6  7  8 10] family
4   -   [ 1  2  3  4  5  6  7  8 10] family
5   -   [ 1  2  3  4  5  6  7  8 10] family
6   -   [ 1  2  3  4  5  6  7  8 10] family
7   -   [ 1  2  3  4  5  6  7  8 10] family
8   -   [ 1  2  3  4  5  6  7  8 10] family
10   -   [ 1  2  3  4  5  6  7  8 10] family
11   -   [ 11] family
20   -   [20 21 22] family
21   -   [20 21 22] family
22   -   [20 21 22] family
</code>```

EXPECTED OUTPUT maxdist=3:

```<code>families [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11], [20, 21, 22]]
1   -   [ 1  2  3  4  5  6  7  8 10 11] family
2   -   [ 1  2  3  4  5  6  7  8 10 11] family
3   -   [ 1  2  3  4  5  6  7  8 10 11] family
4   -   [ 1  2  3  4  5  6  7  8 10 11] family
5   -   [ 1  2  3  4  5  6  7  8 10 11] family
6   -   [ 1  2  3  4  5  6  7  8 10 11] family
7   -   [ 1  2  3  4  5  6  7  8 10 11] family
8   -   [ 1  2  3  4  5  6  7  8 10 11] family
10   -   [ 1  2  3  4  5  6  7  8 10 11] family
11   -   [ 1  2  3  4  5  6  7  8 10 11] family
20   -   [20 21 22] family
21   -   [20 21 22] family
22   -   [20 21 22] family
</code>```

*edit made the example pairing better

Title: python pairing family with scipy

Body:
following
Python algorithm with numpy

import numpy as np
from scipy import sparse
import collections
from scipy.sparse import csgraph

maxdist = 2.
pairings=((1,2),(1,4),(3,2),(3,10),(6,2),(5,8),(5,4),(5,3),(7,10),(7,11),(8,7),(20,21),(20,22))

pairings = np.array(pairings)
node_to_id = np.unique(np.sort(np.ravel(pairings)))
id_to_node = {id_: node for node, id_ in enumerate(node_to_id)}
n_nodes = len(node_to_id)
dok_mat = sparse.dok_matrix((n_nodes, n_nodes), dtype=bool)
for left, right in pairings:
    row, col = id_to_node[left], id_to_node[right]
    dok_mat[row, col] = True
    dok_mat[col, row] = True # undirected graph
csr_mat = dok_mat.tocsr()
del dok_mat
_, components = csgraph.connected_components(csr_mat)
families = collections.defaultdict(list)
for id_, component in zip(node_to_id, components):
    families[component].append(id_)

print("families", list(families.values()))

shortest_paths = csgraph.shortest_path(csr_mat)
for id_, row in zip(node_to_id, shortest_paths):
    immediate_family = node_to_id[row <= maxdist]
    print(id_, "  -  ",immediate_family,"family")

Hi again,

I've been running this code now for a while and it works.
But I noticed that there's room for improvement.
Now the maxdist is set to 2, but it will start at pairing (1,2) so the last won't be in this family.

When it is started on 3 pairing they are all family based on the maxdist of 2.

Is there a way to avoid this issue by giving the best possible family combination based on the maxdist?

I ran above code, and I need to get the best family. Based on the pairings and maxdist=2 they should all be family when starting with the 3 pairs.

OUTPUT maxdist=2:

families [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11], [20, 21, 22]]
1   -   [1 2 3 4 5 6] family
2   -   [ 1  2  3  4  5  6 10] family
3   -   [ 1  2  3  4  5  6  7  8 10] family
4   -   [1 2 3 4 5 8] family
5   -   [ 1  2  3  4  5  7  8 10] family
6   -   [1 2 3 6] family
7   -   [ 3  5  7  8 10 11] family
8   -   [ 3  4  5  7  8 10 11] family
10   -   [ 2  3  5  7  8 10 11] family
11   -   [ 7  8 10 11] family
20   -   [20 21 22] family
21   -   [20 21 22] family
22   -   [20 21 22] family

family member 3 has the biggest family based on de maxdist=2, so all other members should have that family.
If the family is equally big take the smallest number.

so number 11 will be lonely sheep.

EXPECTED OUTPUT maxdist=2:

families [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11], [20, 21, 22]]
1   -   [ 1  2  3  4  5  6  7  8 10] family
2   -   [ 1  2  3  4  5  6  7  8 10] family
3   -   [ 1  2  3  4  5  6  7  8 10] family
4   -   [ 1  2  3  4  5  6  7  8 10] family
5   -   [ 1  2  3  4  5  6  7  8 10] family
6   -   [ 1  2  3  4  5  6  7  8 10] family
7   -   [ 1  2  3  4  5  6  7  8 10] family
8   -   [ 1  2  3  4  5  6  7  8 10] family
10   -   [ 1  2  3  4  5  6  7  8 10] family
11   -   [ 11] family
20   -   [20 21 22] family
21   -   [20 21 22] family
22   -   [20 21 22] family

EXPECTED OUTPUT maxdist=3:

families [[1, 2, 3, 4, 5, 6, 7, 8, 10, 11], [20, 21, 22]]
1   -   [ 1  2  3  4  5  6  7  8 10 11] family
2   -   [ 1  2  3  4  5  6  7  8 10 11] family
3   -   [ 1  2  3  4  5  6  7  8 10 11] family
4   -   [ 1  2  3  4  5  6  7  8 10 11] family
5   -   [ 1  2  3  4  5  6  7  8 10 11] family
6   -   [ 1  2  3  4  5  6  7  8 10 11] family
7   -   [ 1  2  3  4  5  6  7  8 10 11] family
8   -   [ 1  2  3  4  5  6  7  8 10 11] family
10   -   [ 1  2  3  4  5  6  7  8 10 11] family
11   -   [ 1  2  3  4  5  6  7  8 10 11] family
20   -   [20 21 22] family
21   -   [20 21 22] family
22   -   [20 21 22] family

*edit made the example pairing better


问:
react-native-permissions: does request() automatically get called in permission flow?
I'm reading the documentation for react-native-permissions and I'm looking at the flow chart in Understanding Permission Flow. In the iOS flow, it says that once you call check(), if the permissions is requestable, it returns RESULTS.DENIED. It then points to request(). Does this mean that request() is automatically called? Or is it just telling us what will happen if we then do call request()?


问:
Why is the picture not hidden under the container?
I do drag and drop on the image by assigning absolute positioning to the image. But when dragging an image, it goes beyond the viewing-area. I assigned it overflow: auto, that is, scrolling should appear, but the image just pops out. How to hide an image under the viewing-area when it goes beyond it?

https://jsfiddle.net/jakLc1wx/

```<code><div class="viewing-area"></div>
<form name="insert_image">
    <input type="file" name="file" class="file-input" placeholder="">
    <input type="url" name="url" class="url-input" placeholder="https://example.com">
    <input type="button" name="submit" value="Добавить" class="submit">
    <input type="button" name="submit2" value="Добавить (файлом)" class="submit2">
</form>
</code>```
```<code>body {
  background: linear-gradient(72.21deg, #141812 -0.34%, #161422 28.25%, #1C0D0D 68.52%, #1A0623 96.34%);
  height: 100vh;
}

.viewing-area {
  width: 842px;
  height: 553px;
  background: white;

  border: 6px solid #4D4C4C;
  border-radius: 15px;
  overflow: auto;

  img {
    max-width: 80%;
    max-height: 80%;
  }
}

input[type="file"] {
  color: white;
}
</code>```
```<code>let insert_image = document.forms.insert_image;
let url_input = document.querySelector('.url-input');
let file_input = document.querySelector('.file-input');
let submit = document.querySelector('.submit');
let viewing_area = document.querySelector('.viewing-area');
let submit2 = document.querySelector('.submit2');

function dragImage (event) {
    let image = event.target;
    let shiftX = event.clientX - image.getBoundingClientRect().left;
    let shiftY = event.clientY - image.getBoundingClientRect().top;
    let width = image.getBoundingClientRect().width;
    let height = image.getBoundingClientRect().height;

    image.style.position = 'absolute';
    image.style.maxWidth = width + 'px';
    image.style.maxHeight = height + 'px';

    moveAt(event.pageX, event.pageY);

    function moveAt(pageX, pageY) {
        image.style.left = pageX - shiftX + 'px';
        image.style.top = pageY - shiftY + 'px';
    }

    function onMouseMove(event) {
        moveAt(event.pageX, event.pageY);
    }

    viewing_area.addEventListener('mousemove', onMouseMove);

    image.onmouseup = function() {
        viewing_area.removeEventListener('mousemove', onMouseMove);
        image.onmouseup = null;
    };

}

function insertByUrl(event) {
    let image = document.createElement('img');
    image.src = url_input.value;
    viewing_area.append(image);
    image.ondragstart = function () {
        return false;
    };
    image.addEventListener('mousedown', dragImage);
}

function insertByFile() {
    let image = document.createElement('img');
    let file = file_input.files[0];
    let fileReader = new FileReader();

    fileReader.readAsDataURL(file);

    fileReader.onload = function () {
        image.src = fileReader.result;
    }

    viewing_area.append(image);

    image.ondragstart = function () {
        return false;
    };
    image.addEventListener('mousedown', dragImage);
}

submit.addEventListener('click', insertByUrl);
submit2.addEventListener('click', insertByFile);
</code>```

I tried to use z-index but it didn't work out. Perhaps it's the positioning of the parent, or its z-index

Body:
I do drag and drop on the image by assigning absolute positioning to the image. But when dragging an image, it goes beyond the viewing-area. I assigned it overflow: auto, that is, scrolling should appear, but the image just pops out. How to hide an image under the viewing-area when it goes beyond it?

https://jsfiddle.net/jakLc1wx/

<form name="insert_image">
    <input type="file" name="file" class="file-input" placeholder="">
    <input type="url" name="url" class="url-input" placeholder="https://example.com">
    <input type="button" name="submit" value="Добавить" class="submit">
    <input type="button" name="submit2" value="Добавить (файлом)" class="submit2">
</form>

body {
  background: linear-gradient(72.21deg, #141812 -0.34%, #161422 28.25%, #1C0D0D 68.52%, #1A0623 96.34%);
  height: 100vh;
}

.viewing-area {
  width: 842px;
  height: 553px;
  background: white;

  border: 6px solid #4D4C4C;
  border-radius: 15px;
  overflow: auto;

  img {
    max-width: 80%;
    max-height: 80%;
  }
}

input[type="file"] {
  color: white;
}

let insert_image = document.forms.insert_image;
let url_input = document.querySelector('.url-input');
let file_input = document.querySelector('.file-input');
let submit = document.querySelector('.submit');
let viewing_area = document.querySelector('.viewing-area');
let submit2 = document.querySelector('.submit2');

function dragImage (event) {
    let image = event.target;
    let shiftX = event.clientX - image.getBoundingClientRect().left;
    let shiftY = event.clientY - image.getBoundingClientRect().top;
    let width = image.getBoundingClientRect().width;
    let height = image.getBoundingClientRect().height;

    image.style.position = 'absolute';
    image.style.maxWidth = width + 'px';
    image.style.maxHeight = height + 'px';

    moveAt(event.pageX, event.pageY);

    function moveAt(pageX, pageY) {
        image.style.left = pageX - shiftX + 'px';
        image.style.top = pageY - shiftY + 'px';
    }

    function onMouseMove(event) {
        moveAt(event.pageX, event.pageY);
    }

    viewing_area.addEventListener('mousemove', onMouseMove);

    image.onmouseup = function() {
        viewing_area.removeEventListener('mousemove', onMouseMove);
        image.onmouseup = null;
    };

}

function insertByUrl(event) {
    let image = document.createElement('img');
    image.src = url_input.value;
    viewing_area.append(image);
    image.ondragstart = function () {
        return false;
    };
    image.addEventListener('mousedown', dragImage);
}

function insertByFile() {
    let image = document.createElement('img');
    let file = file_input.files[0];
    let fileReader = new FileReader();

    fileReader.readAsDataURL(file);

    fileReader.onload = function () {
        image.src = fileReader.result;
    }

    viewing_area.append(image);

    image.ondragstart = function () {
        return false;
    };
    image.addEventListener('mousedown', dragImage);
}

submit.addEventListener('click', insertByUrl);
submit2.addEventListener('click', insertByFile);

I tried to use z-index but it didn't work out. Perhaps it's the positioning of the parent, or its z-index


问:
Conditional Random Fields and the Label Bias Problem
I was reading this paper about conditional random fields and was confused by the "label bias problem" mentioned in the paper.  I've looked online for some explanations of it but still don't feel like I have a good grasp of the issue. What exactly is the label bias problem? Can someone provide a clear example of it and why it is bad? </p>

ContentLicense: CC BY-SA 3.0


问:
react-table : How can I keep visible globalFilteredRows after editing my data?
I'm using v7 of react-table.

My issue is I have can set global filter but when i update my data it shows all my data and don't keep my filtered data.

How can I keep my filtered data visible when i want to update my react-table data?

```<code>const TableSearchFilter = ({ preGlobalFilteredRows, globalFilter, setGlobalFilter }) => {
    const count = preGlobalFilteredRows.length

    return (
        <div style={{ textAlign: "right", marginBottom: '10px' }}>
            <MaterialUI.FormControl sx={{ m: 1, width: '250px' }} variant="outlined">
                <MaterialUI.Input
                    sx={{ fontSize :'12px' }}
                    value={globalFilter || ""}
                    onKeyDown={(e) => {
                        if (e.keyCode ==13) {
                            e.preventDefault()
                        }
                    }}
                    onChange={(e) => {
                        setGlobalFilter(e.target.value)
                    }}
                    startAdornment={<i className="fas fa-search" style={{ marginRight:'10px' }}></i>}
                    placeholder={`${count} référence${count > 0 ? 's' : ''}`}
                />
            </MaterialUI.FormControl>
        </div>
    )
}
</code>```

in my app.js

```<code><Table columns={columns} data={data}  />
</code>```

Body:
I'm using v7 of react-table.

My issue is I have can set global filter but when i update my data it shows all my data and don't keep my filtered data.

How can I keep my filtered data visible when i want to update my react-table data?

const TableSearchFilter = ({ preGlobalFilteredRows, globalFilter, setGlobalFilter }) => {
    const count = preGlobalFilteredRows.length

    return (

            <MaterialUI.FormControl sx={{ m: 1, width: '250px' }} variant="outlined">
                <MaterialUI.Input
                    sx={{ fontSize :'12px' }}
                    value={globalFilter || ""}
                    onKeyDown={(e) => {
                        if (e.keyCode ==13) {
                            e.preventDefault()
                        }
                    }}
                    onChange={(e) => {
                        setGlobalFilter(e.target.value)
                    }}
                    startAdornment={}
                    placeholder={`${count} référence${count > 0 ? 's' : ''}`}
                />
            </MaterialUI.FormControl>

    )
}

in my app.js


问:
How to Search for data in Firebase android studio
I have an algorithm looking for Firebase data but it doesn't work and records an error to me, I want to register into Edittext Value and it will bring me the appropriate card
I use the recylerView

```<code>recyclerView= findViewById(R.id.recycleview);
getmRootFLY = FirebaseDatabase.getInstance().getReference("FLY");
list = new ArrayList<>();
arrayList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
getmRootFLY.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot dataSnapshot: snapshot.getChildren())
        {
            Fly fly = dataSnapshot.getValue(Fly.class);
            list.add(fly);
        }
        myAdapter.notifyDataSetChanged();
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});
databaseReference = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("First Name");
mRootRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String name = dataSnapshot.getValue().toString();
        TextView myLoginTextFromDB = (TextView)findViewById(R.id.hello_name_from_db);
        myLoginTextFromDB.setText(name);

    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) {
    }
});
EditText editTextTextPersonName = (EditText) findViewById(R.id.editTextTextPersonName);
editTextTextPersonName.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }
    @Override
    public void afterTextChanged(Editable editable) {
        Query query = databaseReference.child("FLY").equalTo(editable.toString());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                {
                    list.clear();
                    for (DataSnapshot dss: snapshot.getChildren())
                    {
                        final Fly fly = dss.getValue(Fly.class);
                        list.add(fly);
                    }
                    MyAdapter myAdapter1 = new MyAdapter(getApplicationContext(),list);
                    recyclerView.setAdapter(myAdapter1);
                    myAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
});
</code>```

}

It is important to note Getmrootfly adds the card to the array and basically shows me the data available in Firebase

And all code that appears as an edittexttexteonname is a code that needs to look for the data

Body:
I have an algorithm looking for Firebase data but it doesn't work and records an error to me, I want to register into Edittext Value and it will bring me the appropriate card
I use the recylerView

recyclerView= findViewById(R.id.recycleview);
getmRootFLY = FirebaseDatabase.getInstance().getReference("FLY");
list = new ArrayList<>();
arrayList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
getmRootFLY.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot) {
        for (DataSnapshot dataSnapshot: snapshot.getChildren())
        {
            Fly fly = dataSnapshot.getValue(Fly.class);
            list.add(fly);
        }
        myAdapter.notifyDataSetChanged();
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) {

    }
});
databaseReference = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("First Name");
mRootRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        String name = dataSnapshot.getValue().toString();
        TextView myLoginTextFromDB = (TextView)findViewById(R.id.hello_name_from_db);
        myLoginTextFromDB.setText(name);

    }
    @Override
    public void onCancelled(@NonNull DatabaseError error) {
    }
});
EditText editTextTextPersonName = (EditText) findViewById(R.id.editTextTextPersonName);
editTextTextPersonName.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }
    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }
    @Override
    public void afterTextChanged(Editable editable) {
        Query query = databaseReference.child("FLY").equalTo(editable.toString());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                {
                    list.clear();
                    for (DataSnapshot dss: snapshot.getChildren())
                    {
                        final Fly fly = dss.getValue(Fly.class);
                        list.add(fly);
                    }
                    MyAdapter myAdapter1 = new MyAdapter(getApplicationContext(),list);
                    recyclerView.setAdapter(myAdapter1);
                    myAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
});

}

It is important to note Getmrootfly adds the card to the array and basically shows me the data available in Firebase

And all code that appears as an edittexttexteonname is a code that needs to look for the data


问:
Grab does not download dependency in soap ui
I am trying to download a dependency via @Grab in SOAP UI, running the below script

```<code>@Grab('com.xlson.groovycsv:groovycsv:1.3')
import static com.xlson.groovycsv.CsvParser.parseCsv

def csv = '''Name,Lastname
Mark,Andersson
Pete,Hansen'''

def data = parseCsv(csv)
for(line in data) {
    println "$line.Name $line.Lastname"
}
</code>```

I am getting this error

Here are the JAR's I am using in SOAP UI ext folder

What is the problem and how do you fix this so that Grab downloads the dependencies.

```<code>Groovy Version: 4.0.6
</code>```

Body:
I am trying to download a dependency via @Grab in SOAP UI, running the below script

@Grab('com.xlson.groovycsv:groovycsv:1.3')
import static com.xlson.groovycsv.CsvParser.parseCsv

def csv = '''Name,Lastname
Mark,Andersson
Pete,Hansen'''

def data = parseCsv(csv)
for(line in data) {
    println "$line.Name $line.Lastname"
}

I am getting this error

Here are the JAR's I am using in SOAP UI ext folder

What is the problem and how do you fix this so that Grab downloads the dependencies.

Groovy Version: 4.0.6


问:
How to "Load Statistics from File" for Raster Supervised Classification in QGIS with SAGA extension
I'm working on bark-beetle outbreaks in the Alpine forests. To do so, I work on UAV-acquired orthophotos with multispectral bands (RGB, NIR, RE). I want to proceed to a raster (VRT) supervised classification, according to field-acquired ROIs.

I successfully did this using SAGA GUI. I'm now trying to repeat the same process but with using QGIS, as I have all my working layers sorted in a project. I want to get the same supervised classification with the built-in SAGA extension, but the algorithm asks here (but not in SAGA GUI) for a mandatory "Load Statistics from File" parameter.

How do I have to set this parameter?

By reading SAGA documentation, I saw it should be the path to the stats file (about my raster to classify?), but no further informations were provided about the content of this stats file. I don't know how to create it, nor if there is a way to create it using QGIS or SAGA GUI.
Neither did I find help about this in the SAGA documentation or somewhere else on internet.


问:
Adding a whole new color-template(range) to bootstrap
I'm trying to add a whole new colour scheme to bootstrap5. As of right now I was able to add a single primary colour, yet I want to add one new primary colour and sub-colours.

I created a new .scss file, and wrote the following (imports omitted, code works)

```<code>$custom-theme-colors: (

    "brand": #4F46E5,
    "neutral": #4B5563,

);

$theme-colors: map-merge($map1: $custom-theme-colors, $map2: $theme-colors );
</code>```

But I want to  create something like how it is in _variables.scss, a whole schema.

```<code>
$brand-900: #312E81;
$brand-800: #3730A3;
$brand-700: #4338CA;
$brand-600: #4F46E5;
$brand-500: #6366F1;
$brand-400: #818CF8;
$brand-300: #A5B4FC;
$brand-200: #C7D2FE;
$brand-100: #E0E7FF;
$brand-50: #EEF2FF;

$brand: (
"brand-100": $brand-100,
"brand-200": $brand-200,
"brand-300": $brand-300,
"brand-400": $brand-400,
"brand-500": $brand-500,
"brand-600": $brand-600,
"brand-700": $brand-700,
"brand-800": $brand-800,
"brand-900": $brand-900 );

</code>```

Thanks in advance :)

Body:
I'm trying to add a whole new colour scheme to bootstrap5. As of right now I was able to add a single primary colour, yet I want to add one new primary colour and sub-colours.

I created a new .scss file, and wrote the following (imports omitted, code works)

$custom-theme-colors: (

    "brand": #4F46E5,
    "neutral": #4B5563,

);

$theme-colors: map-merge($map1: $custom-theme-colors, $map2: $theme-colors );

But I want to  create something like how it is in _variables.scss, a whole schema.

$brand-900: #312E81;
$brand-800: #3730A3;
$brand-700: #4338CA;
$brand-600: #4F46E5;
$brand-500: #6366F1;
$brand-400: #818CF8;
$brand-300: #A5B4FC;
$brand-200: #C7D2FE;
$brand-100: #E0E7FF;
$brand-50: #EEF2FF;

$brand: (
"brand-100": $brand-100,
"brand-200": $brand-200,
"brand-300": $brand-300,
"brand-400": $brand-400,
"brand-500": $brand-500,
"brand-600": $brand-600,
"brand-700": $brand-700,
"brand-800": $brand-800,
"brand-900": $brand-900 );

Thanks in advance :)


问:
Secret Santa generator with IF condition
I´m new at this, trying to make in python a secret santa generator, but i want to make condition that some family members cant give to each other (Example : parents and own children | only gift other relatives)
I have some code and it does the random generation, but I can´t make the condition that I want.

Can someone help?

```<code>def Santa(names, draw):
  matches= []
  while names:
    giver = names.pop() #chooses giver and removes name
    receiver = random.choice(draw) #picks random to receive

    if giver != receiver:
      matches.append([giver, receiver]) #adds pair
      draw.remove(receiver) #removes person from receiving list
      if giver
    else:
      names.append(giver) #if names are the same, adds name back to list
  return matches

family1=['Carlos', 'Minda', 'Ana', 'Catarina']
family2=['Paulo','Alexandre','Luquinhas']
family3=['Ivone','Lucas','Susana','Pedro']
family4=['Tia Ângela','Mãezinha Avó']

</code>```

Body:
I´m new at this, trying to make in python a secret santa generator, but i want to make condition that some family members cant give to each other (Example : parents and own children | only gift other relatives)
I have some code and it does the random generation, but I can´t make the condition that I want.

Can someone help?

def Santa(names, draw):
  matches= []
  while names:
    giver = names.pop() #chooses giver and removes name
    receiver = random.choice(draw) #picks random to receive

    if giver != receiver:
      matches.append([giver, receiver]) #adds pair
      draw.remove(receiver) #removes person from receiving list
      if giver
    else:
      names.append(giver) #if names are the same, adds name back to list
  return matches

family1=['Carlos', 'Minda', 'Ana', 'Catarina']
family2=['Paulo','Alexandre','Luquinhas']
family3=['Ivone','Lucas','Susana','Pedro']
family4=['Tia Ângela','Mãezinha Avó']


问:
Configure WCF service in Azure Container Apps
I'm trying to deploy a WCF service implemented using CoreWCF + .NET 6 to Azure Container Apps exposing https endpoints from a linux container.

I try the same service using http protocol and everything work correctly.

I also expose a gRPC service, but the difference with WCF is the binding configuration. WCF needs to set up the same protocol schema for both client and server. So I suppose it's not possible redirect an https request to a container that expose a WCF service on the port 80. This can be done with REST or gRPC service instead.

I enable ingress in Azure Container Apps and set the port 443. When I try the http endpoint I set the port 80 instead.

The binding of the WCF is BasicHttpBinding with security mode Transport. When i try the http endpoint I set security mode None.

In the dockefile I expose port 80 and 443.

On my local machine I'm able to get thing work because i can use a self signed certificate, but in a production enviroment this doesn't seems to work. I deploy the self signed certificate with the container image, but maybe there isn't a certification authority that can trust this certificate.

I read that for Azure Container Instance it's possible to configure https running Ngix in a sidecar container. But in this case the request is redirected internally on port 80 and so it doesn't work for me.

What can i do for get my service work over https?