问:
Writing widget test for side menus, while building a desktop application
I am getting error when mocking the page controller, I have tried many possibilities but nothing worked.

```<code>class HomePage extends StatefulWidget {
  const HomePage({Key? key, this.sideMenuPageController}) : super(key: key);
  final SideMenuPageController? sideMenuPageController;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  SideMenuPageController? _sideMenuPageController;

  @override
  void initState() {
    _sideMenuPageController = widget.sideMenuPageController ?? SideMenuPageController(setState: setState);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: const Key("home_page_scaffold"),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SideMenuEntry(sideMenuPageController: _sideMenuPageController!),
          // SideMenPageView(sideMenuPageController: _sideMenuPageController!),
        ],
      ),
    );
  }
}
</code>```
```<code>class SideMenuEntry extends StatelessWidget {
  const SideMenuEntry({Key? key, required this.sideMenuPageController}) : super(key: key);
  final SideMenuPageController sideMenuPageController;

  @override
  Widget build(BuildContext context) {
    SideMenuHeading _sideMenuHeading = SideMenuHeading(sideMenuPageController: sideMenuPageController);

    return SideMenu(
      controller: sideMenuPageController.getPageController,
      style: SideMenuCustomStyle().sideMenuStyle,
      title: const SideMenuIcon(),
      footer: const SideMenuFooter(),
      items: _sideMenuHeading.menuEntries.map((heading) {
        return _sideMenuHeading.sideMenuHeading(heading["title"], heading["icon"], heading["priority"]);
      }).toList(),
    );
  }
}
</code>```
```<code>My test code:

@GenerateMocks([], customMocks: [
  MockSpec<SideMenuPageController>(as: #MockSideMenuPageControllerNullStub, returnNullOnMissingStub: true),
  MockSpec<SideMenuHeading>(as: #MockSideMenuHeadingNullStub, returnNullOnMissingStub: true),
  MockSpec<PageController>(as: #MockPageControllerNullStub, returnNullOnMissingStub: true)
])
void main() {
  late SideMenuPageController _sideMenuPageController;
  late SideMenuHeading _sideMenuHeadingMock;
  late PageController _pageControllerMock;

  List menuEntries = [
    {"title": "Customers", "icon": const Icon(Icons.supervisor_account), "priority": 0},
    {"title": "Customer Details", "icon": null, "priority": 1},
    {"title": "Registered Customers", "icon": null, "priority": 2},
    {"title": "Registered Products", "icon": null, "priority": 3},
    {"title": "Calmee Customers", "icon": const Icon(Icons.library_music_rounded), "priority": 4},
    {"title": "Spindler Customers", "icon": null, "priority": 5},
    {"title": "Customer’s Relaxation Survey", "icon": null, "priority": 6},
    {"title": "Feelbelt Usage", "icon": const Icon(Icons.data_usage_sharp), "priority": 7}
  ];

  setUp(() {
    _sideMenuPageController = MockSideMenuPageControllerNullStub();
    _sideMenuHeadingMock = MockSideMenuHeadingNullStub();
    _pageControllerMock = MockPageControllerNullStub();
    when(_sideMenuPageController.getPageController).thenReturn(_pageControllerMock);
    when(_sideMenuHeadingMock.menuEntries).thenReturn(menuEntries);
    when(_sideMenuPageController.changeSelectedPage(0)).thenReturn(null);
    when(_sideMenuPageController.selectedCalmeeUserEmail("")).thenReturn(null);
    when(_sideMenuPageController.getCalmeeUserEmail).thenReturn("");
    when(_sideMenuPageController.getSelectedPage).thenReturn(0);
    when(_pageControllerMock.jumpTo(0)).thenReturn(null);
  });
  testWidgets("Find home page scaffold", (WidgetTester tester) async {
    tester.binding.window.physicalSizeTestValue = const Size(1200, 850);
    tester.binding.window.devicePixelRatioTestValue = 1.0;

    final findScaffold = find.byKey(const Key("home_page_scaffold"));
    await tester.runAsync(() async {
      await tester.pumpWidget(MaterialApp(
        home: HomePage(
          sideMenuPageController: _sideMenuPageController,
        ),
      ));

      await tester.pump();

      expect(findScaffold, findsOneWidget);

      await tester.pumpAndSettle();
    });
  });
}
</code>```

Error:

══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════ The following _CastError was thrown during a scheduler callback: type 'Null' is not a subtype of type 'int' in type cast When the exception was thrown, this was the stack: #0 MockPageControllerNullStub.initialPage (file:///Users/coolwills/datacollector/test/home_page/home_page_test.mocks.dart:92:11) #1 _SideMenuItemState.initState.<anonymous closure>.<anonymous closure> (package:easy_sidemenu/src/side_menu_item.dart:90:41) #2 State.setState (package:flutter/src/widgets/framework.dart:1121:30) #3 _SideMenuItemState.initState.<anonymous closure> (package:easy_sidemenu/src/side_menu_item.dart:89:7) #4 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15) #5 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1089:9) #6 AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:995:9) #9 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41) #10 AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:982:27) #11 WidgetTester.pumpWidget.<anonymous closure> (package:flutter_test/src/widget_tester.dart:548:22) #14 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41) #15 WidgetTester.pumpWidget (package:flutter_test/src/widget_tester.dart:545:27) #16 main.<anonymous closure>.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:50:20) #17 main.<anonymous closure>.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:49:27) #18 AutomatedTestWidgetsFlutterBinding.runAsync.<anonymous closure> (package:flutter_test/src/binding.dart:1039:32) #19 AutomatedTestWidgetsFlutterBinding.runAsync.<anonymous closure> (package:flutter_test/src/binding.dart:1035:42) #22 AutomatedTestWidgetsFlutterBinding.runAsync (package:flutter_test/src/binding.dart:1035:26) #23 WidgetTester.runAsync (package:flutter_test/src/widget_tester.dart:780:17) #24 main.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:49:18) #25 main.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:44:42) #26 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:170:29) <asynchronous suspension> <asynchronous suspension> (elided 7 frames from dart:async and package:stack_trace) ════════════════════════════════════════════════════════════════════════════════════════════════════

Body:
I am getting error when mocking the page controller, I have tried many possibilities but nothing worked.

class HomePage extends StatefulWidget {
  const HomePage({Key? key, this.sideMenuPageController}) : super(key: key);
  final SideMenuPageController? sideMenuPageController;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  SideMenuPageController? _sideMenuPageController;

  @override
  void initState() {
    _sideMenuPageController = widget.sideMenuPageController ?? SideMenuPageController(setState: setState);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: const Key("home_page_scaffold"),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SideMenuEntry(sideMenuPageController: _sideMenuPageController!),
          // SideMenPageView(sideMenuPageController: _sideMenuPageController!),
        ],
      ),
    );
  }
}

class SideMenuEntry extends StatelessWidget {
  const SideMenuEntry({Key? key, required this.sideMenuPageController}) : super(key: key);
  final SideMenuPageController sideMenuPageController;

  @override
  Widget build(BuildContext context) {
    SideMenuHeading _sideMenuHeading = SideMenuHeading(sideMenuPageController: sideMenuPageController);

    return SideMenu(
      controller: sideMenuPageController.getPageController,
      style: SideMenuCustomStyle().sideMenuStyle,
      title: const SideMenuIcon(),
      footer: const SideMenuFooter(),
      items: _sideMenuHeading.menuEntries.map((heading) {
        return _sideMenuHeading.sideMenuHeading(heading["title"], heading["icon"], heading["priority"]);
      }).toList(),
    );
  }
}

My test code:

@GenerateMocks([], customMocks: [
  MockSpec<SideMenuPageController>(as: #MockSideMenuPageControllerNullStub, returnNullOnMissingStub: true),
  MockSpec<SideMenuHeading>(as: #MockSideMenuHeadingNullStub, returnNullOnMissingStub: true),
  MockSpec<PageController>(as: #MockPageControllerNullStub, returnNullOnMissingStub: true)
])
void main() {
  late SideMenuPageController _sideMenuPageController;
  late SideMenuHeading _sideMenuHeadingMock;
  late PageController _pageControllerMock;

  List menuEntries = [
    {"title": "Customers", "icon": const Icon(Icons.supervisor_account), "priority": 0},
    {"title": "Customer Details", "icon": null, "priority": 1},
    {"title": "Registered Customers", "icon": null, "priority": 2},
    {"title": "Registered Products", "icon": null, "priority": 3},
    {"title": "Calmee Customers", "icon": const Icon(Icons.library_music_rounded), "priority": 4},
    {"title": "Spindler Customers", "icon": null, "priority": 5},
    {"title": "Customer’s Relaxation Survey", "icon": null, "priority": 6},
    {"title": "Feelbelt Usage", "icon": const Icon(Icons.data_usage_sharp), "priority": 7}
  ];

  setUp(() {
    _sideMenuPageController = MockSideMenuPageControllerNullStub();
    _sideMenuHeadingMock = MockSideMenuHeadingNullStub();
    _pageControllerMock = MockPageControllerNullStub();
    when(_sideMenuPageController.getPageController).thenReturn(_pageControllerMock);
    when(_sideMenuHeadingMock.menuEntries).thenReturn(menuEntries);
    when(_sideMenuPageController.changeSelectedPage(0)).thenReturn(null);
    when(_sideMenuPageController.selectedCalmeeUserEmail("")).thenReturn(null);
    when(_sideMenuPageController.getCalmeeUserEmail).thenReturn("");
    when(_sideMenuPageController.getSelectedPage).thenReturn(0);
    when(_pageControllerMock.jumpTo(0)).thenReturn(null);
  });
  testWidgets("Find home page scaffold", (WidgetTester tester) async {
    tester.binding.window.physicalSizeTestValue = const Size(1200, 850);
    tester.binding.window.devicePixelRatioTestValue = 1.0;

    final findScaffold = find.byKey(const Key("home_page_scaffold"));
    await tester.runAsync(() async {
      await tester.pumpWidget(MaterialApp(
        home: HomePage(
          sideMenuPageController: _sideMenuPageController,
        ),
      ));

      await tester.pump();

      expect(findScaffold, findsOneWidget);

      await tester.pumpAndSettle();
    });
  });
}

Error:

══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════ The following _CastError was thrown during a scheduler callback: type 'Null' is not a subtype of type 'int' in type cast When the exception was thrown, this was the stack: #0 MockPageControllerNullStub.initialPage (file:///Users/coolwills/datacollector/test/home_page/home_page_test.mocks.dart:92:11) #1 _SideMenuItemState.initState.<anonymous closure>.<anonymous closure> (package:easy_sidemenu/src/side_menu_item.dart:90:41) #2 State.setState (package:flutter/src/widgets/framework.dart:1121:30) #3 _SideMenuItemState.initState.<anonymous closure> (package:easy_sidemenu/src/side_menu_item.dart:89:7) #4 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15) #5 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1089:9) #6 AutomatedTestWidgetsFlutterBinding.pump.<anonymous closure> (package:flutter_test/src/binding.dart:995:9) #9 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41) #10 AutomatedTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:982:27) #11 WidgetTester.pumpWidget.<anonymous closure> (package:flutter_test/src/widget_tester.dart:548:22) #14 TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41) #15 WidgetTester.pumpWidget (package:flutter_test/src/widget_tester.dart:545:27) #16 main.<anonymous closure>.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:50:20) #17 main.<anonymous closure>.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:49:27) #18 AutomatedTestWidgetsFlutterBinding.runAsync.<anonymous closure> (package:flutter_test/src/binding.dart:1039:32) #19 AutomatedTestWidgetsFlutterBinding.runAsync.<anonymous closure> (package:flutter_test/src/binding.dart:1035:42) #22 AutomatedTestWidgetsFlutterBinding.runAsync (package:flutter_test/src/binding.dart:1035:26) #23 WidgetTester.runAsync (package:flutter_test/src/widget_tester.dart:780:17) #24 main.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:49:18) #25 main.<anonymous closure> (file:///Users/coolwills/datacollector/test/home_page/home_page_test.dart:44:42) #26 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:170:29) <asynchronous suspension> <asynchronous suspension> (elided 7 frames from dart:async and package:stack_trace) ════════════════════════════════════════════════════════════════════════════════════════════════════


来源: stackexchange

问:
Search in TEXT[] column in Spring JPA Specification API
I use Postgres in my application. I have a table where I store list of string in a column which is of type text[].
I want to use the Spring JPA Specification API to search the elements in the column.

I would like to use Specification API to search a list of entities where industries are in ['a', 'b', 'c'].
This is how my entity class looks like.

```<code>@Setter
@Getter
@Entity
@Table(name = "TABLE_NAME")
@TypeDef(name = "list-array", typeClass = ListArrayType.class)
public class TableEntity {

    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Type(type = "list-array")
    @Column(name = "INDUSTRIES", columnDefinition = "text[]")
    private List<String> industries;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I use Postgres in my application. I have a table where I store list of string in a column which is of type text[].
I want to use the Spring JPA Specification API to search the elements in the column.

I would like to use Specification API to search a list of entities where industries are in ['a', 'b', 'c'].
This is how my entity class looks like.

@Setter
@Getter
@Entity
@Table(name = "TABLE_NAME")
@TypeDef(name = "list-array", typeClass = ListArrayType.class)
public class TableEntity {

    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Type(type = "list-array")
    @Column(name = "INDUSTRIES", columnDefinition = "text[]")
    private List<String> industries;
}


问:
Filter main table by sub / sub field relation
Seeing this query:

```<code>query ListPosts(
    $filter: ModelPostFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        title
        description
        personID
        media {
          items {
            id
            type
            postID
            taggedPersons{
              items {
                id
                personID
                mediaID
              }
              nextToken
            }
          }
          nextToken
        }
      }
    }
  }
</code>```

I would like to filter the posts:

Where the owner has a personID {filter:{personID:{eq: $personID}}}

OR where the person is in the taggedPersons list

Getting the post by this sub sub relation I can't figure out. How would I do this?

Body:
Seeing this query:

query ListPosts(
    $filter: ModelPostFilterInput
    $limit: Int
    $nextToken: String
  ) {
    listPosts(filter: $filter, limit: $limit, nextToken: $nextToken) {
      items {
        id
        title
        description
        personID
        media {
          items {
            id
            type
            postID
            taggedPersons{
              items {
                id
                personID
                mediaID
              }
              nextToken
            }
          }
          nextToken
        }
      }
    }
  }

I would like to filter the posts:

Where the owner has a personID {filter:{personID:{eq: $personID}}}

OR where the person is in the taggedPersons list

Getting the post by this sub sub relation I can't figure out. How would I do this?


问:
Javascript changing execution order
I have a form page here:

const currencyField = new AutoNumeric('.currency', 'Brazilian');

let tags = [{
    "value": "California",
    "color": "#800000"
  },
  {
    "value": "Texas",
    "color": "#000080"
  },
  {
    "value": "Florida",
    "color": "#f58230"
  },
  {
    "value": "New York",
    "color": "#ffff00"
  },
  {
    "value": "Pennsylvania",
    "color": "#0082c8"
  },
  {
    "value": "Illinois",
    "color": "#000000"
  },
  {
    "value": "Ohio",
    "color": "#4a8722"
  },
  {
    "value": "Georgia",
    "color": "#5d0909"
  },
  {
    "value": "North Carolina",
    "color": "#03440e"
  }
]

$('#tags_field').tagsinput({
  typeahead: ({
    source: tags.map(t => t.value),
    afterSelect: function() {
      this.$element[0].value = '';
      updateTagsinput()
    }
  }),
  tagClass: function(item) {
    return 'badge badge-info';
  }
})

function updateTagsinput() {

  $(`#tags_field_DIV .bootstrap-tagsinput > span.badge`).each(function() {
    $(this).each(function() {
      $(this).addClass('mx-1')
      let tag = tags.find(x => x.value == $(this)[0].innerText)
      if (tag) {
        $(this).css('background-color', `${tag.color}`)
        $(this).css('color', `${blackOrWhiteTextColor(tag.color)}`)
      }
    })
  })
}

function blackOrWhiteTextColor(cor) {
  cor = chroma(cor).brighten(3).hex();
  corRGB = hexToRgb(cor);
  if (corRGB.r * 0.299 + corRGB.g * 0.587 + corRGB.b * 0.114 > 186) {
    return "#000000";
  } else {
    return "#ffffff";
  }
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ?
    {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16),
    } :
    null;
}

function clearForm() {
  $('#form').trigger("reset");
  $("#tags_field").tagsinput('removeAll');
}

function randomize(clear = true) {
  if (clear)
    clearForm()
  $('#text_field_1').val(`${(Math.trunc(Math.random() * 99999999)).toString(36)}`)
  $('#text_field_2').val('Lorem ipsum dolor sit amet.')
  currencyField.set(Math.random() * 99999999)
  for (let i = 0; i < tags.length; i++) {
    if (Math.random() < 0.2) {
      $('#tags_field').tagsinput('add', tags[i].value);
    }
  }

  if (Math.random() > 0.3) {
    $('#option_field').prop("checked", true)
  } else {
    $('#option_field').prop("checked", false)
  }

  $(`#checkList > li`).each(function() {
    if (Math.random() < 0.13) {
      $(this).children(":first").children(":first").prop("checked", true)
    } else {
      $(this).children(":first").children(":first").prop("checked", false)
    }
  });
  updateTagsinput()
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" crossorigin="anonymous">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput-typeahead.css" rel="stylesheet" type="text/css" />
  <style>
    .bootstrap-tagsinput {
      width: 100%;
    }
  </style>
</head>

<body>
  <div>
    <form class="m-2" id="form" action="" method="post" autocomplete="off">
      <div class="form-group">
        <label for="text_field_1">Text Field #1</label>
        <input type="text" class="form-control" id="text_field_1" name="text_field_1">
      </div>
      <div class="form-group">
        <label for="text_field_2">Text Field #2</label>
        <textarea class="form-control" id="text_field_2" name="text_field_2" rows="3"></textarea>
      </div>
      <div class="form-row vertical-align">
        <div class="form-group col-4" id="adicionarProjetoCustoEstimadoDIV">
          <label for="currency_field">Currency Field</label>
          <input type="text" class="form-control currency" id="currency_field" name="currency_field">
        </div>
        <div class="form-group col-4" id="tags_field_DIV">
          <label for="tags_field">Tags Field</label>
          <input type="text" class="form-control tagsinput" data-role="tagsinput" id="tags_field" name="tags_field">
        </div>
        <div class="form-group col-4" id="option_field_DIV" style="text-align:center;">
          <div class="form-check">
            <input type="checkbox" class="form-check-input" id="option_field" name="option_field">
            <label class="form-check-label" for="option_field">Check Field.</label>
          </div>
        </div>
      </div>
      <hr>
      <div>
        <label class="h6">Categoria(s)</label>

        <ul class="chk" id="checkList" style="columns: 3">
          <li style="display:inline-block;">
            <div id="checkOptions" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_1" name="Option #1">
              <label class="custom-control-label" for="option_1">
                                            Option #1
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_2" name="Option #2">
              <label class="custom-control-label" for="option_2">
                                            Option #2
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_3" name="Option #3">
              <label class="custom-control-label" for="option_3">
                                            Option #3
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_4" name="Option #4">
              <label class="custom-control-label" for="option_4">
                                            Option #4
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_5" name="Option #5">
              <label class="custom-control-label" for="option_5">
                                            Option #5
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_6" name="Option #6">
              <label class="custom-control-label" for="option_6">
                                            Option #6
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_7" name="Option #7">
              <label class="custom-control-label" for="option_7">
                                            Option #7
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_8" name="Option #8">
              <label class="custom-control-label" for="option_8">
                                            Option #8
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_9" name="Option #9">
              <label class="custom-control-label" for="option_9">
                                            Option #9
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_10" name="Option #10">
              <label class="custom-control-label" for="option_10">
                                            Option #10
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_11" name="Option #11">
              <label class="custom-control-label" for="option_11">
                                            Option #11
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_12" name="Option #12">
              <label class="custom-control-label" for="option_12">
                                            Option #12
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_13" name="Option #13">
              <label class="custom-control-label" for="option_13">
                                            Option #13
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_14" name="Option #14">
              <label class="custom-control-label" for="option_14">
                                            Option #14
                                        </label></div>
          </li><br>
          <li style="display:inline-block;">
            <div id="checkCategorias" class="custom-control custom-checkbox">
              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_15" name="Option #15">
              <label class="custom-control-label" for="option_15">
                                            Option #15
                                        </label></div>
          </li>
        </ul>

      </div>
      <button type="button" id="clearButton" onclick="clearForm();blur()" class="d-none d-sm-inline-block btn btn-info">Clear form</button>
      <button type="button" id="rendomizeButton" onclick="randomize();blur()" class="d-none d-sm-inline-block btn btn-info">Randomize data</button>
      <button type="button" id="rendomizeButton" onclick="randomize(false);blur()" class="d-none d-sm-inline-block btn btn-info">Randomize data without clear</button>
    </form>
  </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/4.6.0/autoNumeric.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.4.2/chroma.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js"></script></code>```

At the bottom of the page I have 3 buttons to 1) clear the form; 2) clear the form then fill with random data; 3) fill with random data (without cleaning before)

This is the function to randomize data:

```<code>function randomize(clear = true) {
    if (clear)
        clearForm()
    $('#text_field_1').val(`${(Math.trunc(Math.random() * 99999999)).toString(36)}`)
    $('#text_field_2').val('Lorem ipsum dolor sit amet.')
    currencyField.set(Math.random() * 99999999)
    for (let i = 0; i < tags.length; i++) {
        if (Math.random() < 0.2) {
            $('#tags_field').tagsinput('add', tags[i].value);
        }
    }

    if (Math.random() > 0.3) {
        $('#option_field').prop("checked", true)
    } else {
        $('#option_field').prop("checked", false)
    }

        $(`#checkList > li`).each(function () {
        if (Math.random() < 0.13) {
            $(this).children(":first").children(":first").prop("checked", true)
        } else {
            $(this).children(":first").children(":first").prop("checked", false)
        }
    });
    updateTagsinput()
}
</code>```

My problem is, even with my instruction at the function being clear the form BEFORE filling it with random data, the field with AutoNumeric (Currency Field) seems to being filled before the form is cleaned. I can't understand what this is happening. There is no async functions.

When the randomize function is called without the clear command, the field currency is filled.
But when you try to clear the form before fill it, the execution is being in inverse order: the form is filled on Currncy Field, and then it is cleaned right after.

Title: Javascript changing execution order

Body:
I have a form page here:

const currencyField = new AutoNumeric('.currency', 'Brazilian');

let tags = [{
    "value": "California",
    "color": "#800000"
  },
  {
    "value": "Texas",
    "color": "#000080"
  },
  {
    "value": "Florida",
    "color": "#f58230"
  },
  {
    "value": "New York",
    "color": "#ffff00"
  },
  {
    "value": "Pennsylvania",
    "color": "#0082c8"
  },
  {
    "value": "Illinois",
    "color": "#000000"
  },
  {
    "value": "Ohio",
    "color": "#4a8722"
  },
  {
    "value": "Georgia",
    "color": "#5d0909"
  },
  {
    "value": "North Carolina",
    "color": "#03440e"
  }
]

$('#tags_field').tagsinput({
  typeahead: ({
    source: tags.map(t => t.value),
    afterSelect: function() {
      this.$element[0].value = '';
      updateTagsinput()
    }
  }),
  tagClass: function(item) {
    return 'badge badge-info';
  }
})

function updateTagsinput() {

  $(`#tags_field_DIV .bootstrap-tagsinput > span.badge`).each(function() {
    $(this).each(function() {
      $(this).addClass('mx-1')
      let tag = tags.find(x => x.value == $(this)[0].innerText)
      if (tag) {
        $(this).css('background-color', `${tag.color}`)
        $(this).css('color', `${blackOrWhiteTextColor(tag.color)}`)
      }
    })
  })
}

function blackOrWhiteTextColor(cor) {
  cor = chroma(cor).brighten(3).hex();
  corRGB = hexToRgb(cor);
  if (corRGB.r * 0.299 + corRGB.g * 0.587 + corRGB.b * 0.114 > 186) {
    return "#000000";
  } else {
    return "#ffffff";
  }
}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ?
    {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16),
    } :
    null;
}

function clearForm() {
  $('#form').trigger("reset");
  $("#tags_field").tagsinput('removeAll');
}

function randomize(clear = true) {
  if (clear)
    clearForm()
  $('#text_field_1').val(`${(Math.trunc(Math.random() * 99999999)).toString(36)}`)
  $('#text_field_2').val('Lorem ipsum dolor sit amet.')
  currencyField.set(Math.random() * 99999999)
  for (let i = 0; i < tags.length; i++) {
    if (Math.random() < 0.2) {
      $('#tags_field').tagsinput('add', tags[i].value);
    }
  }

  if (Math.random() > 0.3) {
    $('#option_field').prop("checked", true)
  } else {
    $('#option_field').prop("checked", false)
  }

  $(`#checkList > li`).each(function() {
    if (Math.random() < 0.13) {
      $(this).children(":first").children(":first").prop("checked", true)
    } else {
      $(this).children(":first").children(":first").prop("checked", false)
    }
  });
  updateTagsinput()
}

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" crossorigin="anonymous">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput-typeahead.css" rel="stylesheet" type="text/css" />

    <form class="m-2" id="form" action="" method="post" autocomplete="off">

        Text Field #1
        <input type="text" class="form-control" id="text_field_1" name="text_field_1">

        Text Field #2
        <textarea class="form-control" id="text_field_2" name="text_field_2" rows="3"></textarea>

          Currency Field
          <input type="text" class="form-control currency" id="currency_field" name="currency_field">

          Tags Field
          <input type="text" class="form-control tagsinput" data-role="tagsinput" id="tags_field" name="tags_field">

            <input type="checkbox" class="form-check-input" id="option_field" name="option_field">
            Check Field.

        Categoria(s)

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_1" name="Option #1">

                                            Option #1

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_2" name="Option #2">

                                            Option #2

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_3" name="Option #3">

                                            Option #3

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_4" name="Option #4">

                                            Option #4

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_5" name="Option #5">

                                            Option #5

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_6" name="Option #6">

                                            Option #6

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_7" name="Option #7">

                                            Option #7

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_8" name="Option #8">

                                            Option #8

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_9" name="Option #9">

                                            Option #9

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_10" name="Option #10">

                                            Option #10

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_11" name="Option #11">

                                            Option #11

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_12" name="Option #12">

                                            Option #12

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_13" name="Option #13">

                                            Option #13

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_14" name="Option #14">

                                            Option #14

              <input type="checkbox" class="custom-control-input checkboxCategorias" id="option_15" name="Option #15">

                                            Option #15

      <button type="button" id="clearButton" onclick="clearForm();blur()" class="d-none d-sm-inline-block btn btn-info">Clear form</button>
      <button type="button" id="rendomizeButton" onclick="randomize();blur()" class="d-none d-sm-inline-block btn btn-info">Randomize data</button>
      <button type="button" id="rendomizeButton" onclick="randomize(false);blur()" class="d-none d-sm-inline-block btn btn-info">Randomize data without clear</button>
    </form>

At the bottom of the page I have 3 buttons to 1) clear the form; 2) clear the form then fill with random data; 3) fill with random data (without cleaning before)

This is the function to randomize data:

function randomize(clear = true) {
    if (clear)
        clearForm()
    $('#text_field_1').val(`${(Math.trunc(Math.random() * 99999999)).toString(36)}`)
    $('#text_field_2').val('Lorem ipsum dolor sit amet.')
    currencyField.set(Math.random() * 99999999)
    for (let i = 0; i < tags.length; i++) {
        if (Math.random() < 0.2) {
            $('#tags_field').tagsinput('add', tags[i].value);
        }
    }

    if (Math.random() > 0.3) {
        $('#option_field').prop("checked", true)
    } else {
        $('#option_field').prop("checked", false)
    }

        $(`#checkList > li`).each(function () {
        if (Math.random() < 0.13) {
            $(this).children(":first").children(":first").prop("checked", true)
        } else {
            $(this).children(":first").children(":first").prop("checked", false)
        }
    });
    updateTagsinput()
}

My problem is, even with my instruction at the function being clear the form BEFORE filling it with random data, the field with AutoNumeric (Currency Field) seems to being filled before the form is cleaned. I can't understand what this is happening. There is no async functions.

When the randomize function is called without the clear command, the field currency is filled.
But when you try to clear the form before fill it, the execution is being in inverse order: the form is filled on Currncy Field, and then it is cleaned right after.


问:
Uncaught Error: Cannot find module 'path' in React js
I am working on React app and the app was working fine with last week. Now suddenly, I opened the app but saw some weird errors completely occupying my screen. I googled but but after applying all solutions, could help getting my issue resolved. A picture is also attached below that shows the errors when I open my server through npm start or yarn start.

React version is 18.2.0


问:
Is there a way to implement event and lambda for all accounts
I have a challenge where:
when an ec2 state changes it needs to send a rest message to a third party system.
Now I can think in one organisation there can be 100's of accounts.
So what are my optimised approach to this.

Do I need to create 'event bridge' and 'lambda' under each of these accounts or is there any way we create in one and that works for all accounts within an organisation


问:
trying to create diferent directorys in my program to save images
I already make a part of that function but when i do the check on my dir if they exist dont give any error, maybe u can help me found the miss part.
Part of my function:

```<code>    public function teste_mkdir(){

        $rootPath = '/var/www/oncargo/files/oncargophotos/';

        $data = '2022-11-25 23:59:45';
        $ano = date ('Y', strtotime($data));
        $mes = date ('m', strtotime($data));
        $dia = date ('d', strtotime($data));
        $path1 = $rootPath.$ano;
        $path2 = $path1.'/'.$mes;
        $path3 = $path2.'./'.$dia;

//check if folders exists before create
        if(!is_dir($rootPath) == true){
            if(!is_dir($path1) == false)
                mkdir($path1,0777,true);
            if(!is_dir($path1) == true)
                if(!is_dir($path2) == false)
                    mkdir($path2,0777,true);
            if(!is_dir($path2) == true)
                if(!is_dir($path3) == false)
                    mkdir($path3,0777,true);
        }
//        print_r(array('ls' => scandir($path1))); make this to see if they are made but dont show nothing because they arent made
//        print_r(array('ls' => scandir($path2)));
//        print_r(array('ls' => scandir($path3)));
}
</code>```

i alredy try make path1,2 andd 3, made i fail the rootPath is manual created.
So im trying to get a new dir when data change, so every day when i receive a img that function have to create a dir for every single day. Its my purpose.Can u help me?

Body:
I already make a part of that function but when i do the check on my dir if they exist dont give any error, maybe u can help me found the miss part.
Part of my function:

    public function teste_mkdir(){

        $rootPath = '/var/www/oncargo/files/oncargophotos/';

        $data = '2022-11-25 23:59:45';
        $ano = date ('Y', strtotime($data));
        $mes = date ('m', strtotime($data));
        $dia = date ('d', strtotime($data));
        $path1 = $rootPath.$ano;
        $path2 = $path1.'/'.$mes;
        $path3 = $path2.'./'.$dia;

//check if folders exists before create
        if(!is_dir($rootPath) == true){
            if(!is_dir($path1) == false)
                mkdir($path1,0777,true);
            if(!is_dir($path1) == true)
                if(!is_dir($path2) == false)
                    mkdir($path2,0777,true);
            if(!is_dir($path2) == true)
                if(!is_dir($path3) == false)
                    mkdir($path3,0777,true);
        }
//        print_r(array('ls' => scandir($path1))); make this to see if they are made but dont show nothing because they arent made
//        print_r(array('ls' => scandir($path2)));
//        print_r(array('ls' => scandir($path3)));
}

i alredy try make path1,2 andd 3, made i fail the rootPath is manual created.
So im trying to get a new dir when data change, so every day when i receive a img that function have to create a dir for every single day. Its my purpose.Can u help me?


问:
Django Channels do not send message within except block in Celery task
I am currently facing an issue with the Django Channels and Websockets. I have an application that somehow works with files and Sharepoint. Issued code sample where defect occurs:

@shared_task(bind=True)
def upload_to_sharepoint_task(self, user_id: str, document_type: str, upload_file: str, filename: str) -> None:
    """Uploads a file to SharePoint."""
    task_id = self.request.id

    try:
        upload_to_sharepoint(user_id, document_type, upload_file, filename)

        print(f"Task {task_id} completed successfully.")

        async_to_sync(get_channel_layer().group_send)(task_id, {
            "type": "send_task_status",
            "message": {'task_id': task_id, 'status': "SUCCESS", }
        })
    except BackendError as e:

        print(f"Task {task_id} failed with error: {str(e)}")
        async_to_sync(get_channel_layer().group_send)(task_id, {
            "type": "send_task_status",
            "message": {'task_id': task_id, 'status': "FAILURE", 'error': str(e)}
        })

```
<p>If everything the method <code>upload_to_sharepoint</code> does not throw an exception, everything works just fine - the message is sent to the group and, via WebSocket, propagated to the Client. However, if I try to simulate a situation when the exception is thrown (for instance, by throwing the <code>BackendException</code> explicitly), the error message gets printed in the console, but WebSocket does not receive any message nor the Client.</p>
<p>My TaskConsumer:</p>
<pre class="lang-py prettyprint-override"><code>class TaskConsumer(WebsocketConsumer):

    def connect(self):
        self.task_id = self.scope['url_route']['kwargs']['task_id']

        # Join the task_id group
        async_to_sync(self.channel_layer.group_add)(self.task_id, self.channel_name)

        self.accept()

    def disconnect(self, close_code):
        # Leave the task_id group
        async_to_sync(self.channel_layer.group_discard)(
            self.task_id, self.channel_name
        )

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        print(f"Task {self.task_id} received message: {message}")

        async_to_sync(self.channel_layer.group_send)(
            self.task_id, {"type": "send_task_status", "message": message}
        )

    def send_task_status(self, event):
        message = event['message']

        self.send(text_data=json.dumps({"message": message}))

</code>```

Does anyone have an idea what could be wrong and how I can propagate the information about unsuccessful upload back to the Client via used WebSocket?

Body:
I am currently facing an issue with the Django Channels and Websockets. I have an application that somehow works with files and Sharepoint. Issued code sample where defect occurs:

@shared_task(bind=True)
def upload_to_sharepoint_task(self, user_id: str, document_type: str, upload_file: str, filename: str) -> None:
    """Uploads a file to SharePoint."""
    task_id = self.request.id

    try:
        upload_to_sharepoint(user_id, document_type, upload_file, filename)

        print(f"Task {task_id} completed successfully.")

        async_to_sync(get_channel_layer().group_send)(task_id, {
            "type": "send_task_status",
            "message": {'task_id': task_id, 'status': "SUCCESS", }
        })
    except BackendError as e:

        print(f"Task {task_id} failed with error: {str(e)}")
        async_to_sync(get_channel_layer().group_send)(task_id, {
            "type": "send_task_status",
            "message": {'task_id': task_id, 'status': "FAILURE", 'error': str(e)}
        })

If everything the method upload_to_sharepoint does not throw an exception, everything works just fine - the message is sent to the group and, via WebSocket, propagated to the Client. However, if I try to simulate a situation when the exception is thrown (for instance, by throwing the BackendException explicitly), the error message gets printed in the console, but WebSocket does not receive any message nor the Client.

My TaskConsumer:

class TaskConsumer(WebsocketConsumer):

    def connect(self):
        self.task_id = self.scope['url_route']['kwargs']['task_id']

        # Join the task_id group
        async_to_sync(self.channel_layer.group_add)(self.task_id, self.channel_name)

        self.accept()

    def disconnect(self, close_code):
        # Leave the task_id group
        async_to_sync(self.channel_layer.group_discard)(
            self.task_id, self.channel_name
        )

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json["message"]

        print(f"Task {self.task_id} received message: {message}")

        async_to_sync(self.channel_layer.group_send)(
            self.task_id, {"type": "send_task_status", "message": message}
        )

    def send_task_status(self, event):
        message = event['message']

        self.send(text_data=json.dumps({"message": message}))

Does anyone have an idea what could be wrong and how I can propagate the information about unsuccessful upload back to the Client via used WebSocket?


问:
SonarScanner - post - processing fail

dotnet sonarscanner end /d:sonar.login="my-token"
SonarScanner for MSBuild 5.8
Using the .NET Core version of the Scanner for MSBuild
Post-processing started.
Calling the SonarScanner CLI...
Files\Common was unexpected at this time.
The SonarScanner did not complete successfully
Post-processing failed. Exit code: 1

Help with this error while running sonnarscannar on a project.
New to Sonarqube

I believe files/common has to do something with the environament variable , but not sure.

Title: SonarScanner - post - processing fail


问:
Java Gradle Error : Your build is currently configured to use Java 17.0.2 and Gradle 7.3.1
We are attempting to upgrade our project to use Java 17 with a compatible Gradle.  We expect that Java 17.0.2 and Gradle 7.3.1 should be compatible per Gradle Compatibility Matrix

However, when we attempt to run our project we get the following error :

```<code>Unsupported Java.
Your build is currently configured to use Java 17.0.2 and Gradle 7.3.1.

Possible solution:
 - Use Java 16 as Gradle JVM: Open Gradle settings
 - Open Gradle wrapper settings, change `distributionUrl` property to use compatible Gradle version and reload the project
</code>```

We are using IntelliJ with Gradle JVM set to : openjdk-17 version 17.0.2 and Project SDK set to : openjdk-17 version 17.0.2

We are using Gradle distribution url : distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-all.zip

It appears that these should be compatible does anyone know what could be causing this?

Body:
We are attempting to upgrade our project to use Java 17 with a compatible Gradle.  We expect that Java 17.0.2 and Gradle 7.3.1 should be compatible per Gradle Compatibility Matrix

However, when we attempt to run our project we get the following error :

Unsupported Java.
Your build is currently configured to use Java 17.0.2 and Gradle 7.3.1.

Possible solution:
 - Use Java 16 as Gradle JVM: Open Gradle settings
 - Open Gradle wrapper settings, change `distributionUrl` property to use compatible Gradle version and reload the project

We are using IntelliJ with Gradle JVM set to : openjdk-17 version 17.0.2 and Project SDK set to : openjdk-17 version 17.0.2

We are using Gradle distribution url : distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.1-all.zip

It appears that these should be compatible does anyone know what could be causing this?


问:
"Could not load the schema for provider" Both AWS and AzureRM after init
I have a terraform project that I'm working on that I wanted to do automated testing against.

Locally, the testing framework works fine but it's failing on my build/test server.

I have checked and order of events on the server are:

 Check if the terraform folder and lock file exist, they don't

Run terraform init on 'default' workspace

 Check if the terraform folder and lock file exist, they do

Swap terraform workspaces to my intended workspace and run init again

Build a custom tfvars file

Run apply on the workspace with the var file

The error I'm getting is:

```<code>[31mâ•·[0m[0m
[31mâ”‚[0m [0m[1m[31mError: [0m[0m[1mFailed to load plugin schemas[0m
[31mâ”‚[0m [0m
[31mâ”‚[0m [0m[0mError while loading schemas for plugin components: 2 problems:
[31mâ”‚[0m [0m
[31mâ”‚[0m [0m- Failed to obtain provider schema: Could not load the schema for provider
[31mâ”‚[0m [0mregistry.terraform.io/hashicorp/aws: failed to instantiate provider
[31mâ”‚[0m [0m"registry.terraform.io/hashicorp/aws" to obtain schema: Unrecognized remote
[31mâ”‚[0m [0mplugin message:
[31mâ”‚[0m [0m
[31mâ”‚[0m [0mThis usually means that the plugin is either invalid or simply
[31mâ”‚[0m [0mneeds to be recompiled to support the latest protocol..
[31mâ”‚[0m [0m- Failed to obtain provider schema: Could not load the schema for provider
[31mâ”‚[0m [0mregistry.terraform.io/hashicorp/azurerm: failed to instantiate provider
[31mâ”‚[0m [0m"registry.terraform.io/hashicorp/azurerm" to obtain schema: Unrecognized
[31mâ”‚[0m [0mremote plugin message:
[31mâ”‚[0m [0m
[31mâ”‚[0m [0mThis usually means that the plugin is either invalid or simply
[31mâ”‚[0m [0mneeds to be recompiled to support the latest protocol...
[31mâ•µ[0m[0m
</code>```

Both Error: Failed to load plugin schemas | Azure | Terraform and Terraform Error: Failed to load plugin schemas
say to remove the old terraform folder but in this case it doesn't exist prior to the init

I have tried using -upgrade and -reconfigure in the init as well as check if the terraform files exist prior to the init.

I don't understand why I'm getting this failure during the apply stage.

Body:
I have a terraform project that I'm working on that I wanted to do automated testing against.

Locally, the testing framework works fine but it's failing on my build/test server.

I have checked and order of events on the server are:

 Check if the terraform folder and lock file exist, they don't

Run terraform init on 'default' workspace

 Check if the terraform folder and lock file exist, they do

Swap terraform workspaces to my intended workspace and run init again

Build a custom tfvars file

Run apply on the workspace with the var file

The error I'm getting is:

[31mâ•·[0m[0m
[31mâ”‚[0m [0m[1m[31mError: [0m[0m[1mFailed to load plugin schemas[0m
[31mâ”‚[0m [0m
[31mâ”‚[0m [0m[0mError while loading schemas for plugin components: 2 problems:
[31mâ”‚[0m [0m
[31mâ”‚[0m [0m- Failed to obtain provider schema: Could not load the schema for provider
[31mâ”‚[0m [0mregistry.terraform.io/hashicorp/aws: failed to instantiate provider
[31mâ”‚[0m [0m"registry.terraform.io/hashicorp/aws" to obtain schema: Unrecognized remote
[31mâ”‚[0m [0mplugin message:
[31mâ”‚[0m [0m
[31mâ”‚[0m [0mThis usually means that the plugin is either invalid or simply
[31mâ”‚[0m [0mneeds to be recompiled to support the latest protocol..
[31mâ”‚[0m [0m- Failed to obtain provider schema: Could not load the schema for provider
[31mâ”‚[0m [0mregistry.terraform.io/hashicorp/azurerm: failed to instantiate provider
[31mâ”‚[0m [0m"registry.terraform.io/hashicorp/azurerm" to obtain schema: Unrecognized
[31mâ”‚[0m [0mremote plugin message:
[31mâ”‚[0m [0m
[31mâ”‚[0m [0mThis usually means that the plugin is either invalid or simply
[31mâ”‚[0m [0mneeds to be recompiled to support the latest protocol...
[31mâ•µ[0m[0m

Both Error: Failed to load plugin schemas | Azure | Terraform and Terraform Error: Failed to load plugin schemas
say to remove the old terraform folder but in this case it doesn't exist prior to the init

I have tried using -upgrade and -reconfigure in the init as well as check if the terraform files exist prior to the init.

I don't understand why I'm getting this failure during the apply stage.


问:
Multiple updates to same table via stored procedure
I am having recurring deadlocks on my application database and trying to understand what is causing them. Using extended events to track them I have identified two common causes, one via an T-SQL statement in the application and the other using a stored procedure. I'll limit this question just to the stored procedure.

I have a stored procedure called writeNominalTrans, I pass some variables from the software and it will either insert or update a record depending on whether a match is found. The XML Deadlock reports commonly refer to the update statements causing the problems, I'll post both stored procedure and an example XML report below.
I have done some reading to understand Deadlocks but most sources just talk about locking between two tables where as my issues resolve around updating records in a single table and not sure exactly how to resolve this.

I think this issue is that it locks the table by pages, possibly multiple at a time as it searches, looking for the correct row to update. If multiple users call the same procedure at the same time, it causes different pages to be locked, ending up with both waiting on each other to finish and thus a Deadlock. Please correct me if this isnt the case.
Within the stored procedure, there are begin/end statements with multiple update statements and not sure if this is one of the potentially issues. Should I put each update statement within it's own begin/end so it is only trying to do one statement at a time? This is assuming it is firing multiple statements per user and some times there are a larger number of processes than in the example below. Aside from this I'm not sure what else is causing the problem, please if you take a look and lend me your expertise.
Regards
David

Stored Procedure

```<code>[dbo].[spWriteNominalTrans]
@Recordkey Int Output,
@NominalDataKey int,
@NominalCode int,
@NominalType int,
@TransDate datetime,
@Memo  nvarchar(500),
@debit money,
@Credit money,
@VatValueIN money,
@VatValueOut money,
@VatNLAccount int,
@VatRelationKey int,
@Reference nvarchar(50),
@Period int,
@FiscalYear int,
@UserID int,
@DateStamp datetime,
@Transtype nvarchar(150),
@vatcode int,
@vatrate decimal(18,2),
@GoodsValue money,
@AllowMerge bit,
@VatReconcileKey Integer,
@VatOut bit,
@LocationKey int
AS

IF exists ( select * from TblNominalTrans where TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference and vatcode = @vatcode and transtype = @Transtype and @AllowMerge=1 and Memo=@Memo and @Transtype=Transtype and LocationKey =@LocationKey)
-- do an update
    BEGIN
        UPDATE TblNominalTrans SET
        Memo=@Memo,
        Debit = Debit + @Debit ,
        Credit = Credit +@Credit,
        GoodsValue = GoodsValue + @GoodsValue,
        VatValueIN = VatValueIN + @VatValueIN,
        VatValueOut = VatValueOut + @VatValueOut,
        VatOut = @Vatout,
        VatNLAccount=@VatNLAccount,
        VatRelationKey=@VatRelationKey,
        UserId=@UserId,
        DateStamp=@DateStamp,
        VatReconcileKey = @VatReconcileKey
        WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey

        UPDATE TblNominalTrans SET
        Credit = Credit - Debit, debit = 0
        WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and credit >= debit and debit > 0

        UPDATE TblNominalTrans SET
        Debit = Debit - Credit, credit = 0
        WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and debit >= credit and credit > 0
    END
ELSE
-- do an insert
    BEGIN
        INSERT TblNominalTrans (
        NominalDataKey,
        NominalCode,
        NominalType ,
        TransDate ,
        Memo ,
        debit ,
        Credit ,
        VatValueIN,
        VatValueOut ,
        VatNLAccount ,
        VatRelationKey ,
        Reference ,
        Period ,
        FiscalYear ,
        VatOut ,
        TransType ,
        UserID ,
        DateStamp,
        vatcode,
        vatrate,
        Goodsvalue,
        VatReconcileKey,
        LocationKey)
        SELECT
        @NominalDataKey ,
        @NominalCode ,
        @NominalType ,
        @TransDate ,
        @Memo ,
        @debit ,
        @Credit ,
        @VatValueIN,
        @VatValueOut ,
        @VatNLAccount ,
        @VatRelationKey ,
        @Reference ,
        @Period,
        @FiscalYear,
        @VatOut,
        @transtype,
        @UserID,
        @DateStamp,
        @vatcode,
        @vatrate,
        @goodsvalue,
        @VatReconcileKey,
        @LocationKey
    END

</code>```

Deadlock XML Report

```<code><deadlock>
 <victim-list>
  <victimProcess id="process2c457dd0ca8" />
 </victim-list>
 <process-list>
  <process id="process2c457dd0ca8" taskpriority="0" logused="0" waitresource="PAGE: 7:1:23277 " waittime="1684" ownerId="1782665" transactionname="UPDATE" lasttranstarted="2022-12-13T09:46:09" XDES="0x2c314a19900" lockMode="U" schedulerid="3" kpid="3212" status="suspended" spid="66" sbid="0" ecid="2" priority="0" trancount="0" lastbatchstarted="2022-12-13T09:46:08.930" lastbatchcompleted="2022-12-13T09:46:08.923" lastattention="1900-01-01T00:00:00.923" clientapp="Liquidity" hostname="TERM-SERVER" hostpid="5228" isolationlevel="read committed (2)" xactid="1782665" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="43" stmtstart="2092" stmtend="3384" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Memo=@Memo,
         Debit = Debit + @Debit ,
         Credit = Credit +@Credit,
         GoodsValue = GoodsValue + @GoodsValue,
         VatValueIN = VatValueIN + @VatValueIN,
         VatValueOut = VatValueOut + @VatValueOut,
         VatOut = @Vatout,
         VatNLAccount=@VatNLAccount,
         VatRelationKey=@VatRelationKey,
         UserId=@UserId,
         DateStamp=@DateStamp,
         VatReconcileKey = @VatReconcileKey
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKe    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
  <process id="process2c457d96108" taskpriority="0" logused="0" waitresource="PAGE: 7:1:2425 " waittime="1686" ownerId="1782668" transactionname="UPDATE" lasttranstarted="2022-12-13T09:46:09.003" XDES="0x2c45d69d900" lockMode="U" schedulerid="2" kpid="3336" status="suspended" spid="176" sbid="0" ecid="1" priority="0" trancount="0" lastbatchstarted="2022-12-13T09:46:08.817" lastbatchcompleted="2022-12-13T09:46:08.813" lastattention="1900-01-01T00:00:00.813" clientapp="Liquidity" hostname="DESKTOP-O2" hostpid="8728" isolationlevel="read committed (2)" xactid="1782668" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="64" stmtstart="4210" stmtend="4886" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Debit = Debit - Credit, credit = 0
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and debit >= credit and credit >    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
  <process id="process2c457d97468" taskpriority="0" logused="0" waitresource="PAGE: 7:1:23277 " waittime="1686" ownerId="1782665" transactionname="UPDATE" lasttranstarted="2022-12-13T09:46:09" XDES="0x2c3ab371cb0" lockMode="U" schedulerid="2" kpid="5808" status="suspended" spid="66" sbid="0" ecid="1" priority="0" trancount="0" lastbatchstarted="2022-12-13T09:46:08.930" lastbatchcompleted="2022-12-13T09:46:08.923" lastattention="1900-01-01T00:00:00.923" clientapp="Liquidity" hostname="TERM-SERVER" hostpid="5228" isolationlevel="read committed (2)" xactid="1782665" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="43" stmtstart="2092" stmtend="3384" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Memo=@Memo,
         Debit = Debit + @Debit ,
         Credit = Credit +@Credit,
         GoodsValue = GoodsValue + @GoodsValue,
         VatValueIN = VatValueIN + @VatValueIN,
         VatValueOut = VatValueOut + @VatValueOut,
         VatOut = @Vatout,
         VatNLAccount=@VatNLAccount,
         VatRelationKey=@VatRelationKey,
         UserId=@UserId,
         DateStamp=@DateStamp,
         VatReconcileKey = @VatReconcileKey
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKe    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
  <process id="process2c45d6984e8" taskpriority="0" logused="10000" waittime="1624" schedulerid="4" kpid="5024" status="suspended" spid="176" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2022-12-13T09:46:08.817" lastbatchcompleted="2022-12-13T09:46:08.813" lastattention="1900-01-01T00:00:00.813" clientapp="Liquidity" hostname="DESKTOP-O2" hostpid="8728" loginname="LOCAL\debbie.weavers" isolationlevel="read committed (2)" xactid="1782668" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="64" stmtstart="4210" stmtend="4886" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Debit = Debit - Credit, credit = 0
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and debit >= credit and credit >    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
 </process-list>
 <resource-list>
  <pagelock fileid="1" pageid="23277" dbid="7" subresource="FULL" objectname="MDT_DB.dbo.tblNominalTrans" id="lock2c3c82bb300" mode="U" associatedObjectId="287811838279680">
   <owner-list>
    <owner id="process2c457d97468" mode="U" requestType="wait" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c457dd0ca8" mode="U" requestType="wait" />
   </waiter-list>
  </pagelock>
  <pagelock fileid="1" pageid="2425" dbid="7" subresource="FULL" objectname="MDT_DB.dbo.tblNominalTrans" id="lock2c431d37300" mode="U" associatedObjectId="287811838279680">
   <owner-list>
    <owner id="process2c457dd0ca8" mode="U" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c457d96108" mode="U" requestType="wait" />
   </waiter-list>
  </pagelock>
  <pagelock fileid="1" pageid="23277" dbid="7" subresource="FULL" objectname="MDT_DB.dbo.tblNominalTrans" id="lock2c3c82bb300" mode="U" associatedObjectId="287811838279680">
   <owner-list>
    <owner id="process2c45d6984e8" mode="U" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c457d97468" mode="U" requestType="wait" />
   </waiter-list>
  </pagelock>
  <exchangeEvent id="Pipe2c3488ae780" WaitType="e_waitPipeGetRow" nodeId="4">
   <owner-list>
    <owner id="process2c457d96108" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c45d6984e8" />
   </waiter-list>
  </exchangeEvent>
 </resource-list>
</deadlock>
</code>```

Body:
I am having recurring deadlocks on my application database and trying to understand what is causing them. Using extended events to track them I have identified two common causes, one via an T-SQL statement in the application and the other using a stored procedure. I'll limit this question just to the stored procedure.

I have a stored procedure called writeNominalTrans, I pass some variables from the software and it will either insert or update a record depending on whether a match is found. The XML Deadlock reports commonly refer to the update statements causing the problems, I'll post both stored procedure and an example XML report below.
I have done some reading to understand Deadlocks but most sources just talk about locking between two tables where as my issues resolve around updating records in a single table and not sure exactly how to resolve this.

I think this issue is that it locks the table by pages, possibly multiple at a time as it searches, looking for the correct row to update. If multiple users call the same procedure at the same time, it causes different pages to be locked, ending up with both waiting on each other to finish and thus a Deadlock. Please correct me if this isnt the case.
Within the stored procedure, there are begin/end statements with multiple update statements and not sure if this is one of the potentially issues. Should I put each update statement within it's own begin/end so it is only trying to do one statement at a time? This is assuming it is firing multiple statements per user and some times there are a larger number of processes than in the example below. Aside from this I'm not sure what else is causing the problem, please if you take a look and lend me your expertise.
Regards
David

Stored Procedure

[dbo].[spWriteNominalTrans]
@Recordkey Int Output,
@NominalDataKey int,
@NominalCode int,
@NominalType int,
@TransDate datetime,
@Memo  nvarchar(500),
@debit money,
@Credit money,
@VatValueIN money,
@VatValueOut money,
@VatNLAccount int,
@VatRelationKey int,
@Reference nvarchar(50),
@Period int,
@FiscalYear int,
@UserID int,
@DateStamp datetime,
@Transtype nvarchar(150),
@vatcode int,
@vatrate decimal(18,2),
@GoodsValue money,
@AllowMerge bit,
@VatReconcileKey Integer,
@VatOut bit,
@LocationKey int
AS

IF exists ( select * from TblNominalTrans where TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference and vatcode = @vatcode and transtype = @Transtype and @AllowMerge=1 and Memo=@Memo and @Transtype=Transtype and LocationKey =@LocationKey)
-- do an update
    BEGIN
        UPDATE TblNominalTrans SET
        Memo=@Memo,
        Debit = Debit + @Debit ,
        Credit = Credit +@Credit,
        GoodsValue = GoodsValue + @GoodsValue,
        VatValueIN = VatValueIN + @VatValueIN,
        VatValueOut = VatValueOut + @VatValueOut,
        VatOut = @Vatout,
        VatNLAccount=@VatNLAccount,
        VatRelationKey=@VatRelationKey,
        UserId=@UserId,
        DateStamp=@DateStamp,
        VatReconcileKey = @VatReconcileKey
        WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey

        UPDATE TblNominalTrans SET
        Credit = Credit - Debit, debit = 0
        WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and credit >= debit and debit > 0

        UPDATE TblNominalTrans SET
        Debit = Debit - Credit, credit = 0
        WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and debit >= credit and credit > 0
    END
ELSE
-- do an insert
    BEGIN
        INSERT TblNominalTrans (
        NominalDataKey,
        NominalCode,
        NominalType ,
        TransDate ,
        Memo ,
        debit ,
        Credit ,
        VatValueIN,
        VatValueOut ,
        VatNLAccount ,
        VatRelationKey ,
        Reference ,
        Period ,
        FiscalYear ,
        VatOut ,
        TransType ,
        UserID ,
        DateStamp,
        vatcode,
        vatrate,
        Goodsvalue,
        VatReconcileKey,
        LocationKey)
        SELECT
        @NominalDataKey ,
        @NominalCode ,
        @NominalType ,
        @TransDate ,
        @Memo ,
        @debit ,
        @Credit ,
        @VatValueIN,
        @VatValueOut ,
        @VatNLAccount ,
        @VatRelationKey ,
        @Reference ,
        @Period,
        @FiscalYear,
        @VatOut,
        @transtype,
        @UserID,
        @DateStamp,
        @vatcode,
        @vatrate,
        @goodsvalue,
        @VatReconcileKey,
        @LocationKey
    END

Deadlock XML Report

<deadlock>
 <victim-list>
  <victimProcess id="process2c457dd0ca8" />
 </victim-list>
 <process-list>
  <process id="process2c457dd0ca8" taskpriority="0" logused="0" waitresource="PAGE: 7:1:23277 " waittime="1684" ownerId="1782665" transactionname="UPDATE" lasttranstarted="2022-12-13T09:46:09" XDES="0x2c314a19900" lockMode="U" schedulerid="3" kpid="3212" status="suspended" spid="66" sbid="0" ecid="2" priority="0" trancount="0" lastbatchstarted="2022-12-13T09:46:08.930" lastbatchcompleted="2022-12-13T09:46:08.923" lastattention="1900-01-01T00:00:00.923" clientapp="Liquidity" hostname="TERM-SERVER" hostpid="5228" isolationlevel="read committed (2)" xactid="1782665" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="43" stmtstart="2092" stmtend="3384" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Memo=@Memo,
         Debit = Debit + @Debit ,
         Credit = Credit +@Credit,
         GoodsValue = GoodsValue + @GoodsValue,
         VatValueIN = VatValueIN + @VatValueIN,
         VatValueOut = VatValueOut + @VatValueOut,
         VatOut = @Vatout,
         VatNLAccount=@VatNLAccount,
         VatRelationKey=@VatRelationKey,
         UserId=@UserId,
         DateStamp=@DateStamp,
         VatReconcileKey = @VatReconcileKey
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKe    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
  <process id="process2c457d96108" taskpriority="0" logused="0" waitresource="PAGE: 7:1:2425 " waittime="1686" ownerId="1782668" transactionname="UPDATE" lasttranstarted="2022-12-13T09:46:09.003" XDES="0x2c45d69d900" lockMode="U" schedulerid="2" kpid="3336" status="suspended" spid="176" sbid="0" ecid="1" priority="0" trancount="0" lastbatchstarted="2022-12-13T09:46:08.817" lastbatchcompleted="2022-12-13T09:46:08.813" lastattention="1900-01-01T00:00:00.813" clientapp="Liquidity" hostname="DESKTOP-O2" hostpid="8728" isolationlevel="read committed (2)" xactid="1782668" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="64" stmtstart="4210" stmtend="4886" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Debit = Debit - Credit, credit = 0
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and debit >= credit and credit >    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
  <process id="process2c457d97468" taskpriority="0" logused="0" waitresource="PAGE: 7:1:23277 " waittime="1686" ownerId="1782665" transactionname="UPDATE" lasttranstarted="2022-12-13T09:46:09" XDES="0x2c3ab371cb0" lockMode="U" schedulerid="2" kpid="5808" status="suspended" spid="66" sbid="0" ecid="1" priority="0" trancount="0" lastbatchstarted="2022-12-13T09:46:08.930" lastbatchcompleted="2022-12-13T09:46:08.923" lastattention="1900-01-01T00:00:00.923" clientapp="Liquidity" hostname="TERM-SERVER" hostpid="5228" isolationlevel="read committed (2)" xactid="1782665" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="43" stmtstart="2092" stmtend="3384" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Memo=@Memo,
         Debit = Debit + @Debit ,
         Credit = Credit +@Credit,
         GoodsValue = GoodsValue + @GoodsValue,
         VatValueIN = VatValueIN + @VatValueIN,
         VatValueOut = VatValueOut + @VatValueOut,
         VatOut = @Vatout,
         VatNLAccount=@VatNLAccount,
         VatRelationKey=@VatRelationKey,
         UserId=@UserId,
         DateStamp=@DateStamp,
         VatReconcileKey = @VatReconcileKey
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKe    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
  <process id="process2c45d6984e8" taskpriority="0" logused="10000" waittime="1624" schedulerid="4" kpid="5024" status="suspended" spid="176" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2022-12-13T09:46:08.817" lastbatchcompleted="2022-12-13T09:46:08.813" lastattention="1900-01-01T00:00:00.813" clientapp="Liquidity" hostname="DESKTOP-O2" hostpid="8728" loginname="LOCAL\debbie.weavers" isolationlevel="read committed (2)" xactid="1782668" currentdb="7" lockTimeout="4294967295" clientoption1="536870944" clientoption2="128024">
   <executionStack>
    <frame procname="MDT_DB.dbo.spWriteNominalTrans" line="64" stmtstart="4210" stmtend="4886" sqlhandle="0x030007002b291964daa21d01caac000001000000000000000000000000000000000000000000000000000000">
UPDATE TblNominalTrans
         SET
         Debit = Debit - Credit, credit = 0
         WHERE TransDate= @TransDate and NominalCode = @NominalCode and Period = @Period and FiscalYear = @FiscalYear and Reference = @Reference  and vatcode = @vatcode and Memo=@Memo and @Transtype=Transtype and LocationKey = @LocationKey and debit >= credit and credit >    </frame>
   </executionStack>
   <inputbuf>
Proc [Database Id = 7 Object Id = 1679370539]   </inputbuf>
  </process>
 </process-list>
 <resource-list>
  <pagelock fileid="1" pageid="23277" dbid="7" subresource="FULL" objectname="MDT_DB.dbo.tblNominalTrans" id="lock2c3c82bb300" mode="U" associatedObjectId="287811838279680">
   <owner-list>
    <owner id="process2c457d97468" mode="U" requestType="wait" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c457dd0ca8" mode="U" requestType="wait" />
   </waiter-list>
  </pagelock>
  <pagelock fileid="1" pageid="2425" dbid="7" subresource="FULL" objectname="MDT_DB.dbo.tblNominalTrans" id="lock2c431d37300" mode="U" associatedObjectId="287811838279680">
   <owner-list>
    <owner id="process2c457dd0ca8" mode="U" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c457d96108" mode="U" requestType="wait" />
   </waiter-list>
  </pagelock>
  <pagelock fileid="1" pageid="23277" dbid="7" subresource="FULL" objectname="MDT_DB.dbo.tblNominalTrans" id="lock2c3c82bb300" mode="U" associatedObjectId="287811838279680">
   <owner-list>
    <owner id="process2c45d6984e8" mode="U" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c457d97468" mode="U" requestType="wait" />
   </waiter-list>
  </pagelock>
  <exchangeEvent id="Pipe2c3488ae780" WaitType="e_waitPipeGetRow" nodeId="4">
   <owner-list>
    <owner id="process2c457d96108" />
   </owner-list>
   <waiter-list>
    <waiter id="process2c45d6984e8" />
   </waiter-list>
  </exchangeEvent>
 </resource-list>
</deadlock>


问:
How to Resolve this System.Typeload Exception
I have this assignment for uni where we need to solve an LP using microsoft solver foundation (available through NuGet in Visual Studio). I have the following code:

```<code>using System;
using Microsoft.SolverFoundation;
using Microsoft.SolverFoundation.Common;
using Microsoft.SolverFoundation.Services;

SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();

Decision potato    = new Decision(Domain.RealNonnegative, "ingredient_potato");
Decision meat      = new Decision(Domain.RealNonnegative, "ingredient_meat");
Decision vegetable = new Decision(Domain.RealNonnegative, "ingredient_vegetable");

model.AddDecisions(potato, meat, vegetable);

model.AddConstraint("calorie", 800 * potato + 1000 * meat + 5 * vegetable == 600);
model.AddConstraint("protein", 150 <= 5 * potato + 500 * meat <= 250);
model.AddConstraint("vitamin", 10 * potato + 100 * vegetable >= 200);

model.AddGoal("price", GoalKind.Minimize, 5 * potato + 20 * meat + 7 * vegetable);

Solution solution = context.Solve(new SimplexDirective());
Console.Write(solution.GetReport());

</code>```

when running it (.NET 6.0) i get the following error:

System.TypeLoadException: 'Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.'

After some research I think it has to do with the .NET version I'm using, but I'm not sure, and if this were the case, I have no idea which other version is required. Any help at all with this would be greatly appreciated!!

Body:
I have this assignment for uni where we need to solve an LP using microsoft solver foundation (available through NuGet in Visual Studio). I have the following code:

using System;
using Microsoft.SolverFoundation;
using Microsoft.SolverFoundation.Common;
using Microsoft.SolverFoundation.Services;

SolverContext context = SolverContext.GetContext();
Model model = context.CreateModel();

Decision potato    = new Decision(Domain.RealNonnegative, "ingredient_potato");
Decision meat      = new Decision(Domain.RealNonnegative, "ingredient_meat");
Decision vegetable = new Decision(Domain.RealNonnegative, "ingredient_vegetable");

model.AddDecisions(potato, meat, vegetable);

model.AddConstraint("calorie", 800 * potato + 1000 * meat + 5 * vegetable == 600);
model.AddConstraint("protein", 150 <= 5 * potato + 500 * meat <= 250);
model.AddConstraint("vitamin", 10 * potato + 100 * vegetable >= 200);

model.AddGoal("price", GoalKind.Minimize, 5 * potato + 20 * meat + 7 * vegetable);

Solution solution = context.Solve(new SimplexDirective());
Console.Write(solution.GetReport());

when running it (.NET 6.0) i get the following error:

System.TypeLoadException: 'Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.'

After some research I think it has to do with the .NET version I'm using, but I'm not sure, and if this were the case, I have no idea which other version is required. Any help at all with this would be greatly appreciated!!


问:
How to track custom metrics in Application Insights from an Azure .NET Function app
I have a .NET Azure function app that initially is triggered by a timer, but that just starts a process that puts a folder in a queue. The rest of the functions in this app are queue triggered. They are essentially processing folders in Azure storage looking for files to process and placing those in another queue. An instance of one of the functions in this app is spawned for each file in the queue and it is from this function I would like to send custom metrics to Application Insights.

This function evaluates the file and will determine one of 4 things it should do with the file. There can be hundreds instances of this function running simultaneously.

I want to track this data, essentially wanting to see in a given time period how many required action one, how many action two, and so on.

The results of this data gathering for a given run should be something like this:

Files processed: 894

Files new: 793

Files Changed: 25

Files Cleaned Up: 74

So I'm essentially wanting to tick up multiple counters.

Here are the two main documents I have been referencing:

Application Insights API for custom events and metrics

Custom metric collection in .NET and .NET Core

I understand the key point that I don't want to transmit telemetry data from each instance of this function directly to AI as that would be costly in resources, so the use of GetMetric() is the recommended course. That said, the examples involve creating a TelemtryClient in a context that can be referenced by all the code that needs to report data but I'm unsure of how I can do this effectively and efficiently within such a highly parallel function app.

I would love to find that there is a fairly straightforward pattern for this that does not involve some kind of singleton/durable function but that might be the only way.

To be more specific on the code front, here is the general structure:

Timmer Function

When triggered, puts one or more primary folders (PF) in a primary processing queue (PPQ)

Primary Folder Function

Triggered by the PPQ.

Processes all subfolders (SF) of the PF

SF's are placed into a SF queue (SFQ)

Files are placed into the file queue (FQ)

Subfolder Function

Triggered by the SFQ

Processes contents of subfolder (SF)

New subfolders are placed into a SF queue (SFQ)

Files are placed into the file queue (FQ)

Folder Function (FF)

Triggered by the FQ

Processes a given file

Primary point I want to transmit one or more results to tick a counter(s)

The only thing I have tried was writing data directly from timer triggered test function in my app just to see the Application Insights part working.

    public class FunctionTesting
    {
        private readonly TelemetryClient telemetryClient;

        public FunctionTesting(TelemetryConfiguration telemetryConfiguration)
        {
            this.telemetryClient = new TelemetryClient(telemetryConfiguration);
        }
        [FunctionName("FunctionTesting")]
        public async Task Run(
            [TimerTrigger("*/5 * * * * *")] TimerInfo timer,
            ExecutionContext context,
            ILogger log)
        {
            // Generate a random number between 1 and 100
            var random = new Random();
            var num = random.Next(1, 101);

            // Log the number to Application Insights

            this.telemetryClient.TrackMetric("RandomNumber", num);

            // Check if the number is even or odd, and less than or greater than 50
            if (num % 2 == 0)
            {
                this.telemetryClient.TrackEvent("EvenNumber");
            }
            else
            {
                this.telemetryClient.TrackEvent("OddNumber");
            }

            if (num < 50)
            {
                this.telemetryClient.TrackEvent("LessThan50");
            }
            else
            {
                this.telemetryClient.TrackEvent("GreaterThan50");
            }

            log.LogInformation($"Generated random number: {num}");
        }
    }
}

```

My plan, if I'm able to find a pattern that would work is to implement/test it in this test function before adding it to the rest of my code.

Thanks for any help!

Body:
I have a .NET Azure function app that initially is triggered by a timer, but that just starts a process that puts a folder in a queue. The rest of the functions in this app are queue triggered. They are essentially processing folders in Azure storage looking for files to process and placing those in another queue. An instance of one of the functions in this app is spawned for each file in the queue and it is from this function I would like to send custom metrics to Application Insights.

This function evaluates the file and will determine one of 4 things it should do with the file. There can be hundreds instances of this function running simultaneously.

I want to track this data, essentially wanting to see in a given time period how many required action one, how many action two, and so on.

The results of this data gathering for a given run should be something like this:

Files processed: 894

Files new: 793

Files Changed: 25

Files Cleaned Up: 74

So I'm essentially wanting to tick up multiple counters.

Here are the two main documents I have been referencing:

Application Insights API for custom events and metrics

Custom metric collection in .NET and .NET Core

I understand the key point that I don't want to transmit telemetry data from each instance of this function directly to AI as that would be costly in resources, so the use of GetMetric() is the recommended course. That said, the examples involve creating a TelemtryClient in a context that can be referenced by all the code that needs to report data but I'm unsure of how I can do this effectively and efficiently within such a highly parallel function app.

I would love to find that there is a fairly straightforward pattern for this that does not involve some kind of singleton/durable function but that might be the only way.

To be more specific on the code front, here is the general structure:

Timmer Function

When triggered, puts one or more primary folders (PF) in a primary processing queue (PPQ)

Primary Folder Function

Triggered by the PPQ.

Processes all subfolders (SF) of the PF

SF's are placed into a SF queue (SFQ)

Files are placed into the file queue (FQ)

Subfolder Function

Triggered by the SFQ

Processes contents of subfolder (SF)

New subfolders are placed into a SF queue (SFQ)

Files are placed into the file queue (FQ)

Folder Function (FF)

Triggered by the FQ

Processes a given file

Primary point I want to transmit one or more results to tick a counter(s)

The only thing I have tried was writing data directly from timer triggered test function in my app just to see the Application Insights part working.

    public class FunctionTesting
    {
        private readonly TelemetryClient telemetryClient;

        public FunctionTesting(TelemetryConfiguration telemetryConfiguration)
        {
            this.telemetryClient = new TelemetryClient(telemetryConfiguration);
        }
        [FunctionName("FunctionTesting")]
        public async Task Run(
            [TimerTrigger("*/5 * * * * *")] TimerInfo timer,
            ExecutionContext context,
            ILogger log)
        {
            // Generate a random number between 1 and 100
            var random = new Random();
            var num = random.Next(1, 101);

            // Log the number to Application Insights

            this.telemetryClient.TrackMetric("RandomNumber", num);

            // Check if the number is even or odd, and less than or greater than 50
            if (num % 2 == 0)
            {
                this.telemetryClient.TrackEvent("EvenNumber");
            }
            else
            {
                this.telemetryClient.TrackEvent("OddNumber");
            }

            if (num < 50)
            {
                this.telemetryClient.TrackEvent("LessThan50");
            }
            else
            {
                this.telemetryClient.TrackEvent("GreaterThan50");
            }

            log.LogInformation($"Generated random number: {num}");
        }
    }
}

My plan, if I'm able to find a pattern that would work is to implement/test it in this test function before adding it to the rest of my code.

Thanks for any help!


问:
Upload file from browser, process w python, back to the frontend for user download
What is the most basic way for a user to upload a file from the browser,
then I will process it with python on the backend, which will generate some new files,
and then send them back to the frontend for the user to be able to download them.

Preferably using http.server or node.js

process:

user uploads file
shell determines that a file has been uploaded
runs a python script that generates some new files
these appear in the browser
user downloads them


问:
I am not able to login to a website using Python and the Requests library. What am I missing?
My project is retrieve information from a website. After finding that the only browser I can use is firefox 47 and that Selenium doesn't support this version, I decided to try to do it with the Requests library and BeautifulSoup.

The first step is to login to the website, and I can't make it work using Requests.

Here is what I tried:

Using the firefox web development tool, I have retrieved information about the headers, cookie and data which I used to create a session.

```<code>import requests

login_url = "https://ip.adress/website/session/login.php"
protected_url = "https://ip.adress/website/#dashboard/overview/overview"

cookies = {
    'sess': '4rk02yn7r1l3pn0bkj4zk',
    'PHPSESSID': 'ogtkif390qrhur8b3krm4anf53',
}

headers = {
    'Host': 'ip.adress',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://ip.adress/website/session/login.php',
    # 'Cookie': 'sess=4rk02yn7r1l3pn0bkj4zk; PHPSESSID=ogtkif390qrhur8b3krm4anf53',
    'Connection': 'keep-alive',
}

data = {
    'embed': '',
    'bookmark_string': '',
    'user': 'username',
    'passu': 'password',
    'pass': 'random string which depends on the passu value',
}

with requests.Session() as s:
    r1 = s.get(login_url, verify=False)
    r2 = s.post(login_url, cookies=cookies, headers=headers, data=data, verify=False)
    r3 = s.get(protected_url, verify=False)

    print(r3.text)
</code>```

Unfortunately, print(r3.text) gives me the html of the login page.

Also print(r3.history) gives me Response 302.

Here is what the form in the login page looks like if it helps:

```<code><form name="f_login" id="f_login" method="POST" action="login.php">
                    <input type="hidden" name="embed" value=""/>
                    <input type="hidden" name="bookmark_string" id="bookmark_string" value=''/>
....
....
<input type="text" size='25' maxlength="64" id='user' name="user" value="" />

                                                        <input type="password" onfocus="$('#wup').hide(); $('#nt_1').hide(); $('#nt_pass').hide();" id="passu" size='25' name="passu" autocomplete="off"/>
                                                        <input type="hidden" id="pass" name="pass"/>

</code>```

Edit:
r2 headers look like this:

```<code>`header_2 = {'Date': 'Mon, 19 Dec 2022 16:09:58 GMT', 'Server': 'Apache',
            'X-Frame-Options': 'SAMEORIGIN',
            'Strict-Transport-Security': 'max-age=63072000; includeSubdomains; preload',
            'X-XSS-Protection': '1; mode=block',
            'Vary': 'User-Agent,Accept-Encoding',
            'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT',
            'Cache-Control': 'no-store, no-cache, must-revalidate',
            'Pragma': 'no-cache',
            'Content-Encoding': 'gzip',
            'Content-Length': '2946', 'Keep-Alive': 'timeout=5, max=97',
            'Connection': 'Keep-Alive',
            'Content-Type': 'text/html; charset=UTF-8',
            }```
```

Body:
My project is retrieve information from a website. After finding that the only browser I can use is firefox 47 and that Selenium doesn't support this version, I decided to try to do it with the Requests library and BeautifulSoup.

The first step is to login to the website, and I can't make it work using Requests.

Here is what I tried:

Using the firefox web development tool, I have retrieved information about the headers, cookie and data which I used to create a session.

import requests

login_url = "https://ip.adress/website/session/login.php"
protected_url = "https://ip.adress/website/#dashboard/overview/overview"

cookies = {
    'sess': '4rk02yn7r1l3pn0bkj4zk',
    'PHPSESSID': 'ogtkif390qrhur8b3krm4anf53',
}

headers = {
    'Host': 'ip.adress',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://ip.adress/website/session/login.php',
    # 'Cookie': 'sess=4rk02yn7r1l3pn0bkj4zk; PHPSESSID=ogtkif390qrhur8b3krm4anf53',
    'Connection': 'keep-alive',
}

data = {
    'embed': '',
    'bookmark_string': '',
    'user': 'username',
    'passu': 'password',
    'pass': 'random string which depends on the passu value',
}

with requests.Session() as s:
    r1 = s.get(login_url, verify=False)
    r2 = s.post(login_url, cookies=cookies, headers=headers, data=data, verify=False)
    r3 = s.get(protected_url, verify=False)

    print(r3.text)

Unfortunately, print(r3.text) gives me the html of the login page.

Also print(r3.history) gives me Response 302.

Here is what the form in the login page looks like if it helps:

<form name="f_login" id="f_login" method="POST" action="login.php">
                    <input type="hidden" name="embed" value=""/>
                    <input type="hidden" name="bookmark_string" id="bookmark_string" value=''/>
....
....
<input type="text" size='25' maxlength="64" id='user' name="user" value="" />

                                                        <input type="password" onfocus="$('#wup').hide(); $('#nt_1').hide(); $('#nt_pass').hide();" id="passu" size='25' name="passu" autocomplete="off"/>
                                                        <input type="hidden" id="pass" name="pass"/>

Edit:
r2 headers look like this:

`header_2 = {'Date': 'Mon, 19 Dec 2022 16:09:58 GMT', 'Server': 'Apache',
            'X-Frame-Options': 'SAMEORIGIN',
            'Strict-Transport-Security': 'max-age=63072000; includeSubdomains; preload',
            'X-XSS-Protection': '1; mode=block',
            'Vary': 'User-Agent,Accept-Encoding',
            'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT',
            'Cache-Control': 'no-store, no-cache, must-revalidate',
            'Pragma': 'no-cache',
            'Content-Encoding': 'gzip',
            'Content-Length': '2946', 'Keep-Alive': 'timeout=5, max=97',
            'Connection': 'Keep-Alive',
            'Content-Type': 'text/html; charset=UTF-8',
            }```