text:
Q: how can I empty magento 2 orders, customer and products data reset to 1
how can I empty Magento 2
order
customers
products data to reset 1
how I can do this??

when i run in sql
MySQL said: Documentation #1146 - Table 'magento_db.gift_message' doesn't exist

but the table is there in the database

A: Be safe: make a backup of your SQL first.
SET FOREIGN_KEY_CHECKS = 0;

Truncate order tables:
TRUNCATE TABLE `gift_message`;
TRUNCATE TABLE `quote`;
TRUNCATE TABLE `quote_address`;
TRUNCATE TABLE `quote_address_item`;
TRUNCATE TABLE `quote_id_mask`;
TRUNCATE TABLE `quote_item`;
TRUNCATE TABLE `quote_item_option`;
TRUNCATE TABLE `quote_payment`;
TRUNCATE TABLE `quote_shipping_rate`;
TRUNCATE TABLE `reporting_orders`;
TRUNCATE TABLE `sales_bestsellers_aggregated_daily`;
TRUNCATE TABLE `sales_bestsellers_aggregated_monthly`;
TRUNCATE TABLE `sales_bestsellers_aggregated_yearly`;
TRUNCATE TABLE `sales_creditmemo`;
TRUNCATE TABLE `sales_creditmemo_comment`;
TRUNCATE TABLE `sales_creditmemo_grid`;
TRUNCATE TABLE `sales_creditmemo_item`;
TRUNCATE TABLE `sales_invoice`;
TRUNCATE TABLE `sales_invoiced_aggregated`;
TRUNCATE TABLE `sales_invoiced_aggregated_order`;
TRUNCATE TABLE `sales_invoice_comment`;
TRUNCATE TABLE `sales_invoice_grid`;
TRUNCATE TABLE `sales_invoice_item`;
TRUNCATE TABLE `sales_order`;
TRUNCATE TABLE `sales_order_address`;
TRUNCATE TABLE `sales_order_aggregated_created`;
TRUNCATE TABLE `sales_order_aggregated_updated`;
TRUNCATE TABLE `sales_order_grid`;
TRUNCATE TABLE `sales_order_item`;
TRUNCATE TABLE `sales_order_payment`;
TRUNCATE TABLE `sales_order_status_history`;
TRUNCATE TABLE `sales_order_tax`;
TRUNCATE TABLE `sales_order_tax_item`;
TRUNCATE TABLE `sales_payment_transaction`;
TRUNCATE TABLE `sales_refunded_aggregated`;
TRUNCATE TABLE `sales_refunded_aggregated_order`;
TRUNCATE TABLE `sales_shipment`;
TRUNCATE TABLE `sales_shipment_comment`;
TRUNCATE TABLE `sales_shipment_grid`;
TRUNCATE TABLE `sales_shipment_item`;
TRUNCATE TABLE `sales_shipment_track`;
TRUNCATE TABLE `sales_shipping_aggregated`;
TRUNCATE TABLE `sales_shipping_aggregated_order`;
TRUNCATE TABLE `tax_order_aggregated_created`;
TRUNCATE TABLE `tax_order_aggregated_updated`;

Truncate Customer tables:
TRUNCATE TABLE `customer_address_entity`;
TRUNCATE TABLE `customer_address_entity_datetime`;
TRUNCATE TABLE `customer_address_entity_decimal`;
TRUNCATE TABLE `customer_address_entity_int`;
TRUNCATE TABLE `customer_address_entity_text`;
TRUNCATE TABLE `customer_address_entity_varchar`;
TRUNCATE TABLE `customer_entity`;
TRUNCATE TABLE `customer_entity_datetime`;
TRUNCATE TABLE `customer_entity_decimal`;
TRUNCATE TABLE `customer_entity_int`;
TRUNCATE TABLE `customer_entity_text`;
TRUNCATE TABLE `customer_entity_varchar`;
TRUNCATE TABLE `customer_grid_flat`;
TRUNCATE TABLE `customer_log`;
TRUNCATE TABLE `customer_log`;
TRUNCATE TABLE `customer_visitor`;
TRUNCATE TABLE `persistent_session`;
TRUNCATE TABLE `wishlist`;
TRUNCATE TABLE `wishlist_item`;
TRUNCATE TABLE `wishlist_item_option`;

Truncate Review tables:
TRUNCATE TABLE `review`;
TRUNCATE TABLE `review_detail`;
TRUNCATE TABLE `review_entity_summary`;
TRUNCATE TABLE `review_store`;

Truncate Product tables:
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock_status_idx`;
TRUNCATE TABLE `cataloginventory_stock_status_tmp`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product_index_tmp`;
TRUNCATE TABLE `catalog_compare_item`;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_price_index`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_bundle_selection_price`;
TRUNCATE TABLE `catalog_product_bundle_stock_index`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value_to_entity`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value_video`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_index_eav`;
TRUNCATE TABLE `catalog_product_index_eav_decimal`;
TRUNCATE TABLE `catalog_product_index_eav_decimal_idx`;
TRUNCATE TABLE `catalog_product_index_eav_decimal_tmp`;
TRUNCATE TABLE `catalog_product_index_eav_idx`;
TRUNCATE TABLE `catalog_product_index_eav_tmp`;
TRUNCATE TABLE `catalog_product_index_price`;
TRUNCATE TABLE `catalog_product_index_price_bundle_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_bundle_sel_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_sel_tmp`;
TRUNCATE TABLE `catalog_product_index_price_bundle_tmp`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_agr_idx`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_agr_tmp`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_downlod_idx`;
TRUNCATE TABLE `catalog_product_index_price_downlod_tmp`;
TRUNCATE TABLE `catalog_product_index_price_final_idx`;
TRUNCATE TABLE `catalog_product_index_price_final_tmp`;
TRUNCATE TABLE `catalog_product_index_price_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_agr_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_agr_tmp`;
TRUNCATE TABLE `catalog_product_index_price_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_tmp`;
TRUNCATE TABLE `catalog_product_index_tier_price`;
TRUNCATE TABLE `catalog_product_index_website`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_relation`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_url_rewrite_product_category`;
TRUNCATE TABLE `downloadable_link`;
TRUNCATE TABLE `downloadable_link_price`;
TRUNCATE TABLE `downloadable_link_purchased`;
TRUNCATE TABLE `downloadable_link_purchased_item`;
TRUNCATE TABLE `downloadable_link_title`;
TRUNCATE TABLE `downloadable_sample`;
TRUNCATE TABLE `downloadable_sample_title`;
TRUNCATE TABLE `product_alert_price`;
TRUNCATE TABLE `product_alert_stock`;
TRUNCATE TABLE `report_compared_product_index`;
TRUNCATE TABLE `report_viewed_product_aggregated_daily`;
TRUNCATE TABLE `report_viewed_product_aggregated_monthly`;
TRUNCATE TABLE `report_viewed_product_aggregated_yearly`;
TRUNCATE TABLE `report_viewed_product_index`;

Truncate Categories tables:
TRUNCATE TABLE `catalog_category_entity`;
TRUNCATE TABLE `catalog_category_entity_datetime`;
TRUNCATE TABLE `catalog_category_entity_decimal`;
TRUNCATE TABLE `catalog_category_entity_int`;
TRUNCATE TABLE `catalog_category_entity_text`;
TRUNCATE TABLE `catalog_category_entity_varchar`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;

INSERT  INTO `catalog_category_entity`(`entity_id`,`attribute_set_id`,`parent_id`,`created_at`,`updated_at`,`path`,`POSITION`,`level`,`children_count`) VALUES (1,0,0,'2009-02-20 00:25:34','2009-02-20 00:25:34','1',1,0,1),(2,3,0,'2009-02-20 00:25:34','2009-02-20 00:25:34','1/2',1,1,0);
INSERT  INTO `catalog_category_entity_int`(`value_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,32,0,2,1),(2,32,1,2,1);
INSERT  INTO `catalog_category_entity_varchar`(`value_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,31,0,1,'Root Catalog'),(2,33,0,1,'root-catalog'),(3,31,0,2,'Default Category'),(4,39,0,2,'PRODUCTS'),(5,33,0,2,'default-category');

and at last, run:
SET FOREIGN_KEY_CHECKS = 1;

A: For cleaning products data :
SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product_index_tmp`;
TRUNCATE TABLE `catalog_compare_item`;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_price_index`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_bundle_selection_price`;
TRUNCATE TABLE `catalog_product_bundle_stock_index`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value_to_entity`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value_video`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_index_eav`;
TRUNCATE TABLE `catalog_product_index_eav_decimal`;
TRUNCATE TABLE `catalog_product_index_eav_decimal_idx`;
TRUNCATE TABLE `catalog_product_index_eav_decimal_tmp`;
TRUNCATE TABLE `catalog_product_index_eav_idx`;
TRUNCATE TABLE `catalog_product_index_eav_tmp`;
TRUNCATE TABLE `catalog_product_index_price`;
TRUNCATE TABLE `catalog_product_index_price_bundle_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_bundle_sel_idx`;
TRUNCATE TABLE `catalog_product_index_price_bundle_sel_tmp`;
TRUNCATE TABLE `catalog_product_index_price_bundle_tmp`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_agr_idx`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_agr_tmp`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_cfg_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_downlod_idx`;
TRUNCATE TABLE `catalog_product_index_price_downlod_tmp`;
TRUNCATE TABLE `catalog_product_index_price_final_idx`;
TRUNCATE TABLE `catalog_product_index_price_final_tmp`;
TRUNCATE TABLE `catalog_product_index_price_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_agr_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_agr_tmp`;
TRUNCATE TABLE `catalog_product_index_price_opt_idx`;
TRUNCATE TABLE `catalog_product_index_price_opt_tmp`;
TRUNCATE TABLE `catalog_product_index_price_tmp`;
TRUNCATE TABLE `catalog_product_index_tier_price`;
TRUNCATE TABLE `catalog_product_index_website`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_relation`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_url_rewrite_product_category`;
TRUNCATE TABLE `cataloginventory_stock`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock_status_idx`;
TRUNCATE TABLE `cataloginventory_stock_status_tmp`;
TRUNCATE TABLE `downloadable_link`;
TRUNCATE TABLE `downloadable_link_price`;
TRUNCATE TABLE `downloadable_link_purchased`;
TRUNCATE TABLE `downloadable_link_purchased_item`;
TRUNCATE TABLE `downloadable_link_title`;
TRUNCATE TABLE `downloadable_sample`;
TRUNCATE TABLE `downloadable_sample_title`;
TRUNCATE TABLE `product_alert_price`;
TRUNCATE TABLE `product_alert_stock`;
TRUNCATE TABLE `report_compared_product_index`;
TRUNCATE TABLE `report_viewed_product_aggregated_daily`;
TRUNCATE TABLE `report_viewed_product_aggregated_monthly`;
TRUNCATE TABLE `report_viewed_product_aggregated_yearly`;
TRUNCATE TABLE `report_viewed_product_index`;

SET FOREIGN_KEY_CHECKS = 1;

for customer data clear :
SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE `customer_address_entity`;
TRUNCATE TABLE `customer_address_entity_datetime`;
TRUNCATE TABLE `customer_address_entity_decimal`;
TRUNCATE TABLE `customer_address_entity_int`;
TRUNCATE TABLE `customer_address_entity_text`;
TRUNCATE TABLE `customer_address_entity_varchar`;
TRUNCATE TABLE `customer_entity`;
TRUNCATE TABLE `customer_entity_datetime`;
TRUNCATE TABLE `customer_entity_decimal`;
TRUNCATE TABLE `customer_entity_int`;
TRUNCATE TABLE `customer_entity_text`;
TRUNCATE TABLE `customer_entity_varchar`;
TRUNCATE TABLE `customer_grid_flat`;
TRUNCATE TABLE `customer_log`;
TRUNCATE TABLE `customer_visitor`;
TRUNCATE TABLE `persistent_session`;
TRUNCATE TABLE `login_as_customer_assistance_allowed`;

ALTER TABLE `customer_entity` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS = 1;

For order related data reset :
SET FOREIGN_KEY_CHECKS = 0;

TRUNCATE TABLE `gift_message`;
TRUNCATE TABLE `quote`;
TRUNCATE TABLE `quote_address`;
TRUNCATE TABLE `quote_address_item`;
TRUNCATE TABLE `quote_id_mask`;
TRUNCATE TABLE `quote_item`;
TRUNCATE TABLE `quote_item_option`;
TRUNCATE TABLE `quote_payment`;
TRUNCATE TABLE `quote_shipping_rate`;
TRUNCATE TABLE `reporting_orders`;
TRUNCATE TABLE `sales_bestsellers_aggregated_daily`;
TRUNCATE TABLE `sales_bestsellers_aggregated_monthly`;
TRUNCATE TABLE `sales_bestsellers_aggregated_yearly`;
TRUNCATE TABLE `sales_creditmemo`;
TRUNCATE TABLE `sales_creditmemo_comment`;
TRUNCATE TABLE `sales_creditmemo_grid`;
TRUNCATE TABLE `sales_creditmemo_item`;
TRUNCATE TABLE `sales_invoice`;
TRUNCATE TABLE `sales_invoiced_aggregated`;
TRUNCATE TABLE `sales_invoiced_aggregated_order`;
TRUNCATE TABLE `sales_invoice_comment`;
TRUNCATE TABLE `sales_invoice_grid`;
TRUNCATE TABLE `sales_invoice_item`;
TRUNCATE TABLE `sales_order`;
TRUNCATE TABLE `sales_order_address`;
TRUNCATE TABLE `sales_order_aggregated_created`;
TRUNCATE TABLE `sales_order_aggregated_updated`;
TRUNCATE TABLE `sales_order_grid`;
TRUNCATE TABLE `sales_order_item`;
TRUNCATE TABLE `sales_order_payment`;
TRUNCATE TABLE `sales_order_status_history`;
TRUNCATE TABLE `sales_order_tax`;
TRUNCATE TABLE `sales_order_tax_item`;
TRUNCATE TABLE `sales_payment_transaction`;
TRUNCATE TABLE `sales_refunded_aggregated`;
TRUNCATE TABLE `sales_refunded_aggregated_order`;
TRUNCATE TABLE `sales_shipment`;
TRUNCATE TABLE `sales_shipment_comment`;
TRUNCATE TABLE `sales_shipment_grid`;
TRUNCATE TABLE `sales_shipment_item`;
TRUNCATE TABLE `sales_shipment_track`;
TRUNCATE TABLE `sales_shipping_aggregated`;
TRUNCATE TABLE `sales_shipping_aggregated_order`;
TRUNCATE TABLE `tax_order_aggregated_created`;
TRUNCATE TABLE `tax_order_aggregated_updated`;

ALTER TABLE `sales_order` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS = 1;

I hope its work for you.


text:
Q: Why is `sympy.Matrix.inv` slow? Here is a small example. It surprised me at how slow it is.
import numpy as np
import sympy as sp

X = np.empty(shape=(10,3), dtype=object)

for i in range(10):
    for j in range(3):
        X[i,j] = sp.Symbol(f'X{i}{j}')

X = sp.Matrix(X.T @ X)
print(X.inv()) # This is really slow...

I would have thought that taking an inverse of a relatively small matrix would be fast. Am I missing something about the intended use case?

A: Here is your matrix:
In [43]: X
Out[43]:
⎡                  2      2      2      2      2      2      2      2      2      2                                                                                ⎤
⎢               X₀₀  + X₁₀  + X₂₀  + X₃₀  + X₄₀  + X₅₀  + X₆₀  + X₇₀  + X₈₀  + X₉₀                  X₀₀⋅X₀₁ + X₁₀⋅X₁₁ + X₂₀⋅X₂₁ + X₃₀⋅X₃₁ + X₄₀⋅X₄₁ + X₅₀⋅X₅₁ + X₆₀⋅X₆₁ + X₇₀⋅X₇₁ + X₈₀⋅X₈₁ + X₉₀⋅X₉₁  X₀₀⋅X₀₂ + X₁₀⋅X₁₂ + X₂₀⋅X₂₂ + X₃₀⋅X₃₂ + X₄₀⋅X₄₂ + X₅₀⋅X₅₂ + X₆₀⋅X₆₂ + X₇₀⋅X₇₂ + X₈₀⋅X₈₂ + X₉₀⋅X₉₂⎥
⎢                                                                                ⎥
⎢                                                                                2      2      2      2      2      2      2      2      2      2                                                                                ⎥
⎢X₀₀⋅X₀₁ + X₁₀⋅X₁₁ + X₂₀⋅X₂₁ + X₃₀⋅X₃₁ + X₄₀⋅X₄₁ + X₅₀⋅X₅₁ + X₆₀⋅X₆₁ + X₇₀⋅X₇₁ + X₈₀⋅X₈₁ + X₉₀⋅X₉₁                 X₀₁  + X₁₁  + X₂₁  + X₃₁  + X₄₁  + X₅₁  + X₆₁  + X₇₁  + X₈₁  + X₉₁                  X₀₁⋅X₀₂ + X₁₁⋅X₁₂ + X₂₁⋅X₂₂ + X₃₁⋅X₃₂ + X₄₁⋅X₄₂ + X₅₁⋅X₅₂ + X₆₁⋅X₆₂ + X₇₁⋅X₇₂ + X₈₁⋅X₈₂ + X₉₁⋅X₉₂⎥
⎢                                                                                ⎥
⎢                                                                                2      2      2      2      2      2      2      2      2      2               ⎥
⎣X₀₀⋅X₀₂ + X₁₀⋅X₁₂ + X₂₀⋅X₂₂ + X₃₀⋅X₃₂ + X₄₀⋅X₄₂ + X₅₀⋅X₅₂ + X₆₀⋅X₆₂ + X₇₀⋅X₇₂ + X₈₀⋅X₈₂ + X₉₀⋅X₉₂  X₀₁⋅X₀₂ + X₁₁⋅X₁₂ + X₂₁⋅X₂₂ + X₃₁⋅X₃₂ + X₄₁⋅X₄₂ + X₅₁⋅X₅₂ + X₆₁⋅X₆₂ + X₇₁⋅X₇₂ + X₈₁⋅X₈₂ + X₉₁⋅X₉₂                 X₀₂  + X₁₂  + X₂₂  + X₃₂  + X₄₂  + X₅₂  + X₆₂  + X₇₂  + X₈₂  + X₉₂                ⎦

Computing the symbolic inverse of a matrix is usually not a good idea unless the matrix is very small, sparse or has some special symmetry or something. If the matrix is fully symbolic and there is no reason for the expressions in the inverse to simplify then you should expect that symbolic expressions for the inverse will be very complicated. SymPy's inv method will try to simplify these for you because the expression is unlikely to be much use if it cannot be simplified. That simplification is also needed in order to determine whether the matrix actually is invertible. It is the simplification part that is slow here.
If you don't want the simplification and you are happy to assume that the matrix is invertible then you can calculate an expression for the inverse quickly using the standard inverse formula:
In [34]: %time Xinv = X.adjugate() / X.det()
CPU times: user 543 ms, sys: 957 µs, total: 544 ms
Wall time: 543 ms

Even here it is only taking 0.5 seconds because det attempts some simplification.
I won't show the result that is returned for Xinv because it is enormous. Instead I'll just show how long its string representation is:
In [38]: len(str(Xinv))
Out[38]: 618867

In [39]: len(str(Xinv[0,0]))
Out[39]: 68219

Even just the first element of this matrix has a string representation that is too long to be pasted into an answer on SO.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JQuery Date Picker with JSF I'm using JQuery Date Picker plugin for my JSF.
It works fine for a page with only 1 date field but with more than 1 it cannot populate the date value to my input field.
In my case, i would like to have start date and end date.
Below is my code:
JQUERY
$(document).ready(function(){
    $(".dateto").datepicker({ showOn: 'button', buttonImageOnly: true, buttonImage: '../resources/images/calendar.gif' });
    $(".datefrom").datepicker({ showOn: 'button', buttonImageOnly: true, buttonImage: '../resources/images/calendar.gif' });
});

JSF
<h:inputText id="from" value="#{UserManagerBean.startDate}" required="false" styleClass="datefrom" />
<h:inputText id="to" value="#{UserManagerBean.endDate}" required="false" styleClass="dateto" />

For your information, i tried with 2 html input fields and it works fine as well.
Please help!!!
Thank You

A: Since this one got bumped to the top...
This should work (slight tune up might be needed):
    function initDatePickers() {
        $(document).delegate("#from, #to", "focusin", function() {
            var $this = $(this);
            $this.datepicker({
                onClose: function(dateText, inst) {
                  $(".ui-datepicker-calendar").hide();
                }
            });
            $this.attr( 'readOnly' , 'true' );
        });

        $(document).delegate("#from, #to", "focus", function() {
            $(".ui-datepicker-calendar").hide();
        });
    }

I think you better remove the styleClass from your inputs...


text:
Q: How do I properly override `__getattr__` in SQLAlchemy to access dict keys as attributes? I'm trying to override __getattr__ in SQLAlchemy so I can access certain dictionary fields using object.field syntax rather than having to do object.fields["field"].
However, SQLAlchemy isn't recognizing changes to the field if I use the dot notation syntax. Accessing the field using normal object.fields["field"] however works as expected.
I've provided a code sample below.
#!/usr/bin/env python3
import sqlalchemy
from sqlalchemy import Column, Integer, JSON
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy.orm import sessionmaker

Session = sessionmaker()
Base = declarative_base()

class Track(Base):  # noqa: WPS230
    __tablename__ = "track"

    id = Column(Integer, primary_key=True)
    _fields = Column(MutableDict.as_mutable(JSON), default="{}")

    def __init__(self, id):
        self.id = id
        self._fields = {}
        self._fields["custom"] = "field"

    def __getattr__(self, name: str):
        """See if ``name`` is a custom field."""
        try:
            return self.__dict__["_fields"][name]
        except KeyError:
            raise AttributeError from None

    def __setattr__(self, name, value):
        """Set custom fields if a valid key."""
        if "_fields" in self.__dict__ and name in self.__dict__["_fields"]:
            self._fields[name] = value
        else:
            super().__setattr__(name, value)

engine = sqlalchemy.create_engine("sqlite:///:memory:")
Session.configure(bind=engine)
Base.metadata.create_all(engine)  # creates tables
session = Session()

track = Track(id=1)
session.add(track)
session.commit()

assert track.custom
track.custom = "new"
assert track in session.dirty
assert track.custom == "new"

I believe it has something to do with how sqlalchemy loads __dict__, but not sure how to work around it to get my desired behavior.

A: With the help of @CaseIIT on github, I came up with the following solution using a list FIELDS of fields that can be set:
class Track(Base):  # noqa: WPS230
    __tablename__ = "track"

    FIELDS = ["custom"]

    id = Column(Integer, primary_key=True)
    _fields = Column(MutableDict.as_mutable(JSON), default="{}")

    def __init__(self):
        self._fields = {}
        self._fields["custom"] = "field"

    def __getattr__(self, name: str):
        """See if ``name`` is a custom field."""
        if name in self.FIELDS:
            return self._fields[name]
        else:
            raise AttributeError from None

    def __setattr__(self, name, value):
        """Set custom custom_fields if a valid key."""
        if name in self.FIELDS:
            self._fields[name] = value
        else:
            super().__setattr__(name, value)

It feels wrong to have a duplicate list of accessible fields between _fields.keys() and FIELDS, but I can't seem to get around the issues that come with trying to inspect _fields.


text:
Q: Deploying ZIP file to Azure App Services not working I deploy a web app to Azure App Service using zip-deploy:
dotnet build /nologo /p:PublishProfile=Release /p:PackageLocation="c:\Repos\world\world" /p:OutDir="c:\Repos\world\world" /p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /maxcpucount:1 /p:platform="Any CPU" /p:configuration="Release"

az webapp deployment source config-zip --resource-group <resource-group> --name <app-name> --src world.zip

But the app does not start or is not executed properly, leading to the following error when accessing the application url:
You do not have permission to view this directory or page.
I tried using git-deploy and it works and by going to the URL I see
Hello, world!

I put all the code on GitHub for reference: https://github.com/fnbk/world
More details:

*

*It is a very simple ASP.NET Core Web App with only one root route

*.NET core 2.2

*adding the variable WEBSITE_RUN_FROM_PACKAGE at Application Settings to 1 also did not work

A: I don't think this will work. The zip file that gets created I think isn't mountable for Kudu. I did create a github issue (see https://github.com/dotnet/cli/issues/11254) though but since there are other methods, such as Azure local git, I'm not sure when this issue will get resolve.

A: The file created with WebPublishMethod=Package is intended for deployment via Web Deploy, which is a very different deployment technology. You need to use dotnet publish instead, and zip the resulting directory yourself.


text:
Q: Promisify / async-await callback in c# I have a c# function with a signature like:
Foo(List<int> data, Action<string> endAction)
I can't change Foo (it's an external library).
I'm very new to c#, I've mainly been doing JS development in recent years and I wonder if there's something similar to what is called 'promisify' in JS-land. That is, to make the function calling 'Foo' async and await for Foo to call the endAction callback.

A: You can make 'promisify' Foo as follows:
static Task<string> FooAsync(List<int> data)
{
    var tcs = new TaskCompletionSource<string>();
    Action action = () => Foo(data, result => tcs.SetResult(result));
    // If Foo isn't blocking, we can execute it in the ThreadPool:
    Task.Run(action);
    // If it is blocking for some time, it is better to create a dedicated thread
    // and avoid starving the ThreadPool. Instead of 'Task.Run' use:
    // Task.Factory.StartNew(action, TaskCreationOptions.LongRunning);
    return tcs.Task;
}

Now you can call it:
string result = await FooAsync(myList);

A: There isn't any built-in method similar to promisify in C#/.NET but you can use an instance of TaskCompletionSource to create a Task that can be completed when the callback is called.
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
Foo(list, (string callbackData) => { tcs.SetResult(callbackData); });
string result = await tcs.Task;


text:
Q: Cannot resolve the method findViewById (int) in a class I have a fragment Activity Bhawan_page1 and I want to call another activity on button click but I am getting two errors
1. Cannot resolve method 'findViewById(int)'
2. Cannot resolve constructor 'Intent(anonymous android.view.View.OnClickListener, java.lang.Class)'
Here is the code of the Activity
package in.ahmedraza.journey;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import in.ahmedraza.material_tab.ObservableScrollView;
import in.ahmedraza.material_tab.ScrollUtils;
import in.ahmedraza.material_tab.Scrollable;

public class Bhawan_page1 extends FlexibleSpaceWithImageBaseFragment<ObservableScrollView> {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bhawan_page1, container, false);

        final ObservableScrollView scrollView = (ObservableScrollView) view.findViewById(R.id.scroll);
        // TouchInterceptionViewGroup should be a parent view other than ViewPager.
        // This is a workaround for the issue #117:
        // https://github.com/ksoichiro/Android-ObservableScrollView/issues/117
        scrollView.setTouchInterceptionViewGroup((ViewGroup) view.findViewById(R.id.fragment_root));

        // Scroll to the specified offset after layout
        Bundle args = getArguments();
        if (args != null && args.containsKey(ARG_SCROLL_Y)) {
            final int scrollY = args.getInt(ARG_SCROLL_Y, 0);
            ScrollUtils.addOnGlobalLayoutListener(scrollView, new Runnable() {
                @Override
                public void run() {
                    scrollView.scrollTo(0, scrollY);
                }
            });
            updateFlexibleSpace(scrollY, view);
        } else {
            updateFlexibleSpace(0, view);
        }

        scrollView.setScrollViewCallbacks(this);

        return view;

        Button btn1 = (Button) findViewById(R.id.full_story_bhawan);
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent myIntent = new Intent(this, DialogMainActivity.class);
                startActivity(myIntent);
            }
        });
    }

    @Override
    protected void updateFlexibleSpace(int scrollY) {
        // Sometimes scrollable.getCurrentScrollY() and the real scrollY has different values.
        // As a workaround, we should call scrollVerticallyTo() to make sure that they match.
        Scrollable s = getScrollable();
        s.scrollVerticallyTo(scrollY);

        // If scrollable.getCurrentScrollY() and the real scrollY has the same values,
        // calling scrollVerticallyTo() won't invoke scroll (or onScrollChanged()), so we call it here.
        // Calling this twice is not a problem as long as updateFlexibleSpace(int, View) has idempotence.
        updateFlexibleSpace(scrollY, getView());
    }

    @Override
    protected void updateFlexibleSpace(int scrollY, View view) {
        ObservableScrollView scrollView = (ObservableScrollView) view.findViewById(R.id.scroll);

        // Also pass this event to parent Activity
        BhawanHome parentActivity =
                (BhawanHome) getActivity();
        if (parentActivity != null) {
            parentActivity.onScrollChanged(scrollY, scrollView);
        }
    }
}

The code for xml file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <in.ahmedraza.material_tab.ObservableScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:overScrollMode="never"
        android:scrollbars="none">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <View
                android:layout_width="match_parent"
                android:layout_height="@dimen/flexible_space_image_height"
                android:background="@android:color/transparent" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/white"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:text="@string/bhawan_story" />

            <Button
                android:id="@+id/full_story_bhawan"
                android:layout_width="60dp"
                android:layout_height="30dp"
                android:text="Complete Story"
                android:onClick="true"
                android:padding="@color/white"
                android:background="@color/red"
                android:gravity="center"/>
        </LinearLayout>
    </in.ahmedraza.material_tab.ObservableScrollView>
</FrameLayout>

A: Fragments does not have findViewById method. Single invoke of this method need to be fixed from
Button btn1 = (Button) findViewById(R.id.full_story_bhawan);

to
Button btn1 = (Button) view.findViewById(R.id.full_story_bhawan);

Second thing. Dont write code after return statemant. Its never gonna be executed.
Move return of onCreateView after setting onClickListener.
Lastly the onClickListener.
Change this:
Intent myIntent = new Intent(this, DialogMainActivity.class);

to
Intent myIntent = new Intent(getActivity(), DialogMainActivity.class);

first parameter of Intent constructor is context. this in you code refer to anonymous onClickListener not to any kind of context so it needs to be fixed.
Hope it will solve your problem.
Edit:
android:padding="@color/white"

This is never gonna work :P Change it to proper dimension value.


text:
Q: Can't split an string to an array with \n I have data with new lines (\n). I need to split it to an array to show it in a list.
      $scope.proposal = actionProposal;
      var description = actionProposal.ap_description;
      console.log(description.split('#')); //Works
      console.log(description.split('\n')); //Not working

I tried it manually here:
http://jsbin.com/yakosavediye/1/
There it works. But not in angular.
Any ideas?
Update
Here is the full code:
$scope.openDetailModal = function(ap_id){
      $modal.open({
        templateUrl: './template/modal/detail-view.html',
        resolve:{
          actionProposal: function(SingleEnergyActionProposalLoader){
            return new SingleEnergyActionProposalLoader(ap_id);
          }
        },
        controller:function($scope, $modalInstance, actionProposal){
          $scope.proposal = actionProposal;

          var description = actionProposal.ap_description;
          var desc = description.split('\n');
          console.log(desc);

          $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
          };
        }
      });
    };

If I replace my resolve with a handwritten object, then it works. So it has something to do with the loader. I also trid to do a angular.toJson (which cleans the object) and then parse it back. No effect.
Update 2
Here's my loader
.factory('EnergyActionProposal', function ($resource) {
    return $resource('/api/actionproposals/:ap_id', {'ap_id': '@ap_id'});
  })
  .factory('SingleEnergyActionProposalLoader', function(EnergyActionProposal, $q){
    return function(ap_id){
      var delay = $q.defer();
      EnergyActionProposal.get({ap_id: ap_id}, function(energyActionProposal) {
        delay.resolve(energyActionProposal);
      }, function () {
        delay.reject('Unable to fetch energy action proposal');
      });
      return delay.promise;
    };
  });

A: I'd recommend replacing the newlines with another character # or | and then doing your split: desc = description.replace(/\n/,'#');
desc.split('#');

A: try this:
var test = 'Avstängning av 205-LB1 under helger.\n# Lågflödesdrift för 205-LB5 natt och helger.\n# Anpass drift högfart för 205-LB7 till verksamhetstid.\n# Natt & helgavstängning för 255-LB1.\n# St';

t = test.replace(/\n/,'#');

console.log(t);

http://jsbin.com/kifawuvapewo/1/edit

A: Have you tried escaping \n?
description.split('\\n')

Splitting by \n character doesn't seem to work


text:
Q: Composition of 2 modulo functions Let $A = \{1,2,3,4\}$ and define the functions $f,g:A \to A$ by the rules $f(x)= 3^x\mod5$ and $g(x)=2^x\mod 5$.
The questions asks us if

*

*$f$ is injective

*$g$ is surjective

*find $f(g(x))$
Clearly $f$ is not injective and $g$ is not surjective, but i cant figure out the third one

A: It's just a matter of understanding what these words and formulas mean!  We are told that $f(x)= 3^x$ (mod 5) and x can only have 4 values so it is easy to calculate all of them:
$f(1)= 3^1= 3$ (mod 5), $f(2)= 3^2= 9= 4$ (mod 5), $f(3)= 3^3= 27= 2$ (mod 5), and $f(4)= 3^4= 81= 1$ (mod 5).
  Yes, f is "injective" (one to one). Two different values of x always give different values of f(x).
$g(x)= 2^x$ (mod 5) so
 $g(1)= 2^1= 2$ (mod 5), $g()= 2^2= 4$ (mod 5), $g(3)= 2^3= 8= 3$ (mod 5), and $g(4)= 2^4= 16= 1$ (mod 5).
  Yes, g is "surjective" (onto).  For every number, y, in A, there is an x such that f(x)= y. g(4)= 1, g(1)= 2, g(3)= 3, and g(2)= 4.
Now, f(g(x)) is given by
$f(g(1))= f(2)= 4$, $f(g(2))= f(4)= 1$, $f(g(3))= f(3)= 2$, and $f(g(4))= f(1)= 3$.


text:
Q: How do I insert a variable result into a string in C++ I just started learning C++ in Qt and I was wondering how can I put a variables result in a string? I'm trying to use this for a simple application where someone puts their name in a text field then presses a button and it displays there name in a sentence. I know in objective-c it would be like,
NSString *name = [NSString stringWithFormatting:@"Hello, %@", [nameField stringValue]];
[nameField setStringValue:name];

How would I go about doing something like this with C++? Thanks for the help

A: I assume we're talking about Qt's QString class here. In this case, you can use the arg method:
 int     i;           // current file's number
 long    total;       // number of files to process
 QString fileName;    // current file's name

 QString status = QString("Processing file %1 of %2: %3")
                 .arg(i).arg(total).arg(fileName);

See the QString documentation for more details about the many overloads of the arg method.

A: You don´t mention what type your string is. If you are using the standard library then it would be something along the lines of
std::string name = "Hello, " + nameField;

That works for concatenating strings, if you want to insert other complex types you can use a stringstream like this:
std::ostringstream stream;
stream << "Hello, " << nameField;
stream << ", here is an int " << 7;

std::string text = stream.str();

Qt probably has its own string types, which should work in a similar fashion.

A: I would use a stringstream but I'm not 100% sure how that fits into your NSString case...
stringstream ss (stringstream::in);
ss << "hello my name is " << nameField;

I think QString has some nifty helpers that might do the same thing...
QString hello("hello ");
QString message =  hello % nameField;

A: You could use QString::sprintf. I haven't found a good example of it's use yet, though. (If someone else finds one, feel free to edit it in to this answer).
You might be interested in seeing information about the difference between QString::sprintf and QString::arg.


text:
Q: columns not fitting into grid I just started using compass blueprint and I'm making a simple frame with the following:
$blueprint_grid_columns: 12;
$blueprint_grid_width: 60px;
$blueprint-grid-margin: 20px;

@import "blueprint";

.frame {
  @include container;
  .header{
    @include column(12);
    background:#000;
    height:100px;
  }
  .left_bar{
    @include column(1);
    background:#ccc;
    height:450px;
  }
  .content{
    @include column(10);
    background: #000;
    height:450px;
  }
  .right_bar{
    @include column(1);
    backgrounf:#ccc
    height:450px;
  }
}

Html:

The right_bar isn't fitting into the space for the last column but rather appearing exactly under the left_bar. Can anyone tell me why? Any help greatly appreciated.
C

A: I think you have to add true to the header and right_bar classes:
.header{
  @include column(12, true);

....
.right_bar{
  @include column(1, true);

This lets compass know that it's the last column, and that the margin needs to be zeroed out.

A: I figured that out. I added some borders that pushed the grid out of whack a bit. I fixed it by overriding widths but it seems a bit hacky. Is there a blueprint way to take borders into account?


text:
Q: EvaluationObject not appearing By using
ParallelSubmit[1 + 2]

the output is simply
EvaluationObject[16,1+2,<>]

I was expecting to see
.
Even in the help pages for ParallelSubmit this happens. The figure correctly appears in the help before I do any evaluation, but, after I do it, it changes to the text above. These figures work as monitor to the computations in the parallel kernels. They are not essential, but they are helpful.
I am using Mathematica 12.1.1. The option "Dynamic updating", in the Evaluation menu, is enabled. Is this a known issue? Are there workarounds?
Update:
There is a single computer with this issue, I am not sure if it is a particular bug in its instalation, or it is a configuration of some option.
Following @b3m2a1 suggestion, I typed CurrentValue[EvaluationNotebook[], {StyleDefinitions, "Output", DefaultFormatType}] and the result was DefaultOutputFormatType.

A: Switch between StandardForm and OutputForm.


text:
Q: Pedir red social del cliente en el checkout de Woocommerce llevo unos días peleando con este código y seguro que el fallo será una tontería. Quiero recoger en el los pedidos de Woocommerce una red social del cliente para segmentar el envío de la newsletter:
El código es muy sencillo y con un campo tipo TEXT funciona sin problema pero con el RADIO se muestra el campo pero no se guarda el valor ni se refleja en el perfil de usuario. Este es el código:
add_action( 'woocommerce_after_checkout_billing_form', 'jrc_add_user_field_to_checkout' );

function jrc_add_user_field_to_checkout( $checkout ) {
    $current_user = wp_get_current_user();
    $saved_rrss = $current_user->rrss;

    woocommerce_form_field('rrss', array(
            'type' => 'radio',
            'class' => array('rrss form-row-wide'),
            'label' => __('RR SS', 'jcode'),
            'options' => array(
                    1 => __( 'Facebook', 'jcode' ),
                    2 => __( 'Instagram', 'jcode' ),
                    3 => __( 'Otro', 'jcode' ),
                ),
            'default' => '1',
            'required' => false
        ),
    $saved_rrss );

}

add_action( 'woocommerce_checkout_update_user_meta', 'jrc_checkout_field_update_user_meta' );

function jrc_checkout_field_update_user_meta( $user_id ) {
    if ( $user_id && $_POST['rrss'] ) {
    // once again, use "rrss"
       $args = array(
                    'ID' => $user_id,
                    'rrss' => esc_attr( $_POST['rrss'] )
            );

        wp_update_user( $args );
    }
}

Gracias de antemano.


text:
Q: Import multiple csv file and merge, plot in R shiny I'm trying to build a Shiny App that loads multiple CSV which have the same format and merge as one. Finally, the goal is to make a plot from merged data.
It does work till the point of multiple CSV loading but fails to make a plot.
I think the data is not properly merged inside of the code but not sure.
Here is an example of CSV and my code.

col1
col2
col3

1
437.2
0.12

2
435.1
0.11

3
434.4
0.95

library(shinydashboard)
library(ggplot2)
library(data.table)

#======================================================================
# UI
#======================================================================

ui = dashboardPage(

  #header
  dashboardHeader(
    title = 'Test_multiple csv import and plot'
  ),
  #sidebar
  dashboardSidebar(
    sidebarMenu(
      menuItem('Load log files',tabName = 'data_tab'),
      menuItem('Plot log files',tabName = 'plot_tab')
    )
  ),
  #body
  dashboardBody(
    #tabs
    tabItems(
    #tab for import
      tabItem(
        tabName = 'data_tab',
        fileInput('file','Data Loading(*.csv files)',multiple=T, accept = c('.csv'))
      ),
    #tab for plot
      tabItem(
        tabName = 'plot_tab',
        plotOutput('plot')
      )
    )
  )
)

#======================================================================
# Server
#======================================================================

server = function(input,output){

  #load data
  vars = reactiveValues(df = NULL)
  observeEvent(input$file$datapath,{
    req(input$file)
    files= list.files(input$file$datapath)
    temp= lapply(files,fread)
    df = rbindlist(temp)
    vars$df <-as.data.frame(df)
  })

  #plot data
  output$plot = renderPlot({
    data.frame(time=vars$df[,1],emission=vars$df[,2]) %>%
      ggplot(aes(x=time, y=emission))+
      geom_line(color="red")+
      geom_point()
  })

}

#======================================================================
# Run App
#======================================================================

shinyApp(ui,server)

A: The first thing to note is that list.files lists the files in a given directory. You are not passing it a directory, you are passing it a list of files. So you just need to change the code to
observeEvent(input$file$datapath,{
    req(input$file)
    temp= lapply(input$file$datapath,fread)
    df = rbindlist(temp)
    vars$df <-as.data.frame(df)
  })

Secondly, you are constructing a dataframe from a dataframe here
output$plot = renderPlot({
    data.frame(time=vars$df[,1],emission=vars$df[,2]) %>%
      ggplot(aes(x=time, y=emission))+
      geom_line(color="red")+
      geom_point()
  })

You can just set the column names in your csv appropriatly then you can just pass in the dataframe directly as in vars$df %>% ..., but this isn't required to get your example to work.


text:
Q: DQN - How to feed the input of 4 still frames from a game as one single state input I was reading this blog about Deep Q-Learning.
1- In the The input section of the blog, I wanted to know how do we feed the 4 still-frames/screenshots from the game, that represent the input state, into the Policy network? Will all 4 frames be fed in one flattened tensor (where one image ends the next one starts, forming a continuous row input, in one tensor)? Or will they be fed separately one after the other into the network?
2- For preprocessing the images, do we avoid using the Max-pooling stage? My understanding is this process eliminate the need for spacial/position recognition in image-feature recognition. While in normal Conv-Net this is important for recognising image features regardless of where they appear in space and distance (so we us max-pooling). In Q-learning for games, the space/position of different elements on the image is important. Therefore, we remove the use of Max-pooling from the proprocessing stage. Is this correct?
3- Can anyone recommend a good implementation resource of Deep Q-learning, written from scratch (in Python), i.e. without the use of out-of-the-box libraries, like PyTorch, Keras and Scikit-learn ..etc, for a game, where image frame feeds from the game is required as states input. I'm thinking perhaps implementing the model from scratch gives a better control over customisation and fine tuning of the hyper-parameters. Or is it better to use out-out-of-the-box library? Any code implementation on this would be super helpful.
Many thanks in advance.

A: *

*No, the typical approach is to stack the (gray-scaled) frames, such that the input shape becomes [height, width, num_frames], i.e. the frames take on the role that's usually reserved for the color channels in an RGB image. This makes it easy to apply 2D convolutions.

*Yes, that is correct. You don't use pooling, because you don't want to throw away information about spatial location.

*I would advice against this particular approach. I would suggest instead to familiarize yourself with all the building blocks of the function approximator (at least at the conceptual level). This might mean going back to mnist to study the components of CNNs. After that, you probably won't want to implement everything from scratch. Here's a blog post that I found pretty useful:

*

*Beat Atari with Deep Reinforcement Learning! (Part 1: DQN)


text:
Q: Geting specific response body from response and put in a variable in Postman I am trying to set the response in a variable but the response is just an ID, not an object. I used
var resposseBody=pm.response.json();

or
var resposseBody=pm.response.text();

but they didn't work. How can I set the response below in a variable?
"3707ff3d-2af9-4ea1-a6aa-08d9a8ee3cb3"

A: To save that value to a variable, add this to the Tests script:
pm.globals.set('id', pm.response.text());

This is an example using the global scope but the variable can be set at the Environment or Collection level.
There aren't many details in your question so it's difficult to offer any more of a solution than this one.

A: If the response is in json format, like
{"id":"3707ff3d-2af9-4ea1-a6aa-08d9a8ee3cb3"}

then you can get simply with
responseJsonData=pm.response.json();
responseId=responseJsonData.id;


text:
Q: Getting Tomcat to play well with Netbeans 6.7 on Linux I have an external Tomcat server configured to run J2EE applications on my development (Gentoo Linux install) machine. This works great if the server is started prior to opening Netbeans and deploying the code [within the IDE]. This fails when I try to restart the server or to debug the server application. The error I get is that it is unable to find "catalina.sh" and the shutdown/start scripts for tomcat.
The Gentoo guide for this suggests that the scripts were outdated and were replaced with the init.d scripts. Does anyone have a suggestion on where I could find these scripts or how they solved this issue?

A: The lack of a script is due to an issue with the Gentoo Tomcat ebuild... all of the script files were in the bin directory of the src build.
Gentoo Bug Site
Solution:
1. un-tar the src

*Copy all of the script files into the tomcat/bin directory

*Change group ownership of the script files to tomcat

*Enable execute and write group permissions to the script files


text:
Q: functions.php current user equals page_title Is it posssible to create a function that get the post_meta of a page based on the currentuser login and Page Title is a match?
So if user "Test1" is logged in it will get the post_meta of a Page that has the title "Test1". Only when there is a match, otherwise do nothing.
I got this function to retrieve the child of a parent and then load a field but when creating a new page there is no parent yet. That is why I want to create this new function.
function my_acf_load_field( $field ) {
    global $post;
    if ( 0 !== (int) $post->post_parent )
    {
         $some_value = get_post_meta( $post->post_parent, 'rwp_user_score', true );
        if ( ! empty ( $some_value ) )
            switch ( $field['name'] ) {
            case 'gemiddelde_score_hosting_provider':
            $field['value'] = '' . $some_value .'';
            break;
            }
    }
    return $field;
}

add_filter('acf/load_field', 'my_acf_load_field');

A: You can use the get_page_by_title() function, coupled with wp_get_current_user() and do a check for is_user_logged_in() inside a custom function to either return false, or return the page meta you are looking for like this:
function get_user_based_page_meta() {
    //return false if user is not logged in
    if (!is_user_logged_in()) {
        return false;
    }

    //get current user login
    $user_login = wp_get_current_user()->user_login;

    //get page by title - will retun null if no page exists
    $page = get_page_by_title($user_login);

    //check if get_page_by_title was successful and then return meta value, else return false
    if ($page != null) {
        return get_post_meta($page->ID, 'gemiddelde_score_hosting_provider', true;
    } else {
        return false;
    }
}

You can then use this function inside whatever action/filter hook you are using like this:
$user_meta = get_user_based_page_meta();
if ($user_meta) {
    echo $user_meta;
} else {
    //do nothing - no user logged in, or no page with user_login as title found
}


text:
Q: CakePHP2: Declaration of ... should be compatible with I've imported a CakePHP Website hosted at External Server to my local server...
But it doesn't work and I received several remarks.  It has displayed on screen like

I think there is a miss of connection with remote server, but I made all of the standard class database comnnection.
When the index page is requested It's prints a lot of errors with component.
Following is the code for database connection:
 class DATABASE_CONFIG {

    public $default = array(
            'datasource' => 'Database/Mysql',
            'persistent' => false,
            'host' => '186.202.152.111',
            'login' => 'site1386348519',
            'password' => 'xxxxxxx',
            'database' => 'site1386348519',
            'prefix' => 'tb_',
            'encoding' => 'utf8'
    );
 }

How can I solve this?

A: Your issue doesn't appear to be with your database, but your use of methods in your code. The server appears to have strict PHP error reporting on, so it is warning you that you've extended methods in your models and other classes that aren't using the same declaration. You need to check each of the methods being warned about and check that you are extending correctly (for example make sure you are defining the correct number/type of parameters for the methods).


text:
Q: caught TypeError: Cannot read properties of null (reading 'value') at document.getElementById.onclick i think, value of input field is not being read, and there is a problem with onclick method of submit button. when i press the submit button after running, nothing works, and this error is there -- caught TypeError: Cannot read properties of null (reading 'value')  at document.getElementById.onclick. (by nothing works, i mean, the change of innerhtml of paragraph tag doesn't occur)

<!DOCTYPE html>

        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>

number guessing game

        <input id="guessfield">
        <input type="submit" id="submitButton">

i ran this html with
const answer = Math.floor(Math.random() * 10 + 1);
document.getElementById("submitButton").onclick = function () {
    let guess = document.getElementById("guessField").value;
    if (guess==answer) {
        alert("correct answer");
    }
    else if (guess > answer) {
        alert("too high");
    }
    else {
        alert("too low");
    }
}

this javascript.
i got this website-website
here, when i click, nothing happens.
if i open console to check errors,
this error shows up-error
i have tried to make this website a couple more times-
first, with

number guessing game

        Press This button to generate a random number between 1 and 10
        <button id="genRand">generate</button>

        enter a guess here
        <input id="inputNo" type="number" min="1" max="10" placeholder="1-10">

        <input type="submit" id="submitNo">

html
and this-
function random() {
    return Math.floor(Math.random()*10+1)
}
let randomNo;
Number(randomNo)
function genRandNo(a) {
    Number(a)
    a=random()
}
document.getElementById("genRand").onclick = genRandNo(randomNo);
let input;
input=document.getElementById("inputNo").value;
Number(input);
let guide=document.getElementById("guide").innerHTML;
function onSubmitNo() {
    switch (true) {
        case input>randomNo:
            guide="guess a lower number";
            break;

        case input<randomNo:
            guide="guess a higher number";
            break;

        default:
            guide="you have guessed the correct number"
            break;
    }
}

javascript.
then second, with this-
<input type="text" inputmode="numeric" id="inputNo" placeholder="1-10">
        <input type="submit" id="submitNo">

hello

html
and this-
function random() {
    return Math.floor(Math.random()*10+1)
}
let number = random();
let submit = document.getElementById("submitNo").onclick;
let guess = Number(document.getElementById("inputNo").value);
let guide = document.getElementById("guide").innerHTML;
function checkGuess() {
    switch (True) {
        case guess < number:
            guide = "too low";
            break;
        case guess > number:
            guide = "too high";
            break;
        default:
            guide = "correct guess";
            break;
    }
}
submit = checkGuess();

javascript.
in both of these cases too, nothing happened on pressing the submit button
please assist

A: function genRandNo(a) why are you using this random will directly get a random number you don't need to use this
function random() {
    return Math.floor(Math.random()*10)+1
}
let randomNo;
Number(randomNo)
function genRandNo(a) {
    Number(a)
    a=random()
}

instead of using function genRandNo(a) you can set random value directly in random function
let randomNo;
function random() {
   let rand = Math.floor(Math.random()*10)+1
randomNo = rand;
return rand
}

you are using onclick wrongly
document.getElementById("genRand").onclick = genRandNo(randomNo);

It's like this and just call the random function it will get random value
document.getElementById("genRand").onclick = () => {random()};

here you are setting input value it's run with starting js and get input value which is empty and it will not change after it. So, use it in your submit button
let input;
input=document.getElementById("inputNo").value;

using switch is wrong use if-else-if because switch will just get number and will match it with cases in your case it will always run default.
let guide = document.getElementById("guide").innerHTML;

instead of this just use
let guide = document.getElementById("guide")

when you want to change it use this
guide.innerHTML = 'something'

I changed your js and added comment. instead of switch statement use if-else

// random num
let randomNo;

// generate random number
function random() {
let rand = Math.floor(Math.random()*10)+1
// seeting random number value
randomNo =rand
    return rand
}
// setting click on random number
document.getElementById("genRand").onclick=()=>{random();}
// select guide where result will show
let guide=document.getElementById("guide");
// set function on submit click
document.getElementById("submitNo").onclick=()=>{onSubmitNo();}
// on sumbit function
function onSubmitNo() {
// getting input value here whenever submit will click it will get new value
let input = document.getElementById("inputNo").value;
// changing it into number in case of string
input = parseInt(input)
// check if number match the guess
if(input === randomNo){
   guide.innerHTML="you have guessed the correct number";
   // check if number greater than guess
} else if(input > randomNo){
    guide.innerHTML="guess a lower number";
     // check if number lesser than guess
} else if(input < randomNo){
 guide.innerHTML="guess a higher number";
 // in case of wrong output
} else {
     guide.innerHTML="you have guessed the wrong number"
}

}

number guessing game

        Press This button to generate a random number between 1 and 10
        <button id="genRand">generate</button>

        enter a guess here
        <input id="inputNo" type="number" min="1" max="10" placeholder="1-10">

        <input type="submit" id="submitNo">


text:
Q: Idiomatic way to structure Rust trait I have been writing a Ray Caster in Rust following "The Ray Tracer Challenge", and I've been having a hard time figuring out the proper way to implement polymorphism in Rust. My priorities are that the object can be used in a multi-threaded program, and that seems to be the main problem.
I have two cases on this, but I'll focus on one: a shape. There are different kinds of shapes (sticking with the able suffix I originally called my trait Intersectable). Here was a working trait object implementation, but it didn't work with multi-threading:
#[derive(Debug)]
pub struct Shape {
    pub parent: Option<Arc<Shape>>,
    pub transform: Matrix4,
    pub material: Material,
    pub intersectable: Box<Intersectable>,
}
pub trait Intersectable: Debug + IntersectableClone {
    fn local_intersect(&self, ray: &Ray, object: Arc<Shape>) -> Vec<Intersection>;
}

pub trait IntersectableClone {
    fn clone_box(&self) -> Box<Intersectable>;
}

impl<T> IntersectableClone for T
where
    T: 'static + Intersectable + Clone,
{
    fn clone_box(&self) -> Box<Intersectable> {
        Box::new(self.clone())
    }
}

impl Clone for Box<Intersectable> {
    fn clone(&self) -> Box<Intersectable> {
        self.clone_box()
    }
}

#[derive(Clone, Debug)]
pub struct Sphere {}

impl Intersectable for Sphere {
    fn local_intersect(&self, ray: &Ray, object: Arc<Shape>) -> Vec<Intersection> {
        ...sphere specific code
    }
}

#[derive(Clone, Debug)]
pub struct Plane {}

impl Intersectable for Plane {
    fn local_intersect(&self, ray: &Ray, object: Arc<Shape>) -> Vec<Intersection> {
        ...plane specific code
    }
}

As a pure struct, with no official polymorphism, I've written a kind of static dispatch that looks like this:
#[derive(Debug, Clone)]
pub enum IntersectableType {
    Sphere,
    Plane,
}

#[derive(Debug, Clone)]
pub struct Intersectable {
    intersectable_type: IntersectableType,
}

impl Intersectable {
    pub fn local_intersect(&self, ray: &Ray, object: Arc<Shape>) -> Vec<Intersection> {
        match self.intersectable_type {
            IntersectableType::Sphere => self.local_intersect_sphere(ray, object),
            IntersectableType::Plane => self.local_intersect_plane(ray, object),
            _ => Vec::new(),
        }
    }

    fn local_intersect_sphere(&self, ray: &Ray, object: Arc<Shape>) -> Vec<Intersection> {
        ...sphere specific code
    }

    fn local_intersect_plane(&self, ray: &Ray, object: Arc<Shape>) -> Vec<Intersection> {
        ...plane specific implementation
    }
}

This works great, but it feels very non-Rusty. I've hit a few problems with using other implementations:
- Using Box<Intersectable> (when it was a Trait, not a struct), is difficult to clone (I copied How to clone a struct storing a boxed trait object? but didn't love having to use 'static, since that made concurrency impossible).
- Using Arc<Intersectable> seemed to have the same problems as Box, though maybe there is a way to make that work.
Is there a way to do this in Rust that allows me to take advantage of concurrency and not write manual static dispatch like this?

A: I'm also working on "The Ray Tracer Challenge", a bit further behind than you though. I have no concurrency in mind. I now try to follow the idea of the A-Frame ECS:
pub trait Primitive {}

pub struct Shape<T: Primitive> {
    pub transformation: M4x4,
    pub material: Material,
    pub primitive: T,
}

pub struct Sphere;
impl Primitive for Sphere {}


text:
Q: Got propensity score for multiple treatment groups. How can I proceed with matching? I want to perform propensity score matching for multiple treatment categories. I read the popular post of Comparing two or more treatments with inverse probablity of treatment weighting, and used twang, finally got propensity score for three categories.
But my question is that how can i proceed from here to match control to each treatment? I tried to do this with Matching function, which allows only binary classification and failed.


text:
Q: How to add an array to the CvSeq and also how to retrieve the array I am creating an array of double values,I want to add the created array to the CvSeq. I have used cvSeqPush for this purpose.But when I am retrieving this array it only shows the first element of the array and rest is garbage. The code is as follows..
int Ts = 45;
int count = 0;
//Creating a mtrix CL for clusters
CvMat * CL = cvCreateMat(1,newCP->cols,newCP->type);
//Array for storing the clusters
double * arrClust = (double*)malloc(3*sizeof(double));

//Copying 1st row of newCP to arrClust
arrClust[0] = cvmGet(newCP,0,0);
arrClust[1] = cvmGet(newCP,0,1);
arrClust[2] = cvmGet(newCP,0,2);

//array of distances
double * distance = (double*)malloc(1*sizeof(double));

//array of results
double * result = (double*)malloc(1*sizeof(double));

//Creating a seq to store various clusters
CvMemStorage * strgeClust = cvCreateMemStorage(0);
CvSeq * seqClust = cvCreateSeq(0,sizeof(CvSeq),sizeof(double),strgeClust);
CvSeq * s ;
for(int i=2 ; i<newCP->rows ; i++ )
{
    for(int j=0;j<=count;j++)
    {
        double a = arrClust[0] - cvmGet(newCP,i,0); //a = CL0-newCP0
        double b = arrClust[1] - cvmGet(newCP,i,1); //b = CL1-newCP1
        double c = arrClust[2] - cvmGet(newCP,i,2); //c = CL2-newCP2
        double sum = (a*a)+(b*b)+(c*c);             //(a^2 + b^2 + c^2)
        double sqrtSum = sqrt(sum);

        distance[j] = sqrtSum ;

        if(distance[j]<=Ts)
            result[j] = 0;
        else
            result[j] = 1;
    }
    //Checking for zero in result array
    int isZero = 1;
    for(int k =0;k<=count;k++)
    {
        if(result[k] == 0)
        {
            isZero =0;
            break;
        }
    }
    if(isZero!=0)
    {
        count = count+1;
        cvSeqPush(seqClust,arrClust);
        arrClust = (double*)malloc(3*sizeof(double));
        arrClust[0] = cvmGet(newCP,i,0);
        arrClust[1] = cvmGet(newCP,i,1);
        arrClust[2] = cvmGet(newCP,i,2);

    }
    else
    {
        double minElement = fnSortForMin(distance,count+1); //Getting the minimum value from distance array
        int index = fnSearchIndexOfMin(distance,minElement,count+1); //Getting the index of minElement
        if(index == count)
        {
            arrClust[0] = (arrClust[0]+cvmGet(newCP,i,0))/2;
            arrClust[1] = (arrClust[1]+cvmGet(newCP,i,1))/2;
            arrClust[2] = (arrClust[2]+cvmGet(newCP,i,2))/2;
        }
        else
        {
            s = seqClust;
            for(int i = 1;i<index;i++)
            {
                s = seqClust->h_next;
            }
            double * arr = CV_GET_SEQ_ELEM(double,s,index);
            arr[0] = (arr[0]+cvmGet(newCP,i,0))/2;
            arr[1] = (arr[1]+cvmGet(newCP,i,1))/2;
            arr[2] = (arr[2]+cvmGet(newCP,i,2))/2;
        }
    }//End of outer If Block
}//End Of outer For loop

The problem occurs in line where I am using CV_GET_SEQ_ELEM.Can anybody tell me where is the problem??

A: Problem is the that CV_GET_SEQ_ELEM only gets one element at a time, and you have only specified the first element by passing in the index of 1.
You want to call the function cvCvtSeqToArray with arguments like
cvCvtSeqToArray(s, arr, CV_WHOLE_SEQ);
Please note that the array arr passed the second paramter to this function will need to be intialised
E.g. CvPoint* arr = (CvPoint*)malloc( count*sizeof(CvPoint)); where count is the number of elements in the array.
CvSeq is strictly used to represent growable 1d arrays, as opposed to the 2d array you are trying to use. If you want to continue use multidimensional arrays that aren't cvMat, you could try CvSeq of CvSeq but I still think you would have the same problem.
Hence calling CV_GET_SEQ_ELEM only cleanly accesses the single pointer in memory that you give it, which is the first element of the array.
You could also try std::vector of CvSeq or an array of CvSeq but I haven't tried that.


text:
Q: Coturn server - Relay is not working I am trying to setup a COTURN server for my WebRTC based application. However I am stuck with a couple of error messages that I am unable to understand, and can't find any help on them on internet.
Here are some details about the app:

*

*Two users log on to the app, and one of the user can share their screen with the other - so the stream is going in only one direction

*I am able to get the app to work within intranet and on some external networks. So I'm confident that the application is working fine wherever STUN mode is sufficient.

*For some of the networks the STUN candidates are constantly failing, so I need to get a TURN server to relay the stream.
I have collected some server logs from the server, in case someone could identify the  problem based on them:
handle_udp_packet: New UDP endpoint: local addr <IP Address>:3478, remote addr <IP Address2>:59942

handle_turn_command: STUN method 0x1 ignored

handle_udp_packet: New UDP endpoint: local addr <IP Address>:3478, remote addr <IP Address2>:59944

handle_turn_command: STUN method 0x1 ignored

session 128000000000000096: realm <server URL> user <>: incoming packet message processed, error 401: Unauthorised

session 128000000000000097: realm <server URL> user <>: incoming packet message processed, error 401: Unauthorised

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

session 128000000000000096: realm <server URL> user <>: incoming packet message processed, error 401: Unauthorised

session 128000000000000097: realm <server URL> user <>: incoming packet message processed, error 401: Unauthorised

IPv4. Local relay addr: <IP Address>:64306

session 128000000000000096: new, realm=<server URL>, username=<username>, lifetime=600

session 128000000000000096: realm <server URL> user <username>: incoming packet ALLOCATE processed, success

IPv4. Local relay addr: <IP Address>:65384

session 128000000000000097: new, realm=<server URL>, username=<username>, lifetime=600

session 128000000000000097: realm <server URL> user <username>: incoming packet ALLOCATE processed, success

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

session 128000000000000096: realm <server URL> user <username>: incoming packet ALLOCATE processed, success

session 128000000000000097: realm <server URL> user <username>: incoming packet ALLOCATE processed, success

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

handle_turn_command: STUN method 0x1 ignored

session 128000000000000096: refreshed, realm=<server URL>, username=<username>, lifetime=0

session 128000000000000096: realm <server URL> user <username>: incoming packet REFRESH processed, success

session 128000000000000097: refreshed, realm=<server URL>, username=<username>, lifetime=0

session 128000000000000097: realm <server URL> user <username>: incoming packet REFRESH processed, success

session 128000000000000096: closed (2nd stage), user <username> realm <server URL> origin <>, local <IP Address>:3478, remote <IP Address2>:59942, reason: allocation timeout

session 128000000000000096: delete: realm=<server URL>, username=<username>

session 128000000000000097: closed (2nd stage), user <username> realm <server URL> origin <>, local <IP Address>:3478, remote <IP Address2>:59944, reason: allocation timeout

session 128000000000000097: delete: realm=<server URL>, username=<username>

Here's how my turnserver.conf file looks:
listening-port=3478
#tls-listening-port=443
realm=subdomain.domain.com
server-name=subdomain.domain.com
lt-cred-mech
userdb=/etc/turnserdb.conf

cert=/home/ubuntu/certificate.crt
pkey=/home/ubuntu/qc.key
pkey-pwd=L1ght!t

no-stdout-log
Verbose

I am particularly concerned about the following points:

*

*Should I assume that since my code is working with a STUN server, it  would work with a working TURN server as well? Hence, the error means that the problem is with the TURN server?

*I can see a couple of errors stating 'Allocation Timeout'. Does that mean refer to any RAM/CPU/Network allocation that may be insufficient?

*Some of the requests have username portion empty '<>' rather than '', and it is followed by a '401 Unauthorized', while I have triple checked the RTCPeerConnection configurations - they do contain the username and password.

*Apart from the logs above, I have seen '438 Wrong nonce' come in quite frequently as well. I searched a bit about that, but it doesn't seem like something I can control through JS. Is it related to any server configurations?
Thanks! Appreciate your help.

A: How does your config looks like?
My working example for webRTC usage:
sudo nano /etc/turnserver.conf
->
listening-port=80
tls-listening-port=1133
fingerprint
lt-cred-mech
userdb=/etc/turnuserdb.conf
realm=subdomain.domain.com
server-name=subdomain.domain.com
total-quota=100
bps-capacity=0
stale-nonce
log-file=/var/log/turnserver/turn.log
no-loopback-peers
no-multicast-peers

sudo nano /etc/turnuserdb.conf
->Username:Passwort
You also need to allow these ports in your firewall if enabled.
Check your server here: Trickle ICE
Notice, that you always need to use your ip/url with port like 123.456.789.10:80

A: There were a few problems in the TURN server setup I had.

*

*First off, we had taken it from a blog which was about two years old. As a result, the setup was also two years old - Coturn Monza. The ideal way to start would be to get the Coturn AMI (Amazon Machine Image)(Version 4.5.0.6 details) and use it to setup the server. Alternatively, we should have at least taken the most recent setup through the git repository.

*Second problem was with the configurations. Even before posting the question here, we had missed to open the necessary ports on the server. Once we did that, we started getting the STUN responses, but the relay wasn't working yet.

*Third key problem was with the configurations in Turnserver.config file. We had barely gone through all configurations and after Polaris's answer  we did. The config file contains sufficient explanation for each configuration, and the problem was indeed with the configurations.

*The last problem was with the test cases. We wanted to ensure that the relay was "working", and during earlier stages of testing we had identified a particular network setup that would require relay (i.e. only STUNs would not be able to complete the request.) Eventually we learned that even TURN server would not be able to get through that setup.
We did spend some time trying the NOSTUN mode (it's there in the turnserver.config), but due to lack of good test cases, we were never able to confirm that relay was working.
I don't fully understand the test code on Trickle ICE Page, but I believe the results over there are reliable.

A: Here are some troubleshooting tips:

*

*make sure you add the fingerprint option, as mentioned by Polaris

*try just using a static username and password for now, e.g.:
user=username:test

*then include this in your PeerConnectionConfig:
{'url': 'turn:yourserver.com:3478', credential: 'test', username: 'username'}

*Use the "WebRTC Network Limiter" chrome extension to force WebRTC to use the TURN server.

*Comment out the cert and pkey for now.


text:
Q: Using the method SVNClient.Diff Diff (SvnTarget target, SvnRevisionRange range, Stream results) Given two different revisions need to get the differences between them, I intend to use the method duvuelve Diff but I anything as a result, it could be? Thanks.
My code is as follows
using (SvnClient client = new SvnClient())
using (MemoryStream result = new MemoryStream())
{
    client.Authentication.DefaultCredentials = new NetworkCredential("asdf", "asdf/*");
    try
    {
        //SvnUriTarget is a wrapper class for SVN repository URIs
        SvnUriTarget target = new SvnUriTarget(textBox1.Text);
        if (client.Diff(target, rango, result))
            MessageBox.Show("Successfully para" + rango.ToString() + ".");

        StreamReader strReader = new StreamReader(result);

        string str = strReader.ReadToEnd();
    }
}

A: The stream that is returned from the Diff() function is positioned at the end of the stream, so before creating your stream reader, you need to reposition it at the beginning of the stream:
result.Position = 0;
StreamReader strReader = new StreamReader(result);


text:
Q: Multiple selector search via puppeteer library I use puppeteer to get data about the store. I search using the p.shop-page-content__text_large, span.shop-list-item__address selectors, but I ran into such a problem that only one of them can be present on the page. I tried to solve the problem in the following way, but it does not work. Tell me how can this be fixed?
const puppeteer = require('puppeteer');

const browser = await puppeteer.launch({
    headless: false,
    slowMo: 150,
});

const cities = [{'CITY': 'Town1', 'LINK': '/shops/town1/'}, {'CITY': 'Town2', 'LINK': '/shops/town2/'}];

async function getData(page, selector) {
    return await page.$$eval(selector, info => info.map((data) => {
        let str     = data.textContent.trim(),
            from    = str.search(','),
            to      = str.length;

        return {
            'COUNTRY': 'unknow',
            'STREET' : str.substring(from, to)
        }
    }));
}

const result = [];

for (let val of cities) {
    console.log(val.LINK, val.CITY);

    const page = await browser.newPage();
    await page.goto('https://www.example-site.ru' + val.LINK);

    data = await page.waitForFunction('.shop-page-content').then(async() => {
        console.log('ok');
        return await getData(page, 'p.shop-page-content__text_large');
    }).catch(async (e) => {
        console.log('fail');

        await page.waitForSelector('.shops-info__section');
        return await getData(page, 'span.shop-list-item__address');
        // result.push(data);
    });

    result.push(data);
    await browser.close();
}

console.log(result);

A: It turned out like this:
const browser = await puppeteer.launch({
    headless: false,
    slowMo: 150,
});
const cities = [{'CITY': 'Town1', 'LINK': '/shops/town1/'}, {'CITY': 'Town2', 'LINK': '/shops/town2/'}];
const page   = await browser.newPage();
const result = [];

for (let val of cities) {
    await page.goto('https://www.example-site.ru' + val.LINK);

    const list = await page.evaluate(() => {
        const data     = [];
        const elements = document.querySelectorAll('p.shop-page-content__text_large').length
                        ? document.querySelectorAll('p.shop-page-content__text_large')
                        : document.querySelectorAll('span.shop-list-item__address');

        for (const element of elements) {
            data.push(element.innerText);
        }

        return data;
    });

    result.push({
        link: val.LINK,
        city: val.CITY,
        list
    })
}

await browser.close();


text:
Q: Vue - Axios Error : Cannot read properties of undefined (reading 'get') I'm making a Crud using Vue and axios.
My "create component" is working fine, but I have a problem with my "edit component".
The two components are the same except that the edit one have a parameter on the URL ("myweb.com?id=3") and on mounted cycle I make an axios call to retrieve the register data.
mounted() {
this.$http.get("/api/getOrder?id=" + this.order).then((response) => {
     this.complements = response.data
}); ...

I get this error "::: TypeError: this.$http is undefined" that break my code.
In my axios.js I have my prototype defined which is working fine on the rest of components:
Vue.prototype.$http = axiosIns

The weird thing is that this error only appear on production (not on local) and is intermittent (sometimes it works correctly, sometimes fails ... no pattern found)
EDIT ::
I realize that if I remove the axios call from mounted and put it on a button-method it works perfectly
Any help will be appreciate


text:
Q: Make my java application shut down if it stops working Is there a way to make my java application shut down there is an error? e.g. if I have a nullpointerexception, can I just make it completely close out?

A: Any uncaught exception at the top level will automatically halt the thread it's in. If you have more than one thread in your program, the other threads will still survive. If you want to terminate explicitly, you can call System.exit()

A: You can use System.exit(0); to terminate the JVM.
However, you should avoid NullPointerException by checking the reference before using it:
if(foo != null) foo.doSomething();

A: As others have said, catching the exception and calling System.exit() is (generally) the right approach.  But there is more to it than that:
Q: Do I really need to catch it?
A: If your application is a conventional command-line application, and the exception is thrown on the "main" thread, then you may not need to catch it.  Uncaught exceptions on the main thread will cause the application to exit ... if there are no other non-daemon threads in existence.  (In fact, the same thing goes for any thread ... )
However if your thread has more than one non-daemon thread, then you need to do something to stop the application.  Like catch the exception and call exit().
Q: Where do you catch it?
A: On the stack of any thread where the "fatal" exception might be thrown.  There are two ways to do this:

*

*Put a try / catch (Throwable) in the main(String[]) method, a thread's run() method, etcetera.

*Install a default uncaught exception handler.
What you DON'T want to do is to add System.exit() calls all through your codebase.  That approach leads to all sorts of problems with reusability, unit testing and generally figuring out "why has the effing application died again".
Q: What if it is already caught?
A: One reason why your application might not be exiting naturally, is that your code is already catching the exception ... by accident.  For instance:
    try {
       doSomething()
    } catch (Exception ex) {
       handle an IO exception
    }

In the above, some ignorant / lazy programmer hasn't bothered to consider the exceptions that might be thrown in doSomething and has assumed that they are all some kind of IO related exception.  But if the exception was actually an unexpected NullPointerException ... or something worse ... then the code has just squashed it.
The cure for this kind of thing is code-reviews and mentoring to cure the programmer of his bad habits ... hopefully before he does too much damage to the codebase!  And if you find this kind of thing in your codebase, you should fix it immediately ... and probably "grep" for similar occurrences and fix them too.


text:
Q: repeat div element n times how can i duplicate a div so there n copies using javascript or jquery this is the HTML div :

                   @{
                       int TotalNumberofPersons = Model.ViewModel_SessionObject.Parameters.SearchCriteria_NumberOfChildrenPerRoom +
                                                  Model.ViewModel_SessionObject.Parameters.SearchCriteria_NumberOfAdultsPerRoom;

                }
                @*
Room1 : Deluxe Double Room / Best Available Rate
*@

Guest names :

                        @for (int i = 0; i < TotalNumberofPersons; i++)
                        {

                                    <select class="dropdown form-control" style="max-width: 75px;">
                                        <option selected="selected">MR</option>
                                        <option>MRS</option>
                                    </select>

                                <input style="margin-left: -5px;" type="text" class="form-control" placeholder="prename" />
                                <input type="text" class="form-control" placeholder="surname" />

                        }

                            services:

                        @foreach (var item in Model.ViewModel_SessionObject.HotelAvailabilityRSObject.Services)
                        {
                            HotelDetailsRSService HotelService = Model.ViewModel_SessionObject.HotelDetailsRSObject.GetHotelService(item.ServiceCode);

                                @HotelService.Name :
                                @HotelService.Notes

                                    @HotelService.Price.ToString("N2")
                                    @Model.ViewModel_SessionObject.HotelAvailabilityRSObject.CurrencyCode

                                <input type="checkbox" class="v_checkbox" />

                        }

and this is my jquery code but not working here what i want to do :
  for (var i = 0; i < Product.SelectedRooms; i++) {

                         $('#Guest_details_and_servicesDIV').show()

                         jQuery("#Guest_details_and_servicesDIV").append(jQuery("#Guest_details_and_servicesDIV"));

                     }

A: Not sure if appending a plain JQuery-object will work. You better go with jQuery("#Guest_details_and_servicesDIV").append(jQuery("#Guest_details_and_servicesDIV"). html());


text:
Q: CN1 how to deal with the home indicator (iPhone X and such) When we have to deal with (native) device specific objects on the display (such as the home indicator in iPhone X) in case of having a proper layout of our app (avoiding those objects violate the layout), should I adapt the layout in native code or in CN1 specific code?
What would you suggest?

A: Most of our effort was around the notch and not so much on the home button but we probably should add support for iOS's safe area API. Although technically it's a pretty horrible API.
It might be better to add some device detection to the tabs component and add some padding in the bottom of the tabs by default. We can probably do it if you file an issue, you can do this manually too using a library such as this.


text:
Q: Django[AJAX] build url from Django Model Hello friends, I am building a website with Django, I decided to create a filter for my items, you can filter items like this: Item.objects.filter(type=item_type), so basically I created an url which takes a slug:item_type, and returns a JsonResponse with the items parsed as JSON.
Then I created an Ajax call in my js file and when I wanted to call the url to filter by type I keep getting an error:
function filterItemType(type) {
$.ajax({
    type: "GET",
    data: $(this).serialize(),
    url: "{% url 'boring:filter_items' type%}",
...

The Error:
Not Found: /boring/{% url 'boring:filter_items' type%}
[21/Jun/2021 11:32:54] "GET /boring/%7B%%20url%20'boring:filter_items'%20type%%7D HTTP/1.1" 404 6103

So basically, for my understanding, JS is not parsing the Django {% url .... %}.
I have no idea how to do it in order for JS to build the route...like I usually do it in the Templates...
PS: I also tried to build the route with the type separated as -> url: "{% url 'boring:filter_items'  %}" + "/"+ type; But it's not working either, same error.

Github Issue for this matter...

A: Basically the solution is to pass the built url in the TEMPLATE and then you can use it in the JS Ajax call.
For example:
<profile.html>
onclick=filterItemType("{% url 'boring:filter_items' 'Common'%}")

<profile.js>
function filterItemType(url_type) {
$.ajax({
    type: "GET",
    url: url_type,


text:
Q: Passing Java object into closure template? As far as I know, Google Closure Template doesn't allow passing Java object into the template (as compared to FreeMarker). So I can't really do something like:
// Java file
class Course {
  ...
  public function getName() {
    return name;
  }
}

// Main function
public static void main(String args[]) {
  // Get all courses
  List<Course> courses = Courses.getAllCourses();
  Map<String, Object> params = new HashMap<String, Object>();
  params.put("courses", courses);

  String out = tofu.newRenderer("template.listCourses").setData(params);
}

// Soy file
/**
 * @param courses List of courses
 */
{template .listCourses}
  Courses List! <br/>

  {foreach $course in $courses}
        New Course: {$course.name}
  {/foreach}
{/template}

I'm thinking if I want to do this I probably have to write a custom function that uses Reflection to turn Course object into a Map? I'm not experienced with Java Reflection. Is there such a function available?

A: In plovr, I created a utility, SoyDataUtil.java, which takes a JsonElement and converts it into a SoyData. Admittedly, you may only find this useful if you are already using Gson, but the nice thing about this approach is that Gson is likely to take care of the getter/setter reflection for you. For example, I believe you should be able to do:
JsonElement json = (new Gson()).toJsonTree(courses);
SoyData soyData = SoyDataUtil.jsonToSoyData(json);

Map<String, Object> params = new HashMap<String, Object>();
params.put("courses", soyData);

The trick is leveraging Gson to do to the reflection to turn courses into a JsonElement. Not sure whether you're willing to add these dependencies (though the code from plovr is quite small -- you can just copy it directly), but this may be the most expedient solution.


text:
Q: Built-in method to convert a string to title case in .NET Core? The .NET Framework has a method TextInfo.ToTitleCase.
Is there something equivalent in .NET Core?
Edit: I'm looking for a built-in method in .NET Core.

A: You can implement your own extension method:
public static class StringHelper
{
    public static string ToTitleCase(this string str)
    {
        var tokens = str.Split(new[] { " ", "-" }, StringSplitOptions.RemoveEmptyEntries);
        for (var i = 0; i < tokens.Length; i++)
        {
            var token = tokens[i];
            tokens[i] = token == token.ToUpper()
                ? token
                : token.Substring(0, 1).ToUpper() + token.Substring(1).ToLower();
        }

        return string.Join(" ", tokens);
    }
}

Credit: blatently copied form this gist*.
*Added the bit for acronyms Dotnet Fiddle.

A: Unfortunately, still in October 2016, .NET Core does not provide us with a ToTitleCase method.
I created one myself that works for my own needs. You can adjust it by adding your own delimiters to the regular expressions.
Replace _cultureInfo with the CultureInfo instance that is applicable to you.
public static class TextHelper
{
     private static readonly CultureInfo _cultureInfo = CultureInfo.InvariantCulture;

     public static string ToTitleCase(this string str)
     {
         var tokens = Regex.Split(_cultureInfo.TextInfo.ToLower(str), "([ -])");

         for (var i = 0; i < tokens.Length; i++)
         {
             if (!Regex.IsMatch(tokens[i], "^[ -]$"))
             {
                 tokens[i] = $"{_cultureInfo.TextInfo.ToUpper(tokens[i].Substring(0, 1))}{tokens[i].Substring(1)}";
             }
         }

         return string.Join("", tokens);
     }
 }

A: I created a github for the extension with tests, and a dotnet fiddle that includes the other solutions from this post. You will have to uncomment to lines to see what the other solutions output. This solution has covered all scenarios that came to mind. You can verify these in the tests on the git or on the fiddle. I suggest you use this solution if you want to get similar output to the TextInfo.ToTitleCase in non .NET Core.
 public static class StringExtension
{
    /// <summary>
    /// Should capitalize the first letter of each word. Acronyms will stay uppercased.
    /// Anything after a non letter or number will keep be capitalized.
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string ToTitleCase(this string str)
    {
        var tokens = str.Split(new[] { " " }, StringSplitOptions.None);
        var stringBuilder = new StringBuilder();
        for (var ti = 0; ti < tokens.Length; ti++)
        {
            var token = tokens[ti];
            if (token == token.ToUpper())
                stringBuilder.Append(token + " ");
            else
            {
                var previousWasSeperator = false;
                var previousWasNumber = false;
                var ignoreNumber = false;
                for (var i = 0; i < token.Length; i++)
                {

                    if (char.IsNumber(token[i]))
                    {
                        stringBuilder.Append(token[i]);
                        previousWasNumber = true;
                    }
                    else if (!char.IsLetter(token[i]))
                    {
                        stringBuilder.Append(token[i]);
                        previousWasSeperator = true;
                    }
                    else if ((previousWasNumber && !ignoreNumber) || previousWasSeperator)
                    {
                        stringBuilder.Append(char.ToUpper(token[i]));
                        previousWasSeperator = false;
                        previousWasNumber = false;
                    }
                    else if (i == 0)
                    {
                        ignoreNumber = true;
                        stringBuilder.Append(char.ToUpper(token[i]));
                    }
                    else
                    {
                        ignoreNumber = true;
                        stringBuilder.Append(char.ToLower(token[i]));
                    }
                }
                stringBuilder.Append(" ");
            }
        }
        return stringBuilder.ToString().TrimEnd();
    }
}

A: It seems there is no such method built-in to .NET Core.

A: .NET Standard 2.0 added TextInfo.ToTitleCase (source), so you can use it in .NET Core 2.0.
For .NET Core 1.x support, however, you are out of luck.

A: This worked for me in .net core
 public static string ToTitleCase(this string str)
        {
            try
            {
                var tokens = str.Split(new[] { " ", "-" }, StringSplitOptions.RemoveEmptyEntries);
                string final = "";

                for (var i = 0; i < tokens.Length; i++)
                {
                    var token = tokens[i];

                    string first = token.Substring(0, 1);
                    string remaining = token.Substring(1, token.Length - 1);

                    final +=  first.ToUpper() + remaining.ToLower()+" ";

                }

                return final;
            }
            catch {
                return "";
            }
        }


text:
Q: Composite components & ID I want to implement some javas cript into my JSF composite component, but I have problem with id. My java script with:
document.getElementById("myForm:customerId")

does not work, because the id is wrong. I have JSF composite component:
<composite:implementation>

Customer

        <h:form id="myForm">
            <h:inputText id="customerId" value="#{cc.attrs.customerId}"/>
        </h:form>

</composite:implementation>

and HTML output is:

Customer

    <form id="j_idt44:myForm" name="j_idt44:myForm" method="post" ... >
        <input type="hidden" name="j_idt44:myForm" value="j_idt44:myForm" />
        <input id="j_idt44:myForm:customerId" ... name="j_idt44:myForm:customerId" />
    </form>

Why is "j_idt44" used in HTML output?

A: Composite components are NamingContainer components like <h:form>, <h:dataTable>, etc. This allows you to have multiple of them in the same view without conflicting IDs.
You need to give the composite component a fixed ID as well. E.g.
<my:composite id="someId" />

I'd also suggest to use
 instead of
. It will then become someId with the above example.

Unrelated to the concrete problem, this isn't entirely the right purpose of a composite component. A composite component is intented to be of the same kind of <h:inputText>, etc. You seem to rather want a tag file or maybe an include file. See also When to use <ui:include>, tag files, composite components and/or custom components?


text:
Q: Using Data from a Table Relationship Hello All I am a fairly new user to Access 2010 and I have a question relating to using the data from a table relationship. I am creating a database that has a tblUser and tblQA. tblUser stores their FullName, UserName, and Team. tblQA includes the UserName as well many other fields related to individual Quality Assessments. I want to be able to view quality assessments by team as well as single user and I think that proper database design would be to use the relationship rather than to capture the team as a separate field in my tblQA. Here is where I run into trouble- how do I create a query of tblQA that is filtered by the team field of tblUser? Here is the Relationship table: http://imgur.com/a/AY2iI Let me know if I can provide any other info. Its a bit hard to know what all I need to provide even after reading the clear questions section.

A: You seem to have the relationships done more or less.
It's not perfect (for example you use the field name Team in two tables, in tblUser it contains an ID, and in tblTeams it contains a team name I presume) - but it should work.
Now you need to create a query, add the tables that interest you to it, the joins should appear automatically. And then you pull the fields you need (to see and/or set conditions against) from the tables to the field list at the bottom (for joined fields you only need one of the pair), and set conditions that suit your needs, for example UserLogin would have a condition ="jsmith" or Team = "Sales". Run the query and you'll see 1 or more rows with data from all 3 tables.
And you go from there (probably substituting literal conditions like = "jsmith with a variable set by a form or VBA.
If it's not what you need - please comment.