text:
Q: Creating Rolling Periods I am wanting to create a rolling period every 6 months and I am unsure of the best way to do this. I am guessing this might have to been done recursively?
I have a payments table that contains data similar to the following:
CREATE TABLE payments
    ([id] int, [payment_month] int, [payment_date] datetime, [payment_amount] int)
;

INSERT INTO payments
    ([id], [payment_month], [payment_date], [payment_amount])
VALUES
    (1, 201911, '2019-11-01 00:00:00', 50),
    (1, 201912, '2019-12-01 00:00:00', 50),
    (1, 202001, '2020-01-01 00:00:00', 50),
    (1, 202002, '2020-02-01 00:00:00', 50),
    (1, 202003, '2020-03-01 00:00:00', 50),
    (1, 202004, '2020-04-01 00:00:00', 50),
    (1, 202005, '2020-05-01 00:00:00', 50),
    (1, 202006, '2020-06-01 00:00:00', 25),
    (1, 202007, '2020-07-01 00:00:00', 50),
    (1, 202008, '2020-08-01 00:00:00', 50),
    (1, 202009, '2020-09-01 00:00:00', 15),
    (2, 201911, '2019-11-01 00:00:00', 50),
    (2, 201912, '2019-12-01 00:00:00', 50),
    (2, 202001, '2020-01-01 00:00:00', 25),
    (2, 202002, '2020-02-01 00:00:00', 50),
    (2, 202003, '2020-03-01 00:00:00', 45),
    (2, 202004, '2020-04-01 00:00:00', 45),
    (2, 202004, '2020-04-10 00:00:00', 20),
    (2, 202005, '2020-05-01 00:00:00', 25),
    (3, 202004, '2020-04-01 00:00:00', 50),
    (3, 202005, '2020-05-01 00:00:00', 50),
    (3, 202006, '2020-06-01 00:00:00', 50),
    (3, 202007, '2020-07-01 00:00:00', 50),
    (3, 202008, '2020-08-01 00:00:00', 50),
    (3, 202009, '2020-09-01 00:00:00', 300)
;

I also have a calendar table which I am using that returns data like this:
CREATE TABLE calendar
    ([CalendarPeriod] int, [CalendarDate] datetime)
;

INSERT INTO calendar
    ([CalendarPeriod], [CalendarDate])
VALUES
    (202004, '2020-04-30 00:00:00'),
    (202005, '2020-05-31 00:00:00'),
    (202006, '2020-06-30 00:00:00'),
    (202007, '2020-07-31 00:00:00'),
    (202008, '2020-08-31 00:00:00'),
    (202009, '2020-09-30 00:00:00')
;

I am hoping to get an output where each CalendarPeriod from calendar is paired with itself and the 5 preceding months. CalendarPeriod acts as a reporting period and the rolling period for each month is 6 months. My end goal is to join payment_amounts via payment_month to each reporting period where payment_month equals one of the rolling months in a reporting period.
Edit:
My expected output for just months and rolling periods would look like the table below. I can manipulate the table to aggregate by CalendarPeriod if needed.
+----------------+----------------+----------------+
| CalendarPeriod | rolling_period | rolling_amount |
+----------------+----------------+----------------+
| 202004         | 201911         | 100            |
+----------------+----------------+----------------+
| 202004         | 201912         | 100            |
+----------------+----------------+----------------+
| 202004         | 202001         | 75             |
+----------------+----------------+----------------+
| 202004         | 202002         | 100            |
+----------------+----------------+----------------+
| 202004         | 202003         | 95             |
+----------------+----------------+----------------+
| 202004         | 202004         | 165            |
+----------------+----------------+----------------+
| 202005         | 201912         | 100            |
+----------------+----------------+----------------+
| 202005         | 202001         | 75             |
+----------------+----------------+----------------+
| 202005         | 202002         | 100            |
+----------------+----------------+----------------+
| 202005         | 202003         | 95             |
+----------------+----------------+----------------+
| 202005         | 202004         | 165            |
+----------------+----------------+----------------+
| 202005         | 202005         | 125            |
+----------------+----------------+----------------+
| 202006         | 202001         | 75             |
+----------------+----------------+----------------+
| 202006         | 202002         | 100            |
+----------------+----------------+----------------+
| 202006         | 202003         | 95             |
+----------------+----------------+----------------+
| 202006         | 202004         | 165            |
+----------------+----------------+----------------+
| 202006         | 202005         | 125            |
+----------------+----------------+----------------+
| 202006         | 202006         | 75             |
+----------------+----------------+----------------+
| 202007         | 202002         | 100            |
+----------------+----------------+----------------+
| 202007         | 202003         | 95             |
+----------------+----------------+----------------+
| 202007         | 202004         | 165            |
+----------------+----------------+----------------+
| 202007         | 202005         | 125            |
+----------------+----------------+----------------+
| 202007         | 202006         | 75             |
+----------------+----------------+----------------+
| 202007         | 202007         | 100            |
+----------------+----------------+----------------+
| 202008         | 202003         | 95             |
+----------------+----------------+----------------+
| 202008         | 202004         | 165            |
+----------------+----------------+----------------+
| 202008         | 202005         | 125            |
+----------------+----------------+----------------+
| 202008         | 202006         | 75             |
+----------------+----------------+----------------+
| 202008         | 202007         | 100            |
+----------------+----------------+----------------+
| 202008         | 202008         | 100            |
+----------------+----------------+----------------+
| 202009         | 202004         | 165            |
+----------------+----------------+----------------+
| 202009         | 202005         | 125            |
+----------------+----------------+----------------+
| 202009         | 202006         | 75             |
+----------------+----------------+----------------+
| 202009         | 202007         | 100            |
+----------------+----------------+----------------+
| 202009         | 202008         | 100            |
+----------------+----------------+----------------+
| 202009         | 202009         | 315            |
+----------------+----------------+----------------+

-- Alternate:
+----------------+----------------+
| CalendarPeriod | rolling_amount |
+----------------+----------------+
| 202004         | 635            |
+----------------+----------------+
| 202005         | 660            |
+----------------+----------------+
| 202006         | 635            |
+----------------+----------------+
| 202007         | 660            |
+----------------+----------------+
| 202008         | 660            |
+----------------+----------------+
| 202009         | 880            |
+----------------+----------------+

Thanks in advance for you help.

A: As I understand your question, you want a rolling sum of payments for the last 6 months for each period.
I don't think that you really need the intermediate dataset that you are showing to achieve this goal. You can just use window functions:
select c.calendarperiod,
    sum(p.payment_amount) month_amount,
    sum(sum(p.payment_amount)) over(
        order by c.calendarperiod
        rows between 5 preceding and current row
    ) rolling_6_month_amount
from calendar c
left join payments p
    on  p.payment_date >= datefromparts(year(c.calendardate), month(c.calendardate), 1)
    and p.payment_date <  dateadd(day, 1, c.calendardate)
group by c.calendarperiod

The query starts from the calendar, and bring the corresponding payments for each month - I adjusted the date interval, in case there are payments within the very last day of the month. Then, we aggregate by period. Finally, we can use window functions to look back over the last 5 periods and sum the corresponding payments.


text:
Q: median() returns 0 when used with tapply() I have a dataframe D like this:
Number         Date Number2
     0   2015-11-01    1123
     4   2015-11-01    1175
    50   2015-11-01    1139
   122   2015-11-02    1105
    45   2015-11-02    1143
    99   2015-11-02    1123

of course, it has many more observations (around 17000), and some are NA. The column Date is a factor. I want to calculate the median of the column Number by day (using the column Date), for this i use the tapply function, like this:
tapply(D$Number, D$Date, median)

this outputs something like this:
2012-10-01 2012-10-02 2012-10-03 2012-10-04 2012-10-05 2012-10-06
        NA          0          0          0          0          0
2012-10-12 2012-10-13 2012-10-14 2012-10-15 2012-10-16 2012-10-17
         0          0          0          0          0          0
2012-10-23 2012-10-24 2012-10-25 2012-10-26 2012-10-27 2012-10-28
         0          0          0          0          0         NA

This is the problem, why the zeros? I've already calculated the sum and the mean in the same way and it works perfectly, but when i try for the median all the calculations result in 0 or NA, even if i add na.rm = TRUE to the tapply function the result is the same. I really don't understand why this.
If i subset the dataframe "manually" (like D[D$Date=='2012-10-01', 1]) and apply the median function to that subset i get the correct result; however, I don't want to do this given the size of the dataframe.
Could somebody explain me what I'm doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Postfix Relay Servers behind ELB in AWS I have three Relay Servers in a Cluster Sitting behind and ELB. The internal servers on the network connect to the ELB and send their SMTP traffic. The traffic is then routed to the Relay Server which is then sent to the destination Relay Servers. I've been able to confirm this functionality through TelNet, however when I changed the postfix configuration to point to the ELB in the main.cf, I am not able to connect to the Relay Servers. I'm not sure what the issue is: Below is my configuration in main.cf:
# RR: Mon Apr 29, 2013 => added 72.172.71.2/32 to support (LA) Duo VPN
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
mail_owner = postfix
myhostname = test.com
mydomain = test.com
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost

smtpd_delay_reject = yes
smtpd_helo_required = yes
soft_bounce = no
strict_rfc821_envelopes = yes
local_header_rewrite_clients = permit_mynetworks
smtp_generic_maps = pcre:/etc/postfix/generic
unknown_local_recipient_reject_code = 550
broken_sasl_auth_clients = no
smtpd_sasl_application_name = smtpd
smtpd_sasl_auth_enable = no
smtpd_sasl_local_domain =
smtpd_sasl_security_options = noanonymous
#tls_random_source = dev:/dev/urandom
#smtpd_tls_security_level = may
mailbox_size_limit = 102400000
message_size_limit = 51200000
queue_minfree = 76800000
smtpd_client_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unknown_client
smtpd_helo_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_invalid_hostname,
  reject_non_fqdn_hostname
smtpd_sender_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unlisted_sender,
  reject_non_fqdn_sender,
  reject_unknown_sender_domain
smtpd_recipient_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unlisted_recipient,
  reject_non_fqdn_recipient,
  reject_unauth_destination,
  reject_unknown_recipient_domain
# check_recipient_access hash:/etc/postfix/filtered_domains
smtpd_data_restrictions =
  permit_mynetworks,
  reject_unauth_pipelining,
  permit_sasl_authenticated
smtpd_end_of_data_restrictions =
unknown_local_recipient_reject_code = 550
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
debug_peer_level = 2
debugger_command =
  PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
  xxgdb $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.3.3/samples
readme_directory = /usr/share/doc/postfix-2.3.3/README_FILES
#inet_protocols = all
postscreen_upstream_proxy_protocol = haproxy

master.cf:
    #
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master").
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (yes)   (never) (100)
# ==========================================================================
smtp      inet  n       -       n       -       -       smtpd
submission inet n       -       n       -       -       smtpd
#  -o smtpd_enforce_tls=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#smtps     inet  n       -       n       -       -       smtpd
#  -o smtpd_tls_wrappermode=yes
#  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
#628      inet  n       -       n       -       -       qmqpd
pickup    fifo  n       -       n       60      1       pickup
cleanup   unix  n       -       n       -       0       cleanup
qmgr      fifo  n       -       n       300     1       qmgr
#qmgr     fifo  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       n       1000?   1       tlsmgr
rewrite   unix  -       -       n       -       -       trivial-rewrite
bounce    unix  -       -       n       -       0       bounce
defer     unix  -       -       n       -       0       bounce
trace     unix  -       -       n       -       0       bounce
verify    unix  -       -       n       -       1       verify
flush     unix  n       -       n       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
smtp      unix  -       -       n       -       -       smtp
# When relaying mail as backup MX, disable fallback_relay to avoid MX loops
relay     unix  -       -       n       -       -       smtp
        -o fallback_relay=
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       n       -       -       showq
error     unix  -       -       n       -       -       error
discard   unix  -       -       n       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       n       -       -       lmtp
anvil     unix  -       -       n       -       1       anvil
scache    unix  -       -       n       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}
#
# The Cyrus deliver program has changed incompatibly, multiple times.
#
old-cyrus unix  -       n       n       -       -       pipe
  flags=R user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -m ${extension} ${user}
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
cyrus     unix  -       n       n       -       -       pipe
  user=cyrus argv=/usr/lib/cyrus-imapd/deliver -e -r ${sender} -m ${extension} ${user}
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=foo argv=/usr/local/sbin/bsmtp -f $sender $nexthop $recipient

This is what I see in the relay server maillog:
AED0D6093E: message-id=<20170420163035.AED0D6093E<test.com>

And on the mail client it's saying undeliverable. Please let me know if anyone understands what might be going on.

A: I was able to make Postfix see client IP addresses behind an NLB, by checking "Preserve client IP addresses" in the target group attributes. No need to use HAproxy or activate proxy protocol v2.

A: If you want to using postfix behind ELB you must using postscreen and haproxy to make it works. Add the following line to the configuration :
main.cf :
postscreen_upstream_proxy_protocol = haproxy

master.cf:
smtp  inet  n  —  —  —  1  postscreen
smtpd pass  —  —  —  —  —  smtpd

Also you need to change the configuration o fELB, here is the link for set ELB for postfix : https://medium.com/@signalnine/preserving-source-ip-running-postfix-behind-amazon-elastic-load-balancer-2a241b69681a


text:
Q: How to send query request without refresh? I'm working with Woocommerce plugin in Wordpress. When you click add to cart button all it does is add this to the end of the url ?add-to-cart=4689 like so "http://example.com/?add-to-cart=4689" So whatever item id is in the url query gets added to the cart.
However I don't want to do a page refresh each time so right now I'm using  In order to add the item to the cart, but not refresh the page.
Is there anyway to send that page load request to url "http://example.com/?add-to-cart=4689" without using an iframe?

A: This can only be done using javascript.
The following should work with vanilla javascript.
<script>
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://example.com/?add-to-cart=4689');
    xhr.onload = function() {
        if (xhr.status === 200) {
            //add code to render what needs to be rendered
        }
        else {
            alert('Request failed.  Returned status of ' + xhr.status);
        }
    };
    xhr.send();
</script>

The item will be added like this but I presume that you won't see it in your basket until after you refreshed your page or re-rendered the component.


text:
Q: Am I reading the multimeter uncertainty correctly? I am using a multimeter that has an uncertainty (from the manual) of 0.5% plus 5 digits in DC voltage measurements, 4V range.
I have a reading of 1.6172 V. That means an uncertainty of 0.508 V. Isn't that way too much? Like the true value is between 1.1092 V and 2.1252 V. It seems odd to me such a big range of measurement. Or am I misinterpreting what 5 digits means?
Thank you


text:
Q: Calculating the apparent area of a polygon from a view point I want to calculate the apparent area of a polygon from a view point. Say, you are looking at a 2 x 2 meters square from across, the apparent area for you would be 4 m2.
Now image the square is rotated somehow, then the apparent area would be smaller. To do this, I figured I could use the following logic:
V3_c (center of mass of the polygon)
V3_v (viewer's position)

*

*Construct a plane that goes through V3_v with the normal of (V3_c - V3_v).normalize()

*Project the polygon onto this plane and calculate the area

How can I do this in CGAL?

UPDATE:
Upon @mgimeno's suggestions I've used the following (almost pseudo) code.
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/centroid.h>

#include <iostream>
#include <vector>

#include "print_utils.h"

typedef CGAL::Exact_predicates_inexact_constructions_kernel  Kernel;
typedef CGAL::Polygon_with_holes_2<Kernel>                   Polygon_with_holes_2;
typedef Kernel::Point_2 Point_2;
typedef Kernel::Point_3                                      Point_3;
typedef Kernel::Plane_3 Plane_3;
typedef Kernel::Vector_3 Vector_3;
typedef Kernel::FT ValueType;
using namespace std;

int main(int argc, char* argv[])
{
  Point_3 viewer(0, 0, 0);
  cout << "Viewer: " << viewer << endl;

  Point_3 a(-5, -5, 5);
  Point_3 b(-5, -5, -5);
  Point_3 c(5, -5, -5);
  Point_3 d(5, -5, 5);
  cout << "Surface: " << a << ", " << b << ", " << c << ", " << d << endl;

  std::vector<Point_3> vertices;
  vertices.push_back(a);
  vertices.push_back(b);
  vertices.push_back(c);
  vertices.push_back(d);
  Point_3 center = CGAL::centroid(vertices.begin(), vertices.end(), CGAL::Dimension_tag<0>());
  cout << "Center of surface: " << center << endl;

  Vector_3 normal = center - viewer;
  Plane_3 plane(viewer, normal);
  cout << "Plane passing thorough viewer orthogonal to surface: " << plane << endl;

  Point_3 pa = plane.projection(a);
  Point_3 pb = plane.projection(b);
  Point_3 pc = plane.projection(c);
  Point_3 pd = plane.projection(d);

  cout << "Projected surface onto the plane: " << pa << ", " << pb << ", " << pc << ", " << pd << endl;

  Point_2 pa2 = plane.to_2d(pa);
  Point_2 pb2 = plane.to_2d(pb);
  Point_2 pc2 = plane.to_2d(pc);
  Point_2 pd2 = plane.to_2d(pd);

  cout << "to_2d of the projected plane: " << pa2 << ", " << pb2 << ", " << pc2 << ", " << pd2 << endl;
  std::vector<Point_2> vertices2;
  vertices2.push_back(pa2);
  vertices2.push_back(pb2);
  vertices2.push_back(pc2);
  vertices2.push_back(pd2);

  ValueType result;
  CGAL::area_2(vertices2.begin(), vertices2.end(), result);

  cout << "Area of to_2d'ed vertices: " << result << endl;
  return EXIT_SUCCESS;
}

The output is:
Viewer: 0 0 0
Surface: -5 -5 5, -5 -5 -5, 5 -5 -5, 5 -5 5
Center of surface: 0 -5 0
Plane passing thorough viewer orthogonal to surface: 0 -5 0 0
Projected surface onto the plane: -5 0 5, -5 0 -5, 5 0 -5, 5 0 5
to_2d of the projected plane: -5 1, -5 -1, 5 -1, 5 1
Area of to_2d'ed vertices: 20

I'm not sure how to_2d works but certainly not the way I hope it would. The computed area is 20 instead of the actual 100.
BTW, I've also begin to realize that this goal could be achieved by simple computing the angle between the viewing direction (V_c - V_v) and normal ofthe polyong. sin a * original_area should give the area.

A: To compute the centroid of your polygon you can use CGAL::centroid().
Then to construct your plane you can use the constructor of Plane_3 that takes a point and a normal.
After that you can project each point of your polygon using Plane_3::projection(), and then I'd propose to use to_2D() on those new points to get Point_2, and be able to use area_2().


text:
Q: pivot_wider when names_from are duplicated I need help pivoting data and then removing unnecessary rows. I ran a query in SQL that returned a rather large output (60 columns and 2 million rows). A lot of the rows are near duplicates, with the only unique value coming from a "diagnosis" column. I would like to pivot those to new columns and then remove the duplicates. The wrinkle is that my names_from column has duplicates. Here is an example
id <- c("1","1","1","2","2","2")
priority <- c("primary","secondary","tertiary","primary","primary","secondary")
diagnosis <- c("depression","anxiety","anorexia","depression","anxiety","ptsd")

data <- data.frame(id,priority,diagnosis)

id
priority
diagnosis

1
primary
depression

1
secondary
anxiety

1
tertiary
anorexia

2
primary
depression

2
primary
anxiety

2
secondary
PTSD

When I try to pivot_wider, person 2 has both depression and anxiety listed in "primary", but I want them in separate columns.
data2 <- pivot_wider(data,names_from=priority,values_from = diagnosis)

Here is what it is showing me:

id
primary
secondary
tertiary

1
depression
anxiety
anorexia

2
c("depression,"anxiety")
ptsd
NULL

So how can I get it to separate out depression and anxiety for person 2, ideally into something like primary_1, primary_2?

A: Create a sequence by 'id', 'primary' and then do the reshaping
library(dplyr)
library(stringr)
library(tidyr)
library(data.table)
data %>%
  mutate(priority = str_c(priority, '_', rowid(id, priority))) %>%
  pivot_wider(names_from = priority, values_from = diagnosis)

-output
# A tibble: 2 × 5
  id    primary_1  secondary_1 tertiary_1 primary_2
  <chr> <chr>      <chr>       <chr>      <chr>
1 1     depression anxiety     anorexia   <NA>
2 2     depression ptsd        <NA>       anxiety

Or another option is to return the list and then use unnest_wider on the list columns
data %>%
   pivot_wider(names_from = priority, values_from = diagnosis,
    values_fn = list) %>%
   unnest_wider(where(is.list), names_sep = "_")

-output
# A tibble: 2 × 5
  id    primary_1  primary_2 secondary_1 tertiary_1
  <chr> <chr>      <chr>     <chr>       <chr>
1 1     depression <NA>      anxiety     anorexia
2 2     depression anxiety   ptsd        <NA>

If we need to rename with 1, 2 only when the lengths are greater than 1, do the unnest separately after using unnest_wider
data %>%
   pivot_wider(names_from = priority, values_from = diagnosis,
    values_fn = list) %>%
   unnest_wider(where(~ is.list(.x) && max(lengths(.x)) > 1),
         names_sep = "_") %>%
   unnest(where(is.list))

-output
# A tibble: 2 × 5
  id    primary_1  primary_2 secondary tertiary
  <chr> <chr>      <chr>     <chr>     <chr>
1 1     depression <NA>      anxiety   anorexia
2 2     depression anxiety   ptsd      <NA>

If the data is really big, then dcast may be more efficient
dcast(setDT(data), id ~ paste0(priority,  "_", rowid(id, priority)),
   value.var = 'diagnosis')
Key: <id>
       id  primary_1 primary_2 secondary_1 tertiary_1
   <char>     <char>    <char>      <char>     <char>
1:      1 depression      <NA>     anxiety   anorexia
2:      2 depression   anxiety        ptsd       <NA>


text:
Q: How to setup bundle development environment (Eclipse Equinox Maven) I'am trying to setup eclipse environment to develop bundles (With maven-bundle-plugin-bnd)
and run & debug that bundles equinox from eclipse
I created sample bundles with org.apache.felix maven-bundle-plugin  and can  install and start that bundles from eclipse equinox,
but every time i need to run "install file:C:\path\bundle1.jar","install file:C:\path\bundle2.jar"  which causes pain. i searched for run configuration but it only intalls and starts (plugin) projects in workspace not maven projects.
What i have done is create maven project and add dependencies(bundle1,bundle2 etc..)  and added maven-dependency-plugin to copy all depended bundles in one folder (another problem is equinox use "_" delimeter to determine version of bundles but maven uses "-" as delimeter) if i do not strip version in standalone equinox application i need to  give version of bundle in config.ini file but i dont want that,  is this proper way to solve this problem?
<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${bundleDirectory}</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>true</overWriteSnapshots>
              <stripVersion>true</stripVersion>
            </configuration>
          </execution>
        </executions>
      </plugin>

To sum up , i have bundles in folder, which is created with org.apache.felix maven-bundle-plugin , how can i run and debug them from eclipse?

A: I wouldn't say this is a "proper" solution, but it may work for you.
The antrun plugin can be used to modify the dependencies to replace the final hyphen with an underscore, so the dependency plugin doesn't need to strip the version.
My regex is rusty, but from a little testing the following configuration appears to apply the required name change to the files in the bundleDependency directory.
<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
    <execution>
      <id>copy-dependencies</id>
      <phase>package</phase>
      <goals>
        <goal>copy-dependencies</goal>
      </goals>
      <configuration>
        <outputDirectory>${bundleDirectory}</outputDirectory>
        <overWriteReleases>false</overWriteReleases>
        <overWriteSnapshots>true</overWriteSnapshots>
      </configuration>
    </execution>
  </executions>
</plugin>
<plugin>
  <artifactId>maven-antrun-plugin</artifactId>
  <version>1.3</version>
  <executions>
    <execution>
      <phase>package</phase>
      <configuration>
        <tasks>
          <!-- move within same directory is preferred method for a rename-->
          <move todir="${bundleDirectory}">
            <fileset dir="${bundleDirectory}"/>
            <mapper type="regexp" from="([a-zA-Z0-9\.-]+)(-)([0-9\.]+.jar)"
              to="\1_\3"/>
          </move>
        </tasks>
      </configuration>
      <goals>
        <goal>run</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
   <dependency>
     <groupId>ant</groupId>
     <artifactId>ant-nodeps</artifactId>
     <version>1.6.5</version>
   </dependency>
  </dependencies>
</plugin>

A: I wrote a tool called auto-builder (http://code.google.com/p/auto-builder).  It introspects PDE-based projects and generates Ant build files; it supports transitive closure over dependencies and all that jazz.
I posted a write-up: http://empty-set.net/?p=9.  I wrote it because the Maven tools I played with, when integrated with PDE, didn't "just work."  Basically, I wanted to do coding in PDE and have a Hudson-based CI without any fuss in between.
Generating Ant files is nice because it gives you all the benefits of a declarative build tool, but it leaves you with a procedural description of what it is doing.
I am looking for more PDE-based projects to test it on.  There are a couple RFC-0112 Bundle repositories around, and I have some code for downloading dependencies.  If anyone is interested, then I could integrate dependencies download with auto-builder.


text:
Q: WSO2 Identity server - SAML - redirection page keeps loading forever instead of taking me to the application I am implementing the single sign on functionality using WSO2 identity server as the identity provider, PHP-SimpleSamlPhp package and Drupal following this article https://wso2.com/library/articles/2014/10/wso2-identity-server-single-sign-on-with-drupal/
Everything has been setup successfully as below.

*

*Access the drupal app login page and click on the federated link

*This redirects you to the WSO2 IS login page as expected

*You enter the credentials (stored in WSO2) and click login

*The page redirects you to the samlsso URL https://localhost:9443/samlsso?SAMLRequest=fZJNT....

*This page keeps loading forever and the SAMLRequest value in the above URL keeps changing.

Logs

*

*This shows up at the point 2 above

TID: [-1234] [] [2020-04-12 18:48:14,334] [http://localhost/drupal-8.8.5/en/saml_login]  INFO {org.opensaml.core.config.InitializationService} - Initializing OpenSAML using the Java Services API

*

*This shows up at point 5 above

TID: [-1234] [2020-04-12 18:53:06,793] [http://localhost/drupal-8.8.5/en/saml_login]  INFO {AUDIT_LOG} - Initiator=wso2.system.user Action=Get-User-List Target=null Data={"Claim Value":"ebdefe27-3912-4502-ad48-5b1a2ee30224","Users":["wickrema"],"Claim":"http://wso2.org/claims/userid"} Outcome=Success

TID: [-1234] [2020-04-12 18:53:06,793] [http://localhost/drupal-8.8.5/en/saml_login]  INFO {AUDIT_LOG} - Initiator=wso2.system.user Action=Get-User-Claim-Values Target=wickrema Data={"Claims":{"http://wso2.org/claims/username":"wickrema","http://wso2.org/claims/userid":"ebdefe27-3912-4502-ad48-5b1a2ee30224","http://wso2.org/claims/created":"2020-04-11T20:53:00.424Z","http://wso2.org/claims/role":"Internal/everyone","http://wso2.org/claims/fullname":"wickrema","http://wso2.org/claims/modified":"2020-04-11T20:53:33.922Z","http://wso2.org/claims/emailaddress":"wickrema@abc.com","http://wso2.org/claims/lastname":"Edirisooriya","http://wso2.org/claims/givenname":"Wickrema","http://wso2.org/claims/resourceType":"User","http://wso2.org/claims/userprincipal":"wickrema"}} Outcome=Success

TID: [-1234] [2020-04-12 18:53:06,794] [http://localhost/drupal-8.8.5/en/saml_login]  INFO {AUDIT_LOG} - Initiator : wickrema | Action : Login | Target : ApplicationAuthenticationFramework | Data : { "ContextIdentifier" : "4f08f619-e1dd-43be-8119-6cc7ea7238ee","AuthenticatedUser" : "wickrema","AuthenticatedUserTenantDomain" : "carbon.super","ServiceProviderName" : "simplesamlphp","RequestType" : "samlsso","RelyingParty" : "simplesaml","AuthenticatedIdPs" : "eyJ0eXAiOiJKV1QiLCAiYWxnIjoibm9uZSJ9.eyJpc3MiOiJ3c28yIiwiZXhwIjoxNTg2NzA2Nzg2NzcxMzAwMCwiaWF0IjoxNTg2NzA2Nzg2NzcxLCJpZHBzIjpbeyJpZHAiOiJMT0NBTCIsImF1dGhlbnRpY2F0b3IiOiJCYXNpY0F1dGhlbnRpY2F0b3IifV19." } | Result : Success

Images

*

*More from the HTTP logs

0:0:0:0:0:0:0:1 - - [12/Apr/2020:20:04:20 +0300] GET /samlsso?SAMLRequest=fZJRT4MwEMe%2FCuk7a2EdyxpYMrcYl0wlG%2Frgi%2BlokSalxV5x%2Bu0FpnG%2B7KnN3f3%2B%2F7trU%2BCNbtmq87XZy%2FdOgg8%2BG22AjYkMdc4wy0EBM7yRwHzJDqv7HYsnhLXOeltajS6Q6wQHkM4ra1Cw3WTolc5oRZOjmJMpp1WViGRBovmUz%2BKSCCGiOJmRhSA0Iih4lg56MkO9UI8DdHJrwHPj%2BxCJSUhoGMVFNGeEspi8oGDTT6MM9yNVe98Cw1jbkuvagmcLSqd46BnAomD129raGuga6Q7SfahSPu13Z%2FiSxaCaVssBxo0VXX8dlTC04xmHvIRJW7f4BDYOoUVB%2FrOsG2WEMm%2FX93Q8FwG7K4o8zB8PBVqmgzAb53bLP%2F8UX8bT83s%2B9IrbTW61Kr%2BCW%2Bsa7q8bDhElwmosZd5xA0oa369Fa3taO8m9zJB3nUR4ebb8%2F2uW3w%3D%3D&RelayState=http%3A%2F%2Flocalhost%2Fdrupal-8.8.5%2Fen%2Fsaml_login HTTP/1.1 200 6020 - Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36 Edg/80.0.361.111 0.043

*

*Below is the authsources and identity provider configuration

*

*When I did a cookies check as suggested in the comments, this is what I found.

A: Adding answer as steps as requested
By design, domain names must have at least two dots; otherwise the browser will consider them invalid. (See reference on http://curl.haxx.se/rfc/cookie_spec.html)
When working on localhost, the cookie domain must be omitted entirely.
Modify the file /etc/hosts by adding the following entry
localhost.com 127.0.0.1
Then use the domain as localhost.com
For better cookie tracing in your browser, also follow the steps in the link https://brainshark.zendesk.com/hc/en-us/articles/205043644-Performing-a-Browser-Trace-Chrome


text:
Q: Populating property of type Dictionary<> items from within razor view Is there a way to pass values to a property of type Dictionary<> from within a view using Html.BeginForm helper method?
Model
public class LogicTest
{
    public int LogicTestID { get; set; }
    public string SingleString { get; set; }
    public Dictionary<string, string> SimpleDictionary { get; set; }
    public Dictionary<string, Dictionary<string, string>> NestedDictionary { get; set; }
}

ATM I'm trying something like this (obviously without much success)
@model TestNamespace.Models.LogicTest

@using (Html.BeginForm("CreateLogicTest", "LogicTest"))
{
    @Html.LabelFor(n => n.SingleString)

    @Html.EditorFor(n => n.SingleString)

    @Html.LabelFor(n => n.SimpleDictionary)

    @Html.Label("Simple Dictionary Item 1")
    @Html.EditorFor(n => n.SimpleDictionary["key1"])
    @Html.Label("Simple Dictionary Item 2")
    @Html.EditorFor(n => n.SimpleDictionary["key2"])
    @Html.Label("Simple Dictionary Item 3")
    @Html.EditorFor(n => n.SimpleDictionary["key3"])

    <button type="submit">Submit</button>
}

A: You have to create an instance of your class within your controller action. Then return a view with that class.


text:
Q: jQuery form validation: Define container for errors I'm using the jQuery validation plugin, to validate my form. It works (places the error messages, next to the invalid input, which screws up my design), but I'd like to specify the error-container for every input field. I found the errorLabelContainer, but this puts all errors in one container.
Let's say, I have 2 inputs, one with id name and one with firstname. And let's also assume  I have 2 error spans, with ids errorName and errorFirstname. How do I tell jQuery to write the validation error for name into the span with the id errorName.
This is my current jQuery:
$("#form").validate({
    errorLabelContainer: "#errors",
        rules: {
            name: {
                required: true
            },
            firstname: {
                required: true
            }
        },
        messages: {
            name: {
                required: "Enter name"
            },
            firstname: {
                required: "Enter firstname"
            }
        }
    })

A: I think the errorPlacement option suits your needs:

Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.

You can determine the element you want to place the error in based on the invalid element:
$("#form").validate({
    rules: {
        name: {
            required: true
        },
        firstname: {
            required: true
        }
    },
    messages: {
        name: {
            required: "Enter name"
        },
        firstname: {
            required: "Enter firstname"
        }
    },
    errorPlacement: function ($error, $element) {
        var name = $element.attr("name");

        $("#error" + name).append($error);
    }
});

Example: http://jsfiddle.net/R3aEQ/


text:
Q: Aggregating data to a variable with NAs I have the following issue:
I have a panel data set that contains a unique identifier (area), the respective date (year), a dummy for election number (election.dummy; 1 = first election in the panel, 2 = second election in the panel), and controls (e.g. gdp). As the election takes place only every four years, I would like to collapse the controls, with the mean of the previous years and the election year to be assigned to the row with the election dummy (see example). Any ideas how to do that?
Here is a simplified example:
Original dataset:
area <- c(rep(1:2, each = 6))
year <- rep(2001:2006,2)
election.dummy <- c(NA, 1, NA, NA, NA, 2, NA, 1, NA, NA, NA, 2)
gdp <- c(2,4,1,3,1,5,3,5,1,7,3,5)
d2 <- data.frame(area,year,election.dummy,gdp)

Desired outcome:
area <- c(rep(1:2, each = 2))
year <- c(2002, 2006, 2002, 2006)
election.dummy <- c(1, 2, 1, 2)
gdp <- c(3,2.5,4,4)
d_aggregated <- data.frame(area,year,election.dummy,gdp)

A: One option would be to create a grouping variable by the occurence of NA in 'election.dummy' and also group by 'area', then mutate to replace the 'gdp' with the mean of 'gdp', filter out the rows having NA elements in 'election.dummy' and select the columns of interest after ungrouping
library(tidyverse)
d %>%
  group_by(area, grp = cumsum(is.na(election.dummy))) %>%
  mutate(gdp = mean(gdp)) %>%
  filter(!is.na(election.dummy)) %>%
  ungroup %>%
  select(-grp)
# A tibble: 4 x 4
#   area  year election.dummy   gdp
#  <int> <int>          <dbl> <dbl>
#1     1  2002              1     3
#2     1  2004              2     2
#3     2  2002              1     3
#4     2  2004              2     4

Update
With the updated dataset
d2 %>%
    group_by(area) %>%
    mutate(grp = election.dummy) %>%
    fill(grp, .direction = "up") %>%
    group_by(grp, add = TRUE) %>%
    mutate(gdp = mean(gdp)) %>%
    filter(!is.na(election.dummy)) %>%
    ungroup %>%
    select(-grp)
# A tibble: 4 x 4
#   area  year election.dummy   gdp
#  <int> <int>          <dbl> <dbl>
#1     1  2002              1   3
#2     1  2006              2   2.5
#3     2  2002              1   4
#4     2  2006              2   4


text:
Q: How to sort an array that is using map method by props in Javascript/React I have an array called products that is using the map method to list all the elements inside it and i am trying to sort those elements by the price prop. I've tried all types of sort methods and functions but i can't get it to work.
JS
const recentprods = products.map(prod => {
  return <TableRow name={prod.name} price={prod.price} />
})

I tried:
const recentprods = products.map(prod => {
  return <TableRow name={prod.name} price={prod.price} />
}).sort((a,b) => a.price  a.price - b.price)
      // if you want to change the sorting direction: b.price - a.price
  .map(prod => {
     return <TableRow name={prod.name} price={prod.price} />
  });

A: So, yeah basically you need to sort it first and then map it, I've build an example for you:
constructor(props) {
    super(props);

    this.state = {
      products: [
        { name: 'Product 2', price: 2 },
        { name: 'Product 6', price: 6 },
        { name: 'Product 1', price: 1 },
        { name: 'Product 3', price: 3 },
        { name: 'Product 7', price: 7 },
        { name: 'Product 4', price: 4 },
        { name: 'Product 8', price: 8 },
        { name: 'Product 5', price: 5 },
      ],
    };
  }

  render() {
    return (

ONLY MAPPED

        {this.state.products.map((prod, i) => {
          return (

              {prod.name} and its price: {prod.price}

          );
        })}

BOTH SORTED AND MAPPED.

        {this.state.products
          .sort((first, second) => {
            return first.price > second.price ? 1 : -1;
          })
          .map((prod, i) => {
            return (

                {prod.name} and its price: {prod.price}

            );
          })}

    );
  }

Here you can check out the output

A: You want to normalize, sort, and otherwise alter your data as you see fit before applying it to React components. In the following case, the products array holds individual objects each with a price property, so sort the products array beforehand then map over the items.
The .sort method sorts the elements of an array in place and returns the sorted array. The chained .map method will iterate over the sorted array in the order prescribed.
I believe the following is a valid solution. Note that price is seen as a number. If it isn't, the sort may not work correctly.
const recentprods = products
  .sort((a, b) => a.price - b.price)
  .map(item => <TableRow name={item.name} price={item.price} />);

A: consider we have an array of objects with name and price properties.
const Products =  [
{name:"p1",price: 5},
{name:"p2",price: 3},
{name:"p3",price: 2},
{name:"p4",price: 7},

]
We need to sort the Products array in ascending order by using its price property.
console.log(Products.sort((a,b) =>  a.price-b.price )); // descending b.price-a.price

output - >

[
  {name: "p3", price: 2},
  {name: "p2", price: 3},
  {name: "p1",  price: 5},
  {name: "p4", price: 7}
]

Now you can call map function with jsx element you want to add
Products.sort((a,b) =>  a.price-b.price ).map(data => {
   return <TableRow name={prod.name} price={prod.price} />;
});

PS: YOU can use this function directly in your code or use a helper function this way you make sure its sorted jsx.


text:
Q: UV LED operating above Designed Voltage Hazard? I have a 5mm High Brightness UV Led that I bought from Radio Shack that states
Wavelength 405nm ( typ)
View angle 20 Degrees
FW current 20mA
FW supply 3.3V ( typical), 4.0V (max.)
part # 276-0014 pkg. of two
I have put this Led in a key chain light that has two 3V batteries in series making 6V output to the LED. 2V over Max. Will this change the wavelength of the led and intensity ? Is it hazardous to the eyes looking directly at it from a few feet away or looking at its reflection off objects with unprotected eyes. Thanks
Light has a purple violet tone

A: LEDS need a series resistance to control the current passed through them. The resistance 'drops' the excess voltage. Without that even a slight over-voltage will cause current to exceed the rating, and destroy the LED. I have disassembled some keychain lights. The better ones have a resistance or even an electronic current control chip, but cheap ones rely on the tiny batteries having enough internal resistance to limit the current to a value safe for the LED.
If your light is one of these, the LED will probably be over-run for the first few minutes of operation, until the batteries deteriorate and reduce their available current. Overrunning a LED tends to make the emission spectrum broader, with a slightly longer dominant wavelength.
The LED will emit a band of wavelengths, with the highest output being at 405nm, which is visible violet light. (Most of the inexpensive so-called UV leds are actually visible violet emitters, which have an emission spectrum that may include some near-UV). Both the UV and visible violet will excite fluorescent or phosphorescent materials. Visible violet and near-ultraviolet light have slight tanning effects on skin, and are suggested to be involved in premature ageing of skin. Those wavelengths are also have some germicidal and photochemical effect, so are potentially harmful to unprotected living tissue, like eyes. However, sunlight contains a significant amount of 405nm radiation, so limited or low-intensity exposure is not considered hazardous. This type of LED emits so much visible light that discomfort and blinking is likely to prevent excessive eye exposure at close range. At a metre or more distance the hazard is negligible. Prolonged close exposure might eventually cause injury.


text:
Q: Adding postgresql repo to ubuntu 22.04 via ansible fails From the following 2 tasks
- name: Add key for Postgres repo
  apt_key:
    url: https://www.postgresql.org/media/keys/ACCC4CF8.asc
    state: present
  become: true

- name: Add Postgres repo to sources list
  apt_repository:
    repo: 'deb http://apt.postgresql.org/pub/repos/apt/ ubuntu-pgdg main'
    state: present
  become: true

the second one fails as follows:
TASK [common : Add Postgres repo to sources list] ******************************
fatal: [master-node]: FAILED! => {"changed": false, "msg": "apt cache update failed"}

Why is that, given I am sudo-ing to execute it?

A: The third field of an apt repository in the list file should be the codename of your distribution, not the distribution itself:

The sources.list man page specifies this package source format:
deb uri distribution [component1] [component2] [...]

and gives an example:
deb https://deb.debian.org/debian stable main contrib non-free

The distribution part (stable in this case) specifies a subdirectory in $ARCHIVE_ROOT/dists. It can contain additional slashes to specify subdirectories nested deeper, eg. stable/updates. distribution typically corresponds to Suite or Codename specified in the Release files.

Source: https://wiki.debian.org/DebianRepository/Format#Overview
Example of the Release file, containing the codename:
$ head -n 5 /etc/os-release
PRETTY_NAME="Ubuntu 22.04.1 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy

If you don't want to hardcode it, this can be easily achieved with the help of Ansible facts:
- name: Add Postgres repo to sources list
  apt_repository:
    repo: >-
      deb http://apt.postgresql.org/pub/repos/apt/
      {{ ansible_distribution_release }}-pgdg main
    state: present
  become: true

Which presuppose that you, at least, gather the minimal facts, e.g.:
- hosts: localhost
  gather_subset:
    - min

Or that you gather everything, i.e.: that you have no gather_facts: false, at the play level.


text:
Q: separating `multinom` estimations by response (nnet package) in R In a multinomial logistic regression, one uses a set of covariates (x1, x2, ... xn)  to predict the value of a discrete variable y that, for instance,  can take the values of "outcome a", "outcome b", and "outcome c". In R, the most popular way to fit a multinomial logit is to use the multinom function under the nnet package.
When running model <- multinom(outcome ~ x1 + x2 + x3, data=data),
summary(model) would always present the estimations of each outcome together:
Coefficients:
               (Intercept)          x1           x2             x3
outcome b       0.7990265   -0.9426088    0.2295875    -0.01346151
outcome c       0.6516952   -1.0174237    0.3367977    -0.43912425

My question is: how do we present statistical estimations that predict "outcome b" and "outcome c" (assuming "a" is the base category) separately?
Ideally, I would like to use stargazer() and present one coefficient table for outcome b, and another table for outcome c, any suggestions are appreciated!

A: Convert the Coefficients table into data frame and then delete/remove not needed rows maybe?
Like in the following example:
lmfit <- lm(mpg ~ wt + cyl, mtcars)
ab = summary(lmfit)
bc = ab$coefficients
bc = as.data.frame(bc)

wt = bc[c(-1, -3), ]
wt


text:
Q: Loopy newcommand causes hanged processing By a too quick search/replace of "mathcal" by "mc" I ended up with a loopy or recursive statement like
\newcommand{\mc}{\mc}

It seems to cause the compilation of my document to hang. Is this a known bug? (Why has it not been fixed?)

A: The declaration \newcommand{\mc}{\mc} ultimately becomes, in terms of TeX primitives,
\long\def\mc{\mc}

where \long is irrelevant for the case in discussion.
You have to consider that TeX doesn't interpret in any way the replacement text of a macro when it stores the definition for it. It's a necessary feature, because when we expand a macro, we want that the macros in the replacement text use their current meaning, not what was valid at definition time, when they even need not be defined!
To make a silly example, consider the macro definition
\newcommand{\mybreak}{BREAK\\}

In LaTeX, the macro \\ changes its meaning in several occasions; it means something at the outer level, something else when a declaration such as \centering or \raggedright is in force and has a very different meaning when inside array, tabular or tabbing.
This is wanted! The user has to know just that \\ causes a line break. Then \mybreak can be used in any situation where \\ can be given, because the \\ token in the replacement text will be interpreted (expanded and executed) at call time.
Here's an example from the TeXbook:
\def\hex{{\count0=\n \divide\n by16
  \ifnum\n>0 \hex\fi \count2=\n \multiply\count2 by-16
  \advance\count0 by\count2 \hexdigit}}
\def\hexdigit{\ifnum\count0<10 \number\count0
  \else\advance\count0 by-10 \advance\count0 by`A \char\count0 \fi}

The token \n is supposed to be a count register. As you see, the macro \hex has a replacement text calling \hex itself; however at every call the value of \n will decrease, so eventually the call of \hex, which happens in the true branch of a conditional, will not take place and the macro's work will come to a happy ending.
Thus, a simplistic check that the replacement text of a macro doesn't contain the macro itself can't be implemented, because it would make recursion much more difficult, if not impossible.
This of course has a price: your definition causes TeX, when it finds \mc to replace \mc with \mc, which then it replaces with \mc… Bingo! Infinite loop. The program doesn't hang: it's just dutifully replacing a token with itself without using up resources in the computer; no error will be raised, because there's nothing wrong, from the point of view of the machine, which just follows the rules.
A different case would be
\newcommand{\mc}{(\mc)}

Now at the first call of \mc some part of TeX's memory would fill up, in this case the "input stack", which is assigned a size of 5000 by TeX Live 2013 (simultaneous input sources): the expansion of \mc pushes the first ( on the stack while expanding \mc, which pushes ( on the stack while expanding \mc… Another infinite loop, but this one fills the memory.
Assuming \mc is originally defined as a parameterless macro, adding parentheses to either end of its replacement text can be accomplished by
\expandafter\def\expandafter\mc\expandafter{\expandafter(\mc)}

because the chain of \expandafter's will put a finger inside the replacement text before the definition is performed. In this case, however, the new replacement text will not contain \mc (assuming it didn't in the original definition).
An equivalent construction would be
\edef\mc{(\unexpanded\expandafter{\mc})}

but this would take us too far (it need e-TeX, so it's not available with Knuth's TeX).

A: It is possible to define a macro in terms of itself.  As mentioned in the comments, you need to be careful.  The problem with \newcommand\mc{\mc} does not occur when it's defined but when you first try to use it, at which point, if left as is, it will recursively call itself.  Sometimes this is the behavior you want.
But sometimes you want something else, in which case you can use one of the powerful \edef and \xdef to create what you want.
Here's a completely trivial example which illustrates building a tabular environment from a list of elements.  The content of the tabular environment is built up from what was previously defined:  in other words \ae@tabular@content is defined in terms of itself, but precautions are taken not to expand too much (hence the use of tools from etoolbox.
\documentclass{article}
\usepackage{etoolbox}
\usepackage{pgffor}

\makeatletter
\def\ae@tabular@content{}
\def\ae@empty@content{}
\def\aebuildtabular#1{%%
  \def\ae@tabular@content{}%%
  \foreach \myx/\myy in {#1}
  {\ifx\ae@tabular@content\ae@empty@content
    \xdef\ae@tabular@content{\expandonce\myx & \myy }%%
   \else
    \xdef\ae@tabular@content{\expandonce\ae@tabular@content \noexpand\\ \expandonce\myx & \myy }%%
  \fi}
  \begin{tabular}{lr}
    \ae@tabular@content
  \end{tabular}}
\makeatother

\begin{document}

\aebuildtabular{A/Apple,B/Banana,C/Carrot,D/Daikon,E/Endive,F/Fig}

\end{document}

to produce

Sometimes you may want to make a recursive call to trim (or do something else).  This next example takes in a string and throws away tokens until it comes to the first occurence of E in the string.  If there is no E, then it just restores the original string.
\documentclass{article}
\makeatletter
\newcommand\aestriptoFirstE[1]{%%
  \def\ae@old{#1}%%
  #1 $\rightarrow$ \ae@striptoE#1\@nil
}

\def\ae@old{}
\def\ae@E@test{E}
\def\ae@empty@test{}
\def\ae@striptoE#1#2\@nil{%%
  \def\ae@continue{}%%
  \def\ae@first{#1}%%
  \def\ae@second{#2}%%
  \ifx\ae@E@test\ae@first
    #2
  \else
    \ifx\ae@empty@test\ae@second
      (unchanged) \ae@old
    \else
      \def\ae@continue{\ae@striptoE#2\@nil}%%
    \fi
  \fi
  \ae@continue
}

\makeatother
\begin{document}

\aestriptoFirstE{ABCDEFGE}

\aestriptoFirstE{WXYZ}

\end{document}


text:
Q: How to search a string value in an array I have an array with string in Android Studio, I want to search value, the values are with article and space how can I find. I want to search "das Buch"
It shouldn't pay attention to the capital or small letter
that is my Array :
public String myArray []= {"Das Buch","Die Fahne","Das Arbeitsbuch"};

I want to search for fahne and it should show me die Fahne
this is my code :
myText = editText.getText().toString();

if (Arrays.asList(myArray).contains(myText)){
    Toast.makeText(this, myText + " found", Toast.LENGTH_SHORT).show();
else {
    Toast.makeText(this, myText + " not found", Toast.LENGTH_SHORT).show();
}

A: Using Java 8, you can do something like this with array element containing a String, with case insensitive comparison again using a common library, and then returning the list if need all elements in list containing the searched element:
String myArray[] = {"Das Buch", "Die Fahne", "Das Arbeitsbuch"};
List<String> result = Arrays.asList(myArray).stream()
                .filter(x -> org.apache.commons.lang3.StringUtils.containsIgnoreCase(x, "das")).collect(Collectors.toList());
System.out.println(result);


text:
Q: BullMQ start Job from file with IIFE Let's say I have a function1.js (or ts, it doesn't matter in this case),function2.js and any other files which are IIFE with different logic, like that:
(async function F() {
  try {
    //[1,2,..n].map(x => console.log(x));
    //await any other action
  } catch (e) {
    console.error(e)
  }
})()

and I have any job queue manager, in my case, it's BullMQ, but I guess it's relevant for Bull or Agenda. So the question is, can I put in the queue the files themselves?
So in the case of starting a new Worker, it will self-execute itself?
Like this:
const worker = new Worker(queueName, async (job: Job) => {
    // `path/to/functionN.js`
    return 'some value';
});

I understand that queue are created for the cases when one typical function requires args, which should be passed by MQ to do the routine tasks. But in this case, I have various function.js files and want to do managing the queue for them.

A: I have found a relative example in BullMQ docs. Actually, it's called sandbox processors, and only Bull and BullMQ, among any others job queue managers support such feature.
Other, you'll need to write your own implementation.
The alternative is using pm2 programmatic API which would manage files manually. In that case, you pass a direct path to file with IIFE, and then it has been executed via pm2.
    const worker = new Worker('Queue', async (job: Job) => {
      /**
       * job.data is path to file
       * not sure that await before pm2 is nessessary
       */
      console.log(job.data)
      await pm2.connect(err => {
        if (err) console.error(err)
        pm2.start({
          name: 'Task Name',
          script: job.data.path,
          exec_mode: 'cluster',
        }, (err) => {
          if (err) console.error(err)
          pm2.disconnect()
        });
      });
    }, {connection: connectionRedis});

In that case, you are able to monitor your task via pm2 -list command

If you are using TypeScript in your project, then don't forget that path should be to the compiled JS file, otherwise configure pm2 correctly


text:
Q: How to suppress asm.js compilation message? When using asm.js code some browsers emit a compilation message. This one:

Successfully compiled asm.js code (loaded from cache in 201ms)

Is there a way to suppress this message?

A: The message itself is here: https://hg.mozilla.org/mozilla-central/file/tip/js/src/js.msg#l357

MSG_DEF(JSMSG_USE_ASM_TYPE_OK, 1, JSEXN_WARN, "Successfully compiled asm.js code ({0})")

And it is emitted here: https://hg.mozilla.org/mozilla-central/file/tip/js/src/wasm/AsmJS.cpp#l8718

static bool
SuccessfulValidation(AsmJSParser& parser, UniqueChars str)
{
    return parser.warningNoOffset(JSMSG_USE_ASM_TYPE_OK, str.get());
}

Which is called here: https://hg.mozilla.org/mozilla-central/file/tip/js/src/wasm/AsmJS.cpp#l8877

    // Success! Write to the console with a "warning" message.
    *validated = true;
    SuccessfulValidation(parser, Move(message));
    return NoExceptionPending(cx);
}

There is no apparent "optionality" in that line, even the comment says that it is going to the console, period.
Otherwise JSEXN_WARN has a couple real occurrences only (in jsexn.h, jsexn.cpp and in jsapi.h), the latter one descibes it as it is practically an exception type which does not break execution and does not have a scary part ("Error:..."): https://hg.mozilla.org/mozilla-central/file/tip/js/src/jsapi.h#l580

* JSEXN_WARN is used for warnings in js.msg files (for instance because we
* don't want to prepend 'Error:' to warning messages). This value can go away
* if we ever decide to use an entirely separate mechanism for warnings.

And it is true, most checks for JSEXN_WARN are about skipping the throw of an actual exception, in a if ( ... || exnType == JSEXN_WARN || ... ) do nothing fashion, like here (just one, ad-hoc example).
I am not sure what you really need, but

How to supress asm.js compilation message?

Via building your own copy of Firefox: https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions/Simple_Firefox_build


text:
Q: Trying to get property of non-object when i use num_rows I had code which will register the users information to database, and before save them into database has to check if the email address exists or not. They all work fine but always give me an error message:

Notice: Trying to get property of non-object in X:\xampp\htdocs\csg2431\week4\registerUser.php on line 72

Here is the code form line 72
$email_query = "SELECT EmailAddress FROM userdetails WHERE EmailAddress = '".$emailAddress."'";
$email_results = $db->query($email_query);

if (isset($emial_results))
{
    $error_message ='Your database is empty.';
}

if ($email_results->num_rows > 0)  // this is line 72
{
    $error_message = 'Your email address already exists, choose anther.';
}

if ($error_message != '')
{
    echo 'Error: '.$error_message. 'Go Back.';
    echo '';
    exit;
}

It also happend to my other page to search the user information from the database,

Notice: Trying to get property of non-object in X:\xampp\htdocs\csg2431\week4\searchUsers.php on line 43

here is some code:
$results = $db->query($query);

echo '
'.$results->num_rows.' users found.
'; // this is line 43

while ($row = $results->fetch_assoc())
{
    echo '
Name: '. $row['Surname'].','.$row['FirstName'].'
';

    echo 'Gender: '. $row['Gender'].',
';

    echo 'Date of Birth: '. $row['DOB'].',
';

    echo 'Home Phone: '. $row['HomePhone'].',
';

    echo 'Position: '. $row['Position_ID'].',
';

    echo 'Room Number: '. $row['RoomNo'].',
';

    echo 'Work Phone: '. $row['WorkPhone'].',
';

    echo 'Fax: '. $row['Fax'].',
';

    echo 'Mobile: '. $row['mobilePhone'].',
';

    echo 'Email: '. $row['EmailAddress'].',
';

    echo 'Department: '. $row['Dept_ID'].',

';
}

It looks like every time when I use num_rows the error happens


text:
Q: DSC-P52 digital camera power button I have searched and asked in a lot of forums for a long time but my problem with this camera is still there.
Is there anything that I can do to fix it?
My problem is the socket for the power and shutter button is broke off and 2 solder pad.
I think that circuit is multilayer because I can't find where it comes from.
I have solderer some jumper wire and 2 missing pad is unable to be found.
Here is some Image(sorry if it too big):

I hope this is enough information to fix my camera. Thank you!
Image of the missing solder pad:


text:
Q: Как осуществить поиск через Repository? У пользователя есть атрибутом Роль, по умолчанию TENANT, с помощью запроса задаем ему LANDLORD и в таблицу HOUSE он теперь добавляет квартиру с различными атрибутами: описание, цена, city_id и другие. Этот пользователь захотел снять с себя статус LANDLORD, удалить свои квартиры из нашей базы и снова стать просто TENANT, как мне квартирам, которые, если у него были - поставить status INACTIVE? Я только понял как ему роль присвоить, а как найти квартиры, которые ему принадлежали - не догадался. Мой вариант с поиском по id_landlord почему-то не сработал. Прикрепил фотографию того, какие есть атрибуты у House и User.
Заготовка кода выглядит так:
@PutMapping("/{id}")
    @PreAuthorize("hasAuthority('landlord:write')")
    public void TenantPostAdd(@PathVariable(value = "id") Long id) {
        User user = userRepository.findById(id).orElseThrow();
        user.setRole(Role.TENANT);
        House house = houseRepository.findById_landlord(id); - не работает
        house.setStatus(Status.INACTIVELY);
    }

HouseRepository:
@Repository
public interface HouseRepository extends JpaRepository<House, Long> {
    House findById_landlord(@Param("id_landlord") House house);
}

FULL CODE.

A: Сам смог сделать, надеюсь, что достаточно корректно происходят действия.
Пояснения: получил id, нашёл этого user'а, присвоил ему роль "TENANT", дальше нашёл дома, к котором он относится, выставил у них статус и всё сохранил. Правда сохранение не особо нравится, но на скорую руку именно так.
@PutMapping("/{id}")
    @PreAuthorize("hasAuthority('landlord:write')")
    public void landlordPostAdd(@PathVariable(value = "id") Long id) {
        User user = userRepository.findById(id).orElseThrow();
        user.setRole(Role.TENANT);
        Iterable<House> house = houseRepository.findById_landlord(id);
        for (House a : house) {
            a.setStatus(Status.INACTIVELY);
            userRepository.save(user);
        }
    }


text:
Q: How do I print one certain character and the character after a space I'm trying to get through this problem without looking at anyone else's code but i'm finding that extremely difficult. I understand how to iterate over characters and print those characters, I think. But i'm really stuck on how to only print one certain one and how to tell it to print the character after the space. Im guessing its something like, space char + 1?
Here is what I have so far, however its isn't much.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    // prompt user for name
    printf("What is your name? ");
    string s = get_string();
    if (s != NULL)
    {
        for (int i = 0; i < strlen[s]; i++)
        {
            printf("%c", s[0])
        }
    }
}

A: Let's fix that,

iterate over characters and print those characters

This should be done like that :
    int main(void)
    {
    // prompt user for name
      printf("What is your name? ");
      char s[] = "blablabla";
      if (s != NULL)
       {
         for (int i = 0; i < strlen(s); i++)
         {
            printf("%c", s[i]);
         }
       }
     }

how to only print one certain one

Like that :
printf("%c", d[12]); // This will get the 13 (start at 0) char of d

how to tell it to print the character after the space

You idea is the way to go ! The code below will print the next char when
the actual char is a space :
int main(void) {
char str[] = "This is a test";

  for (int forward = 0; forward < strlen(str); forward++) {
     if (str[forward] == ' ' && str[forward + 1] != '\0')
        printf("%c", str[forward + 1]);
  }
}

Will print : iat
Use a simple if statement to check if the current char is a space and the next one isn't the end of the string and print the next char is the statement is valid.


text:
Q: Hash value in Processing code? I saw some code in a Processing sketch with this value: background(#110000). I understood the function but I didn't understand the value. Can you please explain what it means? Because I know that Processing is mainly Java, when I try to use such a value (with a hash #), Eclipse doesn't understand it.

A: This is the hex code of the color as used in HTML for example.
See here: http://html-color-codes.info/
It goes like this #RRGGBB
where RR is for red, GG is for green and BB is for blue.

A: It's a hexadecimal color code, the same as used in CSS, for example. See this tutorial, for example.
#rrggbb where rr, gg and bb are hexadecimal numbers between 00 and FF.
Note: This is not Java syntax, it's valid in Processing but not in Java.


text:
Q: How do you boot Ubuntu Server to RAM? I have installed Ubuntu 12.04 Server on a USB drive, which is the hard drive for this PC. How do I get the bootloader to load Ubuntu onto RAM?
Essentially, this is going to resemble a live-cd type of environment, where the OS is on the CD/USB/HDD (whatever it may be), and gets loaded into RAM.
How do I do this with Ubuntu Server?

A: Have a look at this from the Ubuntu wiki.

A: You can't install the OS on RAM, because it is volatile memory. In other words. as soon as you power off your system, the RAM content is lost. You must install within non-volatile memory such as your HDD or your USB device.
When you boot from non-volatile storage, a boot loader will load your OS from your storage and into RAM.
Hope this helps clarify!

A: You have to instruct/set the BIOS to boot from the USB. At the system splash screen (on start up) press the key that is indicated to enter BIOS Setup (in my system it's F8). Once inside BIOS go to boot device priority and set the USB as first priority. Save and exit.


text:
Q: Chome extension: sending chrome.storage data from background script to popup/contentscript As described in the title, I'm trying to write a background script that will listen for load requests from either the popup.js or contentscript.js. When it receives a load, it get the content of chrome.storage.local, performs a little bit of data processing(for loop) and sends it to the requester.
The current issue, is my code receives the request, but fails to send back the data. My code is listed below:
popup.js:
chrome.runtime.sendMessage({greeting: "Load"}, function(response) {
  console.log(response);
}

background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.greeting=='Load') {
    chrome.storage.local.get(null,function(storeObject){
      var newList=[];
      //Perform some dataprocessing to store part of storeObject into newList
      sendResponse(newList);
    });
  }
});

I think the issue is related to scope, since after debugging it looks like sendResponse is trying to send from chrome.storage instead of background.js. Also, if I send the message outside (before/after) the chrome.storage.local callback, popup.js receives the message.Regardless I'm pretty lost at what to do to get this message passing working and would appreciate any help.

A: According to the docs on `chrome.runtime.onMessage:

sendResponse ( function )
  [...]This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

Since, sendResponse is called asynchronously in chrome.storage.local.get()'s callback, you need to return true from the onMessage listener to prevent the function from being invalidated.
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.greeting === 'Load') {
        chrome.storage.local.get(null, function(storeObject) {
            ...
            sendResponse(newList);
        });
        return true;   // <-- I intend to call `sendResponse` later
    }
    return false;   // <-- I do NOT intend to call `sendResponse`
});


text:
Q: Can I catch discord Dyno bot message and auto reply to it? As title, my scenario is:
Periodically checking if new messages were sent by Dyno bot to specific channel, and reply to it automatically.
Is it possible?
[update1]
Here are some cases:

*

*select the right option based one the message sent by bot

*click the right button based one the message sent by bot

[update2]
add some figures. something like these:

Any suggestion is appreciated.

A: Using discord.py, you can check if a message is written by a bot and reply to it with:
@client.event
async def on_message(self, message): #call the on_message() function
    if (message.author.bot): #check if the author is a bot
        await message.reply('Hello, bot!') #reply to the bot


text:
Q: Creating models with AngularJS I'm trying to create a model with AngularJS the way Backbone has the capability of doing it:
User = Backbone.Model.extend({

defaults: function() {
  return {
      "name": "finding name...",
      "id" : "",
      "age" : "",
      "gender" : ""
    };
 };

So I can later do something like var user = new User();
I found this backbone-style models in angularjs?
and I'm just trying to verify that there's no way of doing the above but through a factory?

A: You can use the value method of a module to store a function instead of having a factory returning a function like this :
var myApp = angular.module('myApp', []);

myApp.value('User', function () {
        return {
            "name": "finding name...",
            "id": "",
            "age": "",
            "gender": ""
        };
});

function ctrl($scope, User) {
    var user = new User();
    console.log(user);
}

A: You can use factory to return a function and then you will be able to use the keyword new to create a new object.
var myApp = angular.module('myApp', []);
myApp.factory('User', function () {
    return function () {
        return {
            "name": "finding name...",
            "id": "",
            "age": "",
            "gender": ""
        };
    };
});

function ctrl($scope, User) {
    var user = new User();
    console.log(user);
}


text:
Q: Force Azure Publish to create empty folder I use Azure websites and my project must have an empty folder on the server. When I publish the project from the Solution Explorer (VS 2013), I don't get it created on the server.
For now, I keep an empty file there to force the creation but I was wondering if there is a proper way to make the publish process create it for me.

A: Assuming you are WebDeploy from VS to publish your site, I think the only way to force creating a folder is to have it on your client side. If you use kudu you can look at post deployment actions
I would suggest updating your code though to create the folder if it doesn't exist. That would make your code more robust and self contained rather than depending on a certain deployment mechanism to create the folder for you.


text:
Q: Websocket error: "Handhshake status 403 forbidden" i have a problem with my written code which i wrote with the help of this documentation: https://exchange.blockchain.com/api/#introduction.
The code should send messages, receive messages and then i want to work with the received messages. And that 3 times per day (in the morning, noon and evening).
However the code seems to be working sometimes, actually up to 6 days (record, yay!) and then it stops working and i get an error output:
Traceback (most recent call last):

  File "<ipython-input-1-052db9d33d34>", line 1, in <module>
    runfile('Pathtofile/File.py', wdir='workingdirectory')

  File "C:\Users\iamdabest\Downloads\latexNpython\WinPython64-3.6.8.0\python-

3.6.8.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line

786, in runfile
    execfile(filename, namespace)

  File "C:\Users\orami?\Downloads\latexNpython\WinPython64-3.6.8.0\python-

3.6.8.amd64\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line

110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "Pathtofile/File.py", line 235, in <module>
    main()

  File "Pathtofile/File.py", line 229, in main
    trigger(updater.bot)

  File "Pathtofile/File.py", line 171, in trigger
    y = price_func()[0]

  File "Pathtofile/File.py", line 46, in price_func
    ws = create_connection(url, **options)

  File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-

3.6.8.amd64\lib\site-packages\websocket\_core.py", line 606, in

create_connection
    websock.connect(url, **options)

  File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-

3.6.8.amd64\lib\site-packages\websocket\_core.py", line 253, in connect
    self.handshake_response = handshake(self.sock, *addrs, **options)

  File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-

3.6.8.amd64\lib\site-packages\websocket\_handshake.py", line 57, in handshake
    status, resp = _get_resp_headers(sock)

  File "C:\Users\name\Downloads\latexNpython\WinPython64-3.6.8.0\python-

3.6.8.amd64\lib\site-packages\websocket\_handshake.py", line 143, in

_get_resp_headers
    raise WebSocketBadStatusException("Handshake status %d %s", status,

status_message, resp_headers)

WebSocketBadStatusException: Handshake status 403 Forbidden

Now please keep in mind that i never got teached this stuff by a trained professional. All the knowledge i gained is from playing around (plotting and analyzing data) with python and the help of the internet.
I don't really understand why it is working few days and then suddenly stops working.
My questions:

*

*In fact i have no problem when the codes doesn't gives an output as long as it keeps running. So how can i tell the code to 'ignore' the error and keep moving or maybe to automatic restart the code if the error occurs? I tried simple stuff like if statement or try and expect but i wasn't successful.

*The error comes because the authentication between Server and Client failed? or what does it mean?

*Is there another workaround? I already read somewhere to use another websocket (websockets) but wasn't able to get it working.

Here is a (M)WE of my code:
from websocket import create_connection
import json

options = {}
options['origin'] = 'https://exchange.blockchain.com'
url = "wss://ws.prod.blockchain.info/mercury-gateway/v1/ws"

def price_func():
        ws = create_connection(url, **options)
        msg = '{"token": "mysecretAPItoken", "action": "subscribe", "channel": "auth"}' # here i subscribe
        ws.send(msg)

        msg = '{"action": "subscribe", "channel": "balances"}' # here i am asking for the json files
        ws.send(msg)
        result1 =  json.loads(ws.recv()) # first answer is the confirmation of connecting
        result2 = json.loads(ws.recv()) # save the received answers to work with them later

        msg = '{"token": "mysecretAPItoken", "action": "unsubscribe", "channel": "balances"}' # unsubscribing, not sure if i need to do that but it seems to me like 'clean' working; if smth goes wrong it unsubscribes.
        ws.send(msg)

        msg = '{"token": "mysecretAPItoken", "action": "unsubscribe", "channel": "auth"}' # unsubscribing; same as 3 lines above
        ws.send(msg)
        ws.close()
        return result2['balances'][0]['rate'], result2['balances'][1]['rate'] # gives me the prices

x = price_func()[0]
print('Price of Shitcoin is around' + str(round(x,2)))

Thx for any help.


text:
Q: Matrix inversion of an analytical function Following problem:
I have a function
$f(x_1,x_2)$
and Im looking for the inverse $finv(x_1,x_2)$ of the function which is defined through:
$\int f(x_1,y)\cdot finv(y,x_2) d y =\delta(x_1,x_2) $
where $\delta(x_1,x_2) $ is the Dirac delta function.
When I'm trying to discretize $f$ and then to invert as usual matrix I get numerically bad results. I mean the result is ok, but I need extremely fine discretization.
I'm sure there should be some other method than the poor man inversion. Something like inversion with weights or similar.
Probably there exist already a c++ library for such problem.

A: In case your $f$ is a function only of $x_1-x_2$ and limits of integration are $-\infty$ to $+\infty $ then a solution via Fourier transform method can be found on Wikipedia.


text:
Q: CQRS: Return created ID I need to return the ID of the entity a command creates to the client.
(For example to redirect from new-potato to potatoes/:id)
I cannot create the ID on the client, for example because:

*

*The quality of client random ID cannot be ensured.

*Short, sequential IDs are required.

Can I return the ID when I submit the command?
For example the command is
{
  type: "CreatePotato",
  eyes: 3
}

the returned payload is
{
  data: {id: 1001}
}

and the event persisted is

{
  type: "PotatoCreated",
  id: 1001,
  eyes: 3
}

A: You can just send an ID with a command:
{
  id: 1001,
  type: "CreatePotato",
  eyes: 3
}

Since in a good system ids should be unique, immutable and never carry any semantic, then you can just generate some GUID, CUID or whatever you are using, right in the command, and assume that if command has succeded, your new entity ID is one that you have sent.


text:
Q: How sort array of objects in collection MongoDB? I am using node.js and MongoDB. I have collection with next schema:
var project = new Schema({
head:{
    head_task: String,
    userID: String
},
access_users: {
    type : Array ,
    "default" : []},
context_task: [{
            from_name: String,
            status: Boolean,
            task: String,
            created_task: {
                type: Date,
                default: Date.now()
             }
        }],
created: {
        type: Date,
        default: Date.now
    }});

How I can get docs sorting by field context_task.created_task by DESC.
I think that I have to using aggregate query
db.tasks.aggregate({$match :{"_id":ObjectId("590e2d7d4d4a5e0b647d0835")}},
 {$sort: {"context_task.created_task": -1}}).pretty();

but sorting doesn't work.
Maybe I have to sort Data on client?
Can anyone help me with this question?

A: $sort is deprecated. You need to use sort function with find.
db.tasks.find({_id : "590e2d7d4d4a5e0b647d0835" })
.sort({context_task.created_task : 1})
.limit(1)


text:
Q: Trying to create a selection bar for a UITableView in iOS app I am trying to create a UITableView that has a selection bar that scrolls to whichever row the user has selected (please don't ask why, I just have to do this).  This is different from the typical selection bar that the UITableView has, because there is no animation there.  What I've done is added a TableView in Interface Builder to my main view, and I've also added an imageView to my main view.  I need this to work similar to the selection bar in the UIPickerView except that in this case it is the selection bar that moves.  I figure the code for this would reside inside:
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    CGRect rect = [tableView rectForRowAtIndexPath:indexPath];
    _imageView.frame = rect;

}

Can anyone explain to me how I would code the animation of the selection bar from cell to cell?
Thanks in advance to all who reply

A: Assuming the code you currently have works:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [UIView animateWithDuration:.3 animations:^{
        CGRect rect = [tableView rectForRowAtIndexPath:indexPath];
        _imageView.frame = rect;
    }];
}

There is also +animateWithDuration:animations:completion: and +animateWithDuration:delay:options:animations:completion:


text:
Q: Why is OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true) causing an OCR running error? I am using MODI to read tiff images and do what I need to do with the text. Some images work fine and then other tiff images always cause the method,
OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true)
to fail. I have researched this and tried different variations such as 'false','false' in the parameter list. I have also tried SYSDEFAULT instead of English but I still get the error. Can anyone please tell me why it would fail on some tiff images and not on others?
I have done some research and found this answer:
One possible cause is MODI trying to process a file without any recognisable text. A blank document, or one which has only drawings/scribbles and is effectively blank, will cause this exception.
Obviously this is not good enough as there is no way I can have an app that decides to OCR some images and not others. I handle the exception, but the OCR object is not then initalised so I can't do what I need to do from there.
This is a bloody nightmare! Why can't the method just do it's bloody job and if the image has some unreadable pages then just ignore them?
I am using Windows 7 Ultimate and Office 2007 Ultimate.
Visual Studio version is 2008
Thanks,
IW

A: OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, true, true)

Instead of above code you can use
OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false)

because the tiff image might be 2400*2496.


text:
Q: AssertionError: If capturable=False, state_steps should not be CUDA tensors I get this error while loading model weights of a previous epoch on Google colab. I'm using PyTorch version 1.12.0. I can't downgrade to a lower version as there are external libraries that Im using that require Pytorch 1.12.0
Thanks!

A: It seems related to a newly introduced parameter (capturable) for the Adam and AdamW optimizers. Currently two workarounds:

*

*forcing capturable = True after loading the checkpoint optim.param_groups[0]['capturable'] = True. This seems to slow down the model training by approx. 10% (YMMV depending on the setup).

*Reverting PyTorch back to previous versions (could be 1.11.0).

Source: https://github.com/pytorch/pytorch/issues/80809#issuecomment-1173481031

A: If you are using PyTorch 1.12.0 with Cuda binaries 11.6/11.7 then on your shell or command prompt, paste the following;
pip install torch==1.12.1+cu116 torchvision==0.13.1+cu116 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu116

The Adam Optimizer regression was removed in the updated torch version
Edit
There's a new torch version use this to install it
pip install torch==1.13.0+cu117 torchvision torchaudio torchtext --extra-index-url https://download.pytorch.org/whl/cu117

A: Can you tell me which Optimizer you are using. I have encountered this with AdamW optimizer. You can avoid it by loading optimizer with the load_state_dict and then mapping it to cpu explicitly using .cpu() function.


text:
Q: Intersection of Subgroups generating all subgroups of a subgroup Say I have $H \leq G$ where $G$ is a group. Can I generate all the subgroups of $H$ by taking $H \cap K$ where $K$ is any other subgroup of $G$? That is, can all subgroups of $H$ be written as the intersection of $H$ with a subgroup of $G$?
I am working on a related problem and have this as a "lemma" might help. Thanks!

A: This is trivially true and doesn't really require a separate lemma, unless I'm misunderstanding. Note that any subgroup of $H$ is already a subgroup of $G$, so there's no reason to consider subgroups not entirely contained in $H$ for this question.


text:
Q: How to flush left one row in align How to flush left the first short row in this align?

Here my MWE:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{align*}
\text{\textbf{Year 1:}}\\ \$1000 + 0.05(\$1000)& = \$1000(1 + 0.05)\\
& = \$1000(1.05)\\
& = \$1050
\end{align*}
\end{document}

A:
\documentclass{article}
\usepackage{amsmath}
\begin{document}

{\setlength\abovedisplayskip{0pt}

\noindent\textbf{Year 1:}
\begin{align*}
\$1000 + 0.05(\$1000)& = \$1000(1 + 0.05)\\
& = \$1000(1.05)\\
& = \$1050
\end{align*}

\bigskip

\begin{align*}
\intertext{\textbf{Year 1:}}
\$1000 + 0.05(\$1000)& = \$1000(1 + 0.05)\\
& = \$1000(1.05)\\
& = \$1050
\end{align*}

}

\end{document}

(new answer after question updated)


text:
Q: R Package Error(s) I'm running into a bunch of errors when trying to install any packages on R 3.4.4 on Windows 7. Originally, installed.packages() wasn't even working. I had to create the temp directory manually that it was trying to access. I've previously installed/uninstalled R on my machine before, so I'm guessing some of these problems might be stemming from that. I can now view my installed packages.
If I try something as simple as install.packages("tidyverse"), I'll get the following:

Installing package into
  'C:/Users/areynolds/Documents/R/win-library/3.4'
  (as 'lib' is unspecified)
  Error in readRDS(dest) : unknown input format

Attempting update.packages() yields the same error. I've deleted my .Rhistory which saves to my Documents folder. My .libPaths() is the following:

[1] "C:/Users/areynolds/Documents/R/win-library/3.4"
  [2] "C:/Program Files/R/R-3.4.4/library"

I'm not really sure what else to try. I've been looking everywhere for the same problem but it's always a little different. I've tried specifying arguments to install.packages like dependencies = TRUE or lib = path. I'd really appreciate any help. Thanks

A: I was getting the same error.
Closing RStudio completely, then reopening it worked for me.
Note: simply restarting the R Session (e.g. .rs.restartR()) did not work - I am not sure why


text:
Q: Create variable with PDO statement for database Today I'm trying to connect to multiple database (I hope I'm calling it right) with one PDO, so my code looks like this:
class DB{
    private $con;
    private $DATABASE_HOST = 'localhost';
    private $DATABASE_USER = 'root';
    private $DATABASE_PASS = '';
    private $DATABASE_NAME = 'phplogin';

    public function __construct(){
        $dsn = "mysql:host=$this->DATABASE_HOST;dbname=$this->DATABASE_NAME";

        try {
            $this->con = new PDO($dsn, $this->DATABASE_USER, $this->DATABASE_PASS);
            $this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
    }

    public function viewData($database){
        $query = "SELECT nome FROM :name";
        $stmt = $this->con->prepare($query);
        $stmt->execute(['name' => $database]);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $data;
    }
}

Doing like that it throws me an error for $database because it tell me that there is a Syntax error or access violation. Now, what I want to do is to give to $database the name of the database I want to connect with when i call the function, but I don't know which is the right way, I thought that PDO could help me but I can't understand why it doesn't work... Can anyone help me?