问:
How do I unit test if http request has been canceled using HttpTestingClientModule?
My component is invoking the method to get data from the server, it happens in ngOnInit lifecycle of the component. The request takes some time, and the user can navigate away from current view and destroy the component. In such a case, the get data request should be canceled. And this is what happens in actual application.

Image of cancelled request in network tab

Now my goal is to unit test this behavior. What approach should I take? My current implementation is pretty naive and doesn't work...

What should I do in order to simulate request cancellation?

Here's my approach:

Component class:

```<code>@Component({
    ...
    providers: [ProjectsOverviewService] <-- Lifecycle of service depends on component
    ...
})
export class ProjectsOverviewComponent implements OnInit {
    constructor(private projectsOverviewService: ProjectsOverviewService) {}

    ngOnInit() {
        this.projectsOverviewService.getSomeData();
    }
}
</code>```

Service class:

```<code>@Injectable()
export class ProjectsOverviewService implements OnDestroy {
    private someData: Data;
    private serviceDestroyed$ = new Subject();

    constructor(private projectPageService: ProjectPageService) {}

    ngOnDestroy() {
        this.serviceDestroyed$.next();
    }

    getSomeData() {
        this.projectPageService.projectsGetAll$
        .pipe(takeUntil(this.serviceDestroyed$))
        .subscribe(data => this.someData = data);
    }
}
</code>```

Spec file:

```<code>let component: ProjectsOverviewComponent;
let fixture: ComponentFixture<ProjectsOverviewComponent>;
let httpTestingController: HttpTestingController;

beforeEach(async () => {
    await TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule
        ],
        declarations: [ProjectsOverviewComponent],
        providers: [ProjectsServiceProxy]
    }).compileComponents();
});

beforeEach(() => {
    fixture = TestBed.createComponent(ProjectsOverviewComponent);
    component = fixture.componentInstance;
    httpTestingController = TestBed.inject(HttpTestingController);
    fixture.detectChanges();
});

it('should cancel get some data request when component is destroyed', () => {
    const req = httpTestingController.expectOne('/api/services/app/Projects/GetAll');

    console.log(req); // TestRequest

    component.ngOnDestroy();

    expect(req.cancelled).toBe(true); // Fails - expected false, to be true.
});
</code>```

Body:
My component is invoking the method to get data from the server, it happens in ngOnInit lifecycle of the component. The request takes some time, and the user can navigate away from current view and destroy the component. In such a case, the get data request should be canceled. And this is what happens in actual application.

Image of cancelled request in network tab

Now my goal is to unit test this behavior. What approach should I take? My current implementation is pretty naive and doesn't work...

What should I do in order to simulate request cancellation?

Here's my approach:

Component class:

@Component({
    ...
    providers: [ProjectsOverviewService] <-- Lifecycle of service depends on component
    ...
})
export class ProjectsOverviewComponent implements OnInit {
    constructor(private projectsOverviewService: ProjectsOverviewService) {}

    ngOnInit() {
        this.projectsOverviewService.getSomeData();
    }
}

Service class:

@Injectable()
export class ProjectsOverviewService implements OnDestroy {
    private someData: Data;
    private serviceDestroyed$ = new Subject();

    constructor(private projectPageService: ProjectPageService) {}

    ngOnDestroy() {
        this.serviceDestroyed$.next();
    }

    getSomeData() {
        this.projectPageService.projectsGetAll$
        .pipe(takeUntil(this.serviceDestroyed$))
        .subscribe(data => this.someData = data);
    }
}

Spec file:

let component: ProjectsOverviewComponent;
let fixture: ComponentFixture<ProjectsOverviewComponent>;
let httpTestingController: HttpTestingController;

beforeEach(async () => {
    await TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule
        ],
        declarations: [ProjectsOverviewComponent],
        providers: [ProjectsServiceProxy]
    }).compileComponents();
});

beforeEach(() => {
    fixture = TestBed.createComponent(ProjectsOverviewComponent);
    component = fixture.componentInstance;
    httpTestingController = TestBed.inject(HttpTestingController);
    fixture.detectChanges();
});

it('should cancel get some data request when component is destroyed', () => {
    const req = httpTestingController.expectOne('/api/services/app/Projects/GetAll');

    console.log(req); // TestRequest

    component.ngOnDestroy();

    expect(req.cancelled).toBe(true); // Fails - expected false, to be true.
});


来源: stackexchange

问:
How to skip / ignore files with ydiff?
How can I exclude certain files / globs when using ydiff? It gives the best side-by-side view, but has no option to ignore / skip certain files.</p>

ContentLicense: CC BY-SA 4.0

Title: How to skip / ignore files with ydiff?


问:
Cannot access 'Directive' before initialization when exported in index.ts
When I export my Directive in the index.ts i get the Cannot "access 'SomeDirective' before initialization" error.
When I import the Directive normally the code works.

I have a BaseDirective

```<code>export class BaseDirective implements OnInit {

  protected baseModel: BaseModel =
  { id: '', type: Type.Undefined };

  ngOnInit(): void {
    // do base stuff
  }

  protected baseFunction() {
    console.log('gets overwritten');
  }

}
</code>```

And the Second directive extending it

```<code>export class SomeDirective extends BaseDirective {

  protected customerDetailsService = inject(CustomerDetailsService);

  constructor() {
    super();
  }

  protected override baseFunction(): void {
    // do something
  }

}
</code>```

the index.ts looks like this

```<code>export * from './base/base.directive';
export * from './some/some.directive';
export * from './base/base.model';
</code>```

When I try to use the SomeDirective in a Component extend and import it via
@directives/index i get the error.
But via
import { SomeDirective } from '@directives/some/some.directive';
it works fine

I am using the standalone approach so there is no module in the project.
Every Component and Directive has the 'standalone': true flag.

I don't understand what the index.ts has to do with initialization. All I found so far was that the error is linked to circular dependency but since I don't use modules I doubt that that is the case

Body:
When I export my Directive in the index.ts i get the Cannot "access 'SomeDirective' before initialization" error.
When I import the Directive normally the code works.

I have a BaseDirective

export class BaseDirective implements OnInit {

  protected baseModel: BaseModel =
  { id: '', type: Type.Undefined };

  ngOnInit(): void {
    // do base stuff
  }

  protected baseFunction() {
    console.log('gets overwritten');
  }

}

And the Second directive extending it

export class SomeDirective extends BaseDirective {

  protected customerDetailsService = inject(CustomerDetailsService);

  constructor() {
    super();
  }

  protected override baseFunction(): void {
    // do something
  }

}

the index.ts looks like this

export * from './base/base.directive';
export * from './some/some.directive';
export * from './base/base.model';

When I try to use the SomeDirective in a Component extend and import it via
@directives/index i get the error.
But via
import { SomeDirective } from '@directives/some/some.directive';
it works fine

I am using the standalone approach so there is no module in the project.
Every Component and Directive has the 'standalone': true flag.

I don't understand what the index.ts has to do with initialization. All I found so far was that the error is linked to circular dependency but since I don't use modules I doubt that that is the case


问:
Flutter - package exists in pubspec.yaml file but doesn't exist in External Packages folder
I'm using a forked package from github with this link : https://github.com/iManar33/flutter-gallery-package

I added the package to a different project and it was working correctly and every update of the package was installed correctly.

When I push an edit on my forked package, I usually delete pubspec.lock in my project then I do flutter pub get then run (maybe stop. and run).

Today,I pushed an edit on my forked package and I did the same of what I do usually in this case ,but the update was not installed.

I then deleted the whole package form dart Packages folder in my project but it was never reinstalled.

I tried adding the package manually to the folder that has all the installed dart Packages of my project in finder, but still can't find the package in the project :(

P.S: I'm using Android Studio


问:
How to extract tables from Excel worksheet?
I am trying to extract table from Excel worksheet (table is present in the worksheet) according to this tutorial: https://samukweku.github.io/data-wrangling-blog/spreadsheet/python/pandas/openpyxl/2020/05/19/Access-Tables-In-Excel.html

My Excel worksheet:

enter image description here

My code:

```<code>import openpyxl

workbook = openpyxl.load_workbook('my_excel.xlsx')
my_worksheet = workbook['my_worksheet']
print(my_worksheet._tables)
print(my_worksheet.tables.items())
</code>```

Unfortunately I receive an error:

```<code>Exception has occurred: AttributeError
'Worksheet' object has no attribute 'tables'
  File "C:\Users\user\TRAINING\main.py", line 6, in <module>
    print(my_worksheet.tables)
</code>```

However my_worksheet._tables gives me a list of all tables in the worksheet where my table is included:

```<code>[<openpyxl.worksheet.table.Table object>
Parameters:
id=1, name='Table1', displayName='Table1', comment=None, ref='A1:C3', tableType=None, headerRowCount=1, insertRow=None, insertRowShift=None, totalsRowCount=None, totalsRowShown=False, published=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowBorderDxfId=None, tableBorderDxfId=None, totalsRowBorderDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, connectionId=None, autoFilter=<openpyxl.worksheet.filters.AutoFilter object>
Parameters:
ref='A1:C3', filterColumn=[], sortState=None, sortState=None, tableColumns=[<openpyxl.worksheet.table.TableColumn object>
Parameters:
id=1, uniqueName=None, name='A', totalsRowFunction=None, totalsRowLabel=None, queryTableFieldId=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, calculatedColumnFormula=None, totalsRowFormula=None, xmlColumnPr=None, extLst=None, <openpyxl.worksheet.table.TableColumn object>
Parameters:
id=2, uniqueName=None, name='B', totalsRowFunction=None, totalsRowLabel=None, queryTableFieldId=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, calculatedColumnFormula=None, totalsRowFormula=None, xmlColumnPr=None, extLst=None, <openpyxl.worksheet.table.TableColumn object>
Parameters:
id=3, uniqueName=None, name='C', totalsRowFunction=None, totalsRowLabel=None, queryTableFieldId=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, calculatedColumnFormula=None, totalsRowFormula=None, xmlColumnPr=None, extLst=None], tableStyleInfo=<openpyxl.worksheet.table.TableStyleInfo object>
Parameters:
name='TableStyleMedium9', showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False]
</code>```

Do you know what may be the reason? I found a simmilar issue on the other website but without the answer.

Body:
I am trying to extract table from Excel worksheet (table is present in the worksheet) according to this tutorial: https://samukweku.github.io/data-wrangling-blog/spreadsheet/python/pandas/openpyxl/2020/05/19/Access-Tables-In-Excel.html

My Excel worksheet:

enter image description here

My code:

import openpyxl

workbook = openpyxl.load_workbook('my_excel.xlsx')
my_worksheet = workbook['my_worksheet']
print(my_worksheet._tables)
print(my_worksheet.tables.items())

Unfortunately I receive an error:

Exception has occurred: AttributeError
'Worksheet' object has no attribute 'tables'
  File "C:\Users\user\TRAINING\main.py", line 6, in <module>
    print(my_worksheet.tables)

However my_worksheet._tables gives me a list of all tables in the worksheet where my table is included:

[<openpyxl.worksheet.table.Table object>
Parameters:
id=1, name='Table1', displayName='Table1', comment=None, ref='A1:C3', tableType=None, headerRowCount=1, insertRow=None, insertRowShift=None, totalsRowCount=None, totalsRowShown=False, published=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowBorderDxfId=None, tableBorderDxfId=None, totalsRowBorderDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, connectionId=None, autoFilter=<openpyxl.worksheet.filters.AutoFilter object>
Parameters:
ref='A1:C3', filterColumn=[], sortState=None, sortState=None, tableColumns=[<openpyxl.worksheet.table.TableColumn object>
Parameters:
id=1, uniqueName=None, name='A', totalsRowFunction=None, totalsRowLabel=None, queryTableFieldId=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, calculatedColumnFormula=None, totalsRowFormula=None, xmlColumnPr=None, extLst=None, <openpyxl.worksheet.table.TableColumn object>
Parameters:
id=2, uniqueName=None, name='B', totalsRowFunction=None, totalsRowLabel=None, queryTableFieldId=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, calculatedColumnFormula=None, totalsRowFormula=None, xmlColumnPr=None, extLst=None, <openpyxl.worksheet.table.TableColumn object>
Parameters:
id=3, uniqueName=None, name='C', totalsRowFunction=None, totalsRowLabel=None, queryTableFieldId=None, headerRowDxfId=None, dataDxfId=None, totalsRowDxfId=None, headerRowCellStyle=None, dataCellStyle=None, totalsRowCellStyle=None, calculatedColumnFormula=None, totalsRowFormula=None, xmlColumnPr=None, extLst=None], tableStyleInfo=<openpyxl.worksheet.table.TableStyleInfo object>
Parameters:
name='TableStyleMedium9', showFirstColumn=False, showLastColumn=False, showRowStripes=True, showColumnStripes=False]

Do you know what may be the reason? I found a simmilar issue on the other website but without the answer.


问:
fail to import detectron2.data
I installed detectron2 via anaconda: conda install -c conda-forge detectron2

The installation succeeded but i fail to run: detectron2.data import build_detection_train_loader

the error message is:

i wonder know what i can do to successfully run my code.

details of my conda environmnt:

I tried to re-install my pytorch, to make sure that its version is corresponding to torchvision

Title: fail to import detectron2.data


问:
Punish False Negatives in Custom Categorical Crossentropy
I have a network which has an outputs a prediction of dim 5513. I am using a softmax activation function on the last axis, because the network predicts 13 classes for 25 different cases. I am using a categoricalcrossentropy (CCC) loss on those 13 classes as well.

However my network is just not learning, the loss is decreasing on most epochs but my network predicts all 0s which is not even a valid prediction as the 13 classes all contain a one (its one-hot encoded). I am using True Positives, True Negatives, False Negatives and False Positives as metrics. During training I have about 500.000 False Negatives and 5.000.000 True Negatives and basically no False Positives or True positives.

Is there a way I can punish my network for predicting False Negatives ? Like a change in the loss function ?

I am using a somewhat custom CCC where I experimented with weights for the differented classes but so far it hasnt helped:

```<code>def weighted_categorical_crossentropy(weights = the_weights):
    """
    A weighted version of keras.objectives.categorical_crossentropy

    Variables:
        weights: numpy array of shape (C,) where C is the number of classes

    Usage:
        weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.
        loss = weighted_categorical_crossentropy(weights)
        model.compile(loss=loss,optimizer='adam')
    """

    weights = K.variable(weights)

    def loss(y_true, y_pred):
        # scale predictions so that the class probas of each sample sum to 1
        y_pred /= K.clip(K.sum(y_pred[...,:], axis=-1, keepdims=True), K.epsilon(), 1 - K.epsilon())
        # clip to prevent NaN's and Inf's
        y_pred = K.clip(y_pred[...,:], K.epsilon(), 1 - K.epsilon())
        # calc
        loss = y_true[...,:] * K.log(y_pred[...,:]) * weights
        loss = K.sum(K.sum((-K.sum(loss, axis=-1)),axis=1),axis=-1)
        #loss = -K.sum(loss, 2)
        return loss

    return loss
</code>```

This is one example epoch of the training:
Epoch 4/10
603/603 [==============================] - 29s 48ms/step - loss: 26.7618 - tp: 0.0000e+00 - fp: 0.0000e+00 - tn: 5788800.0000 - fn: 482400.0000 - precision: 0.0000e+00 - recall: 0.0000e+00 - auc: 0.9771

Body:
I have a network which has an outputs a prediction of dim 5513. I am using a softmax activation function on the last axis, because the network predicts 13 classes for 25 different cases. I am using a categoricalcrossentropy (CCC) loss on those 13 classes as well.

However my network is just not learning, the loss is decreasing on most epochs but my network predicts all 0s which is not even a valid prediction as the 13 classes all contain a one (its one-hot encoded). I am using True Positives, True Negatives, False Negatives and False Positives as metrics. During training I have about 500.000 False Negatives and 5.000.000 True Negatives and basically no False Positives or True positives.

Is there a way I can punish my network for predicting False Negatives ? Like a change in the loss function ?

I am using a somewhat custom CCC where I experimented with weights for the differented classes but so far it hasnt helped:

def weighted_categorical_crossentropy(weights = the_weights):
    """
    A weighted version of keras.objectives.categorical_crossentropy

    Variables:
        weights: numpy array of shape (C,) where C is the number of classes

    Usage:
        weights = np.array([0.5,2,10]) # Class one at 0.5, class 2 twice the normal weights, class 3 10x.
        loss = weighted_categorical_crossentropy(weights)
        model.compile(loss=loss,optimizer='adam')
    """

    weights = K.variable(weights)

    def loss(y_true, y_pred):
        # scale predictions so that the class probas of each sample sum to 1
        y_pred /= K.clip(K.sum(y_pred[...,:], axis=-1, keepdims=True), K.epsilon(), 1 - K.epsilon())
        # clip to prevent NaN's and Inf's
        y_pred = K.clip(y_pred[...,:], K.epsilon(), 1 - K.epsilon())
        # calc
        loss = y_true[...,:] * K.log(y_pred[...,:]) * weights
        loss = K.sum(K.sum((-K.sum(loss, axis=-1)),axis=1),axis=-1)
        #loss = -K.sum(loss, 2)
        return loss

    return loss

This is one example epoch of the training:
Epoch 4/10
603/603 [==============================] - 29s 48ms/step - loss: 26.7618 - tp: 0.0000e+00 - fp: 0.0000e+00 - tn: 5788800.0000 - fn: 482400.0000 - precision: 0.0000e+00 - recall: 0.0000e+00 - auc: 0.9771


问:
Looking for GSM speech encoding/decoding tools (GSM vocoders)
guys, are there some software tools implementing basic GSM vocoders?

For example, I need the following functionality:

feed voice traffic (e.g. as microphone audio traffic with high bitrate) to GSM vocoder input;

get GSM vocoder output as encoded speech with lower bitrate.


问:
Google Smart Home Actions Toggle Trait for Horizontal & Vertical Swing
I am toggling horizontal swing and vertical swing in Hindi language, but assistant is not taking my command and always take me to a web page.

English Utterance: Start Horizontal Swing on Bedroom A/C. (working)
Hindi Utterance: बैडरूम एसी के हॉरिजॉन्टल स्विंग को चालू कर दो.(not working)

I have given all the possible commands in Hindi related to toggle but its not working. Please help me out from this.

Result : Command is to be executed when i am toggling Horizontal swing and vertical swing.

Below is my Google SYNC response:

{
"requestId": "11311483680465073646",
"payload": {
"agentUserId": "123",
"devices": [

```<code>        {
            "id": "stest240",
            "name": {
                "name": "Bedroom A/C",
                "defaultNames": [
                    "Smart Air Conditioner"
                ]
            },
            "type": "action.devices.types.THERMOSTAT",
            "traits": [
                "action.devices.traits.OnOff",
                "action.devices.traits.TemperatureSetting",
                "action.devices.traits.Toggles"
            ],
            "willReportState": false,
            "deviceInfo": {
                "manufacturer": "smart-home",
                "model": "hs1234",
                "hwVersion": "3.2",
                "swVersion": "11.4"
            },
            "attributes": {
                "availableThermostatModes": [
                    "cool",
                    "dry",
                    "fan-only"
                ],
                "thermostatTemperatureUnit": "C",
                "thermostatTemperatureRange": {
                    "minThresholdCelsius": 16,
                    "maxThresholdCelsius": 30
                },
                "availableToggles": [
                    {
                        "name": "horizontalswing",
                        "name_values": [
                            {
                                "name_synonym": [
                                    "horizontal swing"
                                ],
                                "lang": "en"
                            },
                            {
                                "name_synonym": [
                                        "हॉरिजोंटल स्विंग",
                                        "हॉरिजॉन्टल स्विंग"
                                ],
                                "lang": "hi"
                            }
                        ]
                    },
                    {
                        "name": "verticalswing",
                        "name_values": [
                            {
                                "name_synonym": [
                                    "vertical swing"
                                ],
                                "lang": "en"
                            },
                            {
                                "name_synonym": [
                                        "वर्टिकल स्विंग",
                                        "वर्टीकल स्विंग"
                                ],
                                "lang": "hi"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
</code>```

}

Body:
I am toggling horizontal swing and vertical swing in Hindi language, but assistant is not taking my command and always take me to a web page.

English Utterance: Start Horizontal Swing on Bedroom A/C. (working)
Hindi Utterance: बैडरूम एसी के हॉरिजॉन्टल स्विंग को चालू कर दो.(not working)

I have given all the possible commands in Hindi related to toggle but its not working. Please help me out from this.

Result : Command is to be executed when i am toggling Horizontal swing and vertical swing.

Below is my Google SYNC response:

{
"requestId": "11311483680465073646",
"payload": {
"agentUserId": "123",
"devices": [

        {
            "id": "stest240",
            "name": {
                "name": "Bedroom A/C",
                "defaultNames": [
                    "Smart Air Conditioner"
                ]
            },
            "type": "action.devices.types.THERMOSTAT",
            "traits": [
                "action.devices.traits.OnOff",
                "action.devices.traits.TemperatureSetting",
                "action.devices.traits.Toggles"
            ],
            "willReportState": false,
            "deviceInfo": {
                "manufacturer": "smart-home",
                "model": "hs1234",
                "hwVersion": "3.2",
                "swVersion": "11.4"
            },
            "attributes": {
                "availableThermostatModes": [
                    "cool",
                    "dry",
                    "fan-only"
                ],
                "thermostatTemperatureUnit": "C",
                "thermostatTemperatureRange": {
                    "minThresholdCelsius": 16,
                    "maxThresholdCelsius": 30
                },
                "availableToggles": [
                    {
                        "name": "horizontalswing",
                        "name_values": [
                            {
                                "name_synonym": [
                                    "horizontal swing"
                                ],
                                "lang": "en"
                            },
                            {
                                "name_synonym": [
                                        "हॉरिजोंटल स्विंग",
                                        "हॉरिजॉन्टल स्विंग"
                                ],
                                "lang": "hi"
                            }
                        ]
                    },
                    {
                        "name": "verticalswing",
                        "name_values": [
                            {
                                "name_synonym": [
                                    "vertical swing"
                                ],
                                "lang": "en"
                            },
                            {
                                "name_synonym": [
                                        "वर्टिकल स्विंग",
                                        "वर्टीकल स्विंग"
                                ],
                                "lang": "hi"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}

}


问:
Can I access the information of an error in a continue handler?
In a stored procedure, I can have a continue handler that handles errors. Can I somehow access the details of the respective error inside the handler?

Small example:

```<code>DROP PROCEDURE IF EXISTS `DO_SOMETHING_WRONG`;
DELIMITER $$
CREATE PROCEDURE `DO_SOMETHING_WRONG`()
BEGIN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Hey, this is an error!';
END $$
DELIMITER ;
</code>```

(That's obviously the failing part of the example)

```<code>DROP PROCEDURE IF EXISTS `CALL_SOMETHING_WRONG`;
DELIMITER $$
CREATE PROCEDURE `CALL_SOMETHING_WRONG`()
BEGIN
    DECLARE ERROR_OCCURRED BOOLEAN DEFAULT FALSE;
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET ERROR_OCCURRED := TRUE;

    CALL DO_SOMETHING_WRONG();

    IF ERROR_OCCURRED IS TRUE THEN
        SELECT 'An error occurred!' AS Output;
    ELSE
        SELECT 'No error occurred!' AS Output;
    END IF;
END $$
DELIMITER ;
</code>```

When I call CALL CALL_SOMETHING_WRONG(); it gives me An error occurred! as it should, but can I let it tell me, what error? So, get hold of the 45000 and the Hey, this is an error! in this example?

Body:
In a stored procedure, I can have a continue handler that handles errors. Can I somehow access the details of the respective error inside the handler?

Small example:

DROP PROCEDURE IF EXISTS `DO_SOMETHING_WRONG`;
DELIMITER $$
CREATE PROCEDURE `DO_SOMETHING_WRONG`()
BEGIN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Hey, this is an error!';
END $$
DELIMITER ;

(That's obviously the failing part of the example)

DROP PROCEDURE IF EXISTS `CALL_SOMETHING_WRONG`;
DELIMITER $$
CREATE PROCEDURE `CALL_SOMETHING_WRONG`()
BEGIN
    DECLARE ERROR_OCCURRED BOOLEAN DEFAULT FALSE;
    DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET ERROR_OCCURRED := TRUE;

    CALL DO_SOMETHING_WRONG();

    IF ERROR_OCCURRED IS TRUE THEN
        SELECT 'An error occurred!' AS Output;
    ELSE
        SELECT 'No error occurred!' AS Output;
    END IF;
END $$
DELIMITER ;

When I call CALL CALL_SOMETHING_WRONG(); it gives me An error occurred! as it should, but can I let it tell me, what error? So, get hold of the 45000 and the Hey, this is an error! in this example?


问:
Unable to append data to Json array object with desired output
My code

```<code>
import json
import re
from http.client import responses

import vt
import requests

with open('/home/asad/Downloads/ssh-log-parser/ok.txt', 'r') as file:
file = file.read()

pattern = re.compile(r'\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}')
ips = pattern.findall(file)
unique_ips = list(set(ips))

# print(unique_ips)

# print(len(unique_ips))

headers = {
"accept": "application/json",
"x-apikey": "9765ba5d9fd52f5747dde5240606019f83d32758cb664abc63a43488aa42812d"
}
i = 0
url = "https://www.virustotal.com/api/v3/ip_addresses/"

# messages = \[\]

f = open('formater.json')

# returns JSON object as

# a dictionary

data = json.load(f)
f.close()
no = 0
while i \< len(unique_ips):

    furl = url + str(unique_ips[i])
    # response = requests.get(furl, headers=headers)

    # data_ = response.json()

    # print(data_)

    # messages = [data_['data']['attributes']['last_analysis_results']]
    messages = [data['data']['attributes']['last_analysis_results']]

    y = json.dumps(messages)
    y1 = json.loads(y)

    # print(y1)
    a = []
    r = []
    v = []
    cnt = 0
    store = len(y1[0])
    out_json_new = []
    out_json1 ={}

    for o in y1:
            for k, vv in o.items():

                a_ = vv['result']
                a.append(a_)

                r_ = vv['engine_name']
                r.append(r_)

                v_ = vv['category']

                v.append(v_)

                out_json = {
                    "indicators": [{
                        "value": str(unique_ips[i]),
                        "type": 'ip',

                    }]
                }

                out_json1 ={
                                       "providers":[{
                                       "provider": str(r),
                                                 "verdict": str(a),
                                                 "score": str(v)

                                    }]             }

                out_json1['providers'].append(out_json1)

    i += 1

    print(out_json,out_json1)

\#for aaa in a:
\#print(a\[0\])\`
</code>```

Outputs as

```<code>{'indicators': [{'value': '192.91.72.201', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}
 {'indicators': [{'value': '192.91.72.101', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}
</code>```

I want to change the output to this format.

```<code> {
 "providers":\[
 {
 "provider":"['Bkav']",
 "verdict":"['clean']",
 "score":"['harmless']"
 },
 {
 "provider":"['CMC Threat Intelligence']",
 "verdict":"['clean']",
 "score":"['harmless']"
 },
 {
 "provider":"['CMC sarah']",
 "verdict":"['hate']",
 "score":"['harmless']"
}
 ]
 }
</code>```

My current code, groups under one key e.g provider instead it should be appended one after another like in output above. I tried to use append logic but its not working as i attended. It output as

```<code>            `out_json1['providers'].append(out_json1)`
</code>```

{'indicators': [{'value': '192.91.72.101', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}

RELEVANT FILES

In order to run the code these files are required.
ok.txt

```<code>Aug 22 09:45:08 ip-170-32-23-64 sshd\[1546\]: Invalid user HPSupport from 192.91.72.201
Aug 22 09:45:08 ip-170-32-23-64 sshd\[1546\]: Invalid user HPSupport from 192.91.72.101
</code>```

formater.json

```<code>{
"data": {
"attributes": {
"country": "US",
"last_analysis_stats": {
"harmless": 86,
"malicious": 0,
"suspicious": 0,
"undetected": 0,
"timeout": 0
},
"last_analysis_results": {
"Bkav": {
"category": "harmless",
"result": "clean",
"method": "blacklist",
"engine_name": "Bkav"
},
"CMC Threat Intelligence": {
"category": "harmless",
"result": "legs",
"method": "blacklist",
"engine_name": "CMC Threat Intelligence"
},
"CMC sarah ": {
"category": "sarah",
"result": "hate",
"method": "you",
"engine_name": "CMC sarah "
}
}
}
}
}
</code>```

Body:
My code

import json
import re
from http.client import responses

import vt
import requests

with open('/home/asad/Downloads/ssh-log-parser/ok.txt', 'r') as file:
file = file.read()

pattern = re.compile(r'\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}')
ips = pattern.findall(file)
unique_ips = list(set(ips))

# print(unique_ips)

# print(len(unique_ips))

headers = {
"accept": "application/json",
"x-apikey": "9765ba5d9fd52f5747dde5240606019f83d32758cb664abc63a43488aa42812d"
}
i = 0
url = "https://www.virustotal.com/api/v3/ip_addresses/"

# messages = \[\]

f = open('formater.json')

# returns JSON object as

# a dictionary

data = json.load(f)
f.close()
no = 0
while i \< len(unique_ips):

    furl = url + str(unique_ips[i])
    # response = requests.get(furl, headers=headers)

    # data_ = response.json()

    # print(data_)

    # messages = [data_['data']['attributes']['last_analysis_results']]
    messages = [data['data']['attributes']['last_analysis_results']]

    y = json.dumps(messages)
    y1 = json.loads(y)

    # print(y1)
    a = []
    r = []
    v = []
    cnt = 0
    store = len(y1[0])
    out_json_new = []
    out_json1 ={}

    for o in y1:
            for k, vv in o.items():

                a_ = vv['result']
                a.append(a_)

                r_ = vv['engine_name']
                r.append(r_)

                v_ = vv['category']

                v.append(v_)

                out_json = {
                    "indicators": [{
                        "value": str(unique_ips[i]),
                        "type": 'ip',

                    }]
                }

                out_json1 ={
                                       "providers":[{
                                       "provider": str(r),
                                                 "verdict": str(a),
                                                 "score": str(v)

                                    }]             }

                out_json1['providers'].append(out_json1)

    i += 1

    print(out_json,out_json1)

\#for aaa in a:
\#print(a\[0\])\`

Outputs as

{'indicators': [{'value': '192.91.72.201', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}
 {'indicators': [{'value': '192.91.72.101', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}

I want to change the output to this format.

 {
 "providers":\[
 {
 "provider":"['Bkav']",
 "verdict":"['clean']",
 "score":"['harmless']"
 },
 {
 "provider":"['CMC Threat Intelligence']",
 "verdict":"['clean']",
 "score":"['harmless']"
 },
 {
 "provider":"['CMC sarah']",
 "verdict":"['hate']",
 "score":"['harmless']"
}
 ]
 }

My current code, groups under one key e.g provider instead it should be appended one after another like in output above. I tried to use append logic but its not working as i attended. It output as

            `out_json1['providers'].append(out_json1)`

{'indicators': [{'value': '192.91.72.101', 'type': 'ip'}]} {'providers': [{'provider': "['Bkav', 'CMC Threat Intelligence', 'CMC sarah ']", 'verdict': "['clean', 'legs', 'hate']", 'score': "['harmless', 'harmless', 'sarah']"}, {...}]}

RELEVANT FILES

In order to run the code these files are required.
ok.txt

Aug 22 09:45:08 ip-170-32-23-64 sshd\[1546\]: Invalid user HPSupport from 192.91.72.201
Aug 22 09:45:08 ip-170-32-23-64 sshd\[1546\]: Invalid user HPSupport from 192.91.72.101

formater.json

{
"data": {
"attributes": {
"country": "US",
"last_analysis_stats": {
"harmless": 86,
"malicious": 0,
"suspicious": 0,
"undetected": 0,
"timeout": 0
},
"last_analysis_results": {
"Bkav": {
"category": "harmless",
"result": "clean",
"method": "blacklist",
"engine_name": "Bkav"
},
"CMC Threat Intelligence": {
"category": "harmless",
"result": "legs",
"method": "blacklist",
"engine_name": "CMC Threat Intelligence"
},
"CMC sarah ": {
"category": "sarah",
"result": "hate",
"method": "you",
"engine_name": "CMC sarah "
}
}
}
}
}


问:
DirectLine response is not included in function response, execution completes too quickly
I am trying to send a message and get a response using " directLine.activity$" -- although my function execution completes before the directLine.activity$ detects a "received activity".

Below is my entire code.  I'm just wondering, how can I wait for the WebSocket to receive at least 1 "received activity" before processing the response.

When I run this code it just quickly executes and says "Executed 'Functions.twilioagogo' (Succeeded, Id=xxxxxx-c1a9-4092-b740-xxxxxx, Duration=272ms)"

```<code>const express = require('express');
const { MessagingResponse } = require('twilio').twiml;

const app = express();

//DirectLine

global.XMLHttpRequest = require('xhr2');
global.WebSocket = require('ws');

const { DirectLine } = require('botframework-directlinejs');
const { twiml } = require('twilio');

module.exports = async function (context, req) {

//global variables
var myPhone
var myActivity
var responseCount = 0

const twiml = new MessagingResponse();
var directLine = new DirectLine({
    secret: 'xxxxxxxxxxxxxxxxxx',

});

async function myfunction() {
console.log('Inside of myfunction');
console.log("start")

const name = (req.query.name || (req.body && req.body.name));
// const responseMessage = name
  //  ? "Hello, " + name + ". This HTTP triggered function executed successfully."
  //  : "This HTTP triggered function executed successfully. Pass a name in the   query string or in the request body for a personalized response.";

  //new

  //  twiml.message('The Robots are coming! Head for the hills!');

  //get from phone #

  var myInfo = req.body.toString().split("&")

  for (i = 0; i < myInfo.length; i++) {

    if (myInfo[i].toString().includes("From=")) {

        myPhone = myInfo[i].toString()
    }

}

}

async function myfunction2() {
console.log('Inside of myfunction2');
console.log("start2")

directLine.postActivity({
    from: { id: '123'}, // required (from.name is optional)
    type: 'message',
    text: 'a message for you, Rudy'
}).subscribe(
    id => {console.log("Posted activity, assigned ID ", id)
    directLine.activity$
    .subscribe(
        activity => {
            if (activity.from.id === "tbot1000v5") {
            console.log("received activity ", activity.text)
            myActivity = activity.text
            console.log("myactivity here " + myActivity)
            responseCount++
            console.log("ResponseCount is " + responseCount)
            twiml.message(myActivity);
            console.log("here")

            } //end if

        }

    )

},
    error => console.log("Error posting activity", error)
)

 } //end myfunction2

 async function myfunction3() {

 console.log('Inside of myfunction3');
 console.log("start3")

 }

 function start() {

return myfunction();
}

function start2() {

return myfunction2();

}

function start3() {

return myfunction3();

}
// Call start
(async() => {
console.log('before start');

await start();
await start2();
await start3();
console.log("send response begin")

context.res = {

    // status: 200, /* Defaults to 200 */
   // body: 'The Robots are coming! Head for the hills!'
   headers: { 'Content-Type': 'application/xml' },
   body: twiml.toString()
};

})();

}
</code>```

Body:
I am trying to send a message and get a response using " directLine.activity$" -- although my function execution completes before the directLine.activity$ detects a "received activity".

Below is my entire code.  I'm just wondering, how can I wait for the WebSocket to receive at least 1 "received activity" before processing the response.

When I run this code it just quickly executes and says "Executed 'Functions.twilioagogo' (Succeeded, Id=xxxxxx-c1a9-4092-b740-xxxxxx, Duration=272ms)"

const express = require('express');
const { MessagingResponse } = require('twilio').twiml;

const app = express();

//DirectLine

global.XMLHttpRequest = require('xhr2');
global.WebSocket = require('ws');

const { DirectLine } = require('botframework-directlinejs');
const { twiml } = require('twilio');

module.exports = async function (context, req) {

//global variables
var myPhone
var myActivity
var responseCount = 0

const twiml = new MessagingResponse();
var directLine = new DirectLine({
    secret: 'xxxxxxxxxxxxxxxxxx',

});

async function myfunction() {
console.log('Inside of myfunction');
console.log("start")

const name = (req.query.name || (req.body && req.body.name));
// const responseMessage = name
  //  ? "Hello, " + name + ". This HTTP triggered function executed successfully."
  //  : "This HTTP triggered function executed successfully. Pass a name in the   query string or in the request body for a personalized response.";

  //new

  //  twiml.message('The Robots are coming! Head for the hills!');

  //get from phone #

  var myInfo = req.body.toString().split("&")

  for (i = 0; i < myInfo.length; i++) {

    if (myInfo[i].toString().includes("From=")) {

        myPhone = myInfo[i].toString()
    }

}

}

async function myfunction2() {
console.log('Inside of myfunction2');
console.log("start2")

directLine.postActivity({
    from: { id: '123'}, // required (from.name is optional)
    type: 'message',
    text: 'a message for you, Rudy'
}).subscribe(
    id => {console.log("Posted activity, assigned ID ", id)
    directLine.activity$
    .subscribe(
        activity => {
            if (activity.from.id === "tbot1000v5") {
            console.log("received activity ", activity.text)
            myActivity = activity.text
            console.log("myactivity here " + myActivity)
            responseCount++
            console.log("ResponseCount is " + responseCount)
            twiml.message(myActivity);
            console.log("here")

            } //end if

        }

    )

},
    error => console.log("Error posting activity", error)
)

 } //end myfunction2

 async function myfunction3() {

 console.log('Inside of myfunction3');
 console.log("start3")

 }

 function start() {

return myfunction();
}

function start2() {

return myfunction2();

}

function start3() {

return myfunction3();

}
// Call start
(async() => {
console.log('before start');

await start();
await start2();
await start3();
console.log("send response begin")

context.res = {

    // status: 200, /* Defaults to 200 */
   // body: 'The Robots are coming! Head for the hills!'
   headers: { 'Content-Type': 'application/xml' },
   body: twiml.toString()
};

})();

}


问:
application under Nginx switching IPs, how to make always the same?
I am running application under nginx with configuration:

```<code>upstream myup {
   server localhost:8833
   server localhost:8844
}
server {
  listen 80;
  server_name: localhost;
  location / {
       proxy_pass http://myup.com
  }
}
</code>```

This configuration works for me, but when I am watching IP using app in logs, I see the following:

```<code>127.0.0.1/ - - - [11/JAN] "GET /info HTTP/1.0" 200
0.0.0.0.0.0.0.1 - - - [11/JAN] "GET /image.css HTTP/1.0" 200
127.0.0.1/ - - - [11/JAN] "GET /script.js HTTP/1.0" 200
0.0.0.0.0.0.0.1 - - - [11/JAN] "GET /logo.svg HTTP/1.0" 200
</code>```

every second request changes IP between (127.0.0.1, 0.0.0.0.0.0.0.1)

Logs from Nginx there always have IP: 127.0.0.1

Logs from my app without Nginx always have IP: 0.0.0.0.0.0.0.1

How do I manage to work continuously with the same IP as my application depends on it?

Body:
I am running application under nginx with configuration:

upstream myup {
   server localhost:8833
   server localhost:8844
}
server {
  listen 80;
  server_name: localhost;
  location / {
       proxy_pass http://myup.com
  }
}

This configuration works for me, but when I am watching IP using app in logs, I see the following:

127.0.0.1/ - - - [11/JAN] "GET /info HTTP/1.0" 200
0.0.0.0.0.0.0.1 - - - [11/JAN] "GET /image.css HTTP/1.0" 200
127.0.0.1/ - - - [11/JAN] "GET /script.js HTTP/1.0" 200
0.0.0.0.0.0.0.1 - - - [11/JAN] "GET /logo.svg HTTP/1.0" 200

every second request changes IP between (127.0.0.1, 0.0.0.0.0.0.0.1)

Logs from Nginx there always have IP: 127.0.0.1

Logs from my app without Nginx always have IP: 0.0.0.0.0.0.0.1

How do I manage to work continuously with the same IP as my application depends on it?


问:
How to create a sorted, stacked bar plot after using groupby()
My data is as follows:

```<code>data = pd.DataFrame([[2019, "Mercedes"],
                   [2019, "Mercedes"],
                   [2019, "Audi"],
                   [2019, "Volvo"],
                   [2020, "Mercedes"],
                   [2020, "Mercedes"],
                   [2020, "Mercedes"],
                   [2020, "Volvo"],
                   [2020, "Volvo"],
                   [2020, "Hyundai"],
                   [2020, "Tesla"],
                   [2020, "VW"],
                   [2021, "Mercedes"],
                   [2021, "Mercedes"],
                   [2021, "Kia"],
                   [2021, "VW"]],
                  columns=["year", "brand"])
</code>```

I want to create a sorted, stacked, normalized bar plot. I failed to sort my bars. I currently have:

```<code>brandsPerYear = data.groupby('year')['brand'].value_counts(normalize=True)
brandsPerYear = brandsPerYear.unstack('brand')
brandsPerYear.plot.barh(stacked=True)
</code>```

In the code above I group the data by year, count the number of occurances per brand, normalize such that the sum over every year is 1. The result is a grouped dataframe, so I unstack it. However, sorting does not work on this unstacked dataframe.

The code generates:

and the dataframe "brandsPerYear" looks as follows:

I tried brandsPerYear.sort_values("brand") but it gives me a keyerror. The error arises, because the columnname is "brand" as seen in the picture above.

Body:
My data is as follows:

data = pd.DataFrame([[2019, "Mercedes"],
                   [2019, "Mercedes"],
                   [2019, "Audi"],
                   [2019, "Volvo"],
                   [2020, "Mercedes"],
                   [2020, "Mercedes"],
                   [2020, "Mercedes"],
                   [2020, "Volvo"],
                   [2020, "Volvo"],
                   [2020, "Hyundai"],
                   [2020, "Tesla"],
                   [2020, "VW"],
                   [2021, "Mercedes"],
                   [2021, "Mercedes"],
                   [2021, "Kia"],
                   [2021, "VW"]],
                  columns=["year", "brand"])

I want to create a sorted, stacked, normalized bar plot. I failed to sort my bars. I currently have:

brandsPerYear = data.groupby('year')['brand'].value_counts(normalize=True)
brandsPerYear = brandsPerYear.unstack('brand')
brandsPerYear.plot.barh(stacked=True)

In the code above I group the data by year, count the number of occurances per brand, normalize such that the sum over every year is 1. The result is a grouped dataframe, so I unstack it. However, sorting does not work on this unstacked dataframe.

The code generates:

and the dataframe "brandsPerYear" looks as follows:

I tried brandsPerYear.sort_values("brand") but it gives me a keyerror. The error arises, because the columnname is "brand" as seen in the picture above.


问:
Laravel subquery other table
How can I get data from another table?

```<code>// ServiceComplexController
public function index(Store $store): JsonResponse
{
    /* @var User $user */
    $user = auth()->user();
    $this->listQuery = $user->store->serviceComplexes()->getQuery();
    return response()->json([
        'data' => StoreServiceComplexResource::collection($this->listQuery->get()),
    ]);
}

// StoreServiceComplexResource
public function toArray($request): array
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'description' => $this->description,
        'base_service_ids' => $this->base_service_ids,
        'more_service_ids' => $this->more_service_ids,
    ];
}

// Dump $this->listQuery->get()
array (
  0 =>
  array (
    'id' => 3,
    'name' => 'Complex 1',
    'description' => 'Desc complex 1',
    'base_service_ids' =>
    array (
      0 => 1,
      1 => 2,
    ),
    'more_service_ids' =>
    array (
      0 => 10,
    ),
  ),
)

</code>```

How to get base services from another table(services) based on field "base_service_ids" and "more_service_ids" and add them to response ?

Is it possible to give this data also through Collection Resource ? For example

```<code>// StoreServiceComplexResource
public function toArray($request): array
{
    return [
        ...
        'service' => [] //StoreServiceResource::collection() ....
        ...
    ];
}
</code>```

Title: Laravel subquery other table

Body:
How can I get data from another table?

// ServiceComplexController
public function index(Store $store): JsonResponse
{
    /* @var User $user */
    $user = auth()->user();
    $this->listQuery = $user->store->serviceComplexes()->getQuery();
    return response()->json([
        'data' => StoreServiceComplexResource::collection($this->listQuery->get()),
    ]);
}

// StoreServiceComplexResource
public function toArray($request): array
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'description' => $this->description,
        'base_service_ids' => $this->base_service_ids,
        'more_service_ids' => $this->more_service_ids,
    ];
}

// Dump $this->listQuery->get()
array (
  0 =>
  array (
    'id' => 3,
    'name' => 'Complex 1',
    'description' => 'Desc complex 1',
    'base_service_ids' =>
    array (
      0 => 1,
      1 => 2,
    ),
    'more_service_ids' =>
    array (
      0 => 10,
    ),
  ),
)

How to get base services from another table(services) based on field "base_service_ids" and "more_service_ids" and add them to response ?

Is it possible to give this data also through Collection Resource ? For example

// StoreServiceComplexResource
public function toArray($request): array
{
    return [
        ...
        'service' => [] //StoreServiceResource::collection() ....
        ...
    ];
}


问:
Captured Android Emulator API 28 log lacking logcat logs frequently
We are facing frequently (every second to third run) the issue that the actual logcat logs are missing in our captured log file. This issue only appears with an Android emulator employing a x86 image with API level 28. The following logs are captured in such a faulty case:

```<code>INFO    | Your emulator is out of date, please update by launching Android Studio:
 - Start Android Studio
 - Select menu "Tools > Android > SDK Manager"
 - Click "SDK Tools" tab
 - Check "Android Emulator" checkbox
 - Click "OK"

VERBOSE | onGuestSendCommand: [0x871dad0] Adb connected, start proxing data
VERBOSE | _hwFingerprint_connect: connect finger print listen is called
VERBOSE | got message from guest system fingerprint HAL
INFO    | boot completed
INFO    | boot time 24250 ms
INFO    | Increasing screen off timeout, logcat buffer size to 2M.
INFO    | Revoking microphone permissions for Google App.
VERBOSE | onGuestClose: [0x871da00] Adb closed by guest
VERBOSE | onGuestClose: [0x871dad0] Adb closed by guest
VERBOSE | onGuestSendCommand: [0x8eccf70] Adb connected, start proxing data
VERBOSE | Emulator killed by console kill command.
VERBOSE | Saving state on exit with session uptime 3729156 ms
INFO    | Shutting down gRPC endpoint
INFO    | Shutting down gRPC endpoint
VERBOSE | Done with QEMU main loop
VERBOSE | User configuration saved to /dev/shm/auermich/tmp02g33cw1/.android/avd/PixelXL_API_28.avd/emulator-user.ini
VERBOSE | Adb transition disconnected -> disconnected
</code>```

While in a successful execution the logcat logs are captured after the 'out of date' info log, e.g.:

```<code>--------- beginning of main
01-10 22:42:01.020  1538  1538 W auditd  : type=2000 audit(0.0:1): initialized
01-10 22:42:01.740  1538  1538 I auditd  : type=1403 audit(0.0:2): policy loaded auid=4294967295 ses=4294967295
01-10 22:42:01.750  1538  1538 W auditd  : type=1404 audit(0.0:3): enforcing=1 old_enforcing=0 auid=4294967295 ses=4294967295
01-10 22:42:02.494  1539  1539 I SELinux : SELinux: Loaded service_contexts from:
01-10 22:42:02.496  1539  1539 I SELinux :     /system/etc/selinux/plat_service_contexts
01-10 22:42:02.500     1     1 W init    : type=1400 audit(0.0:4): avc: denied { setattr } for name="slabinfo" dev="proc" ino=4026532041 scontext=u:r:init:s0 tcontext=u:object_r:proc:s0 tclass=file permissive=0
01-10 22:42:02.500     1     1 W init    : type=1400 audit(0.0:5): avc: denied { setattr } for name="slabinfo" dev="proc" ino=4026532041 scontext=u:r:init:s0 tcontext=u:object_r:proc:s0 tclass=file permissive=0 01-10 22:42:02.511  1541  1541 I SELinux : SELinux: Loaded service_contexts from:
01-10 22:42:02.512  1541  1541 I SELinux :     /vendor/etc/selinux/vndservice_contexts
01-10 22:42:02.537  1540  1540 I hwservicemanager: hwservicemanager is ready now.
01-10 22:42:02.558  1547  1547 I android.hardware.keymaster@3.0-impl: Fetching keymaster device name default
01-10 22:42:02.558  1547  1547 I android.hardware.keymaster@3.0-impl: Could not find any keystore module, using software-only implementation.
01-10 22:42:02.559  1547  1547 I ServiceManagement: Removing namespace from process name android.hardware.keymaster@3.0-service to keymaster@3.0-service.
01-10 22:42:02.559  1547  1547 I android.hardware.keymaster@3.0-service: Registration complete for android.hardware.keymaster@3.0::IKeymasterDevice/default.
--------- beginning of system
</code>```

We are typically conducting experiments (thousands of runs) with a x86 image with API level 25 and there this issue doesn't appear at all, but we would like to update to a more recent API level. We are facing the issue both on Windows and Linux. More details regarding the emulator:

Android emulator version 31.2.9.0 (build_id 8316981) (CL:N/A

system-images/android-28/default/x86/

Nexus 5 or Pixel XL AVD

The capturing of the log files is handled by a little python script:

```<code>self.f = open(emu_conf["logfile"], "a")
self.f_err = open(emu_conf["logfile_err"], "a")
self.emu_proc = subprocess.Popen(self.emu_command, stdout=self.f, stderr=self.f_err)
</code>```

where the emu command is actually the following:

Running command
['/dev/shm/auermich/tmp02g33cw1/Android/Sdk/emulator/emulator',
'-avd', 'PixelXL_API_28', '-verbose', '-logcat', 'E,acc',
'-wipe-data', '-no-window']

UPDATE: Even if we use the option -logcat-output to log directly to a file, the same fault appears. The adjusted command now is:

Running command
['/dev/shm/auermich/tmp6wr4semi/Android/Sdk/emulator/emulator',
'-avd', 'Pixel_XL_API_28', '-verbose', '-logcat', 'E,acc',
'-logcat-output', 'log/logcat.log', '-wipe-data', '-no-window']

The specified log file remains empty in such a case.

Body:
We are facing frequently (every second to third run) the issue that the actual logcat logs are missing in our captured log file. This issue only appears with an Android emulator employing a x86 image with API level 28. The following logs are captured in such a faulty case:

INFO    | Your emulator is out of date, please update by launching Android Studio:
 - Start Android Studio
 - Select menu "Tools > Android > SDK Manager"
 - Click "SDK Tools" tab
 - Check "Android Emulator" checkbox
 - Click "OK"

VERBOSE | onGuestSendCommand: [0x871dad0] Adb connected, start proxing data
VERBOSE | _hwFingerprint_connect: connect finger print listen is called
VERBOSE | got message from guest system fingerprint HAL
INFO    | boot completed
INFO    | boot time 24250 ms
INFO    | Increasing screen off timeout, logcat buffer size to 2M.
INFO    | Revoking microphone permissions for Google App.
VERBOSE | onGuestClose: [0x871da00] Adb closed by guest
VERBOSE | onGuestClose: [0x871dad0] Adb closed by guest
VERBOSE | onGuestSendCommand: [0x8eccf70] Adb connected, start proxing data
VERBOSE | Emulator killed by console kill command.
VERBOSE | Saving state on exit with session uptime 3729156 ms
INFO    | Shutting down gRPC endpoint
INFO    | Shutting down gRPC endpoint
VERBOSE | Done with QEMU main loop
VERBOSE | User configuration saved to /dev/shm/auermich/tmp02g33cw1/.android/avd/PixelXL_API_28.avd/emulator-user.ini
VERBOSE | Adb transition disconnected -> disconnected

While in a successful execution the logcat logs are captured after the 'out of date' info log, e.g.:

--------- beginning of main
01-10 22:42:01.020  1538  1538 W auditd  : type=2000 audit(0.0:1): initialized
01-10 22:42:01.740  1538  1538 I auditd  : type=1403 audit(0.0:2): policy loaded auid=4294967295 ses=4294967295
01-10 22:42:01.750  1538  1538 W auditd  : type=1404 audit(0.0:3): enforcing=1 old_enforcing=0 auid=4294967295 ses=4294967295
01-10 22:42:02.494  1539  1539 I SELinux : SELinux: Loaded service_contexts from:
01-10 22:42:02.496  1539  1539 I SELinux :     /system/etc/selinux/plat_service_contexts
01-10 22:42:02.500     1     1 W init    : type=1400 audit(0.0:4): avc: denied { setattr } for name="slabinfo" dev="proc" ino=4026532041 scontext=u:r:init:s0 tcontext=u:object_r:proc:s0 tclass=file permissive=0
01-10 22:42:02.500     1     1 W init    : type=1400 audit(0.0:5): avc: denied { setattr } for name="slabinfo" dev="proc" ino=4026532041 scontext=u:r:init:s0 tcontext=u:object_r:proc:s0 tclass=file permissive=0 01-10 22:42:02.511  1541  1541 I SELinux : SELinux: Loaded service_contexts from:
01-10 22:42:02.512  1541  1541 I SELinux :     /vendor/etc/selinux/vndservice_contexts
01-10 22:42:02.537  1540  1540 I hwservicemanager: hwservicemanager is ready now.
01-10 22:42:02.558  1547  1547 I android.hardware.keymaster@3.0-impl: Fetching keymaster device name default
01-10 22:42:02.558  1547  1547 I android.hardware.keymaster@3.0-impl: Could not find any keystore module, using software-only implementation.
01-10 22:42:02.559  1547  1547 I ServiceManagement: Removing namespace from process name android.hardware.keymaster@3.0-service to keymaster@3.0-service.
01-10 22:42:02.559  1547  1547 I android.hardware.keymaster@3.0-service: Registration complete for android.hardware.keymaster@3.0::IKeymasterDevice/default.
--------- beginning of system

We are typically conducting experiments (thousands of runs) with a x86 image with API level 25 and there this issue doesn't appear at all, but we would like to update to a more recent API level. We are facing the issue both on Windows and Linux. More details regarding the emulator:

Android emulator version 31.2.9.0 (build_id 8316981) (CL:N/A

system-images/android-28/default/x86/

Nexus 5 or Pixel XL AVD

The capturing of the log files is handled by a little python script:

self.f = open(emu_conf["logfile"], "a")
self.f_err = open(emu_conf["logfile_err"], "a")
self.emu_proc = subprocess.Popen(self.emu_command, stdout=self.f, stderr=self.f_err)

where the emu command is actually the following:

Running command
['/dev/shm/auermich/tmp02g33cw1/Android/Sdk/emulator/emulator',
'-avd', 'PixelXL_API_28', '-verbose', '-logcat', 'E,acc',
'-wipe-data', '-no-window']

UPDATE: Even if we use the option -logcat-output to log directly to a file, the same fault appears. The adjusted command now is:

Running command
['/dev/shm/auermich/tmp6wr4semi/Android/Sdk/emulator/emulator',
'-avd', 'Pixel_XL_API_28', '-verbose', '-logcat', 'E,acc',
'-logcat-output', 'log/logcat.log', '-wipe-data', '-no-window']

The specified log file remains empty in such a case.


问:
Calendar wrong date depends on start day of the week
If I run this code I got the wrong date and the wrong calendar, if I select the first day as Monday I get the right calendar.
Can someone please help me with this? the code was working fine till last week.
If I print the year, month, and day I'm getting the right result.</p>
```<code>  from tkinter import *
  from tkcalendar import *
  import time

  root= Tk()
  Y= int (time.strftime('%Y'))
  M= int(time.strftime('%m'))
  D= int(time.strftime("%d"))

  cal= Calendar(root, year=Y, month=M, day=D,firstweekday='sunday', selectmode='none)
  cal.grid(row=1, column=0)
  root.mainloop()
</code>```

Body:
If I run this code I got the wrong date and the wrong calendar, if I select the first day as Monday I get the right calendar.
Can someone please help me with this? the code was working fine till last week.
If I print the year, month, and day I'm getting the right result.

  from tkinter import *
  from tkcalendar import *
  import time

  root= Tk()
  Y= int (time.strftime('%Y'))
  M= int(time.strftime('%m'))
  D= int(time.strftime("%d"))

  cal= Calendar(root, year=Y, month=M, day=D,firstweekday='sunday', selectmode='none)
  cal.grid(row=1, column=0)
  root.mainloop()


问:
When using snap-scroll my site is being cut off on mobile devices (Tested with android google chrome)
I am super new to html, css and java- literally just started.
As a "learning-by-doing" project I am creating a website for a friend of mine.

I am using snap-scrolling to be able to "jump" sites.
Unfortunately on my mobile (android phone) the bottom of each page is cut-off due to the Chrome Browser navigation.

I was told to not use 100vh but 100% instead. Did so and still can't find my mistake.

The website is live at LINK.

The section with the most visible issue at the bottom is the last page.
the Snapscroll div is wrapping all sites.

I am wrapping all pages with the snap-scroll which only works with 100vh?
the pages themselve are set to 100% height.

```<code>.snap_scroll {
max-width: 100%;
height: 100vh;
scroll-snap-type: y mandatory;
overflow-y: scroll;
max-height: -webkit-fill-available;
}
</code>```
```<code>.contact{
  height: 100%;
  width: 100%;
  background: url(./img/app_background_2.jpg) no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;
  scroll-snap-align: start;
  overflow: hidden;
  margin: 0;
}
</code>```

Body:
I am super new to html, css and java- literally just started.
As a "learning-by-doing" project I am creating a website for a friend of mine.

I am using snap-scrolling to be able to "jump" sites.
Unfortunately on my mobile (android phone) the bottom of each page is cut-off due to the Chrome Browser navigation.

I was told to not use 100vh but 100% instead. Did so and still can't find my mistake.

The website is live at LINK.

The section with the most visible issue at the bottom is the last page.
the Snapscroll div is wrapping all sites.

I am wrapping all pages with the snap-scroll which only works with 100vh?
the pages themselve are set to 100% height.

.snap_scroll {
max-width: 100%;
height: 100vh;
scroll-snap-type: y mandatory;
overflow-y: scroll;
max-height: -webkit-fill-available;
}

.contact{
  height: 100%;
  width: 100%;
  background: url(./img/app_background_2.jpg) no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;
  scroll-snap-align: start;
  overflow: hidden;
  margin: 0;
}


问:
spring cloud gcp pub/sub Jackson messageConverter deserialize fail
I'm trying to receive and process messages through GCP Pub/Sub.

I tried to convert and receive the payload part of the message through JacksonPubSubMessageConverter, but it failed.

It seems that I am not handling byte[] properly inside JacksonPubSubMessageConverter. Do I need to change ObjectMapper settings or override JacksonPubSubMessageConverter?

Below is a code example.

@Slf4j
@Configuration
public class PubSubConfig {

    @Bean
    public PubSubMessageConverter pubSubMessageConverter(ObjectMapper objectMapper) {
        return new JacksonPubSubMessageConverter(objectMapper);
    }
}

// ...

@Getter
@Setter
@ToString
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class MessageDTO {

    private PubSubAction action;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate startedAt;
    private Boolean dryRun;
}

// ...

public enum PubSubAction {
    MY_ACTION("my action"),
    ETC("etc action");
    private final String description;

    PubSubAction(String description) {
        this.description = description;
    }

    @JsonCreator
    public static PubSubAction create(String name) {
        return Stream.of(PubSubAction.values())
            .filter(pubSubAction -> pubSubAction.name().equals(name))
            .findAny()
            .orElse(null);
    }
}
// ...

class MyConsumer() {
    private final String subscriptionName;
    private final PubSubTemplate pubSubTemplate;

   public MyConsumer(
        String subscriptionName,
        PubSubTemplate pubSubTemplate
   ) {
        this.subscriptionName = subscriptionName;
        this.pubSubTemplate = pubSubTemplate;
   }

    private void consume(
        ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO> convertedMessage) {
        try {
            MessageDTO payload = convertedMessage.getPayload();
            log.debug("payload {}", payload);
            // payload MessageDTO(action=MY_ACTION, startedAt=null, dryRun=null)
            convertedMessage.ack();
        } catch (Exception e) {
            log.error("Unknown Exception {} {}", e.getMessage(), this.subscriptionName, e);
        }
    }

    private Consumer<ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO>> convertConsumer() {
        return this::consume;
    }

   public void subscribe() {
        log.info("Subscribing to {}", subscriptionName);
        pubSubTemplate.subscribeAndConvert(subscriptionName, this.convertConsumer(),
            MessageDTO.class);
    }
}
```


问:
printf in Windows x86-64 shellcode, strings on stack, and alignment
From x64 shellcode on Windows 10, I want to call printf("String: %s\n", "Hello World") with the string "Hello World" defined on the stack. I ran into problems that I’ve somewhat fixed, but I understand neither the problem nor my solution. I read that the x64 ABI mandates the stack to be 16-byte aligned before call instructions, but this does not seem to explain all of it.

After some playing around with nasm, I arrived at the following code, which works:

```<code>bits 64
default rel

segment .data
    msg db "String: %s", 0xd, 0xa, 0

segment .text
global main
extern ExitProcess

extern printf

main:
    push rbp
    mov  rbp, rsp
    sub  rsp, 64  ; relevant number 1

    mov  rdx, rsp
    add  rdx, 32  ; relevant number 2
    mov  dword [rdx],     "Hell"
    mov  dword [rdx + 4], "o Wo"
    mov  dword [rdx + 8], "rld"

    lea  rcx, [msg]
    call printf

    xor  rcx, rcx
    call ExitProcess
</code>```

Curiously, there are certain combinations of values for the rsp and the position rdx of the string on the stack that work and certain combinations that don’t. However, I don’t see the general rule.

Number 1
Number 2
Works?
Output

64
0
no

64
8
no
x¨/(☻

64
16
no
Pf{tè☻

64
24
no
Ï¨;í

64
32
yes
Hello World

64
40
yes
Hello World

64
48
yes
Hello World

64
56
yes
Hello World

64
64
yes
Hello World

32
0
no

32
8
no
°²øRg

32
16
no
ákG×│☺

32
24
no
↑°wd¢

32
32
yes
Hello World

What’s going on? Why do we need to store the string at least 32 bytes away from the rsp? This seem unrelated to the 16-byte alignment requirement.

Body:
From x64 shellcode on Windows 10, I want to call printf("String: %s\n", "Hello World") with the string "Hello World" defined on the stack. I ran into problems that I’ve somewhat fixed, but I understand neither the problem nor my solution. I read that the x64 ABI mandates the stack to be 16-byte aligned before call instructions, but this does not seem to explain all of it.

After some playing around with nasm, I arrived at the following code, which works:

bits 64
default rel

segment .data
    msg db "String: %s", 0xd, 0xa, 0

segment .text
global main
extern ExitProcess

extern printf

main:
    push rbp
    mov  rbp, rsp
    sub  rsp, 64  ; relevant number 1

    mov  rdx, rsp
    add  rdx, 32  ; relevant number 2
    mov  dword [rdx],     "Hell"
    mov  dword [rdx + 4], "o Wo"
    mov  dword [rdx + 8], "rld"

    lea  rcx, [msg]
    call printf

    xor  rcx, rcx
    call ExitProcess

Curiously, there are certain combinations of values for the rsp and the position rdx of the string on the stack that work and certain combinations that don’t. However, I don’t see the general rule.

Number 1
Number 2
Works?
Output

64
0
no

64
8
no
x¨/(☻

64
16
no
Pf{tè☻

64
24
no
Ï¨;í

64
32
yes
Hello World

64
40
yes
Hello World

64
48
yes
Hello World

64
56
yes
Hello World

64
64
yes
Hello World

32
0
no

32
8
no
°²øRg

32
16
no
ákG×│☺

32
24
no
↑°wd¢

32
32
yes
Hello World

What’s going on? Why do we need to store the string at least 32 bytes away from the rsp? This seem unrelated to the 16-byte alignment requirement.


问:
Query on sql server to concatenate all selects
I'm trying to concatenate all rows of a query in one result... but when i do it, it shows that the result is too long...

First i tryed:

```<code>SELECT STRING_AGG(LINE, ' - ') FROM (SELECT TOP(8)
                CONCAT('<td class="text-center">',ID,'</td><td class="text-center">',
                        CODIGO_META,'</td><td class="text-center">',
                        ANO,'</td>') AS LINE
            FROM METAS ORDER BY CODIGO_META) as ALLINONE
</code>```

Then this error appears:

Msg 9829, Level 16, State 0, Line 1
STRING_AGG aggregation result exceeded the limit of 8000 bytes. Use LOB types to avoid result truncation.

Well, i tryed then create a local var of other type (TEXT) to receive it all. It becames like it:

```<code>DECLARE @final TEXT;

SET @final = (SELECT STRING_AGG(LINE, ' - ') FROM (SELECT TOP(8)
                CONCAT('<td class="text-center">',ID,'</td><td class="text-center">',
                CODIGO_META,'</td><td class="text-center">',
                ANO'</td>') AS LINE
            FROM METAS ORDER BY CODIGO_META) as ALLINONE)
</code>```

But i received this error:

Msg 2739, Level 16, State 1, Line 1
The text, ntext, and image data types are invalid for local variables.

How can i do it? "/

Body:
I'm trying to concatenate all rows of a query in one result... but when i do it, it shows that the result is too long...

First i tryed:

SELECT STRING_AGG(LINE, ' - ') FROM (SELECT TOP(8)
                CONCAT('',ID,'	',
                        CODIGO_META,'	',
                        ANO,'	') AS LINE
            FROM METAS ORDER BY CODIGO_META) as ALLINONE

Then this error appears:

Msg 9829, Level 16, State 0, Line 1
STRING_AGG aggregation result exceeded the limit of 8000 bytes. Use LOB types to avoid result truncation.

Well, i tryed then create a local var of other type (TEXT) to receive it all. It becames like it:

DECLARE @final TEXT;

SET @final = (SELECT STRING_AGG(LINE, ' - ') FROM (SELECT TOP(8)
                CONCAT('',ID,'	',
                CODIGO_META,'	',
                ANO'	') AS LINE
            FROM METAS ORDER BY CODIGO_META) as ALLINONE)

But i received this error:

Msg 2739, Level 16, State 1, Line 1
The text, ntext, and image data types are invalid for local variables.

How can i do it? "/


问:
django-plotly-dash Cannot find Dashapp in the query
I've been trying to implement a dashapp into my django project, and I'm doing so by following the demonstration of the official documentation of django-plotly-dash.

Weirdly enough my Dashapp does not get registered, the queryset in
def get_object_or_404(klass, *args, **kwargs): which is in django shortcuts.py is returned empty, whereas in the working example it is a list of Dashapp objects registered.

Any help is much appreciated.


问:
VS Code Extension. Code highlighting for comparison does not work
I'm writing an extension in Visual Studio Code that should generate assembler code from the current open code "C" or "C++". And after hovering over a line of code in "C" or "C++", the section of code generated from this line should be highlighted. Kind of like a comparison.

extensions.js

```<code>const { exec } = require("child_process");
const vscode = require("vscode");
const path = require('path');

function activate(context) {
  let decorationType = vscode.window.createTextEditorDecorationType({
    backgroundColor: 'rgba(200, 200, 200, 0.5)'
  });

  let mapping = {};

  // Register the hover provider
  vscode.languages.registerHoverProvider(['c', 'cpp'], {
    provideHover(document, position) {
      let lineNum = position.line;
      let assemblerEditor = vscode.window.visibleTextEditors.find(e => e.document.languageId === 'assembler');
      if (assemblerEditor) {
        let assemblerLineNum = mapping[lineNum];
        if (assemblerLineNum !== undefined) {
          assemblerEditor.setDecorations(decorationType, [
            new vscode.Range(assemblerLineNum, 0, assemblerLineNum, Number.MAX_SAFE_INTEGER)
          ]);
        }
      }
    }
  });

  // Register the command that generates the assembly code and opens it
  let disposable = vscode.commands.registerCommand(
    "extension.showAssembly",
    function () {
      let editor = vscode.window.activeTextEditor;
      if (!editor) {
        return;
      }

      // Choice compiler
      let config = vscode.workspace.getConfiguration();
      let compiler = config.get("cvass.compiler.choice");
      let currentFilePath = editor.document.uri.fsPath;
      let dirPath = path.dirname(currentFilePath);
      let oFile = path.join(dirPath, 'output.s');
      let iFile = currentFilePath;

      exec(`${compiler} -S -o "${oFile}" "${iFile}"`, (error, stdout, stderr) => {
        if (error) {
          vscode.window.showErrorMessage(error);
          return;
        }

        // populate the mapping object
        let output = stdout + stderr;
        let lines = output.split('\n');
        lines.forEach((line, index) => {
          if (line.startsWith(currentFilePath)) {
            let cLineNum = parseInt(line.match(/:(\d+)/)[1]);
            mapping[cLineNum] = index;
          }
        });

        vscode.workspace.openTextDocument(oFile).then(doc => {
          vscode.window.showTextDocument(doc, vscode.ViewColumn.Beside, true);
        });
      });
    });

  context.subscriptions.push(disposable);
}

exports.activate = activate;

function deactivate() { }

module.exports = {
  activate,
  deactivate
};

</code>```

In the code above, my attempt at implementation.

For generation I use "g++" and "clang++"

Expected: that the generated source code file will open in a new tab to the right of the "C", "C++" source code. And when you hover over a line of code in "C", "C++" in the assembler code, the section of code created from this line will be highlighted.

The very generation of the assembler and opening it on the right in a new tab is ready.

I really hope for your help, it is not possible to write this functionality at all.

Body:
I'm writing an extension in Visual Studio Code that should generate assembler code from the current open code "C" or "C++". And after hovering over a line of code in "C" or "C++", the section of code generated from this line should be highlighted. Kind of like a comparison.

extensions.js

const { exec } = require("child_process");
const vscode = require("vscode");
const path = require('path');

function activate(context) {
  let decorationType = vscode.window.createTextEditorDecorationType({
    backgroundColor: 'rgba(200, 200, 200, 0.5)'
  });

  let mapping = {};

  // Register the hover provider
  vscode.languages.registerHoverProvider(['c', 'cpp'], {
    provideHover(document, position) {
      let lineNum = position.line;
      let assemblerEditor = vscode.window.visibleTextEditors.find(e => e.document.languageId === 'assembler');
      if (assemblerEditor) {
        let assemblerLineNum = mapping[lineNum];
        if (assemblerLineNum !== undefined) {
          assemblerEditor.setDecorations(decorationType, [
            new vscode.Range(assemblerLineNum, 0, assemblerLineNum, Number.MAX_SAFE_INTEGER)
          ]);
        }
      }
    }
  });

  // Register the command that generates the assembly code and opens it
  let disposable = vscode.commands.registerCommand(
    "extension.showAssembly",
    function () {
      let editor = vscode.window.activeTextEditor;
      if (!editor) {
        return;
      }

      // Choice compiler
      let config = vscode.workspace.getConfiguration();
      let compiler = config.get("cvass.compiler.choice");
      let currentFilePath = editor.document.uri.fsPath;
      let dirPath = path.dirname(currentFilePath);
      let oFile = path.join(dirPath, 'output.s');
      let iFile = currentFilePath;

      exec(`${compiler} -S -o "${oFile}" "${iFile}"`, (error, stdout, stderr) => {
        if (error) {
          vscode.window.showErrorMessage(error);
          return;
        }

        // populate the mapping object
        let output = stdout + stderr;
        let lines = output.split('\n');
        lines.forEach((line, index) => {
          if (line.startsWith(currentFilePath)) {
            let cLineNum = parseInt(line.match(/:(\d+)/)[1]);
            mapping[cLineNum] = index;
          }
        });

        vscode.workspace.openTextDocument(oFile).then(doc => {
          vscode.window.showTextDocument(doc, vscode.ViewColumn.Beside, true);
        });
      });
    });

  context.subscriptions.push(disposable);
}

exports.activate = activate;

function deactivate() { }

module.exports = {
  activate,
  deactivate
};

In the code above, my attempt at implementation.

For generation I use "g++" and "clang++"

Expected: that the generated source code file will open in a new tab to the right of the "C", "C++" source code. And when you hover over a line of code in "C", "C++" in the assembler code, the section of code created from this line will be highlighted.

The very generation of the assembler and opening it on the right in a new tab is ready.

I really hope for your help, it is not possible to write this functionality at all.


问:
"Timed out waiting for launcher to connect" preventing debugger from launching
I am trying to run a debugger, but it consistently sends back a message with the above quote and an option to open the launch.json file.

```<code> {
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}
</code>```

This is what my launch.json file looks like. I've currently tried:

Deleting and recreating the launch.json file

Altering the launch.json file according to Time out waiting for launcher to connect in VS code

Going back to an earlier version of the python extension

Uninstalling all of my python extensions and reinstalling them

My Python version is currently 3.9.0 according to the text at the bottom right corner of the VScode window. The rest of VScode with Python appears to work as expected.

This is what my terminal looks like:

```<code>PS C:\Users\alexs\Documents\BEng\Software 1\Formative Assessment\2\SOF1-2022-23-EvenYears-Formative-2\ClosedExamination> \Users\alexs\AppData\Local\Microsoft\WindowsApps\python3.7.exe' 'c:\Users\alexs\.vscode\extensions\ms-python.python-2022.20.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '57863' '--' 'c:\Users\alexs\Documents\BEng\Software 1\Formative Assessment\2\SOF1-2022-23-EvenYears-Formative-2\ClosedExamination\test_question_4.py'
>>  'C:
</code>```

Body:
I am trying to run a debugger, but it consistently sends back a message with the above quote and an option to open the launch.json file.

 {
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}

This is what my launch.json file looks like. I've currently tried:

Deleting and recreating the launch.json file

Altering the launch.json file according to Time out waiting for launcher to connect in VS code

Going back to an earlier version of the python extension

Uninstalling all of my python extensions and reinstalling them

My Python version is currently 3.9.0 according to the text at the bottom right corner of the VScode window. The rest of VScode with Python appears to work as expected.

This is what my terminal looks like:

PS C:\Users\alexs\Documents\BEng\Software 1\Formative Assessment\2\SOF1-2022-23-EvenYears-Formative-2\ClosedExamination> \Users\alexs\AppData\Local\Microsoft\WindowsApps\python3.7.exe' 'c:\Users\alexs\.vscode\extensions\ms-python.python-2022.20.2\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '57863' '--' 'c:\Users\alexs\Documents\BEng\Software 1\Formative Assessment\2\SOF1-2022-23-EvenYears-Formative-2\ClosedExamination\test_question_4.py'
>>  'C:


问:
Compute a Bounding Box with defined orientation
I have some objects (given as segments in 3D slicer, also given as 3D npy image).
I want to use vtk to compute an Oriented Bounding Box. But the objects have a rather unregular shape, and if I use the vtkOBBTree Class to compute an OBB, the OBB does not match the intended orientation of my object.

I was able to define an orientation for one axis, and this orientation is supposed to define one axis of the OBB
like this Is there a way to compute a bounding Box (with vtk?) with a predefined orientation?


问:
Re-export namespace using type specifier
Is it possible to re-export a namespace that was imported using the type specifier? In the below example (that doesn't work properly) I'm importing the tslib namespace from typescript/lib/tsserverlibrary.js and then trying to re-export the tslib.server.protocol sub-namespace from it while also including the type specifier.

```<code>import type tslib from 'typescript/lib/tsserverlibrary.js';

export type tsp = typeof tslib.server.protocol;
</code>```

I've tried both:

```<code>export type tsp = typeof tslib.server.protocol;
</code>```

which doesn't work at import-sites because tsp is a type and not a namespace anymore:

'tsp' only refers to a type, but is being used as a namespace here. typescript(2702)

I've also tried:

```<code>export import tsp = tslib.server.protocol;
</code>```

but that errors with:

An import alias cannot reference a declaration that was imported using 'import type'. typescript(1380)

Body:
Is it possible to re-export a namespace that was imported using the type specifier? In the below example (that doesn't work properly) I'm importing the tslib namespace from typescript/lib/tsserverlibrary.js and then trying to re-export the tslib.server.protocol sub-namespace from it while also including the type specifier.

import type tslib from 'typescript/lib/tsserverlibrary.js';

export type tsp = typeof tslib.server.protocol;

I've tried both:

export type tsp = typeof tslib.server.protocol;

which doesn't work at import-sites because tsp is a type and not a namespace anymore:

'tsp' only refers to a type, but is being used as a namespace here. typescript(2702)

I've also tried:

export import tsp = tslib.server.protocol;

but that errors with:

An import alias cannot reference a declaration that was imported using 'import type'. typescript(1380)


问:
how to connect postgres to azure ? (golang-azure)
I have an application that has only the POST method, and every time I make a request in that application, it saves some data for me in my postgres database..
locally my application works properly, but when I deploy and try to test it through the azure function app it returns a 500 error and says that it was not possible to store my information in the database..
here are some code snippets

go code:

func (h handler) sendgridWeb(c *gin.Context) {

    data, _ := io.ReadAll(c.Request.Body)
    var ListaEventoEmail []Email
    if err := json.Unmarshal(data, &ListaEventoEmail); err != nil {

        log.Fatal("Error when unrealizing content contained in Body")

    }
    for _, email := range ListaEventoEmail {
        email.SgMessageId = email.SgMessageId[:strings.IndexByte(email.SgMessageId, '.')]

        //-- PROCESSED --//

        if email.Event == "processed" {

            inserting := `insert into email (email_destinatario, enviado, id_sendgrid) values ($1, $2, $3)`
            _, err := h.DB.Exec(inserting, email.Email, true, email.SgMessageId)
            if err != nil {
                log.Fatal("Error inserting data into email table")
            }

        }
        //-- DELIVERED --//

        if email.Event == "delivered" {
            _, err := h.DB.Exec(`UPDATE email SET recebido=true WHERE id_sendgrid=$1`, email.SgMessageId)
            if err != nil {
                log.Fatal("Error when uploading email with DELIVERED event")
            }

            //-- OPEN --//

        } else if email.Event == "open" {
            _, err := h.DB.Exec(`UPDATE email SET recebido=true, aberto=true WHERE id_sendgrid=$1`, email.SgMessageId)
            if err != nil {
                log.Fatal("Error when uploading email with OPEN event")
            }
        } else if email.Event == "click" {
            _, err := h.DB.Exec(`UPDATE email SET click = click + 1 WHERE id_sendgrid=$1`, email.SgMessageId)
            if err != nil {
                log.Fatal("Error when uploading email with CLICK event")
            }
        }```
</div>
</div>
</p>
<p>my connection string is stored in a toml file..
connection string:</p>
```# filename: config.toml
[postgres]
host = "132.168.0.22"
port =  5432
user = "postgres"
password = "ivaneteJC"
dbname = "webhook"
```
<p>you can see that, in the HOST field I put my IP (fictitious ip)..
in my logic, when deploying to azure, my connection string should point to my machine, so I used the ip, thus performing the necessary operations on my database, but this does not happen .. when making a POST request by the postman (using the endpoint that o was provided when deploying to the azure function app, I get a 500 error and in my logs I get the message "Error inserting data into the email table" which is an error described in my go app, I believe I made a mistake somewhere that has a connection to the database, can someone help me?</p>
<p>function.json:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}</code>```

host.json:

```<code>{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.*, 4.0.0)"
  },
  "customHandler": {
    "description": {
      "defaultExecutablePath": "main.exe",
      "workingDirectory": "",
      "arguments": []
    },
    "enableForwardingHttpRequest": true
  }
}
</code>```

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "custom"
  }
}```
</div>
</div>
</p>
<p>I did as mentioned in a comment, I treated the error in an original way .. and the following error appeared:</p>
```"connectex: An attempt was made to access a socket in a way prohibited by its access permissions."
```
<p>db:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>type handler struct {
    DB *sql.DB
}

type PostgreConfig struct {
    Host     string
    Port     int
    User     string
    Password string
    Dbname   string
}

type MyConfig struct {
    Postgres *PostgreConfig
}

func Init() *sql.DB {
    doc, err := os.ReadFile("config.toml")
    if err != nil {
        panic(err)
    }

    var cfg MyConfig

    err = toml.Unmarshal(doc, &cfg)
    if err != nil {
        panic(err)
    }

    stringConn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", cfg.Postgres.Host, cfg.Postgres.Port, cfg.Postgres.User, cfg.Postgres.Password, cfg.Postgres.Dbname)

    db, err := sql.Open("postgres", stringConn)
    if err != nil {
        log.Fatal("Erro ao realizar conexão")
    } else {
        fmt.Println("Conectado")
    }
    fmt.Println(stringConn)

    db.Ping()
    return db

}
func OpenDB(DB *sql.DB) handler {
    return handler{DB}
}</code>```

Body:
I have an application that has only the POST method, and every time I make a request in that application, it saves some data for me in my postgres database..
locally my application works properly, but when I deploy and try to test it through the azure function app it returns a 500 error and says that it was not possible to store my information in the database..
here are some code snippets

go code:

func (h handler) sendgridWeb(c *gin.Context) {

    data, _ := io.ReadAll(c.Request.Body)
    var ListaEventoEmail []Email
    if err := json.Unmarshal(data, &ListaEventoEmail); err != nil {

        log.Fatal("Error when unrealizing content contained in Body")

    }
    for _, email := range ListaEventoEmail {
        email.SgMessageId = email.SgMessageId[:strings.IndexByte(email.SgMessageId, '.')]

        //-- PROCESSED --//

        if email.Event == "processed" {

            inserting := `insert into email (email_destinatario, enviado, id_sendgrid) values ($1, $2, $3)`
            _, err := h.DB.Exec(inserting, email.Email, true, email.SgMessageId)
            if err != nil {
                log.Fatal("Error inserting data into email table")
            }

        }
        //-- DELIVERED --//

        if email.Event == "delivered" {
            _, err := h.DB.Exec(`UPDATE email SET recebido=true WHERE id_sendgrid=$1`, email.SgMessageId)
            if err != nil {
                log.Fatal("Error when uploading email with DELIVERED event")
            }

            //-- OPEN --//

        } else if email.Event == "open" {
            _, err := h.DB.Exec(`UPDATE email SET recebido=true, aberto=true WHERE id_sendgrid=$1`, email.SgMessageId)
            if err != nil {
                log.Fatal("Error when uploading email with OPEN event")
            }
        } else if email.Event == "click" {
            _, err := h.DB.Exec(`UPDATE email SET click = click + 1 WHERE id_sendgrid=$1`, email.SgMessageId)
            if err != nil {
                log.Fatal("Error when uploading email with CLICK event")
            }
        }

my connection string is stored in a toml file..
connection string:

# filename: config.toml
[postgres]
host = "132.168.0.22"
port =  5432
user = "postgres"
password = "ivaneteJC"
dbname = "webhook"

you can see that, in the HOST field I put my IP (fictitious ip)..
in my logic, when deploying to azure, my connection string should point to my machine, so I used the ip, thus performing the necessary operations on my database, but this does not happen .. when making a POST request by the postman (using the endpoint that o was provided when deploying to the azure function app, I get a 500 error and in my logs I get the message "Error inserting data into the email table" which is an error described in my go app, I believe I made a mistake somewhere that has a connection to the database, can someone help me?

function.json:

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

host.json:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[3.*, 4.0.0)"
  },
  "customHandler": {
    "description": {
      "defaultExecutablePath": "main.exe",
      "workingDirectory": "",
      "arguments": []
    },
    "enableForwardingHttpRequest": true
  }
}

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "custom"
  }
}

I did as mentioned in a comment, I treated the error in an original way .. and the following error appeared:

"connectex: An attempt was made to access a socket in a way prohibited by its access permissions."

db:

type handler struct {
    DB *sql.DB
}

type PostgreConfig struct {
    Host     string
    Port     int
    User     string
    Password string
    Dbname   string
}

type MyConfig struct {
    Postgres *PostgreConfig
}

func Init() *sql.DB {
    doc, err := os.ReadFile("config.toml")
    if err != nil {
        panic(err)
    }

    var cfg MyConfig

    err = toml.Unmarshal(doc, &cfg)
    if err != nil {
        panic(err)
    }

    stringConn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", cfg.Postgres.Host, cfg.Postgres.Port, cfg.Postgres.User, cfg.Postgres.Password, cfg.Postgres.Dbname)

    db, err := sql.Open("postgres", stringConn)
    if err != nil {
        log.Fatal("Erro ao realizar conexão")
    } else {
        fmt.Println("Conectado")
    }
    fmt.Println(stringConn)

    db.Ping()
    return db

}
func OpenDB(DB *sql.DB) handler {
    return handler{DB}
}