text:
Q: I want to filter using CheckboxListTile in flutter but i have not showing any reflection of filtering in listview when i use Alert dialog? I filter the one litview builder list to another checkbox list and this is working, but when i add this CheckboxListTile in Alert dialog when no filter reflection showing.
I used StatefulBuilder also but is not useful to filtering listview.
[This is first link to show Product list data][1]
This is second link of filter list

I am stuck in how to one data filter to another item filter that availiable in Alert dialog.

This is Api link

const String baseUrl = "https://run.mocky.io/v3/";
const String productDataUrl = baseUrl + "4ecbd2ea-a725-438b-b8fc-da8fc08bc875";
const String productCategoryDataUrl =
    baseUrl + "0595387e-732e-47cf-9675-244fed9fc014";

This is product model class that listview model that we want to filter

class ProductDataModel {
  int? productId;
  String? productName;
  int? productPrice;
  int? productKG;
  String? productCategoryId;

  ProductDataModel(
      {this.productId,
      this.productName,
      this.productPrice,
      this.productKG,
      this.productCategoryId});

  ProductDataModel.fromJson(Map<String, dynamic> json) {
    productId = json['ProductId'];
    productName = json['ProductName'];
    productPrice = json['ProductPrice'];
    productKG = json['ProductKG'];
    productCategoryId = json['ProductCategoryId'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ProductId'] = this.productId;
    data['ProductName'] = this.productName;
    data['ProductPrice'] = this.productPrice;
    data['ProductKG'] = this.productKG;
    data['ProductCategoryId'] = this.productCategoryId;
    return data;
  }
}

This ProductCategory Model class for using filter and this model class
data in CheckboxTile

class ProductCategoryDataModel {
  int? productCategoryId;
  String? productCategoryName;
  bool? isChecked=false;

  ProductCategoryDataModel(
      {this.productCategoryId, this.productCategoryName, this.isChecked});

  ProductCategoryDataModel.fromJson(Map<String, dynamic> json) {
    productCategoryId = json['ProductCategoryId'];
    productCategoryName = json['ProductCategoryName'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['ProductCategoryId'] = this.productCategoryId;
    data['ProductCategoryName'] = this.productCategoryName;
    return data;
  }
}

This is code of showing listview and filter data using
checkboxlisttile that data in Alert dialog .

import 'dart:convert';
import 'dart:developer';

import 'package:dummy_checkbox_filter_list/commons/api_url.dart';
import 'package:dummy_checkbox_filter_list/model/product_category_data_model.dart';
import 'package:dummy_checkbox_filter_list/model/product_data_model.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<ProductDataModel> productDataList = [];
  Set<ProductDataModel> productDataListDisplay = {};
  List<ProductCategoryDataModel> productCategoryDataList = [];
  List<ProductCategoryDataModel> selectProductCategoryDataList = [];

  ScrollController scrollController = ScrollController();
  bool isShowLoader = false;

  getProductList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=> ${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productDataList.add(ProductDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  getProductCategoryList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productCategoryDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=>${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productCategoryDataList
              .add(new ProductCategoryDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productCategoryDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    getProductList();
    getProductCategoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    filterProduct(productDataList);
    return Scaffold(
      body: SafeArea(
        child: isShowLoader == false
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                builder: (context, setState) {
                                  return AlertDialog(
                                    titlePadding: EdgeInsets.zero,
                                    backgroundColor: Color(0xFF242424),
                                    title: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        IconButton(
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                            icon: Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 25,
                                            ))
                                      ],
                                    ),
                                    contentPadding: EdgeInsets.zero,
                                    content: Container(
                                      padding: EdgeInsets.all(5),
                                      width: double.maxFinite,
                                      child: ListView(
                                        padding: EdgeInsets.all(8.0),
                                        children: [
                                          Text(
                                            "dfff "+productCategoryDataList[0].isChecked.toString(),
                                            style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 16),
                                          ),
                                          ...productCategoryDataList
                                              .map((e) => CheckboxListTile(
                                                    controlAffinity:
                                                        ListTileControlAffinity
                                                            .leading,
                                                    title: Text(
                                                      "${e.productCategoryName}",
                                                      style: TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 16),
                                                    ),
                                                    value: e.isChecked,
                                                    selected:
                                                        selectProductCategoryDataList
                                                            .contains(e),
                                                    onChanged: (val) {
                                                      print("val: "+val.toString());
                                                      setState(() {

                                                        e.isChecked = val;
                                                        selectProductCategoryDataList
                                                                .contains(e)
                                                            ? selectProductCategoryDataList
                                                                .remove(e)
                                                            : selectProductCategoryDataList
                                                                .add(e);
                                                        print(
                                                            "_isChecked: ${e.isChecked}");
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            });
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                          onPrimary: Colors.white,
                          minimumSize: Size(
                              MediaQuery.of(context).size.width * 0.30,
                              MediaQuery.of(context).size.height * 0.05)),
                      child: Text(
                        "Filter",
                        style: TextStyle(fontSize: 15),
                      ),
                    ),

                    Container(
                      child: ListView.builder(
                        itemCount: productDataListDisplay.length,
                        shrinkWrap: true,
                        controller: scrollController,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Container(
                              padding: EdgeInsets.only(top: 15, bottom: 15),
                              color: (index % 2 == 0)
                                  ? Colors.grey.shade100
                                  : Colors.white,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(productDataListDisplay
                                      .elementAt(index)
                                      .productId
                                      .toString()),
                                  Center(
                                    child: Text(
                                      productDataListDisplay
                                          .elementAt(index)
                                          .productName
                                          .toString(),
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productKG.toString()} KG",
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
              ),
      ),
    );
  }

  void filterProduct(allProducts) {
    productDataListDisplay.clear();
    if (selectProductCategoryDataList != null &&
        selectProductCategoryDataList.isNotEmpty) {
      final List<int> idsOfSelectedCategories = selectProductCategoryDataList
          .map((category) => category.productCategoryId!)
          .toList();
      print("idsOfSelectedCategories=> $idsOfSelectedCategories");
      Set<ProductDataModel> storesInSelectedCategories =
          getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
      setState(() {
        productDataListDisplay.addAll(storesInSelectedCategories);
        print(allProducts.length);
        print(storesInSelectedCategories.length);
      });

    } else {
      setState(() {
        productDataListDisplay.addAll(allProducts);
      });
    }
  }

  Set<ProductDataModel> getStoresFromSelectedCategories(
      List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
    Set<ProductDataModel> allProductsFromCategory = {};

    for (var categoryId in idsOfSelectedCategories) {
      var productMatched = allProducts
          .where((store) => store.productCategoryId!
              .split(" ")
              .contains(categoryId.toString()))
          .toList();
      print("Stores Matched runtime=>${productMatched.runtimeType}");
      allProductsFromCategory.addAll(productMatched);
    }
    return allProductsFromCategory;
  }
}

A: Add .then((value) {if (mounted) {setState(() {});}}); to showdialog so that state gets refreshed when alertdialog closes.
class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  List<ProductDataModel> productDataList = [];
  Set<ProductDataModel> productDataListDisplay = {};
  List<ProductCategoryDataModel> productCategoryDataList = [];
  List<ProductCategoryDataModel> selectProductCategoryDataList = [];

  ScrollController scrollController = ScrollController();
  bool isShowLoader = false;

  getProductList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=> ${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productDataList.add(ProductDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  getProductCategoryList() async {
    try {
      setState(() {
        isShowLoader = true;
      });
      final response = await http.get(Uri.parse(productCategoryDataUrl));
      log("Response URL=> ${response.toString()}");
      if (response.statusCode == 200) {
        var decode = jsonDecode(response.body);
        log("Response Body=>${decode.toString()}");
        for (int i = 0; i < decode.length; i++) {
          productCategoryDataList
              .add(new ProductCategoryDataModel.fromJson(decode[i]));
        }
        setState(() {
          isShowLoader = false;
        });
        return productCategoryDataList;
      } else {
        setState(() {
          isShowLoader = false;
        });
        throw "Unable to retrieve product data.";
      }
    } catch (e) {
      setState(() {
        isShowLoader = false;
      });
      print('Something went wrong.');
    }
  }

  @override
  void initState() {
    getProductList();
    getProductCategoryList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    filterProduct(productDataList);
    return Scaffold(
      body: SafeArea(
        child: isShowLoader == false
            ? SingleChildScrollView(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ElevatedButton(
                      onPressed: () {
                        showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return StatefulBuilder(
                                builder: (context, setState) {
                                  return AlertDialog(
                                    titlePadding: EdgeInsets.zero,
                                    backgroundColor: const Color(0xFF242424),
                                    title: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        IconButton(
                                            onPressed: () {
                                              Navigator.of(context).pop();
                                            },
                                            icon: const Icon(
                                              Icons.close,
                                              color: Colors.white,
                                              size: 25,
                                            ))
                                      ],
                                    ),
                                    contentPadding: EdgeInsets.zero,
                                    content: Container(
                                      padding: EdgeInsets.all(5),
                                      width: double.maxFinite,
                                      child: ListView(
                                        padding: EdgeInsets.all(8.0),
                                        children: [
                                          Text(
                                            "dfff ${productCategoryDataList[0].isChecked}",
                                            style: const TextStyle(
                                                color: Colors.white,
                                                fontSize: 16),
                                          ),
                                          ...productCategoryDataList
                                              .map((e) => CheckboxListTile(
                                                    controlAffinity:
                                                        ListTileControlAffinity
                                                            .leading,
                                                    title: Text(
                                                      "${e.productCategoryName}",
                                                      style: const TextStyle(
                                                          color: Colors.white,
                                                          fontSize: 16),
                                                    ),
                                                    value: e.isChecked,
                                                    selected:
                                                        selectProductCategoryDataList
                                                            .contains(e),
                                                    onChanged: (val) {
                                                      print("val: $val");
                                                      setState(() {
                                                        e.isChecked = val;
                                                        selectProductCategoryDataList
                                                                .contains(e)
                                                            ? selectProductCategoryDataList
                                                                .remove(e)
                                                            : selectProductCategoryDataList
                                                                .add(e);
                                                        print(
                                                            "_isChecked: ${e.isChecked}");
                                                      });
                                                    },
                                                  ))
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              );
                            }).then((value) {
                          if (mounted) {
                            setState(() {});
                          }
                        });
                      },
                      style: ElevatedButton.styleFrom(
                          primary: Colors.black,
                          onPrimary: Colors.white,
                          minimumSize: Size(
                              MediaQuery.of(context).size.width * 0.30,
                              MediaQuery.of(context).size.height * 0.05)),
                      child: const Text(
                        "Filter",
                        style: TextStyle(fontSize: 15),
                      ),
                    ),
                    Container(
                      child: ListView.builder(
                        itemCount: productDataListDisplay.length,
                        shrinkWrap: true,
                        controller: scrollController,
                        itemBuilder: (context, index) {
                          return Card(
                            child: Container(
                              padding: EdgeInsets.only(top: 15, bottom: 15),
                              color: (index % 2 == 0)
                                  ? Colors.grey.shade100
                                  : Colors.white,
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceAround,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(productDataListDisplay
                                      .elementAt(index)
                                      .productId
                                      .toString()),
                                  Center(
                                    child: Text(
                                      productDataListDisplay
                                          .elementAt(index)
                                          .productName
                                          .toString(),
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productKG.toString()} KG",
                                    ),
                                  ),
                                  Center(
                                    child: Text(
                                      "${productDataListDisplay.elementAt(index).productCategoryId.toString()}",
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              )
            : Center(
                child: CircularProgressIndicator(
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.blue)),
              ),
      ),
    );
  }

  void filterProduct(allProducts) {
    productDataListDisplay.clear();
    if (selectProductCategoryDataList != null &&
        selectProductCategoryDataList.isNotEmpty) {
      final List<int> idsOfSelectedCategories = selectProductCategoryDataList
          .map((category) => category.productCategoryId!)
          .toList();
      print("idsOfSelectedCategories=> $idsOfSelectedCategories");
      Set<ProductDataModel> storesInSelectedCategories =
          getStoresFromSelectedCategories(allProducts, idsOfSelectedCategories);
      setState(() {
        productDataListDisplay.addAll(storesInSelectedCategories);
        print(allProducts.length);
        print(storesInSelectedCategories.length);
      });
    } else {
      setState(() {
        productDataListDisplay.addAll(allProducts);
      });
    }
  }

  Set<ProductDataModel> getStoresFromSelectedCategories(
      List<ProductDataModel> allProducts, List<int> idsOfSelectedCategories) {
    Set<ProductDataModel> allProductsFromCategory = {};

    for (var categoryId in idsOfSelectedCategories) {
      var productMatched = allProducts
          .where((store) => store.productCategoryId!
              .split(" ")
              .contains(categoryId.toString()))
          .toList();
      print("Stores Matched runtime=>${productMatched.runtimeType}");
      allProductsFromCategory.addAll(productMatched);
    }
    return allProductsFromCategory;
  }
}


text:
Q: Delegate painting of custom Swing component to parent My goal
I want my custom Swing component CellLabel extends JLabel to paint certain things (X) always, and certain other elements (Y) only if its parent - (a JPanel holding a grid of CellLabels) - tells it to. The painting of (Y) depends on the state of the neighbouring cells in the grid, and only the JPanel can get this information and decide if and how (Y) should be painted for every child CellLabel.
My question
How can I externalize (into a method with parameters that allow me to describe how to paint (Y) exactly) the painting behavior so that the parent can decide whether it wants a CellLabel child to paint (Y) or not?
My problem
Every Swing tutorial out there tells me I should overwrite the paintComponent method when creating a custom component; however, in my application, the component can't decide for itself if and how (Y) should be painted since it lacks the necessary information.
I tried to write a CellLabel::paintY(int offset) method that I could call from the parent once it has decided how and if to paint (Y):
class CellLabel extends JLabel {
    void paintComponent(Graphics g) {
        super.paintComponent(g);
        // Paint elements (X) which should always be painted, independent
        // of external state
    }

    void paintY(int[] params){
        Graphics2D g2 = (Graphics2D) this.getGraphics();

        // Perform some calculation with params that decide how painting is done

        // (*) Actually paint elements (Y) by using the g2 graphics context
    }
}

However, it seems I can't get a hold of the Graphics context outside of the predefined paint methods that convention tells me to overwrite. I get the following exception at (*) (when actually trying to paint with g2):
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at CellLabel.paintY(CellLabel.java:77)
at AutomatonUI.createAndShowGUI(AutomatonUI.java:50)
at AutomatonUI.access$000(AutomatonUI.java:22)
at AutomatonUI$1.run(AutomatonUI.java:29)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

I have a solid amount of experience coding business logic and number-crunching, but I'm quite new to Swing (and UI programming) in general, so please excuse me (and educate me) if I'm doing something horribly wrong.

A: A better approach might be to separate your logic from the Swing GUI library. For example, defining a CellContainer class that contains Cell objects, which can be updated before each render (where in the update you can update Cells from CellContainer however you wish). You could then have CellContainerPanel and a CellLabel class that extend the appropriate Swing class which take a reference to CellContainer and Cell each which just draw the state that their references make available.

A: IIRC, your paintComponent function needs to call super.paintComponent(g);
The last time I wrote a program with swing, i declared a static graphics object in a class that everything could access (this is probably a horrible thing to do, but it was a workaround which helped me to complete my task). Instead of storing the information inside of a two dimensional array, store "information" objects inside the array. Those information objects (object x, for example) can contain all the information about the cell itself, as well as a "draw(g)" method. That draw method can dictate how this cell is drawn. In the paintComponent function, you can now call
//where g is the graphics object
for (array x : array of arrays) {
    for (informationObject y : x) {
        y.draw(g);
    }
}

Now you can do all the calculations inside the object itself, instead of having to deal with obtaining external information and doing calculations outside. (Then, the code will be easier to debug as well)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to click on the save button when pop-up appears? I am using Internet Explorer to click on a file.
I get to a point where an Internet Explorer pop-up appears saying "Do you want to open or save the file?":

I want to write a VBA code that clicks on the save button.
I realized it is not possible to right click and "inspect element" in order to show the HTML page because the pop-up is not part of the internet explorer webpage.
So I tried the sendKeys method even though it is not reliable. I tried different options such as :
Application.SendKeys "%S"
Application.SendKeys "%s"
Application.SendKeys "%{S}"
Application.SendKeys "%{s}"
SendKeys ("%S")
SendKeys ("%s")
SendKeys ("%{S}")
SendKeys ("%{s}")

Application.SendKeys "%{S}"

When I run the code, none of them save the file.
Where is my error?
Are there other propositions to click on that "Save" button?
Maybe the object to which I am applying SendKeys should not be "Application"?

A: If you wish to use the UIAutomationCore.dll and reference it, you can do something like:
Public Function AutoSave() As Boolean
On Error Goto handler
    Dim sysAuto As New UIAutomationClient.CUIAutomation
    Dim ieWindow As UIAutomationClient.IUIAutomationElement
    Dim cond As IUIAutomationCondition
    Set cond = sysAuto.CreateAndCondition(sysAuto.CreatePropertyCondition(UIA_NamePropertyId, "Notification"), _
                                      sysAuto.CreatePropertyCondition(UIA_PropertyIds.UIA_ControlTypePropertyId, UIA_ToolBarControlTypeId))
    Set ieWindow = sysAuto.GetRootElement.FindFirst(TreeScope_Descendants, cond)

    Dim tField As UIAutomationClient.IUIAutomationElement
    Dim tFieldCond As IUIAutomationCondition
    Set tFieldCond = sysAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_ControlTypeIds.UIA_SplitButtonControlTypeId)
    Set tField = ieWindow.FindFirst(TreeScope_Descendants, tFieldCond)

    Dim invPattern As UIAutomationClient.IUIAutomationInvokePattern
    Set invPattern = tField.GetCurrentPattern(UIA_InvokePatternId)
    invPattern.Invoke
    AutoSave = True

Exit Function
handler:

End Function

And call that routine after clicking on the item - perhaps give it a Hard Wait to allow the Notification bar to show.
EDIT
To invoke the Close Button:
Set cond = sysAuto.CreateAndCondition(sysAuto.CreatePropertyCondition(UIA_NamePropertyId, "Close"), _
                                      sysAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_ControlTypeIds.UIA_ButtonControlTypeId))
Dim closeButton As IUIAutomationElement
Set closeButton = WaitForElement(ieWindow, cond, 10)
If closeButton Is Nothing Then Exit Sub

Dim clickButtonPattern As IUIAutomationInvokePattern
Set clickButtonPattern = closeButton.GetCurrentPattern(UIA_InvokePatternId)
clickButtonPattern.Invoke
........

Helper function:
Function WaitForElement(rootElement As IUIAutomationElement, condition As IUIAutomationCondition, timeout As Long) As IUIAutomationElement
    Dim startTime As Date
    startTime = Now

    Dim element As IUIAutomationElement
    Set element = rootElement.FindFirst(TreeScope_Descendants, condition)
    While element Is Nothing And 100000 * (Now - startTime) < timeout
        Application.Wait Now + TimeValue("00:00:01")
        Set element = rootElement.FindFirst(TreeScope_Descendants, condition)
    Wend

    Set WaitForElement = element
End Function

You would typically wait until the 'Notification bar Text' element text had changed to have "download has completed" at the end.
This can be done with a couple of helper functions:
Function WaitForTextValue(textElement As IUIAutomationElement, text As String, timeout As Long, Optional exactMatch As Boolean = False) As Boolean
Dim startTime As Date
startTime = Now

Dim result As String
result = ReadValue(textElement)
Dim isMatch As Boolean
If exactMatch Then
    isMatch = result = text
Else
    isMatch = InStr(1, result, text, vbTextCompare) > 0
End If

'keep reading the element until we have a match, or the timeout has expired
While Not isMatch And 100000 * (Now - startTime) < timeout
    Application.Wait Now + TimeValue("00:00:01")
    result = ReadValue(textElement)
    If exactMatch Then
        isMatch = result = text
    Else
        isMatch = InStr(1, result, text, vbTextCompare) > 0
    End If
Wend

WaitForTextValue = isMatch
End Function

Function ReadValue(element As IUIAutomationElement) As String
Dim valPattern As IUIAutomationValuePattern
Set valPattern = element.GetCurrentPattern(UIA_ValuePatternId)

If Not valPattern Is Nothing Then
    ReadValue = element.GetCurrentPropertyValue(UIA_ValueValuePropertyId)
Else
    ' raise error here if element's value cannot be read - err.Raise
End If

End Function

And you would call this check after clicking the 'Save' button like so:
Set cond = sysAuto.CreateAndCondition(sysAuto.CreatePropertyCondition(UIA_NamePropertyId, "Notification bar Text"), _
                                      sysAuto.CreatePropertyCondition(UIA_ControlTypePropertyId, UIA_ControlTypeIds.UIA_TextControlTypeId))
Dim barText As IUIAutomationElement
Set barText = WaitForElement(ieWindow, cond, 10)
If barText Is Nothing Then Exit Sub

If Not WaitForTextValue(barText, "download has completed", 30, False) Then Exit Sub
'if we get to here, then text has changed, and we can go ahead and click close button

A: Reproduce your problem on my side, it seems that before clicking the Save button, we need time to display the popup file download prompt. So, please try to use the Application.Wait method to wait the prompt display.
Code like this:
Sub Test()
    Dim ie As Object
    Dim Rank As Object
    Set ie = CreateObject("InternetExplorer.application")
    ie.Visible = True
    ie.Navigate ("http://localhost:54382/HtmlPage47.html")
    Do
        If ie.ReadyState = 4 Then
            Exit Do
        Else
        End If
    Loop

    Set doc = ie.document

    doc.getElementsByTagName("tr")(1).getElementsByTagName("td")(5).getElementsByTagName("a")(0).Click

    Application.Wait (Now + TimeValue("0:00:02"))
    Application.SendKeys "%{S}"

End Sub

The screenshot as below:


text:
Q: Laravel 8 in subfolder on server having issue in loading css and js I have installed my Laravel application on the server inside a folder named admin
However, I am experiencing a problem with css and js files not loading on the correct path
They are loading with root domain instead of example.com/admin
I have done the following:
I tried to rewrite htaccess but it didn't work
I tried overriding the asset function and found that it returned the correct path
My comment above indicates that I'm having an htaccess issue, something redirecting the asset to the root url
This is my htaccess at in subfolder
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
    Options +FollowSymLinks
</IfModule>

RewriteEngine On
RewriteBase /admin
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ ^$1 [N]

RewriteCond %{REQUEST_URI} (\.\w+$) [NC]
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ server.php

and this is in public folder
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews -Indexes
</IfModule>

RewriteEngine On
RewriteBase /admin
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]


text:
Q: How to use `clojure --main` When reading clojure -h* I found the --main option:
  main options:
    -m, --main ns-name  Call the -main function from a namespace with args

Having the following code:
(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!"))

Is it possible to utilize the --main argument to call directly the -main function without using lein?
*clojure = java ${JAVA_OPTS} -jar path_to_clojure.jar "$@"

A: Yes. Assuming -main function is in the file ./src/foo/core.clj the following will run it:
java -cp "path_to_clojure.jar:src" clojure.main --main foo.core (note the src in the classpath)


text:
Q: Use p4 shelve in perl script without opening the editor I'm trying to shelve my changes via perl script. After running p4 shelve it opens up an editor where I need to enter the description, save and exit.
The problem I'm facing here is this script will be running on server side where we don't need user input so I need to handle this interactive mode to non-interactive so that I can shelve and proceed my next steps with shelved changelist. Are there any options ?
use P4;
my $client = $ENV{client};
my $p4 = P4->new();
$p4->Connect();
$p4->SetClient($client);
$p4->Run('shelve');

A: Use the -c flag to shelve an existing pending changelist rather than opening an editor to create a new numbered pending changelist.  I haven't used P4Perl, but according to the doc you can create a new changelist by doing something like:
$change = $p4->FetchChange();
$change->{ 'Description' } = "Some description";
$p4->SaveChange($change)  # get a $changenum from the output of this

so you should be able to do that and then shelve that changelist by doing:
$p4->Run('shelve', '-c', $changenum);


text:
Q: Disable to wrap for iframes I want/need to create a dashboard, which shows four different screens.
So far I tried solving it by simply including the "displays" per iframes:

Now I have the problem, that the browserwindow always stacks the windows vertically, because they're slightly too large. I want them to be in a 2x2. How can I realize that it puts two frames next to each other, instead of moving them around so they fit.
I tried different options already, but non of them seem to work.
Any help would be appreciated

A: You can put your iframes in grid/flex to achieve the solution

A: You can put the iframes in a 2x2 grid.
However, importantly you need to make sure that the aspect ratio remains the same as the original.
This snippet ensures this by using the CSS property aspect-ratio taking your original iframe dimensions to set this.

.container {
  width: 50vw;
  /* set just for this demo make it what you want */
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 2vw;
}

iframe {
  aspect-ratio: 1920 / 1080;
  width: 100%;
}


text:
Q: ReactiveVar not getting new value on Tracker.autorun in Meteor I'm instantiating a new ReactiveVar:
Template.myTemplate.onCreated(function() {
   this.var1 = new ReactiveVar(0);
}

I'm having a Tracker.autorun force a rerun when the user selects a new year value:
Template.myTemplate.onRendered(function() {
  Tracker.autorun(function() {
  var year = Session.get('chartYear').toString(); // This session is from another template
  // Do stuff
  ...
  Template.instance().var1.set(new data);
  }
}

My helpers to rerun the function:
Template.myTemplate.helpers({
  function1: function () {
    return Template.instance().var1.get();
}

Not sure what's going on but when a year value is selected on first go, everything runs fine. But when the user selects a new year value, a TypeError results:
"TypeError: null is not an object (evaluating 'Template.instance().var1')"

However, if I replace the ReactiveVars with Sessions instead, everything works fine when the user selects different year values. Could anyone help out?

A: It's not clear which line is throwing that error (if the following doesn't apply post the full error indicating if this is from the helper or onRendered event, etc).
However I suspect this is from the Template.onRendered event, which requires you to access the template instance from the this object, like you are in your Template.onCreated event.

*

*In 'lifecycle' events, e.g. Template.onRendered, Template.onCreated, Template.onDestroyed, the current template instance is the this object

*In 'helper' functions, the current template instance is accessed using Template.instance()

*In 'DOM' events, e.g. 'click #myButton'(event, instance), the current template instance is the second argument passed to the event handler.  (Template.instance() also works here, but convention is to name the second argument 'instance', and use in instead)
So try changing your onRendered function to this:
Template.myTemplate.onRendered(function() {
  templateInstance = this;
  Tracker.autorun(function() {
    var year = Session.get('chartYear').toString(); // This session is from another template
    // Do stuff
    ...
    templateInstance.var1.set(newData);
  }
}


text:
Q: C# Windows Application Form to Html Form I'm working on a project where I need to convert a C# windows application form to an HTML form programmatically.
I'm having problems with sizing the HTML text boxes appropriately.  I set the width and height to the exact same width and height (in pixels) used on the winforms equivalent but it ends up being bigger than the winforms equivalent.
The other controls (label, groupbox ...) appear OK. Clues anyone?

A: The CSS trick for Box Sizing would come in rescue for your case:
textarea {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}

More detials you can find here: http://css-tricks.com/box-sizing/


text:
Q: Generating Python code from a diagram / UML / visual representation I have some Python classes that I pretend to manage with a visual tool of some sort. Each class has some methods that can perform operations (while also accepting arguments or returning values or other class instances).
Let's say that the classes are "Person", "Hat" and "Handwatch". Now, let's say that "Person" has the methods getName() and putOn(object).
From a code point of view, attaching a "handwatch" or a "hat" to a "person" (given the classes I just mentioned) would be as easy as:
person = Person()
if person.getName() == "Fred":
    handwatch = Handwatch()
    person.putOn(handwatch)
else:
    hat = Hat()
    person.putOn(hat)

But what if I wanted to be able to "draw" that sort of interaction between instances of my classes?
Imagine a visual UML-like tool that would let me "represent" code by dragging from a palette of "classes" and dropping "instances" of those classes, and that then would generate code that would behave exactly like that.

Are there any libraries that I could use in order to even begging implementing something like that? Or maybe even some literature on the subject?

A: You cannot require to generate code from a diagram (a diagram is a normalized picture showing a part of the model), you are requiring a tool generating code from an activity (which can be shown in diagram(s)).
As a state machine an activity is a behavior and can represent the definition of an operation, contrarily to an interaction for instance (may be shown through a sequence diagram)
In your code it seems artificial to get the name of a newly created Person whose name is not given in parameter at the creation. Let say that instance is received through the input parameter person and the activity representing your code can be :

where the actions in green are call operation actions (there are named by the called operation to be clear), and the blue are create object actions (whose name indicates the class to be clear).
Also for the clarity of the diagram the pin 'name' has in fact the direction return etc
There is nothing against generating Python code from that activity, note also to help the definition of an action can be an opaque form where you can directly put Python code.
Do I know a modeler doing that ? no, sorry, even I imagined to do in BoUML through a plug-out in the same way I made a state machine generator (producing C++ code), but nobody asked for. So, just do it ?


text:
Q: How to set frame UITableviewCell image size? I use a small image size, such are 26*27, 15*28,... but the image is stretched and how to avoid and to set all image alignment are center.

A: You can set your image to center of image using UIViewContentModeCenter
Using code
imageView.contentMode=UIViewContentModeCenter;

using Nib

A: i think u want :
imageView.contentMode = UIViewContentModeScaleAspectFill;

A: Use following method for to specify the height and width of image
+ (UIImage*)resizeImage:(UIImage*)image withWidth:(int)width withHeight:(int)height
{
    CGSize newSize = CGSizeMake(width, height);
    float widthRatio = newSize.width/image.size.width;
    float heightRatio = newSize.height/image.size.height;

    if(widthRatio > heightRatio)
    {
        newSize=CGSizeMake(image.size.width*heightRatio,image.size.height*heightRatio);
    }
    else
    {
        newSize=CGSizeMake(image.size.width*widthRatio,image.size.height*widthRatio);
    }

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

This method return NewImage, with a specific size that you specify


text:
Q: How to account for tabwidget height in layout? I have a two activities that I switch using tabs. I am having a problem where my activity content does not resize properly to account for the height of the tab widget (therefore the activity content shows clipped behind the tabs). I have the tabs at the bottom. I have tried playing with the tab layout, etc but with no luck.
Is there a way when designing a layout (for the tab content activity) to account for the tab height in android? My guess is that the way I have designed my layout for the activity is too tall after adding it to the tab host. This is possible on iOS but don't know how to do it on android. Any ideas?
    <?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_above="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </FrameLayout>
    </RelativeLayout>

</TabHost>

A: A very simple solution is to use fixed size tabs e.g.
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="64dp">
    </TabWidget>


text:
Q: Copy folder context menu requires user input We copy a lot of data around in our organisation, and we like using RoboCopyPlus for the robustness and the email reports at the end.
I've added the RoboCopyPlus string to the folder context menu in the registry as:
cmd /c robocopyplus "%1" "C:\Data" *.* /s

But that means I can only copy a folder to C:\Data.
What's the best way to prompt for user input or create a variable that I can pass in to the command? Ideally I would like a folder browser dialogue to pop up and ask them the location, but accepting that that's probably complicating the matter, how would I prompt for user input in the shell?

A: Write a simple application to have the user select a file, then launch RoboCopyPlus using the path that was selected. Add an entry to your context menu that launches this application instead. Here's an example in C# using the FolderBrowserDialog class and Process.Start().
using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace RobocopyLauncher
{
    class Launcher
    {
        static void Main(string[] args)
        {
            FolderBrowserDialog browser = new FolderBrowserDialog();
            if (browser.ShowDialog() == DialogResult.OK && args.Length == 1)
            {
                // Not sure of the exact command but it would be
                // something like this
                Process.Start(string.Format("robocopyplus \"{0}\" \"{1}\"",
                    args[0], browser.SelectedPath);
            }
        }
    }
}


text:
Q: Understanding how the C# compiler deals with chaining linq methods I'm trying to wrap my head around what the C# compiler does when I'm chaining linq methods, particularly when chaining the same method multiple times.
Simple example: Let's say I'm trying to filter a sequence of ints based on two conditions.
The most obvious thing to do is something like this:
IEnumerable<int> Method1(IEnumerable<int> input)
{
    return input.Where(i => i % 3 == 0 && i % 5 == 0);
}

But we could also chain the where methods, with a single condition in each:
IEnumerable<int> Method2(IEnumerable<int> input)
{
    return input.Where(i => i % 3 == 0).Where(i => i % 5 == 0);
}

I had a look at the IL in Reflector; it is obviously different for the two methods, but analysing it further is beyond my knowledge at the moment :)
I would like to find out:
a) what the compiler does differently in each instance, and why.
b) are there any performance implications (not trying to micro-optimize; just curious!)

A: The answer to (a) is short, but I'll go into more detail below:
The compiler doesn't actually do the chaining - it happens at runtime, through the normal organization of the objects! There's far less magic here than what might appear at first glance - Jon Skeet recently completed the "Where clause" step in his blog series, Re-implementing LINQ to Objects. I'd recommend reading through that.
In very short terms, what happens is this: each time you call the Where extension method, it returns a new WhereEnumerable object that has two things - a reference to the previous IEnumerable (the one you called Where on), and the lambda you provided.
When you start iterating over this WhereEnumerable (for example, in a foreach later down in your code), internally it simply begins iterating on the IEnumerable that it has referenced.

"This foreach just asked me for the next element in my sequence, so I'm turning around and asking you for the next element in your sequence".

That goes all the way down the chain until we hit the origin, which is actually some kind of array or storage of real elements. As each Enumerable then says "OK, here's my element" passing it back up the chain, it also applies its own custom logic. For a Where, it applies the lambda to see if the element passes the criteria. If so, it allows it to continue on to the next caller. If it fails, it stops at that point, turns back to its referenced Enumerable, and asks for the next element.
This keeps happening until everyone's MoveNext returns false, which means the enumeration is complete and there are no more elements.
To answer (b), there's always a difference, but here it's far too trivial to bother with. Don't worry about it :)

A: *

*The first will use one iterator, the second will use two. That is, the first sets up a pipeline with one stage, the second will involve two stages.

*Two iterators have a slight performance disadvantage to one.


text:
Q: Потенциальные поля, установка потенциала в матрицу Как можно установить в двумерный массив потенциал?
К примеру я задаю точки (X, Y) в которые нужно установить потенциал, например, хочу в матрице установить потенциал размером 10 в координаты (2, 2) и вот что я ожидаю получить:
{
    2, 4,  6, 4, 2,
    4, 6,  8, 6, 4,
    6, 8, 10, 8, 6,
    4, 6,  8, 6, 4,
    2, 4,  6, 4, 2
}

Т. е. нужно чтобы из данный точки градиентом расходились значения от максимального к минимальному.
Как это можно сделать красиво? У меня есть лишь нелепые конструкции, которые выглядят ужасно. Можно увидеть пример реализации такой штуки?
Для наглядности еще вот картинка:

Здесь установлены 2 точки, со значениями 10 и -10.

Еще о потенциалах:

*

*Использование потенциальных полей в сценарии стратегии реального времени (Хабр)

*Поиск пути: метод потенциальных полей

A: Когда начал писать ответ, заметил, что авторский массив «то что ожидаю получить» не совпадает с картинкой. Конкретики в этом вопросе мало. Поэтому приведу две разные версии таких полей.
1. Общий код
Общий для обеих версий код:
#include <stdio.h>
#include <math.h>

#define MAP_WIDTH  30
#define MAP_HEIGHT 30

void print_map(int* map, int w, int h) {
    for (int y = 0; y < MAP_HEIGHT; ++y) {
        for (int x = 0; x < MAP_WIDTH; ++x) {
            // Вместо нулей печатаем пробелы, чтобы не сломать глаза :)
            (map[x + y*MAP_WIDTH] == 0) ? printf("   ")
                                        : printf("%2i ", map[x + y*MAP_WIDTH]);
        }
        putchar('\n');
    }
}

<...>

int main() {
    int map[MAP_HEIGHT][MAP_WIDTH] = {{0}};

2. Уменьшение веса точки в зависимости от расстояния до центра
Вес каждой точки должен уменьшатся по мере удаления от центра. Но как? Если честно, я так и не смог подобрать правило, чтобы веса уменьшались как на картинке. Поэтому предоставлю код для линейного уменьшения весов.
// map - матрица целых чисел, w, h -- его высота и ширина соответственно.
// x и y -- координаты центра поля.
// start_value -- очевидно, начальное значение.
// attenuation_constant -- коэффициент затухания.

void set_potential(int* map, int w, int h, int x, int y, int start_value, int attenuation_constant) {
    // Вычисляем максимальное удаление от центра по вертикали/горизонтали.
    int verical_and_horizontal_steps_nm = start_value / attenuation_constant;

    int box[2][2] = {
        {x - verical_and_horizontal_steps_nm + 2,
         y - verical_and_horizontal_steps_nm + 2},
        {x + verical_and_horizontal_steps_nm - 1,
         y + verical_and_horizontal_steps_nm - 1}
    };

    for (int dot_y = box[0][1]; dot_y < box[1][1]; ++dot_y) {
        for (int dot_x = box[0][0]; dot_x < box[1][0]; ++dot_x) {
            // Считаем расстояние до точки по формуле d = sqrt((x0-x1)^2 + (y0-y1)^2).
            int distance = sqrt((x-dot_x)*(x-dot_x) + (y-dot_y)*(y-dot_y));

            // Значение текущей точки меняется линейно.
            int dot_value = start_value - distance * attenuation_constant;

            // Если точка не лежит на вертикали или горизонтали от центральной мы считаем
            // значение по-другому, т. к. диагональ квадрата всегда больше его стороны.
            // Т. к. длина стороны у нас -- 1, то длина диагонали будет sqrt(2).
            if (dot_y != y && dot_x != x)
                dot_value = start_value - round(sqrt(2) * distance * attenuation_constant);

            // Чтобы не было отрицательных коэффициентов по углам добавляем условие.
            map[dot_x + dot_y*MAP_WIDTH] = dot_value > 0 ? dot_value : 0;
        }
    }
}

Вот вывод для set_potential((int*)map, MAP_WIDTH, MAP_HEIGHT, 15, 15, 10, 2):
   2  2  4  2  2
2  4  4  6  4  4  2
2  4  7  8  7  4  2
4  6  8 10  8  6  4
2  4  7  8  7  4  2
2  4  4  6  4  4  2
   2  2  4  2  2

Не очень похоже на картинку, зато веса зависят непосредственно от расстояния до центра.
3. Даже не знаю, как назвать вариант. Смотрите сами…
Если мы получше рассмотрим левую нижнюю (а вообще, любую) четверть картинки или массив «ожидания» автора, то заметим, что

*

*Все числа, расположенные на одной диагонали, равны;

*Каждое число на следующей диагонали (при расхождении от центра) ровно на один шаг (я назвал его коэффициентом затухания) больше любого числа на предыдущей диагонали;

*Длина каждой диагонали больше предыдущей на единицу.

Сложно объяснить словами, взгляните сами (коэфф. затухания = 2):

1.        10 (- 2 = 8)
2.       8 8 (- 2 = 6)
3.     6 6 6 (- 2 = 4)
4.   4 4 4 4 (- 2 = 2)
5. 2 2 2 2 2

Четыре таких четверти (правильно повернутые) дадут нужную картинку (которая, кстати, является ромбом, что и нужно автору (см. комментарии к вопросу)).
Алгоритм рисования очень простой, думаю, все будет понятно из кода:
void set_potential2(int* map, int w, int h, int x, int y, int start_value, int attenuation_constant) {
    // Заполняем центр.
    map[x + y*MAP_WIDTH] = start_value;

    // Вычисляем максимальное удаление от центра по вертикали/горизонтали.
    int verical_and_horizontal_steps_nm = start_value / attenuation_constant;

    // Здесь i -- расстояние от центра до текущей точки.
    for (int i = 1; i < verical_and_horizontal_steps_nm; ++i) {
        int dot_value = start_value - attenuation_constant * i;

        // Заполняем левый нижний угол:
        //
        // dot_y = y+i        -- переходим в точку максимального отдаления по вертикали от центра.
        // dot_x =   x        -- координата x точки равна координате центра.
        // do_y >= y; --dot_y -- пока находимся выше центра, поднимаемся вверх.
        // --dot_x            -- смещаемся влево.
        //
        // Т. е. мы как-бы по ступенькам поднимаемся вверх-влево, вверх-влево, вверх-влево...
        // Для остальных углов меняем только направления в заголовке цикла.
        for (int dot_y = y+i, dot_x = x; dot_y >= y; --dot_y, --dot_x)
            // Тоже самое, что map[dot_x][dot_y]
            map[dot_x + dot_y*MAP_WIDTH] = dot_value;

        // Правый нижний угол
        for (int dot_y = y+i, dot_x = x; dot_y >= y; --dot_y, ++dot_x)
            map[dot_x + dot_y*MAP_WIDTH] = dot_value;

        // Левый верхний угол
        for (int dot_y = y-i, dot_x = x; dot_y <= y; ++dot_y, --dot_x)
            map[dot_x + dot_y*MAP_WIDTH] = dot_value;

        // Правый верхний угол
        for (int dot_y = y-i, dot_x = x; dot_y <= y; ++dot_y, ++dot_x)
            map[dot_x + dot_y*MAP_WIDTH] = dot_value;
    }
}

Вот что выдает алгоритм при set_potential2((int*)map, MAP_WIDTH, MAP_HEIGHT, 9, 9, 10, 2):
            2
         2  4  2
      2  4  6  4  2
   2  4  6  8  6  4  2
2  4  6  8 10  8  6  4  2
   2  4  6  8  6  4  2
      2  4  6  4  2
         2  4  2
            2

Автор привел обрезанный массив:

{
    2, 4,  6, 4, 2,
    4, 6,  8, 6, 4,
    6, 8, 10, 8, 6,
    4, 6,  8, 6, 4,
    2, 4,  6, 4, 2
}

Обрежем наш результат:
2  4  6  4  2
4  6  8  6  4
6  8 10  8  6
4  6  8  6  4
2  4  6  4  2

Сходство налицо. Думаю, это именно то, что нужно было автору. По-моему, красота :)
P. S. Код не очень, конечно, но для иллюстрации идеи — пойдет.
P. S. S. Если честно, не знаю как правильно перевести «коэффициент затухания»: «attenuation constant» или «damping constant». Если кто исправит, будут признателен.

A: Ну, задайте какую-то функцию падения потенциала и вычисляйте потенциал в конкретных ячейках, исходя из их расстояния до центральной, и округляя значения до целых, если вам нужны именно они.

A: Вот еще способ (он иной чем описан выше):
#ifndef POTENTIALFIELD_H
#define POTENTIALFIELD_H

#include <iostream>

template <size_t x, size_t y>
class PotentialField {
public:

PotentialField() {
    size_x = x;
    size_y = y;

    fillAll(0.f);
}

/*
    x, y            - координаты в матрице
    value           - максимальное значение данной точки
    force           - применяемая сила к данной точке (force * value)
    fixedRadius     - рисовать только по радиусу а не по всей карте
    radius          - радиус (работает только когда fixedRadius == true)
*/
void setPoint(size_t _x, size_t _y, float value, float force = 0.08f, bool fixedRadius = false, float radius = 0.f) {
    if (_x > size_x - 1 || _y > size_y - 1) // TODO: возможно стоит выкинуть исключение
        return;

    size_t distance = 0;
    for (size_t i = 0; i < size_y; i++) {
        for (size_t j = 0; j < size_x; j++) {
            if (fixedRadius && (j < _x - radius || j > _x + radius || i < _y - radius || i > _y + radius) )
                continue;

            distance = getDistance(_x, _y, j, i);
            if (distance == 0) {
                matrix[i][j] = value * force;
            } else {
                matrix[i][j] += force * value / distance;
            }
        }
    }

}

float getDistance(float x1, float y1, float x2, float y2) {
    return std::sqrt( ((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)) );
}

// Матрица затирается заданным значением
void fillAll(float val = 0.f) {
    float *ptr = &matrix[0][0];
    float *end = &matrix[size_y - 1][size_x];

    while (ptr < end) {
        *ptr = val;
        ++ptr;
    }
}

void print() {
    for (size_t i = 0; i < size_y; i++) {
        for (size_t j = 0; j < size_x; j++) {
            std::cout.width(5);
            std::cout.precision(2);
            std::cout << matrix[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

private:
    size_t  size_x;
    size_t  size_y;

    float       matrix[y][x];
};

#endif

Пример использования:
int main(){
    PotentialField<20, 20>  field();
    field.setPoint(0, 0, 10);
}

Создается поле размером 20 на 20, и в координаты x = 0, y = 0 устанавливается потенциал который распространяется по формуле force * value / distance
Вдруг кому пригодиться =)


text:
Q: A pandas-y way to do simple calculations on rows selected from DataFrame Suppose I have the following data:
import pandas as pd

boxes = {'Color': ['Green','Green','Green','Blue','Blue','Red','Red','Red'],
         'Shape': ['Rectangle','Rectangle','Square','Rectangle','Square','Square','Square','Rectangle'],
         'Price': [10,15,5,5,10,15,15,5]
        }

df = pd.DataFrame(boxes, columns= ['Color','Shape','Price'])

How do I find the average price of every color (ignoring shape) without for-loops? Or the difference between the maximum and minimum price of every color?
In short, I want the following outcome:
        Mean    Range
Green   10.00   10
Blue    7.50    5
Red     11.67   10

This example has only three colors, but if we had 1000 colors, is the method still the same/the most efficient one?

A: You can use the following :
df = df.groupby('Color').agg([np.mean, np.ptp])
df.columns = ['Mean', 'Range']

And you will get the expected result.
Pandas groupby can use multiple aggregation functions. The easiest way to proceed is by using dataframes' native functions such as .mean() or .max(). One can also use .agg()and pass an array of functions to apply such as numpy functions, or even lambda function.

A: Groupby on the color column, get the aggregates, and for the range, get the difference between the max and min
result = (df.groupby("Color")
          .agg(["mean","max","min"])
          .droplevel(0,axis=1)
           #access the max column with brackets
           #rather than dot access
           #as it is a built-in function
          .assign(Range= lambda x: x['max'] - x['min'],
                  mean = lambda x: x['mean'].round(2)
                 )
          .iloc[:,[0,-1]]
         )

result

        mean  Range
Color
Blue    7.50    5
Green   10.00   10
Red     11.67   10

A: g = df.groupby('Color')['Price']
df = pd.concat([g.mean(), g.max() - g.min()], axis=1)
df.columns = ['Mean', 'Range']
print(df)

Prints:
            Mean  Range
Color
Blue    7.500000      5
Green  10.000000     10
Red    11.666667     10


text:
Q: Run one test without transactions I'd like to run one of the tests in our test suite without using the transactional tests strategy. I found I can do this by adding the following line to the top of the test:
self.use_transactional_tests = false

I'm worried this will leave my test database polluted unless I clean up any records created during the test.

*

*Is that assumption correct, or does rails use another cleanup strategy when you turn off the transactional strategy?

*If that's correct, what's the best way to clear out the whole database and load fixtures again after the test has run?


text:
Q: Run Python Webapplication on internal Company Server I would like to create something like an attendance system for the employees in the company with python plotly and dash.
We already have a internal server with an intranet (based on Wordpress). I thought about the same server and run there the dash application. Is this possible or do i need to use services like heroku, python anywhere etc. The internal server runs with 18.04 Ubuntu.
My idea was to create a folder for the python application, install all libraries and run the python dash application there so it should run on a specific url like 192.168.22.222/attendance.
Would be nice to know if this is possible the way i thought about it and if not why and what i have to consider before the start.
The server will be created by the it department (my job is the dash application (i have already created some))
thanks for your help


text:
Q: Why do motorola android devices install >60 background processes and services, and how can they be removed? Folks,
We are debugging unexplained crashes of our Android app on motorola devices. We have an unhandled exception handler that catches crashes and uploads them to our server, but our users weren't generating these logs, meaning that the OS itself was choosing to kill our app. We typically test on motorola devices that aren't activated with cell service.
As a result of user complaints, we incorporated a task manager to see what other applications were running concurrently. On our development devices we would see between 6-10 applications and services that were not android-specific (ie, all com.google or com.android processes were filtered out).
On one customer device that was experiencing problems, we got the following list:
[Process] android.tts: 577 kb / 2221 kb
[Process] com.appspot.scruffapp: 8384 kb / 15683 kb
[Process] com.motorola.blur.providers.contacts: 4306 kb / 1466 kb
[Process] com.motorola.blur.service.blur: 1831 kb / 3515 kb
[Process] com.motorola.blur.service.main: 7047 kb / 5563 kb
[Process] com.motorola.blur.contacts.data: 914 kb / 1041 kb
[Process] com.motorola.blur.home.message: 1205 kb / 1813 kb
[Process] com.motorola.process.system: 911 kb / 911 kb
[Process] com.motorola.blur.alarmclock: 783 kb / 791 kb
[Process] com.motorola.blur.home: 5747 kb / 5004 kb
[Process] com.motorola.blur.conversations: 3054 kb / 4026 kb
[Process] com.motorola.blur.weather: 1124 kb / 1408 kb
[Process] com.motorola.blur.home.newsstatus: 2529 kb / 2031 kb
[Process] com.motorola.blur.socialmessaging: 776 kb / 927 kb
[Process] com.motorola.blur.contacts: 943 kb / 1069 kb
[Process] com.flexaspect.android.everycallcontrol: 810 kb / 1204 kb
[Process] com.yahoo.mobile.client.android.mail: 2394 kb / 2777 kb
[Process] com.fusionone.android.sync.service: 870 kb / 809 kb
[Process] com.motorola.vvm: 803 kb / 918 kb
[Process] com.wsandroid: 937 kb / 1271 kb
[Process] com.motorola.blur.messaging: 1404 kb / 1476 kb
[Process] com.motorola.blur.email: 1635 kb / 2258 kb
[Process] com.rechild.advancedtaskkiller: 3280 kb / 5080 kb
[Process] com.motorola.photowidget: 1210 kb / 1014 kb
[Process] com.motorola.togglewidgets: 672 kb / 732 kb
[Process] com.davidgoemans.simpleClockWidget: 930 kb / 1179 kb
[Process] com.motorola.android.buacontactadapter: 551 kb / 636 kb
[Process] com.motorola.vclipboard: 593 kb / 626 kb
[Process] com.groupon: 997 kb / 1352 kb
[Process] com.motorola.blur.home.other: 1262 kb / 890 kb
[Process] com.motorola.cmas: 654 kb / 630 kb
[Process] com.motorola.android.datamanager: 1247 kb / 939 kb
[Process] com.motorola.videoplayer: 656 kb / 631 kb
[Process] com.motorola.android.syncml.service: 786 kb / 684 kb
[Process] com.motorola.android.dm.service: 569 kb / 574 kb
[Process] com.motorola.usb: 655 kb / 757 kb
[Process] com.motorola.batterymanager:deviceStats: 573 kb / 595 kb
[Process] com.motorola.batterymanager: 594 kb / 599 kb
[Process] com.motorola.blur.datamanager.app: 614 kb / 582 kb
[Process] com.motorola.android.provisioning: 593 kb / 692 kb
[Process] com.motorola.android.AudioEffectSettings: 552 kb / 595 kb
[Process] com.motorola.globalunplug: 574 kb / 569 kb
[Process] com.swype.android.inputmethod: 558 kb / 585 kb
[Process] com.wsandroid.uninstall_listener: 570 kb / 636 kb
[Process] com.svox.pico: 535 kb / 547 kb
[Process] com.motorola.atcmd: 507 kb / 495 kb
[Process] com.nuance.android.vsuite.vsuiteapp: 556 kb / 634 kb
[Service] com.motorola.photowidget/.PhotoWidgetAppProvider$WidgetService: 1210 kb / 1014 kb
[Service] com.motorola.usb/.UsbService: 655 kb / 757 kb
[Service] com.fusionone.android.sync.service/.SyncService: 870 kb / 809 kb
[Service] com.motorola.blur.service.snmessaging.engine/.SNMessagingService: 7047 kb / 5563 kb
[Service] com.motorola.blur.news/.widget.NewsWidgetProvider$WidgetService: 2529 kb / 2031 kb
[Service] android/com.android.internal.service.wallpaper.ImageWallpaper: 6341 kb / 22102 kb
[Service] com.motorola.android.buacontactadapter/.AuthenticationService: 551 kb / 636 kb
[Service] com.motorola.togglewidgets/.GpsToggle$UpdateService: 672 kb / 732 kb
[Service] com.motorola.blur.richtext/.service.RichClipboardService: 7047 kb / 5563 kb
[Service] com.appspot.scruffapp/.C2DMReceiver: 8384 kb / 15687 kb
[Service] com.motorola.blur.service.email/.provider.activesync.ActiveSyncEmailService: 7047 kb / 5563 kb
[Service] com.motorola.blur.weather/.service.WeatherService: 1124 kb / 1408 kb
[Service] com.motorola.blur.service.blur/.BlurServiceMother: 1831 kb / 3515 kb
[Service] com.motorola.blur.weather/.WeatherWidgetProvider$WidgetService: 1124 kb / 1408 kb
[Service] com.motorola.photowidget/.WidgetAidService: 1210 kb / 1014 kb
[Service] com.motorola.blur.contacts/.CacheService: 943 kb / 1069 kb
[Service] com.motorola.android.syncml.service/.SyncEngineService: 786 kb / 684 kb
[Service] com.motorola.blur.home.status/.StatusWidgetProvider$WidgetService: 2529 kb / 2031 kb
[Service] com.motorola.blur.service.email/.engine.EmailEngine: 7047 kb / 5563 kb
[Service] com.motorola.android.datamanager/.DataManagerService: 1247 kb / 939 kb
[Service] com.motorola.blur.policymgr.service/.PolicyMgrService: 7047 kb / 5563 kb
[Service] com.motorola.blur.service.email/.provider.activesync.ActiveSyncPushService: 7047 kb / 5563 kb
[Service] com.yahoo.mobile.client.android.mail/.provider.MailSyncService: 2394 kb / 2777 kb
[Service] com.yahoo.mobile.client.android.mail/com.yahoo.mobile.client.share.push.HTTPKeepAliveService: 2394 kb / 2777 kb
[Service] com.motorola.blur.service.blur/.syncstatus.SyncStatusService: 1831 kb / 3515 kb
[Service] com.motorola.blur.quickcontact/.QuickContactService: 1262 kb / 890 kb
[Service] com.motorola.globalunplug/.service.GlobalUnplugService: 574 kb / 569 kb
[Service] com.motorola.blur.service.storagemon/.StorageMonitorService: 7047 kb / 5563 kb
[Service] com.motorola.blur.service.blur/.sync.ws.impl.BlurSyncWSClient2: 1831 kb / 3515 kb
[Service] com.flexaspect.android.everycallcontrol/.core.CallControlService: 810 kb / 1204 kb
[Service] com.davidgoemans.simpleClockWidget/.SimpleClockUpdateService: 934 kb / 1179 kb
[Service] android.tts/.TtsService: 577 kb / 2221 kb
[Service] com.motorola.blur.news/.NewsRetrievalService: 2529 kb / 2031 kb
[Service] com.motorola.blur.home.message/.MessageWidgetProvider$WidgetService: 1205 kb / 1813 kb
[Service] com.motorola.blur.adminfeed/.AdminFeedNotifierService: 7047 kb / 5563 kb
[Service] com.motorola.android.extdispservice/.ExtDispService: 911 kb / 911 kb

This list was retrieved by calling the following code:
List<RunningAppProcessInfo> runningApps = activityManager.getRunningAppProcesses();
    List<RunningServiceInfo> runningServices = activityManager.getRunningServices(100);

There are 83 processes and services listed, showing native PSS and other PSS. Our app downloads, displays and caches images from the internet, and is the second one listed. We have higher usage than most other apps, but the OS should be able to multitask and page our memory accordingly.
Other than our app, more than 60 of those begin with com.motorola. Can anyone explain if all these processes are needed and if/how users can remove some of these? Device memory exhaustion is the best explanation we can come up with for these unexplained application crashes that are not the result of unhandled exceptions.

A: Most processes seem to be related to the Motorola modified framework (blur). Others look like running apps, most probably Widgets in the home screen.
There's no way for your app to change that. If you can contact the user, ask to stop some of the running apps and remove some home Widgets.
Re-reading the list, the fist suspect would be: com.rechild.advancedtaskkiller. See the app description here. Perhaps is using the auto kill feature? Try asking to add your app in the exclusion list.


text:
Q: The following optimization function is interpreted correctly? I want to confirm if I interpreted following optimization function correctly?
Let's say we have a set of nodes (say users connected to a Base Station in cellular network), denoted as, $$U={u_1,u_2,...,u_M}$$ and let $$Throughput(u_m), \forall u_m \in U$$ be a function (say throughput calculating function) defined on each element in $U$.
I define an optimization problem as, "find a user in $U$ such that it has the minimum throughput."
For above optimization problem, I define following function,$$i\gets \underset{m\ :\ u_m\in \ U}{argmin} \ Throughput(u_m)$$
I want to confirm if I have interpreted the function correctly?
Thanks!

A: The sentence you give and the notation (defining a variable $i$) give the same meaning; they both give you a user. However, an optimization problem should be defined in terms of numbers... not "users". So for an optimization problem, you would want to probably optimize $Throughput(i)$, that is
$$\min_{u_m \in U} Throughput(u_m)$$


text:
Q: Changing scala local variables scope The following is a Scala code snippet of an error handler I'm making for a streaming application. It uses akka streams to consume messages ('errormsg') in a Kafka topic and write them to a table in Kudu.
val kafkaMessages: Source[ConsumerMessage.CommittableMessage[String, Array[Byte]], Consumer.Control] = Consumer.committableSource(
    consumerSettings,
    Subscriptions.topics(conf.getString("kafka.topics.errorRawCdr")))

  val cdrs: Source[Errors, Consumer.Control] = kafkaMessages.map(msg => {
    val bytes: Array[Byte] = msg.record.value()
    val errormsg = (bytes.map(_.toChar)).mkString
    new Errors(1235, "filename", "cdr", "cdr_type", 0, errormsg)
  })

  cdrs.to(new ErrorKuduSink(session, table)).run()

I'd like to re-use the variable 'errormsg' further down, as part of a few lines that email me that message.
How do I escape 'errormsg' (or alternatively incorporate the code snippet below), so that the variable scope is appropriate?
  send a new Mail (
    from = ("errorhandler@domain.com"),
    to = "myemailadres@domain.com",
    subject = "Encountered error",
    message = errormsg
  )

A: Here I propose an easy fix to your problem by using a MutableList:
val kafkaMessages: Source[ConsumerMessage.CommittableMessage[String, Array[Byte]], Consumer.Control] = Consumer.committableSource(
    consumerSettings,
    Subscriptions.topics(conf.getString("kafka.topics.errorRawCdr")))

    import scala.collection.mutable._
    val errorMessages: MutableList[String] = new MutableList

  val cdrs: Source[Errors, Consumer.Control] = kafkaMessages.map(msg => {
    val bytes: Array[Byte] = msg.record.value()
    val errormsg = (bytes.map(_.toChar)).mkString
    errorMessages += errormsg
    new Errors(1235, "filename", "cdr", "cdr_type", 0, errormsg)
  })

  cdrs.to(new ErrorKuduSink(session, table)).run()

A: Solution 1: send email right in your map method (will send email on every kafka message)
def sendEmail(errormsg: String): Unit = ???

val cdrs: Source[Errors, Consumer.Control] =
  kafkaMessages.map { msg =>
    val bytes: Array[Byte] = msg.record.value()
    val errormsg = (bytes.map(_.toChar)).mkString
    sendEmail(errormsg) // call function that sends email
    new Errors(1235, "filename", "cdr", "cdr_type", 0, errormsg)
  }

Solution 2: if you want more complex usage of errormsg in downstream stages you need to return a tuple from your map stage:
val kafkaMessages: Source[ConsumerMessage.CommittableMessage[String, Array[Byte]], Consumer.Control] =
  Consumer.committableSource(consumerSettings, Subscriptions.topics(conf.getString("kafka.topics.errorRawCdr")))

val cdrs: Source[Errors, Consumer.Control] =
  kafkaMessages.map { msg =>
    val bytes: Array[Byte] = msg.record.value()
    val errormsg = (bytes.map(_.toChar)).mkString
    (new Errors(1235, "filename", "cdr", "cdr_type", 0, errormsg), errormsg) // we are returning a tuple so type of downstream elements will be (Errors, String)
  }.map { case i@(errors, errormsg) =>
    sendEmail(errormsg)
    i
  }.map { tuple =>
    ...
  }.map(_._1) // as we dont need a tuple any more we can get original element and continue processing of it

cdrs.to(new ErrorKuduSink(session, table)).run()

Solution 3: if you want even more complex processing (for example to batch multiple errormsg in one email) you may want to create a RunnableGraph
val g = RunnableGraph.fromGraph(GraphDSL.create() { implicit builder: GraphDSL.Builder[NotUsed] =>
  import GraphDSL.Implicits._
  val in = Consumer.committableSource(consumerSettings, Subscriptions.topics(conf.getString("kafka.topics.errorRawCdr")))
    .map { msg =>
      val bytes: Array[Byte] = msg.record.value()
      val errormsg = (bytes.map(_.toChar)).mkString
      (new Errors(1235, "filename", "cdr", "cdr_type", 0, errormsg), errormsg)
    }
  val kuduout = new ErrorKuduSink(session, table)
  val emailout = Sink.foreach[Seq[String]] { errormsgs =>
    sendEmail(errormsgs)
  }
  val f1 = Flow[(Errors, String)]
    .map(_._1) // take errors

  val f2 = Flow[(Errors, String)]
    .map(_._2) // take errormsgs
    .groupedWithin(100, 1.hour)

  val bcast = builder.add(Broadcast[Int](2))

  in ~> bcast
  bcast ~> f1 ~> kuduout
  bcast ~> f2 ~> emailout
  ClosedShape
})


text:
Q: Get data from SQL data base without refreshing use Ajax and node js How to get data from SQL database without refreshing using Ajax with xmlrequest or fetch method, When I insert data or update it from SQL table how i can see this change without refresh or press any button
Please I need exemple with node JS server and EJS client page to resolve this problem


text:
Q: Displaying currency symbol in NumericUpDown I am trying to display a "£" in a NumericUpDown in VB.NET. So far, I have created a custom control called CurrencyUpDown and in the designer code, changed the inherits line so that it inherits NumericUpDown properties. I know I have to use an override for this control, but I'm not sure what to do next.

A: You need to override the UpdateEditText method:
Public Class CurrencyUpDown
  Inherits NumericUpDown

  Protected Overrides Sub UpdateEditText()
    Me.Text = String.Format("{0:C}", Me.Value)
  End Sub

End Class


text:
Q: How to retrive int data from database to a variable in javascript? I have a code in asp.net page for my progress bar i'm having a back end code to retrieve percentage  my problem is how to retrieve that int value to my java script
here is the code for progress bar is

Total Potential

          Potential Till Date :
     <button class="w3-btn w3-white w3-round-xlarge" onclick="move1()">Click Here</button>

0%

and javascript code for this one is

the backend code for this one is
    protected void potent()
    {
        string query = "select ( sum(oppfp /100000)* 100.0)AS percentage from opprt";

        using (SqlConnection con = new SqlConnection("Data Source=PO-PC\\SQLEXPRESS;Initial Catalog=leadsp;User ID=sa;Password=123;"))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.CommandType = CommandType.Text;

                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        ListItem item = new ListItem();
                        string per = sdr["percentage"].ToString();
                        int percentage = Convert.ToInt32(per);

                    }
                }
                con.Close();
            }
        }
    }

how to retrieve this data as int and pass it to per variable in java script

A: As Khalid said you can use an ajax call to the server to retrive the update value.
You can use a timer to call the site every second as long as you need it.
A simple example could be:
var myTimer = setTimeout(function(){
  $.ajax(siteUrl, {
    success: function(data) {
       // do your thing with the downloaded data
    },
    error: function(xhr,status,error) {
       alert(error)
    }
  });
, 1000);

When you are done you can stop the timer with:
clearTimeout(myTimer);


text:
Q: How to include Bootstrap in container specific scss? I'm working to upgrade to the latest version of reactstrap & Bootstrap, I used to have: reactstrap in my package.json and bootstrap SCSS downloaded in my client/src/styles/bootstrap directory.
I now have in my package.json:
"reactstrap": "^5.0.0-alpha.3",
"bootstrap": "^4.0.0-beta",

For my container & component specific SCSS files, this used to work:
home.jsx:
import '../styles/home/Home.css'

home.scss
@import "../bootstrap/variables";
@import "../bootstrap/custom";
@import "../bootstrap/mixins/breakpoints";

@include media-breakpoint-down(sm) {
    ...
}

These @import files are no longer available with the new reactstrap and Bootstrap. How can import bootstrap items like @import "../bootstrap/mixins/breakpoints";? Or am I doing this all wrong?

A: You need to import files from the bootstrap module in the node_modules directory. So the path from your root directory would be node_modules/bootstrap/scss/mixins/breakpoints.


text:
Q: What's the difference between 'service' and 'server'? I can imagine that the 'server' can be a machine/host but can be also a program like ftp server, smtp server, etc..
The 'service' on the other hand refers mainly to applications/programms..
Why can then for example the Sql Server cannot be called as Sql Service? It has the same semanthics. Or the other way round: MS Azure service: why it isn't called Azure Server? :)

A: I would say:

*

*A server is expected to give a response

*A service is not

Additionally, a service may include more than a server - it may well be an environment, hardware, SLA and more.

A: The services are features offered by the servers.

A: A server is a (possibly virtualized) piece of equipment that can be used to provide a service.
A service is something that you can use (usually remotely) that is provided by one or more servers.
The other difference is that these are really concepts at different levels of abstraction. Servers are concrete things. Services are abstract. Yet people mostly use services, and don't really care about what servers are used to implement them. Do you care about what servers are used to provide Google's web search service? No, you don't. Do you care about what servers are used to provide Amazon's cloud service? No, you don't.

A: A server is a a software program, or the computer on which that program runs, that provides a specific kind of service to client software running on the same computer or other computers on a network.
Per Microsoft - Windows Azure: operating system as an online service.
SQL Server is a Server, Any Stored Procedures or functions you write are Services. (A Query is a dynamic Service that has a life of just the call, it is sent to the Database, compiled, The Server executes the compiled code and returns the results)

A: I would say that there's no difference. They're used more-or-less interchangeably.
Or, if you prefer: you can come up with a definition, and someone will come up with a counter-example.


text:
Q: Visual Studio 2015 MySql LinQ to Entities Get generated query I am using MySql LinQ to entities with Visual Studio. The code works except for the part that is commented out.  That works with SQL but not with MySQL. Does anyone know the MySql equivalent of the code that is commented out?
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace TestMySql_Nuget_etc
{
    class Program
    {
        static void Main(string[] args)
        {
            worldEntities db = new worldEntities();
            var countries = from c in db.countries
                            where c.Name.StartsWith("A")
                            select c;
            //string query = ((ObjectQuery)countries.ToTraceString());
            foreach(var c in countries)
            {
                Console.WriteLine(c.Name);
            }
            Console.ReadLine();
        }
    }
}

A: You need to explain in more details why it's not working and what kind of exceptions/error is throwing out, if it is.
At first, you can't unbox a string directly to another Type (like ObjectQuery).
You just can unbox from a base class to an inherited one, vice versa.
The following is something you can do:
int number = 30;
object obj = number;
number = (int) obj;// if it fails, will throw a cast exception

...

class A
{
    public string Name {get;set;}
}

class B : A
{
    public int Age {get;set;}
}

class C
{
    public int Age {get;set;}
}

...

A objectA = new A();
A objectAAndB = new B();
B objectJustB = (B) objectAAndB;
B objectB = (B) A; // It'll throw a cast exception

And follows something you can not do:
A objectA = new A();
B objectB = new B();
C objectC = new C();
A objectC1 = new C(); // It won't compile
C objectC2 = (C) objectA; // It won't compile
C objectC3 = (C) objectB; // It won't compile
A objectA1 = (A) objectC; // It won't compile
B objectB1 = (B) objectC; // It won't compile

I hope it helps you.


text:
Q: Why does function overload resolution in C++ consider non-static member functions for static calls? I was wondering why function overload resolution in C++ does consider non-static member functions when calling a static method.
I have read the documentation here and it states that

If any candidate function is a member function (static or non-static), but not a constructor, it is treated as if it has an extra parameter (implicit object parameter) which represents the object for which they are called and appears before the first of the actual parameters.

So consider the following code.
struct A {
   static void foo(int a, float b){...}
   void foo(float a, int b){...}
};

Then the call A::foo(1.f, 1.f) is ambiguous.
Static member functions are considered for overload resolution of non-static function calls, which makes sense.
A a;
a.foo(1, 1.f); //can safely call static method

But why is it also done the other way around (considering non-static member functions when calling a function with Class::function)? Why can't the compiler simply choose static void foo(int a, float b)?

A:
Why can't the compiler simply choose static void foo(int a, float b)?

My understanding of your questions is that you assume the syntax A::foo is unambiguous due to the non-instance A:: prefix. But have a look at this scenario:
struct A {
   static void foo(int, float);
   void foo(float, int);
};

struct B : A {
   // Hide the base class foo
   void foo()
   {
      // Now explicitly call it... this is ambiguous!
      A::foo(1.f, 1.f);
   }
};

Hence, the A:: prefix can refer to both static and non-static member functions, depending on the context. The compiler can't assume that it's referring to a static member function only.
There are more scenarios where a qualified non-static member function call like A::foo is necessary, e.g. in a diamond inheritance structure (if you don't use virtual inheritance). This is why any member function can be invoked like this (even when it's unnecessary and doesn't make sense: A a; a.A::foo(1, 2.f);.


text:
Q: mongodb nodejs each vs toArray I've had a quick look around and not found anything that's satisfied me with an answer but basically I've started to use node.js with express and mongodb to create a webapi rather than the usual .Net MVC Web API route.
One thing I've noted though is in order to return a collection of results I'm doing it in a rather bulky way, or that's how it feels at least.
app.get('/property', function (req, res) {
    var propArray = [];
    MongoClient.connect(settings.connection,
        function (err, db) {
            if (err) throw err;

            var properties = db.collection("PROPERTIES");

            var searchParams = {
                Active: true,
                Deleted: false
            }

            properties.count(searchParams, function (err, count) {
                properties.find(searchParams).toArray(function (err, result) {
                    for (i = 0; i < count; i++)
                        propArray.push(new models.propertyModel(result[i]));

                    db.close();

                    return res.json(propArray);
                });
            });
        }
    );
});

Now I've noted that there's a .each function rather than .toArray which I would prefer to use as I could cut out the .count function but obviously you can only return a response once. I wondered if you guys could enlighten me with some of your mongo knowledge.
properties.find(searchParams).each(function (err, result) {
    return res.json(result);
});

Something like that, cutting out 6 lines of code and an extra call to the database.

A: The count() can still be cut out with toArray():
   properties.find(searchParams).toArray(function (err, result) {
     var i, count;
     for (i = 0, count = result.length; i < count; i++) {
       propArray.push(new models.propertyModel(result[i]));
     }
     db.close();
     return res.json(propArray);
   });


text:
Q: how to test i18n in Rails with RSpec Question context:
let say that there is some really important row in config/locales/en.yml that is crucial to exist.
en:
  foo:
    bar: "bubla!"

*

*I don't want to test every single line  but

*I don't want the test to be too brittle (so no I18n.t('foo.bar').should =~ /bubla/)

so way I'm testing currently is like this
#spec/locals_spec.rb

require 'spec_helper'
describe I18n do
  it do
    I18n.t('date.datepicker').should be_kind_of(String)
  end
end

this way I'm just ensuring that translation exist and that it don't continues (e.g. 'foo.bar.car.lol'
but still I'm not satisfied
Question: What's the best practice to test I18n translations with RSpec and where in spec folder I should place them ?

A: Check this StackOverflow question for some ideas.  My preferred way is this answer on the same question.
Update: These days I tend to use the i18n-tasks gem to handle testing related to i18n, and not what I wrote above or have answered on StackOverflow previously.
I wanted to use i18n in my RSpec tests primarily to make sure that I had translations for everything ie there were no translations missed.  i18n-tasks can do that and more through static analysis of my code, so I don't need to run tests for all I18n.available_locales anymore (apart from when testing very locale-specific functionality, like, for example, switching from any locale to any other locale in the system).
Doing this has meant I can confirm that all i18n keys in the system actually have values (and that none are unused or obsolete), while keeping the number of repetitive tests, and consequently the suite running time, down.

A: i think that i would write an acceptance test for such a "crucial" thing.
in most cases you need the translation in some specific context, ie. displaying something in a datepicker. i would test that context using capybara or whatever works with a javascript driver.
just testing that this translation exists is useless if you don't have the context that it's used within.


text:
Q: how i can calculate parameters for copula exponentiated Exponential distribution? data = {{2, 6.5}, {2, 6.5}, {2.1, 10.1}, {2.2, 7.2}, {2.2, 7.6}, {2.2,
 7.9}, {2.2, 8.5}, {2.2, 9.1}, {2.2, 9.6}, {2.2, 9.6}, {2.2,
10.7}, {2.3, 9.6}, {2.4, 7.3}, {2.4, 7.9}, {2.4, 7.9}, {2.4,
9.1}, {2.4, 9.3}, {2.5, 7.9}, {2.5, 8.6}, {2.5, 8.8}, {2.5,
8.8}, {2.5, 9.3}, {2.5, 11}, {2.5, 12.7}, {2.5, 12.7}, {2.6,
7.7}, {2.6, 8.3}, {2.6, 9.4}, {2.6, 9.4}, {2.6, 10.5}, {2.6,
11.5}, {2.7, 8}, {2.7, 9}, {2.7, 9.6}, {2.7, 9.6}, {2.7,
9.8}, {2.7, 10.4}, {2.7, 11.1}, {2.7, 12}, {2.7, 12.5}, {2.8,
9.1}, {2.8, 10}, {2.8, 10.2}, {2.8, 11.4}, {2.8, 12}, {2.8,
13.3}, {2.8, 13.5}, {2.9, 9.4}, {2.9, 10.1}, {2.9, 10.6}, {2.9,
11.3}, {2.9, 11.8}, {3, 10}, {3, 10.4}, {3, 10.6}, {3, 11.6}, {3,
12.2}, {3, 12.4}, {3, 12.7}, {3, 13.3}, {3, 13.8}, {3.1,
9.9}, {3.1, 11.5}, {3.1, 12.1}, {3.1, 12.5}, {3.1, 13}, {3.1,
14.3}, {3.2, 11.6}, {3.2, 11.9}, {3.2, 12.3}, {3.2, 13}, {3.2,
13.5}, {3.2, 13.6}, {3.3, 11.5}, {3.3, 12}, {3.3, 14.1}, {3.3,
14.9}, {3.3, 15.4}, {3.4, 11.2}, {3.4, 12.2}, {3.4, 12.4}, {3.4,
12.8}, {3.4, 14.4}, {3.5, 11.7}, {3.5, 12.9}, {3.5, 15.6}, {3.5,
15.7}, {3.5, 17.2}, {3.6, 11.8}, {3.6, 13.3}, {3.6, 14.8}, {3.6,
15}, {3.7, 11}, {3.8, 14.8}, {3.8, 16.8}, {3.9, 14.4}, {3.9,
20.5}};

this is is coupla bivariate exponentiated Exponential
dist1= ProbabilityDistribution[{"CDF", (1 -  E^-(\[Lambda]*x))^\[Alpha]}, {x, 0, \[Infinity]},Assumptions -> {\[Lambda] > 0, \[Alpha] > 0}];
dist2= ProbabilityDistribution[{"CDF", (1 -  E^-(\[Lambda]*x))^\[Alpha]}, {x, 0, \[Infinity]},Assumptions -> {\[Lambda] > 0, \[Alpha] > 0}];

bidist = CopulaDistribution[{"FGM",\[Gamma]}, {dist1, dist2}];

i want to calculate parameters and goddeness of fit for this distrbition
please any help i will be thankfull


text:
Q: Difference between display of html code on website and in QTextEdit I crawled the html code from a website, which I want to display in a QTextEdit form PyQt5. The html code is supposed to look like this:

When I put the html code into the QTextEdit, it looks like this:

In the enumerations there is an offset in 'QTextEdit', that is not on the website. How do I get rid of this offset so it looks like the website?
The code is on the QTextEdit is set with setHtml.
The html code is the following:

(2) Das Genehmigungserfordernis erstreckt sich auf alle vorgesehenen

1.

Anlagenteile und Verfahrensschritte, die zum Betrieb notwendig sind, und

2.

Nebeneinrichtungen, die mit den Anlagenteilen und Verfahrensschritten nach Nummer 1 in einem räumlichen und betriebstechnischen Zusammenhang stehen und die von Bedeutung sein können für

a)

das Entstehen schädlicher Umwelteinwirkungen,

b)

die Vorsorge gegen schädliche Umwelteinwirkungen oder

c)

das Entstehen sonstiger Gefahren, erheblicher Nachteile oder erheblicher Belästigungen.

(3) Die im Anhang 1 bestimmten Voraussetzungen sind auch erfüllt, wenn mehrere Anlagen derselben Art in einem engen räumlichen und betrieblichen Zusammenhang stehen (gemeinsame Anlage) und zusammen die maßgebenden Leistungsgrenzen oder Anlagengrößen erreichen oder überschreiten werden. Ein enger räumlicher und betrieblicher Zusammenhang ist gegeben, wenn die Anlagen

1.

auf demselben Betriebsgelände liegen,

2.

mit gemeinsamen Betriebseinrichtungen verbunden sind und

3.

einem vergleichbaren technischen Zweck dienen.