text:
Q: Serial port communication not working via .net 5 for Marlin board I am trying to get a simple Serial Port connection between dotnet 5 and a Marlin based printer board which is running some variant of a micro controller (LPC1768FBD100 https://www.arrow.com/en/products/lpc1768fbd100551/nxp-semiconductors).
I can open a connection to the board using other tools, send a "M503\n" command and receive a response, the tools I've used successfully are

*

*Pronterface (Windows)

*Arduino Serial Monitor (Windows)

*miniterm (Linux)

*putty (Windows)

So I know the board to be functioning correct in both Linux and Windows, but when attempting from .net, I am yet to succeed in getting any response back from the board. I have uploaded a simple tool in .net 5 that connects to a serial port and allows you to TX / RX strings,
https://github.com/devoctomy/SerialPortTester
I have tested this code in Windows and Linux, same port settings, no response back. I have also tested this exact code against a simple echo program running on an Arduino Uno board and it all works as expected, but for the life of me I can't get anything back from the other board.
I'm wondering if there's something about serial comms that these other apps are doing that I just don't know about.  I'm using the same port settings which are shown in device manager across the board when testing in Windows, and also the same settings when testing in Linux.
In Linux the board comes up as ttyACM0, which is how my Arduino Uno is also mounted.
Any suggestions?  I'm sure this isn't a "Marlin" issue, as only one of the other tools I've tested with is specific for Marlin and the Arduino serial monitor is about as basic as you can get.  There's something I'm not doing in the .net code I think...
I've also tried someone elses old .net code and it also doesn't get a response back from this board, but does from my Arduino Uno running the echo program.
https://www.codeproject.com/Articles/23656/Termie-A-Simple-RS232-Terminal
Nick.
Edit:
I'm currently looking to see if it's just .net and the underlying mechanisms that is effected here and have found this page,
https://www.sparxeng.com/blog/software/must-use-net-system-io-ports-serialport
I've modified my tester code to access to base stream for sending / receiving data just in-case, but this has not fixed the issue.

A: Okay I got it, I knew I was missing something,
port.DtrEnable = true;

This fixes it and now I'm receiving and sending data to the Marlin board.


text:
Q: Generalized long wave and KdV equation I have read many papers about benjamin-bona-mahony (BBM) equation or Regularized Long Wave (RLW) equation and found that BBM equation can be derived from KdV equation. from other papers i got others equation abitu long wave,namely generalized long wave (GRLW) and modified regularized long wave (MRLW). i got some questions about all of the equation:

*

*what is the reason to change
$\frac{\partial^3 u}{\partial x^3}$ with $\frac{\partial^3 u}{\partial x^2t}$ when try to derive BBM equation from KdV equation?

*how does it get GRLW equation from RLW? till now i have not got the explanation about that.

*same like second question, how does it get MRLW equation?

thank you for the answer and explantion.
may be it can help
bbm equation: $\frac{\partial u}{\partial t }+\frac{\partial u}{\partial x}+u\frac{\partial u}{\partial x}-\frac{\partial^3 u}{\partial x^2t}=0$
kdv equation: $\frac{\partial u}{\partial t}+u\frac{\partial u}{\partial x}+\delta^2\frac{\partial^3u}{\partial x^3}=0$
mrlw equation:$\frac{\partial u}{\partial t }+\frac{\partial u}{\partial x}+\delta u\frac{\partial u}{\partial x}-\mu\frac{\partial^3 u}{\partial x^2t}=0$

redpajama_set_name: RedPajamaStackExchange


text:
Q: r: normalmixEM not consistent? I have the following data: http://s000.tinyupload.com/?file_id=00083355432555420222
I want to fit a mixture density of two normal distributions.
I have the formula:
\begin{align}
f(l)=\pi \phi(l;\mu_1,\sigma^2_1)+(1-\pi)\phi(l;\mu_2,\sigma^2_2)
\end{align}
my R code is:
normalmix<-normalmixEM(dat,k=2,fast=TRUE)

pi<-normalmix$lambda[1]
    mu1<-normalmix$mu[1]
mu2<-normalmix$mu[2]
    sigma1<-normalmix$sigma[1]
sigma2<-normalmix$sigma[2]

Now I have the problem, that the output is not consistent, i.e. every time I run the code, I get different outputs! And they are very different, no small differences, which could be due to the precision of the numerical procedures.
E.g.
sometimes for pi I get
[1] 0.2653939

or
[1] 0.3318069

I already recognized, that sometimes the numbering is changed, so the pi of 0.7 would be equal to a pi of 0.3. Okay, I got this, I don't know why the R procedures does this, but this would not be a problem. But the problem is, that the outputs are way to different, sometimes I even get an error message (german):
Fehler in while (dl > eps && iter < maxit) { :
  Fehlender Wert, wo TRUE/FALSE nötig ist
Also, the number of iterations is very different, from 29 up to 1000 ......
edit: I now tried to set the initial values manually....
In the Rmanual it says:

Lambda: "Initial value of mixing proportions. Automatically repeated
  as necessary to pro- duce a vector of length k , then normalized to
  sum to 1"

I started to try it with giving different values of lambda:
1.
normalmix<-normalmixEM(dat,lambda=c(0.5,0.5),k=2,fast=TRUE)
normalmix$loglik
    normalmix$mu
normalmix$sigma

which gives a loglik of 617.2996 and the parameters:
> normalmix$mu
    [1]  0.0003769442 -0.0008892282
    > normalmix$sigma
[1] 0.02814997 0.01232638

2.
normalmix<-normalmixEM(dat,lambda=c(0.8,0.2),k=2,fast=TRUE)
normalmix$loglik
    normalmix$mu
normalmix$sigma

which also gives a loglik of 617.2996 ? and the parameters
> normalmix$mu
    [1]  0.0003767148 -0.0008892515
    > normalmix$sigma
[1] 0.02814819 0.01232488

mh, I don' know....
then, I tried it with different values of $\mu$:
1.
normalmix<-normalmixEM(dat,mu=c(-0.001,0.002),k=2,fast=TRUE)
normalmix$loglik
    normalmix$mu
normalmix$sigma

which also leads to a loglik of 617.2996 and the parameter output:
> normalmix$mu
    [1]  0.0003767138 -0.0008892516
    > normalmix$sigma
[1] 0.02814818 0.01232487

2.
normalmix<-normalmixEM(dat,mu=c(0.02,0.01),k=2,fast=TRUE)
normalmix$loglik
    normalmix$mu
normalmix$sigma

which again! leads to a loglik of 617.2996 and the parameter output:
> normalmix$mu
    [1]  0.0003769462 -0.0008892280
    > normalmix$sigma
[1] 0.02814999 0.01232639
>

what should I do now?

A: The problem is that the default number of iterations (maxit=1000) is not enough to guarantee the convergence of the EM algorithm in general and you have to fiddle a bit with this (and sometimes other) feature.  It seems like maixt=10000 produces stable results. See the following code (run it several times to convince yourself).
normalmix<-normalmixEM(dat,k=2,fast=TRUE,maxit=10000)

pi<-normalmix$lambda[1]
    mu1<-normalmix$mu[1]
mu2<-normalmix$mu[2]
    sigma1<-normalmix$sigma[1]
sigma2<-normalmix$sigma[2]

c(pi,mu1,mu2,sigma1,sigma2)

Now, check the fit of the estimated mixture.
mix2 <- function(x) return( pi*dnorm(x,mu1,sigma1)+(1-pi)*dnorm(x,mu2,sigma2))

vec <- seq(-0.05,0.05,0.0001)

plot(vec,mix2(vec),type="l",col="red")
hist(dat,probability=T,add=T)


text:
Q: How to use a fixed point sin function in Vivado HLS I am calculating the intersection point of two lines given in the polar coordinate system:
typedef ap_fixed<16,3,AP_RND> t_lines_angle;
typedef ap_fixed<16,14,AP_RND> t_lines_rho;

bool get_intersection(
        hls::Polar_< t_lines_angle, t_lines_rho>* lineOne,
        hls::Polar_< t_lines_angle, t_lines_rho>* lineTwo,
        Point* point)
{
    float angleL1 = lineOne->angle.to_float();
    float angleL2 = lineTwo->angle.to_float();
    t_lines_angle rhoL1 = lineOne->rho.to_float();
    t_lines_angle rhoL2 = lineTwo->rho.to_float();
    t_lines_angle ct1=cosf(angleL1);
    t_lines_angle st1=sinf(angleL1);
    t_lines_angle ct2=cosf(angleL2);
    t_lines_angle st2=sinf(angleL2);
    t_lines_angle d=ct1*st2-st1*ct2;

    // we make sure that the lines intersect
    // which means that parallel lines are not possible
    point->X = (int)((st2*rhoL1-st1*rhoL2)/d);
    point->Y = (int)((-ct2*rhoL1+ct1*rhoL2)/d);

    return true;
}

After synthesis for our FPGA I saw that the 4 implementations of the float sine (and cos) take 4800 LUTs per implementation, which sums up to 19000 LUTs for these 4 functions. I want to reduce the LUT count by using a fixed point sine. I already found a implementation of CORDIC but I am not sure how to use it. The input of the function is an integer but i have a ap_fixed datatype. How can I map this ap_fixed to integer? and how can I map my 3.13 fixed point to the required 2.14 fixed point?

A: With the help of one of my colleagues I figured out a quite easy solution that does not require any hand written implementations or manipulation of the fixed point data:
use #include "hls_math.h" and the hls::sinf() and hls::cosf() functions.
It is important to say that the input of the functions should be ap_fixed<32, I> where I <= 32. The output of the functions can be assigned to different types e.g., ap_fixed<16, I>
Example:
void CalculateSomeTrig(ap_fixed<16,5>* angle, ap_fixed<16,5>* output)
{
    ap_fixed<32,5> functionInput = *angle;
    *output = hls::sinf(functionInput);
}

LUT consumption:
In my case the consumption of LUT was reduced to 400 LUTs for each implementation of the function.

A: You can use bit-slicing to get the fraction and the integer parts of the ap_fixed variable, and then manipulate them to get the new ap_fixed. Perhaps something like:
constexpr int max(int a, int b) { return a > b ? a : b; }

template <int W2, int I2, int W1, int I1>
ap_fixed<W2, I2> convert(ap_fixed<W1, I1> f)
{
    // Read fraction part as integer:
    ap_fixed<max(W2, W1) + 1, max(I2, I1) + 1> result = f(W1 - I1 - 1, 0);
    // Shift by the original number of bits in the fraction part
    result >>= W1 - I1;
    // Add the integer part
    result += f(W1 - 1, W1 - I1);
    return result;
}

I haven't tested this code well, so take it with a grain of salt.


text:
Q: Creating an abstract generic method I have a C# class with a method such as below:
public class MyType
{
    public MyType Clone()
    {
        var clone = (MyType)MemberwiseClone();

        // Do some other stuff here with the clone's properties

        return clone;
    }
}

I have a bunch of other classes where I want to implement the Clone method so I was thinking I could create an abstract base class where I could define the Clone method generically so I don't have to put a concrete implementation in each class.
I would think this is possible but I haven't worked too much with generics and my attempts to do this in the past (months ago, so discarded my code out of frustration) haven't been successful.
Is this possible? If so, how could it be done?

A: Create an abstract generic base and then implement the concrete type on the derived ones:
public abstract class ClonableBase<T>
{
    public T Clone()
    {
        return (T)this.MemberwiseClone();
    }
}

public class RealClass : ClonableBase<RealClass> { }

A: The usefulness of this approach depends significantly on what it is that you're cloning.
Here's a method that I use. The cloning method is a bit crude. It's specifically for objects that are meant to be serialized as JSON.
That's why the generic constraint (TEntity : BaseEntity) is there. I don't want just anything passed into this method, only something that I know is serializable.
I also avoided using the generic argument for JsonConvert.DeserializeObject because while I want to cast the result as a specific type, I don't want to pass in an inherited type and get back an instance of a base type.
public static TEntity CloneEntity<TEntity>(this BaseEntity input) where TEntity
    : BaseEntity
{
    if (input == null) return null;
    var serialized = JsonConvert.SerializeObject(input);
    return (TEntity)JsonConvert.DeserializeObject(serialized, input.GetType());
}

Although it's already been accepted, I don't recommend adding this to a base class unless absolutely necessary. Before long you might find that you need to clone something that already inherits from a different base class.
This requires the Newtonsoft.JSON package.
As mentioned in a comment, this will do a deep clone. As I stated at the top, this method applies only if serialization/deserialization cloning is appropriate to the types you need to clone. If there were a universally applicable way to clone objects that applied in every case then object would probably have a public Clone method.
If we're cloning classes it's likely because they contain data, and where that's the case deep cloning is likely preferable. For example, suppose we have a Customer class, and one if its properties exposes an Address object. MemberwiseClone will clone the value types, but will result in two Customer objects that share a reference to the same Address. If we're cloning it's usually because we're trying to create entirely distinct objects. If we think we've cloned something but beneath the surface the original and clone share object references then there's a good chance we'll have bugs.

A: Built on @Gusman's solution I add the possibility to do some initialization
public abstract class ClonableBase<T>
{
    public T Clone()
    {
        T clone = (T)MemberwiseClone();
        Initialize(clone)
        return clone;
    }

    protected virtual void Initialize(T clone)
    {
    }
}

If the initialization is mandatory, you can also make Initialize abstract instead.
public class RealClass : ClonableBase<RealClass> {
    protected override void Initialize(T clone)
    {
        // Do some other stuff here with the clone's properties
    }
}


text:
Q: No Internet Connection after plugging of second wifi interface I've set up ubuntu server (16.04TLS) as Access Point with hostapd and dnsmasq.
For internet connection I use my built-in wifi network card (RTLINK) and for Access Point - wifi-usb adapter.
Without Wifi-Usb being plugged in there is stable internet connection (I can surf internet with curl). After plugging USb-Stick (Edimax EW-7811Un) in, I can connect my devices to it (it broadcasts access point), but then there is no more any internet connection.
What can be a problem?
Gateway is 192.168.2.1
rc.local
iptables -t nat -A POSTROUTING -s 192.168.2.0/24 ! -d 192.168.2.0/24 -j MASQUERADE

/etc/network/interfaces
    auto lo
iface lo inet loopback
auto wlx74da382e3878
iface wlx74da382e3878 inet static
hostapd /etc/hostapd/hostapd.conf
address 192.168.2.1
netmask 255.255.255.0

auto wlo1
allow-hotplug wlo1
iface wlo1 inet dhcp
...wpa-settings

$ifconfig (wlo1 used for connection to ADSL-Router for Internet connection)
 lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:190 errors:0 dropped:0 overruns:0 frame:0
          TX packets:190 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:15885 (15.8 KB)  TX bytes:15885 (15.8 KB)

wlo1      Link encap:Ethernet  HWaddr bc:85:56:47:69:37
          inet addr:192.168.2.103  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: fe80::be85:56ff:fe47:6937/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6935 errors:0 dropped:0 overruns:0 frame:0
          TX packets:600 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2412406 (2.4 MB)  TX bytes:78228 (78.2 KB)

wlx74da382e3878 Link encap:Ethernet  HWaddr 74:da:38:2e:38:78
          inet addr:192.168.2.1  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: fe80::76da:38ff:fe2e:3878/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:792 (792.0 B)

iwconfig ( wlx74da382e3878 (usb-wifi-adapter) serves as Access Point)
> wlo1      IEEE 802.11bgn  ESSID:"TP-LINK_D"
>           Mode:Managed  Frequency:2.417 GHz  Access Point: A0:F3:C1:D7:33:38
>           Bit Rate=1 Mb/s   Tx-Power=20 dBm
>           Retry short limit:7   RTS thr:off   Fragment thr:off
>           Encryption key:off
>           Power Management:off
>           Link Quality=70/70  Signal level=-39 dBm
>           Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
>           Tx excessive retries:0  Invalid misc:11   Missed beacon:0
>
> wlx74da382e3878  IEEE 802.11bgn  Mode:Master  Tx-Power=20 dBm
>           Retry short limit:7   RTS thr:off   Fragment thr:off
>           Power Management:on

hostapd.conf
interface=wlx74da382e3878
logger_syslog=-1
logger_syslog_level=2
logger_stdout=-1
logger_stdout_level=2
ctrl_interface=/var/run/hostapd
ctrl_interface_group=0
ssid=TEST-WLAN
hw_mode=g
channel=1
beacon_int=100
dtim_period=2
max_num_sta=255
rts_threshold=2347
fragm_threshold=2346
macaddr_acl=0
auth_algs=3
ignore_broadcast_ssid=0
eapol_key_index_workaround=0
eap_server=0
own_ip_addr=127.0.0.1
rsn_pairwise=CCMP
wmm_enabled=1

$route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.2.1     0.0.0.0         UG    0      0        0 wlo1
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 wlo1
192.168.2.0     0.0.0.0         255.255.255.0   U     0      0        0 wlx74da382e3878

A: Ok, Ipor Sircer with his comment was right, I'd used somehow the same ip-range in my settings (for AP-connection and for Managed-connection).
As my Router has 192.168.2.1 gateway-ip, I'd set up the same range for my Hostapd-wifi-adapter.
The problem was resolved after setting up the address for hostapd on 10.0.0.1


text:
Q: SQL Group by ordering results My table looks like this:
----------------------------------------------------------
| ID | League | Reference | Created_at           | Value |
----------------------------------------------------------
| 1  | Test   | Exa       | 2018-08-05 11:52:30  | 12.00 |
----------------------------------------------------------
| 2  | Test   | Alch      | 2018-08-05 12:52:30  | 9.12  |
----------------------------------------------------------
| 3  | Test   | Chrom     | 2018-08-05 12:50:30  | 6.00  |
----------------------------------------------------------
| 4  | Test   | Chrom     | 2018-08-05 10:50:30  | 2.00  |
----------------------------------------------------------

Every 5 minutes I save a reference value on the table
I want to retrieve values of each reference (latest ones ordering by created_at DESC. Currently on my code I just loop over an array of references [exa, alch, ...] and execute the following query (for each league):
SELECT created_at, league, value, reference
FROM currency
WHERE league = ? AND reference = ?
ORDER BY created_at DESC
LIMIT 1

Basically I execute that query for each reference of each league, resulting in a lot of queries executed, and leading to high response times on my server...
The expected result should be, gather each reference value from X league, but only gather the latest inserted value (created_at DESC), each reference type (exa, alch, ...) will have different created_at values (may or not be equal to other reference types)
I tried using group_by with no success at all since I will only get the first results (older ones) of the table:
SELECT created_at, league, value, reference
FROM currency
WHERE league = ? AND reference IN ('exa', 'alch', ...)
GROUP BY created_at DESC

I assume this group_by approach would be faster since its one query for each league, but I always get older results instead of recently created ones...

A: Have a sub-query that returns each league's max created_at value. JOIN with that result:
select c1.*
from currency c1
join (select league, max(created_at) max_created_at
      from currency
      group by league) c2
  on  c1.league = c2.league
  and c1.created_at = c2.max_created_at

A: You can use subquery with limit clause  :
select c.*
from currency c
where id = (select c1.id
            from currency c1
            where c1.league = c.league and
                  c1.Reference = c.Reference -- might be you need this also
            order by c1.created_at desc
            limit 1
           );

A: Try the following query-:
with cte as
(
select created_at, league, value, reference,ROW_NUMBER() over (partition by league,reference  order by   Created_at desc) rn
from currency
)select * from cte where rn=1

SQL Server

A: This query seems more efficient, you can chech the fiddle here: http://sqlfiddle.com/#!9/2b2dfe/8
If still have problems in production, review your indexes.
SELECT
  currency.ID,
  currency.League,
  currency.Reference,
  currency.Created_at,
  currency.Value
 FROM
   currency
JOIN (
SELECT
  League,
  Reference,
  MAX(Created_at) AS Created_at
 FROM
   currency
 GROUP BY
   League,
   Reference
 ) AS a
 ON
   currency.League = a.League
   AND currency.Reference = a.Reference
   AND currency.Created_at = a.Created_at

A: Use filtering:
select c.*
from currency c
where c.created_at = (select max(c2.created_at)
                      from currency c2
                      where c2.league = c.league
                     );


text:
Q: Running FxCop on a ASP.NET MVC application Hi I'm implementing an FxCop analysis over our MVC application.  Does anyone have a recommended version and ruleset?
Thanks!

A: We use the version built into VS Pro+ with a custom ruleset which is essentially "all rules" minus one or two which are irrelevant to us (e.g., code signing).


text:
Q: Creating table efficiently in numpy I'm implementing the cky algorithm and I tried it once with list of lists in python and once with numpy.zeros and the list of lists is faster every time. I would think numpy would be faster, but I am new to using it and it is likely that I am not writing it in the most efficient way possible. It is also possible that I am just using a small dataset and list of lists are just faster on smaller datasets.
The only bit that is different is the instantialization of the tables:
straight python:
  table = [[[] for i in range(length)] for j in range(length)]

and numpy:
 table = np.zeros((n_dimension, n_dimension), dtype=object)
  for i in range(n_dimension):
      for j in range(n_dimension):
          table[i][j] = []

I think that numpy is acting slower because I am not optimizing how I form my table, while the pythonic way is as efficient as that can be written. How can I make a similar, optimized implementation in numpy so that I can accurately assess the time differences between the two? Or are list of lists just faster in this case? At what point does numpy become more efficient than list of lists?


text:
Q: Magento - Category redirect when language is changed I got an issue with magento and category url's when I change the language.
When I view a category and then switch to another language it works and gives the right translated url, but when I want to change back to the default language it doesn't change the url to the right language and gives a 404. The strange thing is that it works with products but it doesn't with categories.
Does someone now what I'm doing wrong?
I'm using magento CE 1.8.1, cleared my cache often and also reindexed lots of times..


text:
Q: Using the same variable name for (multi?)threading in python I'm new to threading in python and I've began by creating a simple program which uses two threads to print the numbers 1-100. The first thread prints all of the odd numbers and the second thread prints all of the even numbers.
Initially, I encountered a problem where my threads were just printing the numbers as fast as they could, so the numbers weren't always in order. I don't know (and neither have I researched) how to synchronise threads in python so I've implemented a simple technique where I use Boolean flags and switch them on and off, and use a delay to 'sync' the threads.
Looking at my code, I've just realised that my flags have the exact same variable names as my threads.
Why isn't python throwing any errors?
My code:
import time, threading

def printOdd():

    global odd, even

    for i in range(1, 101, 2):

        while not odd:
            time.sleep(0.01)

        if odd:
            print(i)
            odd = False
            even = True

def printEven():

    global odd, even

    for i in range(2, 101, 2):

        while not even:
            time.sleep(0.01)

        if even:
            print(i)
            odd = True
            even = False

odd = True
even = False

odd = threading.Thread(target = printOdd)
even = threading.Thread(target = printEven)

odd.daemon = True
even.daemon = True

odd.start()
even.start()

A: What kind of errors do you expect?

*

*Python is dynamically typed, so you can assign the same variable to objects of different types no problem;

*That the even, odd variables are no longer assigned to the thread objects doesn't mean the threads don't run, so that's fine too;

*if condition: is actually if bool(condition):, and, provided that a Thread object is truthy, the first thread does get into the first if statement and assigns the even, odd variables to plain booleans.

It's simple to see that Thread objects are indeed truthy:
>>> import threading
>>> th = threading.Thread(target=print)
>>> bool(th)
True


text:
Q: Markov chain: closed, finite classes are recurrent? In Norris: Markov Chains the closed class C is defined as one for which $i\in C$ and $P_i(X_n=j \text{ for some }n\ge0)>0$ implies that $j\in C$.
Here's theorem 1.5.6 from the book with proof
Every finite closed class is recurrent.
Proof: Suppose C is closed and finite and that the chain $X_n$ starts in $C$. Then for some $i\in C$ we have
$$0<P(X_n =i\text{ for infinitely many }n)=P(X_n =i \text{ for some } n)P_i(X_n =i\text{ for infinitely many }n)$$
by the strong Markov property. So $i$ is not transient, hence $C$ is recurrent.
I'm confused because take for example a state the chain never reaches, say $y$. Then the union of an irreducible set (where all pairs of states communicate) and $y$ is not irreducible anymore but it is  closed. So $y$ cannot be recurrent since it is never reached. Hence the irreducibility condition might be needed in addition closed + finiteness to imply recurrence?

A: The word "class" as defined in the book means "comunicating class" (i.e. class = irreducible set). Since you have added the state $y$ it is not anymore comunnicating since it is unreachable and thus the property does not apply.

A: In your example, provided that $y$ itself belongs to a closed class, then $y$ is recurrent and is hit infinitely often starting at $y$. That is,
$$\mathbb{P}_y(X_n=y\mbox{ for infinitely many }n)>0.$$
Be careful, the definition of a recurrent state depends on the starting point, and it certainly doesn't guarantee that we hit state $y$ infinitely often starting somewhere else.


text:
Q: Any way to include a function as message with mosquitto in python?

import dweepy
import os

_=os.system("clear")

myThing = "4400D_sensor" #Add value: add your dweet thing name

print("getting latest dweet...")
latest_dweet = dweepy.get_latest_dweet_for(myThing) #get latest dweet
latest_created = latest_dweet[0]["created"]  #put the created value of the lastest dweet into a variable
latest_content = latest_dweet[0]["content"]
print("Latest dweet time:", latest_created)
print("Latest dweet content:", latest_content)
print("Latest dweet JSON")
print(latest_dweet)
print()
os.system('mosquitto_pub -d -h 172.19.0.12 -t cisco/iots/user -m "testing"')

The above is my current code and I am trying to figure out a way to replace the string "testing" with my latest_dweet variable so I can send a different message each time instead of hardcoding it. Any idea how I can do that?
I am trying to play around with that line where I want to achieve my goal however right now I am still unable to do so.

A: Don't!
Go look at the Paho Python library to send MQTT messages directly from the python code rather than shelling out to mosquitto_pub
https://www.eclipse.org/paho/clients/python/


text:
Q: How can I prove $\int_{0}^{\infty}\frac{x^2+1}{(x^4+2ax^2+1)(x^s+1)} dx=\frac{π}{2\sqrt{2a+2}}$ Question:- Prove that $$\int_{0}^{\infty}\frac{x^2+1}{(x^4+2ax^2+1)(x^s+1)} dx=\frac{π}{2\sqrt{2a+2}}$$
I Recenty got stuck on evaluating this integral,the result is independent of $s$. with $s=2$ , I verified the result.I don't know how to start evaluating the integral, since known method such as subsitution, Beta function(since it involves in these kind of problems) to me doesn't help here.
Could someone help me?

A: Let  $$I = \int_{0}^{\infty}\frac{x^2+1}{(x^4+2ax^2+1)(x^s+1)} dx$$
Start by substituting $x = 1/t$
$$\implies I = \int_{0}^{\infty}\frac{t^2+1}{(t^4+2at^2+1)(1+\frac1{t^s})} dt$$
$$ = \int_{0}^{\infty}\frac{(t^2+1)t^s}{(t^4+2at^2+1)(t^s+1)} dt$$
$$ = \int_{0}^{\infty}\frac{(t^2+1)(t^s+1)-(t^2+1)}{(t^4+2at^2+1)(t^s+1)} dt$$
$$ = \int_{0}^{\infty}\frac{t^2+1}{(t^4+2at^2+1)} dt - I$$
$$\implies 2I = \int_{0}^{\infty}\frac{t^2+1}{(t^4+2at^2+1)} dt$$
Now divide the numerator and denomintor by $t^2$
$$\implies 2I = \int_{0}^{\infty}\frac{1+\frac{1}{t^2}}{(t-\frac1t)^2+2a+2} dt$$
Now a simple substitution should do it.


text:
Q: Kazam always record only 1/4 of the screen I'm trying to use Kazam to take videos of the screen. It always records the 1/4 of top left of my screen, no matter what I do. No matter if I select the entire screen, a window or select a piece of the screen to record.
I guess it has to do with scaling. I use scaling in my ubuntu because it's a 4k monitor. Is there a way to overcome this?

A: Indeed, has to do with the scaling configuration of your monitor. I also have a 4K and I need to use 200% scaling.
This patch solves the issue, it's very simple to apply. I tested it on Ubuntu 22.04.1 and it works perfectly.

A: Found the same issue on the kazam github https://github.com/hzbd/kazam/pull/47.
@sllorente prepared the path for 1 file only (instead of 2) which fixes the issue, see https://bugs.launchpad.net/kazam/+bug/1283424/comments/13
The patch can be downloaded from https://bugs.launchpad.net/kazam/+bug/1283424/+attachment/5499618/+files/kazam-1.4.5-patch
--- kazam-1.4.5/backend/prefs.py    2014-08-18 18:48:36.000000000 +0200
+++ kazam/backend/prefs.py  2021-05-23 15:30:44.876596507 +0200
@@ -312,22 +312,31 @@
             self.default_screen = Gdk.Screen.get_default()
             self.logger.debug("Found {0} monitor(s).".format(self.default_screen.get_n_monitors()))

+            combined_width = 0
+            combined_height = 0
             for i in range(self.default_screen.get_n_monitors()):
                 rect = self.default_screen.get_monitor_geometry(i)
-                self.logger.debug("  Monitor {0} - X: {1}, Y: {2}, W: {3}, H: {4}".format(i,
+                scale = self.default_screen.get_monitor_scale_factor(i)
+
+                self.logger.debug("  Monitor {0} - X: {1}, Y: {2}, W: {3}, H: {4}, scale: {5}".format(i,
                                                                                rect.x,
                                                                                rect.y,
                                                                                rect.width,
-                                                                                rect.height))
-                self.screens.append({"x": rect.x,
-                                     "y": rect.y,
-                                     "width": rect.width,
-                                     "height": rect.height})
+                                                                                rect.height,
+                                                                                scale))
+                self.screens.append({"x": rect.x * scale,
+                                     "y": rect.y * scale,
+                                     "width": rect.width * scale,
+                                     "height": rect.height * scale,
+                                     "scale": scale})
+
+                combined_width = combined_width + rect.width * scale
+                combined_height = combined_height + rect.height *scale

             if self.default_screen.get_n_monitors() > 1:
                 self.combined_screen = {"x": 0, "y": 0,
-                                        "width": self.default_screen.get_width(),
-                                        "height": self.default_screen.get_height()}
+                                        "width": combined_width,
+                                        "height": combined_height}
                 self.logger.debug("  Combined screen - X: 0, Y: 0, W: {0}, H: {1}".format(self.default_screen.get_width(),
                                                                                self.default_screen.get_height()))
             else:

FYI the file can be patched with the command
sudo patch /usr/lib/python3/dist-packages/kazam/backend/prefs.py < ~/Desktop/kazam-1.4.5.diff


text:
Q: AWS GLUE import xls/xlsx file I'm setting up a AWS GLUE job for my customers. Their files are excel with xls/xlsx extension and have multiple sheets and they don't want to do any convert job before uploading. How do I extract data from xls/xlsx file directly or can GLUE convert xls/xlsx file to csv file?

A: xls/xlsx is not supported in GLUE as of now. The easiest way is to write a python shell job in glue to convert excel to csv and then run crawler over it.  Below is sample in python
 import xlrd
 import csv

 def csv_from_excel():

    wb = xlrd.open_workbook('your_workbook.xls')
    sh = wb.sheet_by_name('Sheet1')
    your_csv_file = open('your_csv_file.csv', 'wb')
    wr = csv.writer(your_csv_file, quoting=csv.QUOTE_ALL)

    for rownum in xrange(sh.nrows):
        wr.writerow(sh.row_values(rownum))

    your_csv_file.close()

A: Excel read is possible in glue version 2 not in glue version 3.
Steps:

*

*Go to glue job and edit script with below code

code:
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import pandas as pd

args = getResolvedOptions(sys.argv, ['JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

excel_path= r"s3://input/employee.xlsx"
df_xl_op = pd.read_excel(excel_path,sheet_name = "Sheet1")
df=df_xl_op.applymap(str)
input_df = spark.createDataFrame(df)
input_df.printSchema()

job.commit()

*Save script

*Goto Action - Edit Job - Select Glue version2   and set key value under security configuration
key : --additional-python-modules
value : pandas==1.2.4,xlrd==1.2.0,numpy==1.20.1,fsspec==0.7.4

*Save and run the job
It will resolve your error and you will be able to read the excel file

A: The xls/xlsx file type is not available at the moment. You need to write transformer script to convert the file from xls/xlsx to CSV.
Classifier API


text:
Q: How do I properly send the "this" object to a function I have a function which I want to trigger on certain events. This function has to access the "this" object of the element that the event happened on. I am having hard time passing it to the function.
This is my code but it's not working, it looks like the problem is with the "thisVariable" not being the original element. I have similar code which is split into more functions but works, and I just wanted to simplify things.
$(document).on('focusin', '.formInput', function () {
    freezingScanNewRowEvaluation(this);
});

function freezingScanNewRowEvaluation(thisVariable) {
    var currentInput = thisVariable;
// other stuff, more event listeners binded to the original element
}

Should this aproach actually work and I am doing something else wrong, or is passing "this" like this nonsense? Thanks
Edit: My whole function:
Edit2: The problem seems to be on binding more events to $(currentInput), it registers the Enter button, but nothing else is detected, and no errors show in console.
function freezingScanNewRowEvaluation(thisVariable) {
    var currentInput = thisVariable;
    var parentRow = thisVariable.closest(".formRow");
    var parentComponent = thisVariable.closest(".newScanRowComponent");
    var nextRow = $(parentRow).next();
    if ($(parentRow).hasClass("formRow--editMode") == false) {
        return;
}

$(parentRow).find("label").text($(".newScanRowComponent").length);

// Save current value of element
$(currentInput).data('oldVal', $(currentInput).val());

// Look for changes in the value
$(currentInput).bind("propertychange change click keyup input paste", function (event) {

    if (event.which == 13) {
       // stuff - This detects ok, but none of the other events do...
    }

    // If value has changed...
    var inputValueNew = $(currentInput).val();
    var inputValueOld = $(currentInput).data('oldVal');

    if (inputValueOld != inputValueNew) {
        // Updated stored value
       $(currentInput).data('oldVal', $(currentInput).val());

        if (inputValueNew.length - inputValueOld.length > 6) {
        rowSuccessMarkerShow(parentRow);
        switchInputRowType(parentRow);

        // stuff
        }
    }
});

function switchInputRowType(row) {
    if ($(row).hasClass("formRow--editMode" && $(row).find("input").val() != "")) {
        // stuff
    } else if (row.hasClass("formRow--active")) {
        // stuff
    }
}

function rowSuccessMarkerShow(row) {
    if (!$(row).hasClass("formInput1") && $(row).find("input").val() != "") {
        // stuff
    }
}
}

A: Thanks everyone for the replies, you were all most helpful!
The most important things I needed to ask I learned from the first two replies by CertainPerformance and VLAZ.
It appears that my error was that I put brackets behind the callback function here:
$(document).on('focusin', '.formInput', freezingScanNewRowEvaluation**()**);
After removing them it now works fine.
Thanks again!


text:
Q: TSP implementation in docplex python Is there any python implementation available of TSP using the IBM cplex tool, with Dantzig-Fulkerson-Johnson formulation.
If there is any can I get the link for it?

A: The exact same question was asked here. Here is my (slightly modified) answer from there:
The distribution does not have an example implementation in Python, but there is one in OPL: opl/examples/opl/models/TravelingSalesmanProblem/tsp.mod in your installation. This could serve as a good starting point when implementing things in Python.
In the example the problem is solved in a loop: after each solve, subtour elimination constraints are separated. In Python you would probably want to do this using a lazy constraint callback.
In general, subtour elimination constraints are usually not added directly to the model since there exponentially many of them.


text:
Q: NAS as (direct) datastore for esxi host I'm using a NAS box as a datastore for my esxi host. The NAS and esxi host are connected to each other via a switch.
I want to experiment a little and was thinking of ways to connect the NAS box to the host directly, and was wandering if it even possible and what effect(s) it will have
(1) if the NAS box and esxi host have another, spare ethernet port, can I connect them to each other directly? Instead of through a network? Would this have much of a performance gain?
(2) USB 3.0. Can I connect the NAS box to the esxi via usb 3.0 cables so that the NAS appears as a mass storage device? Given the performance of USB 3.0, would this be beneficial?

A: This depends on your NAS unit. You can attach the NAS as a datastore either via NFS or preferably iSCSI if that is a supported option.
Whether connecting them directly has a performance benefit depends on your network topology and how much traffic your VMs produce. If your VMs do not produce too much traffic and both the hypervisor and the NAS are attached to the same switch, the performance gain would be rather small. But if both units have a spare port anyway, there isn't really a reason not to.
Using USB as a datastore is not supported in ESXi, so I wouldn't do it. But it is possible and might be faster again depending on the exact hardware of both machines.
Another solution would be to connect both machines via 10 GbE or eSATA. eSATA is also not officially supported but it is better than USB.

A: 1) Yes. Performance gain due to eliminating the switch: Effectively zero. It still can help (potentially a lot) if the other network port has other traffic on it, as the direct connection is exclusive for the NAS traffic.
2) As far as you are asking if you can use USB block storage to format it with VMFS: Effectively no. It's still not official supported to my knowledge, and while there exist posts on the internet that explain how to do it anyway, I believe this is bad practice.

A: *

*Yes, it will work. The performance will will be negligible, unless your switch is completely overloaded or super duper crappy.

*Possible, yet. Supported, no. You will have to test to see if it's faster.


text:
Q: Unable to read VSTS Online release variables I'm working with VSTS environment variables and stuck with variables of a secret type.
I'm using POSH script (file) to generate a variable (in fact, to obtain the value from Azure Key Vault and the set this value to the variable):
# Add as a script parameter during the release step
-ResourceGroupNameArg "$(ResourceGroupName)" -KeyVaultNameArg "$(KeyVaultName)" -KeyVaultSecretNameArg "$(KeyVaultSecretName)"

# The script itself
Param(
   [string]$ResourceGroupNameArg,
   [string]$KeyVaultNameArg,
   [string]$KeyVaultSecretNameArg
)
<...>
$secret = Get-AzureKeyVaultSecret -VaultName $KeyVaultNameArg -Name $KeyVaultSecretNameArg
$secretValue = $secret.SecretValueText
Write-Host "##vso[task.setvariable variable=SQLAdministratorPassword;issecret=true]$secretValue"

Here I can pass to the script different KeyVault names (according to my needs) - by substituting the $KeyVaultNameArg and $KeyVaultSecretNameArg variables.
For any other variables configured using ##vso[task.setvariable variable= I am able to retrieve them using the construction  $env:DatabaseName (for example in another POSH script) or $(DatabaseName) in agent phase step (using Hosted 2017 agent).
However, for the issecret=true variable or even for a manually created variable I'm unable to retrieve its values during the release deployment process.

According to this article,

The values of hidden (secret) variables are stored securely on the
  server and cannot be viewed by users after they are saved. During a
  deployment, the Release Management service decrypts these values when
  referenced by the tasks and passes them to the agent over a secure
  HTTPS channel.

So IMO the variables should be accessible for the script (or even agent phase step) despite they are secret.

A: Refer to these steps to do it:

*

*Click Library tab

*Click + Variable group

*Specify variable group name

*Enable Link secrets for an Azure Key vault as variables and link Azure key vault

*Click +Add to add necessary secret(s)

*Edit release definition

*Choose Variables tab

*Select Variable groups

*Click Link variable group to link that variable group

*Using the related variable directly in release task ($(variable name))


text:
Q: Express: app.use() adding middeware as multiple args versus separate statements? Let's say I have an express web app for which I'm adding some of the standard middleware:
app.use(express.static(config.staticRoot, { maxAge: 300000 }));
app.use(compression());
app.use(cookieParser());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(passport.initialize());
app.use(passport.session());

What's the difference between the above and if I had called it like this:
app.use(
  express.static(config.staticRoot, { maxAge: 300000 }),
  compression(),
  cookieParser(),
  bodyParser.json(),
  bodyParser.urlencoded({ extended: true }),
  passport.initialize(),
  passport.session()
);

A: There is a difference
Take a look at express documentation
app.use([path,] callback [, callback...])

callback - Callback functions can be:

*

*A middleware function.

*A series of middleware functions (separated by commas).

*An array of middleware functions.

*A combination of all of the above.

You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
So to be confident that your middleware executes, write them as your first version
Also notice that by default router uses /route, when you call app.use separately for each middleware, you have more control over which route they should be plugged
// GOOD
app.use('/', express.static(config.staticRoot, { maxAge: 300000 }));
app.use('/', compression());

// BAD
app.use('/', express.static(config.staticRoot, { maxAge: 300000 }), compression(), cookieParser());

Bad because compression() middleware could call next('/someOtherPage'); which will skip other middlwares bound to /

A: Invoke app.use() with separate statements is much more flexible than multiple args. Here are some examples:

*

*What if some middlewares are only applied under specific condition? Like:
if (isProductionMode) {
  app.use(middlewareOnlyInProduction);
} else {
  app.use(middlewareOnlyInDevelopment);
}

Of course you can implement similar logic with app.use.apply(...) and pass the correct middleware array, but that would increase the complexity.

*What if some middlewares are only applied after an async call?
app.use(middlewareA);
aPromise.then(function() {
  app.use(middlewareB);
}).catch(function() {
  app.use(middlewareC);
});

With "multiple args" solution, there is no way to implement such logic.
With "separate statements" solution, you can add middleware no matter where or when. With "multiple args" solution, you can only add middleware once, which is very restricted.


text:
Q: Is there anything bad about using $_SESSION in Laravel 5.8 and if so what and why? I am trying to access a Laravel 5.8 session and unset an array inside an object in the session but I cant seem to figure it out.
I can use native php $_SESSION and just unset($_SESSION["object"]->myarray[row_number]) and all is good in the world but It does not seem that easy with Laravel sessions.
I would like to avoid Laravel sessions all together and use the native php to save time and finish this project and I am just wondering if there are any long term Cons to using native php sessions in laravel
I have searched google and Laravel docs but can't find anything on accessing objects with multidimensional arrays in Laravel.

A:
I would like to avoid Laravel sessions all together and use the native php to save time and finish this project and I am just wondering if there are any long term Cons to using native php sessions in laravel

This is a little tricky as it verges way from Stack Overflow's remit into opinions, but here goes:
You should always use Laravel's functions where possible as it provides you with protection that you may not be aware of, and it future-proofs changes. It also keeps your code consistent.
For example, if you wanted to change how you store session variables in the future, you would have to re-write every piece of code where you've used $_SESSION["object"]. Using Laravel's interface means that if you were to change how this was stored in the future, you would not have to update your code in your site to reflect this change.
See other suggestions on better ways to write this using Laravel, but to answer the question "Is there anything bad about using $_SESSION in Laravel 5.8 and if so what and why?" – yes, in short.

A: In Laravel you can utilize the session vars like so. Link to documentation.
$request->session()->get('object');

You should be able to do what you want with something similar like.
$index = 0;
$request->session()->forget('object.myarray.' . index);

A: Try to do this  $value = $request->session()->get('key.value');
See session docs

A: for a multidimensional array for
$tempCategories = array(
    0 => array(
        'cat' => 'Wood'
    ),
    1 => array(
        'cat' => 'Metal'
    ),
);
<h5>{{$cat['cat']}}</h5>


text:
Q: Convert double to float in Java I am facing an issue related to converting double to float. Actually, I store a float type, 23423424666767, in a database, but when we get data from the database in the below code, getInfoValueNumeric(), it's of double type. The value we get is in the 2.3423424666767E13 form.
So how do we get a float format data like 23423424666767?
2.3423424666767E13 to 23423424666767
public void setInfoValueNumeric(java.lang.Double value) {
    setValue(4, value);
}

@javax.persistence.Column(name = "InfoValueNumeric", precision = 53)
public java.lang.Double getInfoValueNumeric() {
    return (java.lang.Double) getValue(4);
}

A: Converting from double to float will be a narrowing conversion. From the doc:

A narrowing primitive conversion may lose information about the
  overall magnitude of a numeric value and may also lose precision and
  range.
A narrowing primitive conversion from double to float is governed by
  the IEEE 754 rounding rules (§4.2.4). This conversion can lose
  precision, but also lose range, resulting in a float zero from a
  nonzero double and a float infinity from a finite double. A double NaN
  is converted to a float NaN and a double infinity is converted to the
  same-signed float infinity.

So it is not a good idea. If you still want it you can do it like:
double d = 3.0;
float f = (float) d;

A:
To answer your query on "How to convert 2.3423424666767E13 to
  23423424666767"

You can use a decimal formatter for formatting decimal numbers.
     double d = 2.3423424666767E13;
     DecimalFormat decimalFormat = new DecimalFormat("#");
     System.out.println(decimalFormat.format(d));

Output : 23423424666767

A: I suggest you to retrieve the value stored into the Database as BigDecimal type:
BigDecimal number = new BigDecimal("2.3423424666767E13");

int myInt = number.intValue();
double myDouble = number.doubleValue();

// your purpose
float myFloat = number.floatValue();

BigDecimal provide you a lot of functionalities.

A: Convert Double to Float
public static Float convertToFloat(Double doubleValue) {
    return doubleValue == null ? null : doubleValue.floatValue();
}

Convert double to Float
public static Float convertToFloat(double doubleValue) {
    return (float) doubleValue;
}

A: Just cast your double to a float.
double d = getInfoValueNumeric();
float f = (float)d;

Also notice that the primitive types can NOT store an infinite set of numbers:
float range: from 1.40129846432481707e-45 to 3.40282346638528860e+38
double range: from 1.7e–308 to 1.7e+308

A: This is a nice way to do it:
Double d = 0.5;
float f = d.floatValue();

if you have d as a primitive type just add one line:
double d = 0.5;
Double D = Double.valueOf(d);
float f = D.floatValue();

A: The problem is, your value cannot be stored accurately in single precision floating point type. Proof:
public class test{
    public static void main(String[] args){
        Float a = Float.valueOf("23423424666767");
        System.out.printf("%f\n", a); //23423424135168,000000
        System.out.println(a);        //2.34234241E13
    }
}

Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.

A: First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float. Float is short for floating point, and floating point types of various precisions exist. Java types float and double are both floating point types of different precision. In a database both are called FLOAT. Since double has a higher precision than float, it probably is a better idea not to cast your value to a float, because you might lose precision.
You might also use BigDecimal, which represent an arbitrary-precision number.

A: Use dataType casting.  For example:
// converting from double to float:
double someValue;
// cast someValue to float!
float newValue = (float)someValue;

Cheers!
Note:
Integers are whole numbers, e.g. 10, 400, or -5.
Floating point numbers (floats) have decimal points and decimal places, for example 12.5, and 56.7786543.
Doubles are a specific type of floating point number that have greater precision than standard floating point numbers (meaning that they are accurate to a greater number of decimal places).

A: Float.parseFloat(String.valueOf(your_number)


text:
Q: Replacement for deprecated `keypress` DOM event According to MDN article keypress event is deprecated:

But I can't find any information elsewhere on whether we should use this event in a new projects. If we shouldn't, what is the replacement?
Could somebody give an insight?

A: Since the event is deprecated, you should avoid using it in new code, and plan on removing it from old code. The W3C specification says this about deprecated features:

Features marked as deprecated are included in the specification as reference to older implementations or specifications, but are OPTIONAL and discouraged. Only features which have existing or in-progress replacements MUST be deprecated in this specification. Implementations which do not already include support for the feature MAY implement deprecated features for reasons of backwards compatibility with existing content, but content authors creating content SHOULD NOT use deprecated features, unless there is no other way to solve a use case. Other specifications which reference this specification SHOULD NOT use deprecated features, but SHOULD point instead to the replacements of which the feature is deprecated in favor. Features marked as deprecated in this specification are expected to be dropped from future specifications.

The specification of the keypress event says:

Warning The keypress event type is defined in this specification for  reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.

You can also use the keydown and/or keyup events. See What's the difference between keyup, keydown, keypress and input events?
However, since beforeinput doesn't yet have much support, if none of these other events fits your use case you'll have to continue to use keypress for now (that's the "unless there is no other way to solve a use case" exception in the spec).

A:  const handleKeyDown = (e: any) => {
  if (e.code === "Enter") {
  triggerBusqueda(e.target.value);
  }
};

onKeyDown={handleKeyDown}

You can use this code, it works very well.

A: Not super hard to work around unless (shame on you) you or something you use has been clobbering event bubbling indiscriminately at every opportunity.
Simple but powerful utility like this is exactly why you should only do that for isolated node leaves of your HTML.
In those cases where you did have to prevent keydown bubbling you could simply wrap the following in a function that takes an argument in place of document.body and simply apply at the point where bubbling is stopped if you still want 'keypress2' events available to that HMTL.
const keyBlacklist = [
    'Shift',
    'Alt',
    'Control',
    'Meta'
];

document.body.addEventListener('keydown',(e)=>{
    if(keyBlacklist.indexOf(e.key) === -1){
        const newKeyPress = new CustomEvent('keypress2',{detail:e});
        e.target.dispatchEvent(newKeyPress);
    }
});

document.body.addEventListener('keypress2',e=>{console.log(e.detail);});


text:
Q: GitHub Actions fails while the script is working locally without no problem on self-hosted because NPM warnings GitHub Actions fails while the bash script is working locally without no problem on self-hosted because NPM warnings.
Every time, on NPM warnings the script fails with the error: "Error: Process completed with exit code 1" only when running the script using Github Actions. The script works fine when i am running the script locally on the same SERVER i am running the actions-runner service.
When i am fixing the "NPM Warning" it goes fine but fail on the next warning.. i don't want to waste time on fixing that warnings but still want to use GitHub actions.
adding --silent to the npm install command solves the problem but I don't want to add it. why can't GitHub action just work according to the error level? why to fail according to the output text?
I also tried set CI variable to false but without success


text:
Q: Md2 model vertices loading issue I'm trying to load an MD2 model but I can't seem to get the vertices to draw correctly. I'm not loading UVs or normals at the moment just want to see the model appear correctly in a single frame then take it from there.
Here's my md2 structures (mostly taken from here):
struct v3
{
    union
    {
        struct
        {
            union { float x; float r; };
            union { float y; float g; };
            union { float z; float b; };
        };
        float At[3];
    };
};

struct md2_header
{
    unsigned int Magic;
    unsigned int Version;

    unsigned int TextureWidth;
    unsigned int TextureHeight;

    unsigned int FrameSize;

    unsigned int NumTextures;
    unsigned int NumVertices;
    unsigned int NumUVs;
    unsigned int NumTrigs;
    unsigned int NumGLCommands;
    unsigned int NumFrames;

    unsigned int OffsetTextures;
    unsigned int OffsetUVs;
    unsigned int OffsetTrigs;
    unsigned int OffsetFrames;
    unsigned int OffsetGLCommands;
    unsigned int OffsetEnd;
};

struct md2_vertex
{
    unsigned char At[3];
    unsigned char NormalIndex;
};

struct md2_frame
{
    float       Scale[3];
    float       Translate[3];
    char        Name[16];
    md2_vertex  *Vertices;
};

struct md2_skin
{
    char Name[64];
};

struct md2_uv
{
    unsigned short u;
    unsigend short v;
}

struct md2_triangle
{
    unsigned short Vertices[3];
    unsigned short UVs[3];
};

struct md2_model
{
    md2_header Header;
    md2_uv *UVs;
    md2_triangle *Triangles;
    md2_frame *Frames;
    md2_skin *Skins;
    int *GLCommands;
    unsigned int Texture;
    unsigned int VAO, VBO;
};

And here's my simple loading function:
void MD2LoadModel (char *FilePath, md2_model *Model)
{
    FILE *File = fopen (FilePath, "rb");
    if (!File)
    {
        fprintf (stderr, "Error: couldn't open \"%s\"!\n", FilePath);
        return;
    }

#define FREAD(Dest, Type, Count)\
    fread(Dest, sizeof(Type), Count, File)

#define FSEEK(Offset)\
    fseek(File, Offset, SEEK_SET)

#define ALLOC(Type, Count)\
    (Type *)malloc(sizeof(Type) * Count)

    /* Read Header */
    FREAD(&Model->Header, md2_header, 1);

    if ((Model->Header.Magic != 844121161) ||
        (Model->Header.Version != 8))
    {
        fprintf (stderr, "Error: bad md2 Version or identifier\n");
        fclose (File);
        return;
    }

    /* Memory allocations */
    Model->Skins = ALLOC(md2_skin, Model->Header.NumTextures);
    Model->UVs = ALLOC(md2_uv, Model->Header.NumUVs);
    Model->Triangles = ALLOC(md2_triangle, Model->Header.NumTrigs);
    Model->Frames = ALLOC(md2_frame, Model->Header.NumFrames);
    Model->GLCommands = ALLOC(int, Model->Header.NumGLCommands);

    /* Read model data */
    FSEEK(Model->Header.OffsetTextures);
    FREAD(Model->Skins, md2_skin, Model->Header.NumTextures);

    FSEEK(Model->Header.OffsetUVs);
    FREAD(Model->UVs, md2_uv, Model->Header.NumUVs);

    FSEEK(Model->Header.OffsetTrigs);
    FREAD(Model->Triangles, md2_triangle, Model->Header.NumTrigs);

    FSEEK(Model->Header.OffsetGLCommands);
    FREAD(Model->GLCommands, int, Model->Header.NumGLCommands);

    /* Read frames */
    FSEEK(Model->Header.OffsetFrames);
    for (int i = 0; i < Model->Header.NumFrames; i++)
    {
        /* Memory allocation for vertices of this frame */
        Model->Frames[i].Vertices = (md2_vertex *)
            malloc(sizeof(md2_vertex) * Model->Header.NumVertices);

        /* Read frame data */
        FREAD(&Model->Frames[i].Scale, v3, 1);
        FREAD(&Model->Frames[i].Translate, v3, 1);
        FREAD(Model->Frames[i].Name, char, 16);
        FREAD(Model->Frames[i].Vertices, md2_vertex, Model->Header.NumVertices);
    }

    v3 *Vertices = ALLOC(v3, Model->Header.NumVertices);

    md2_frame *Frame = &Model->Frames[0];
    For(u32, i, Model->Header.NumVertices)
    {
        Vertices[i] = V3(
            (Frame->Vertices[i].At[0] * Frame->Scale[0]) + Frame->Translate[0],
            (Frame->Vertices[i].At[1] * Frame->Scale[1]) + Frame->Translate[1],
            (Frame->Vertices[i].At[2] * Frame->Scale[2]) + Frame->Translate[2]);
    }

    glGenBuffers(1, &Model->VBO);
    glBindBuffer(GL_ARRAY_BUFFER, Model->VBO);
    glBufferData(GL_ARRAY_BUFFER, Model->Header.NumVertices * sizeof(v3), Vertices, GL_STATIC_DRAW);

    glGenVertexArrays(1, &Model->VAO);
    glBindVertexArray(Model->VAO);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    fclose (File);
    free(Vertices);

#undef FSEEK
#undef FREAD
#undef ALLOC
}

Only passing the vertices data. Which, from my understanding Header->NumVertices is the number of vertices in each frame. So I'm taking an arbitrary frame (frame 0 in this case) and reading its uncompressed vertices data into Vertices.
Now I read in a book that Quake had their y and z axes flipped, but that still didn't change much.
Here's how I'm drawing the model:
GLuint Shader = Data->Shaders.Md2Test;
ShaderUse(Shader);
ShaderSetM4(Shader, "view", &WorldToView);
ShaderSetM4(Shader, "projection", &ViewToProjection);

glBindVertexArray(DrFreak.VAO);
{
    ModelToWorld = m4_Identity;
    ShaderSetM4(Shader, "model", &ModelToWorld);
    glDrawArrays(GL_TRIANGLES, 0, DrFreak.Header.NumVertices);
}
glBindVertexArray(0);

The matrices are calculated in a CameraUpdate function which I can verify is working correctly because everything else in the scene render properly except the MD2 model. See:

Everything in yellow is supposed to be the MD2 model.
Here are my shaders (pretty much the same shaders for the crates and planes except there's only one 'in' variable, the position and no UVs):
#version 330 core
layout (location = 0) in vec3 position;

uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    gl_Position = projection * view * model * vec4(position, 1.0f);
}

#version 330 core
out vec4 color;
void main()
{
    color = vec4(1, 1, 0, 1);
}

I've been stuck here for a couple of days. I stepped into the loading code and I seem to be getting valid values. I'm not sure what's the issue. What am I doing wrong/missing?
Any help is appreciated.

A: I fixed the problem by duplicating the vertices/uvs getting them from the tirangles data. I didn't have to flip the 't' UV coordinate like many tutorials do. I switched the y and z coordinates cause they're flipped.
u32 NumVerts = Model->Header.NumTrigs * 3;
u32 NumUVs = NumVerts;

v3 *Vertices = ALLOC(v3, NumVerts);
v2 *UVs = ALLOC(v2, NumUVs);

md2_frame *Frame = &Model->Frames[0]; // render first frame for testing

For(u32, i, Model->Header.NumTrigs)
{
    For(u32, j, 3)
    {
        u32 VertIndex = Model->Triangles[i].Vertices[j];
        Vertices[i * 3 + j] = V3(
            (Frame->Vertices[VertIndex].At[0] * Frame->Scale[0]) + Frame->Translate[0],
            (Frame->Vertices[VertIndex].At[2] * Frame->Scale[2]) + Frame->Translate[2],
            (Frame->Vertices[VertIndex].At[1] * Frame->Scale[1]) + Frame->Translate[1]);

        u32 UVIndex = Model->Triangles[i].UVs[j];
        UVs[i * 3 + j] = V2(
            Model->UVs[UVIndex].u / (r32)Model->Header.TextureWidth,
            Model->UVs[UVIndex].v / (r32)Model->Header.TextureHeight);
    }
}

glGenVertexArrays(1, &Model->VAO);
glBindVertexArray(Model->VAO);

glGenBuffers(1, &Model->VBO);
glBindBuffer(GL_ARRAY_BUFFER, Model->VBO);
glBufferData(GL_ARRAY_BUFFER, NumVerts * sizeof(v3), Vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

u32 UVBuffer;
glGenBuffers(1, &UVBuffer);
glBindBuffer(GL_ARRAY_BUFFER, UVBuffer);
glBufferData(GL_ARRAY_BUFFER, NumUVs * sizeof(v2), UVs, GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);

glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);

I will probably use indexed arrays and glDrawElements. But for my testing purposes glDrawArrays is good enough. If anyone knows of a better way to do all this feel free to leave a comment.
And there's Dr Freak chillin'


text:
Q: Can the likelihood function in MLE be equal to zero? We have likelihood function
$$
L\left(\mathbf{\Theta} \middle| x_1, \ldots, x_n \right) = \prod^n_{i=1} f\left( x_i \middle| \mathbf{\Theta} \right)
$$
and a score function
$$
V\left(\mathbf{\Theta} \middle| x_1, \ldots, x_n \right) = \nabla_\Theta \sum^n_{i=1} \ln{f\left(x_i, \mathbf{\Theta} \right)},
$$
where $x_i$ are observations and $\mathbf{\Theta}$ is the vector of parameters.
If we consider the maximum likelihood estimator $\mathbf{\Theta^{\ast}}$, it's the extreme of $L$, so
$$
V\left(\mathbf{\Theta^{\ast}}\right) = 0,
$$
but we need $L\left(\mathbf{\Theta^{\ast}}\middle| x_1, \ldots, x_n \right) \neq 0$.
So, is this inequality always true or is there a situation, where the likelihood with the MLE could be equal to zero?

A: If you have a very inadequate model such that at least one discretely (or continuously) distributed observation has zero probability (or probability density) for any parameter value $\theta\in\Theta$, that is, you essentially observe something that is impossible under that model, then yes, your maximum likelihood would be zero.

A: If you observe a sample that has zero probability density under every possible parameter value then the likelihood function is zero over the parameter space.  In this case every parameter value is a legitimate value of the MLE (i.e., the MLE is the whole parameter space) and the likelihood is zero at every point that is an MLE.  That situation is unusual (and usually entails a misspecified model).  The more usual situation is when the likelihood function is positive for at least one parameter value in the parameter space, in which case the likelihood at any MLE point must be positive (proof below).

Theorem: Consider a likelihood function $L_\mathbf{x}: \Theta \rightarrow \mathbb{R}$ where we have:
$$L_\mathbf{x}(\theta) > 0 \quad \text{for some } \theta \in \Theta.$$
Any point $\hat{\theta} \in \Theta$ that is an MLE of this likelihood function must satisfy $L_\mathbf{x}(\hat{\theta}) > 0$.
Proof: We proceed using a proof by contradiction.  Suppose, contrary to the theorem that there is a point $\hat{\theta}$ that is an MLE and has $L_\mathbf{x}(\hat{\theta}) \leqslant 0$.  Since this point is an MLE it must satisfy:
$$L_\mathbf{x}(\hat{\theta}) \geqslant L_\mathbf{x}(\theta) \quad \text{for all } \theta \in \Theta.$$
This implies that $L_\mathbf{x}(\theta) \leqslant L_\mathbf{x}(\hat{\theta}) \leqslant 0$ for all $\theta \in \Theta$ which contradicts the condition on the likelihood in the theorem.  By contradiction, this completes the proof.  $\blacksquare$

A: When you define the MLE as the unique point where the likelihood function has a maximum, and if the parameter space consists of multiple points then the likelihood in the MLE must be non-zero.
The reason is that the likelihood must be non-negative and thus zero is the minimum value of the entire range. If the MLE has zero likelihood then this leads to a contradiction. This is because: if the extremum value equals the minimum value of the entire range then there can not be a unique extremum point. Every point will have the same value.

A: To add a concrete example to the answer by @Jarle Tufto: If $X_1, X_2, \dotsc, X_n$ are iid $\mathcal{U}(0, \theta)$, then any $\theta$ lesser than the maximum observed value give a zero likelihood, since under this model all observations must be lesser (or equal) to $\theta$.


text:
Q: How can I use whole android project inside a new android project I have source code of indic-keyboard, and I want to use functionality of this project in my app, I have tried converting indic-project into a library, but that seems tough, so I am looking for some other workaround for this thing.
What can/have I try/tried-

*

*I try to change "apply plugin: 'com.android.application'' to "apply plugin: 'com.android.library", then synced the gradle and got this some errors(check this issue), there I got confirmation developer of indic-keyboard that it will be tough to convert it into a library as this project is an input-method which relies on system settings.

*So now I am thinking to use whole the project within my app, such that it will compile just after the installation of my app, but I am not sure where to start, I mean what things should I remove from build.gradle of indic-keyboard so that it stop generating apk, if somehow I am able to do that then it  may not be that tough,I need just the idea how should I proceed, so if you have worked on these type of things then please provide your valuable suggestions.

*edit - I have also tried importing as module(suggested by  zgc7009) but that produces error as shown in following images

A: The Indic Keyboard is already available on the play store, I would suggest to check at runtime if the user has that package (details here) and act accordingly: if the user has the package then fine, otherwise you can open the play store (details here)


text:
Q: How to unmount a mountpoint I mounted with FUSE earlier, after `sshfs` process is gone? I used sshfs example.com:/path/to/remote/directory foobar to successfully mount a remote directory at a mountpoint I created with mkdir foobar (I own the directory). But the mounting was done on a shared host which kills user processes under some conditions, so the sshfs process is now gone and ls -la grep foobar now tells me:

ls: cannot access 'foobar': Transport endpoint is not connected
d??????????  ? ?     ?        ?            ? foobar/

Furthermore, the recommended unmounting procedure fusermount -u foobar does not work:

fusermount: failed to chdir to /path/to/remote/directory: Permission denied

I can't even remove the mountpoint with rm, getting the same "Transport endpoing is not connected" error. unlink foobar also gives me "unlink: cannot unlink 'foobar': Is a directory". Remounting with sshfs does not work either.
Am I out of options here, as far as unmounting goes? Where do I go from here?


text:
Q: iPhone: screenshot Is there any method that calls in app when user made screenshot (hold home button + power) ???
Or which methods could be called ? Like applicationDidBecomeActive or something else ? Thanks...

A: You could periodically check the latest photo in the library using code from this answer.
Then check some properties to see if it is NOT coming from the camera or other source:

*

*the format should be PNG

*dimensions should match the screen size

*some additional metadata, perhaps

A: In iOS 4.0, there was a notification fired PictureWasTakenNotification, but not anymore in iOS 5.0 or latter.


text:
Q: Mp3 file to Base64 encode string conversion in android phonegap I have a function to encode an mp3 file to base64 string.But when the file get executed some errors are generating.My function is follows :
function recordAudioToBase64() {
console.log('encodeing fun reached');
var file = 'jivebirdrecord.mp3';
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFile, fail);

}
function gotFile(fileSystem) {
fileSystem.root.getFile("jivebirdrecord.mp3", null, gotFileEntry, fail);

}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);

}
function gotFile(file) {
readDataUrl(file);

}
function readDataUrl(file) {
 var reader = new FileReader();
 reader.onloadend = function(evt) {
    base = evt.target.result;
  };
  reader.readAsBinaryString(file);

}
function fail() {
 console.log('failed......');

}
And i have the following error :
**processMessage failed: Error: TypeError: Failed to execute 'readAsDataURL' on 'FileReader': The argument is not a Blob.
processMessage failed: Stack: TypeError: Failed to execute 'readAsDataURL' on 'FileReader': The argument is not a Blob.
at FileReader.readAsDataURL (file:///android_asset/www/plugins/org.apache.cordova.file/www/FileReader.js:201:33)

at readDataUrl (file:///android_asset/www/js/script.js:293:14)

at gotFile (file:///android_asset/www/js/script.js:283:4)

at file:///android_asset/www/plugins/org.apache.cordova.file/www/requestFileSystem.js:52:25
at success (file:///android_asset/www/plugins/org.apache.cordova.file/www/fileSystems-roots.js:40:13)

at Object.cordova.callbackFromNative (file:///android_asset/www/cordova.js:292:54)

at processMessage (file:///android_asset/www/cordova.js:1039:21)

at Function.androidExec.processMessages (file:///android_asset/www/cordova.js:1076:13)

at pollOnce (file:///android_asset/www/cordova.js:944:17)

at pollOnceFromOnlineEvent (file:///android_asset/www/cordova.js:939:5)

processMessage failed: Message: S01 File810616738

 [{"fullPath":"\/","filesystemName":"temporary","isDirectory":true,"nativeURL":"file:\/\/\/storage\/emulated\/0\/Android\/data\/com.phonegap.helloworld\/cache\/","filesystem":0,"isFile":false,"name":""},

{"fullPath":"/","filesystemName":"persistent","isDirectory":true,"nativeURL":"file:///storage/emulated/0/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"content","isDirectory":true,"nativeURL":"cdvfile://localhost/content/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"files","isDirectory":true,"nativeURL":"file:///data/data/com.phonegap.helloworld/files/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"files-external","isDirectory":true,"nativeURL":"file:///storage/emulated/0/Android/data/com.phonegap.helloworld/files/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"documents","isDirectory":true,"nativeURL":"file:///data/data/com.phonegap.helloworld/files/Documents/","filesystem":1,"isFile":false,"name":""},{"fullPath":"/","filesystemName":"sdcard","isDirectory":true,"nativeURL":"file:///storage/emulated/0/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"cache","isDirectory":true,"nativeURL":"file:///data/data/com.phonegap.helloworld/cache/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"cache-external","isDirectory":true,"nativeURL":"file:///storage/emulated/0/Android/data/com.phonegap.helloworld/cache/","filesystem":1,"isFile":false,"name":""},
{"fullPath":"/","filesystemName":"root","isDirectory":true,"nativeURL":"file:///","filesystem":1,"isFile":false,"name":""}]**
Please help me to find a solution for converting an mp3 file to base64 string using phonegap and jquery mobile.
Thnaks

A: It's bit late but for others this might help.
directoryReader.readEntries(function(entries){
                                for (var i=0; i<entries.length; i++) {
                                    var reader = new FileReader();

                                    var entry = entries[i];
                                    entry.file(function(file){
                                            reader.readAsDataURL(file);
                                            reader.onload = doOnload(entry.name);

                                    });

                                }
                            });


text:
Q: How to retrieve some output values from SPSS Custom Tables? I have been trying to retrieve some specific output values from SPSS Custom Tables and export them to Excel.
The problem is my Ctables syntax generates 2 different tables and I want to retrieve some specific output values from both these tables and then export to Excel.
Link to screenshot of SPSS custom tables. I have highlighted the values in red that I want to retrieve. I am trying to retrieve these values in XML format, but I am getting an error message. Here is the code.
      *1. Retrieve some output values and insert them into text.
 begin program.
import spssaux
gar="CTABLES
    /VLABELS VARIABLES=Institution RES_PAY Status DISPLAY=LABEL
    /TABLE  Status [C] > RES_PAY [C] BY Institution [C][COUNT F40.0, COLPCT.COUNT PCT40.1]
   /CATEGORIES VARIABLES=Institution ORDER=A KEY=VALUE EMPTY=INCLUDE  TOTAL=YES POSITION=AFTER
   /CATEGORIES VARIABLES=RES_PAY EMPTY=INCLUDE
   /CATEGORIES VARIABLES=Status ORDER=A KEY=VALUE EMPTY=INCLUDE
   /SIGTEST TYPE=CHISQUARE ALPHA=0.05 INCLUDEMRSETS=YES  CATEGORIES=ALLVISIBLE."

   cmd = spssaux.CreateXMLOutput(gar, visible=True)
   result=spssaux.GetValuesFromXMLWorkspace(cmd, 'CTABLES', cellAttrib ='text',colCategory='Cat1', rowCategory='Research with pay',rowSubCategory='Yes')
   result1=spssaux.GetValuesFromXMLWorkspace(cmd, 'CTABLES', tableSubtype='CHISQUARE', cellAttrib = 'text',colCategory='Status', rowCategory='Research with pay',rowSubCategory='Sig.')
   OUTPUT NEW
   print result[1]
   print result1[1]

   end program.

  *2. Export output to Excel.

  OUTPUT EXPORT
  /CONTENTS EXPORT= ALL LAYERS=PRINTSETTING MODELVIEWS=PRINTSETTING
 /XLSX DOCUMENTFILE='U:/report1.xlsx'
 OPERATION=CREATEFILE
 LOCATION=STARTCELL('C4') NOTESCAPTIONS=YES.

This is the error message that I am getting
 File "<string>", line 4
    gar="CTABLES
     SyntaxError: EOL while scanning string literal      ^

Can anyone please help me with the code?

A: You have a syntax error in the Python code.  The line starting gar= is introducing a multi-line literal, so you need to enclose it in triple quotes,
gar="""CTABLES
    /VLABELS VARIABLES=Institution RES_PAY Status DISPLAY=LABEL
    /TABLE  Status [C] > RES_PAY [C] BY Institution [C][COUNT F40.0,   COLPCT.COUNT PCT40.1]
   /CATEGORIES VARIABLES=Institution ORDER=A KEY=VALUE EMPTY=INCLUDE  TOTAL=YES POSITION=AFTER
   /CATEGORIES VARIABLES=RES_PAY EMPTY=INCLUDE
   /CATEGORIES VARIABLES=Status ORDER=A KEY=VALUE EMPTY=INCLUDE
   /SIGTEST TYPE=CHISQUARE ALPHA=0.05 INCLUDEMRSETS=YES    CATEGORIES=ALLVISIBLE."""
However, once you get these values, you are just printing them to the Viewer and exporting everything to the Viewer, which is probably not what you want, since these values were already in a table that will be exported.  This seems to be a very roundabout way of doing all this.  Perhaps if you describe the whole process a simpler solution can be found.


text:
Q: AWS S3 Bucket Policy - Read only access for specific "folder" I am trying to limit access for one of the IAM users to a "folder" within an S3 bucket. I thought I had this configured correctly, but the read access does not appear to be working.
{
        "Sid": "TEST_PublicReadGetObject",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::807676775814:user/project/api/testuserapi-abc123"
        },
          "Action": [
            "s3:GetObject",
            "s3:ListBucket",
            "s3:ListBucketByTags",
            "s3:ListBucketMultipartUploads",
            "s3:ListBucketVersions",
            "s3:ListMultipartUploadParts"
        ],
        "Resource":
            "arn:aws:s3:::testbucket-securitytest/timeline/*"
    }

Is there something I am missing? Is there sometimes a delay in making these changes or should it be instant?

A: I think I figured it out I had to allow ListBucket access first and then add the Action to allow only GetObject for that "folder". :) --- Just need to read the documentation a little more thoroughly
{
        "Sid": "TEST_ListItems",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::807676775814:user/project/api/testuserapi"
        },
        "Action": "s3:ListBucket",
        "Resource": "arn:aws:s3:::testbucket"
    },
    {
        "Sid": "TEST_PublicReadGetObject",
        "Effect": "Allow",
        "Principal": {
            "AWS": "arn:aws:iam::807676775814:user/project/api/testuserapi
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::testbucket/Timeline/*"
    }`


text:
Q: How to tag FB event with Bundle in android I have encountered a strange behavior to log facebook events with a specific Bundle.
Here is my code that works
fbLogger.logEvent("account_created");

If i see logs, i get
Result: Success
Events JSON: [
{
"_eventName": "account_created",
"_logTime": 1450255727,
"_ui": "UserCreateFbActivity_"
}
]

But if i try to send Bundle like this
Bundle extras = new Bundle();
if (userToPost.getSponsorCode() != null && !userToPost.getSponsorCode().isEmpty()) {
    extras.putBoolean("sponsor", true);
} else {
    extras.putBoolean("sponsor", false);
}

extras.putBoolean("facebook_connect", true);
fbLogger.logEvent("account_created", extras);

Logs are differents and event is not logged
Invalid app event name or parameter:
Result: Success
Events JSON: [
null
]

sdk version : 4.8.1

A: Solution is do not use boolean type ><. Thx to @ifaour
So here is my solution
Bundle extras = new Bundle();
if (userToPost.getSponsorCode() != null && !userToPost.getSponsorCode().isEmpty()) {
    extras.putString("sponsor", "true");
} else {
    extras.putString("sponsor", "false");
}

I don't understand why boolean type is not valid but this solution works ...


text:
Q: Buggy fade in/out code in JavaScript/CSS I'm not the most proficient in coding and have been stuck at trying to get this function working right for days and hope that someone could help me...
The idea is for the red div to show by default and the blue/yellow divs to be called upon by pressing the 'fade 1' and 'fade 2' buttons. When either of the buttons are pressed the red div is hidden and wont be called for.
The current code bugs up when the buttons are pressed continuously, they either wont show, the fade effect wont work or the red div appears.
Thanks!
            <!DOCTYPE html>

                <input class="myBtn" type="button" value="Fade 1" onclick="fade1(myImg1);" />
                <input class="myBtn" type="button" value="Fade 2" onclick="fade2(myImg2);" />

A: You could use jquery like this- jsFiddle
$(document).ready(function () {
    $(".fade1").click(function () {
        $("#myImg1").fadeToggle();
        $("#myImg2").fadeOut();
    });
});
$(document).ready(function () {
    $(".fade2").click(function () {
        $("#myImg2").fadeToggle();
        $("#myImg1").fadeOut();
    });
});


text:
Q: Kotlin Platform Types and Generics I am stuck at the last Kotlin Koans task 28 where I get these error messages when I try to call my partitionTo function:
Error:(25, 12) Kotlin: Type inference failed. Expected type mismatch: found: kotlin.Pair<kotlin.Collection<kotlin.String!>, kotlin.Collection<kotlin.String!>> required: kotlin.Pair<kotlin.List<kotlin.String>, kotlin.List<kotlin.String>>
Error:(30, 12) Kotlin: Type inference failed. Expected type mismatch: found: kotlin.Pair<kotlin.Collection<kotlin.Char!>, kotlin.Collection<kotlin.Char!>> required: kotlin.Pair<kotlin.Set<kotlin.Char>, kotlin.Set<kotlin.Char>>

I read that the exclamation mark at the end of a type marks a platform type. But then I would have expected the type java.lang.String! and not kotlin.String!. Do I have to enforce null checks somewhere? Maybe someone can help me with this last task. I am using IntelliJs Kotlin Plugin version 0.10.195.
This is my code:
fun List<String>.partitionWordsAndLines(): Pair<List<String>, List<String>> {
    return partitionTo(ArrayList<String>(), ArrayList<String>()) { s -> !s.contains(" ") }
}
fun Set<Char>.partitionLettersAndOtherSymbols(): Pair<Set<Char>, Set<Char>> {
    return partitionTo(HashSet<Char>(), HashSet<Char>()) { c -> c in 'a'..'z' || c in 'A'..'Z'}
}
inline fun <reified T> Collection<T>.partitionTo(first: MutableCollection<T>, second: MutableCollection<T>, predicate: (T) -> Boolean): Pair<Collection<T>, Collection<T>> {
    for (element in this) {
        if (predicate(element)) {
            first.add(element)
        } else {
            second.add(element)
        }
    }
    return Pair(first, second)
}

A: The problem is that you promised to return a pair of Lists:
fun List<String>.partitionWordsAndLines(): Pair<List<String>, List<String>> {

But in fact returned a pair of Collections:
inline fun <reified T> Collection<T>.partitionTo(...): Pair<Collection<T>, Collection<T>> {

A useful hint from the task:
    The signature of the function 'toCollection()' from standard library may help you.

See it here: https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/generated/_Snapshots.kt#L207
P.S. Why did you want to use inline and reified on partitionTo?

A: Check you return types partitionWordsAndLines(): **Pair, List>**, extensions require List or Set where partitionTo returns Collection
Here is fixed version
inline fun <reified T, C: MutableCollection<T>> Collection<T>.partitionTo(first: C, second: C, predicate: (T) -> Boolean): Pair<C, C>


text:
Q: Run a simple Cascading program in local mode I am struggling to get this simple cascading program to run. For some reason it does nothing. Least I would expect it to print the records. Any help would be appreciated.
package com.myLearning.cascading;

import cascading.flow.Flow;
import cascading.flow.FlowDef;
import cascading.flow.local.LocalFlowConnector;
import cascading.operation.Debug;
import cascading.operation.expression.ExpressionFilter;
import cascading.pipe.Each;
import cascading.pipe.Pipe;
import cascading.scheme.Scheme;
import cascading.scheme.local.TextDelimited;
import cascading.tap.SinkMode;
import cascading.tap.Tap;
import cascading.tap.local.FileTap;
import cascading.tuple.Fields;

public class operations_example
{
    public static void main(String[] args)
    {
    Scheme sourceScheme = new TextDelimited(new Fields("username", "age"), true, ",");
    String sourcePath = "C:/Users/Desktop/cascading/data/names.txt";
    Tap sourceTap = new FileTap(sourceScheme, sourcePath);

    Scheme targetScheme = new TextDelimited(new Fields("username", "age"), true, ",");
    String targetPath = "C:/Users/Desktop/cascading/data/output2.txt";
    Tap targetTap = new FileTap(targetScheme, targetPath, SinkMode.REPLACE);

    Pipe dataPipe = new Pipe("data");
    dataPipe = new Each(dataPipe, new Debug());
    ExpressionFilter filter = new ExpressionFilter("age >= 30", Integer.TYPE);

    dataPipe = new Each( dataPipe,new Fields("username","age"), filter);

    FlowDef flowdef = FlowDef.flowDef().
            addSource(dataPipe, sourceTap).
            addTailSink(dataPipe, targetTap);

    Flow flow = new LocalFlowConnector().connect(flowdef);
    flow.stop();
    }
}

A: You didn't execute the flow.
After the flow is created, call either complete() (blocking) or start() to execute it. Calling stop() is not going to execute the flow.
http://docs.cascading.org/impatient/impatient1.html
http://docs.cascading.org/cascading/1.2/javadoc/cascading/flow/Flow.html#complete()


text:
Q: How to convert isi date to iso in js I am getting the date as
data.created = "Wed May 03 2017 15:41:49 GMT 0530(IST)"

I want to convert it to
    regular isi format like
 2017-03-12

My code,
 var created = new Date(data.created);
  created = created.toISOString()

Can anyone help me.Thanks.

A: You can use Date $filter to get the formatted string.
var formatedStr = $filter('date')(new Date(data.created),'yyyy-MM-dd');

A: Since your input is URL encoded, first you have to decodeURIComponent (which replaces things like %20 with spaces and so on).
Then convert the result into a Date object.
Then use the getFullYear, getMonth and getDate functions to get these data, but don't forget to pad it with 0 (for numbers lower than 10).

var input = "Wed%20May%2003%202017%2015:41:49%20GMT%200530%20(IST)";

function formatDate(d) {
    var month = (d.getMonth() + 1)
      , day = '' + d.getDate()
      , year = d.getFullYear()
      ;

    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;

    return [year, month, day].join('-');
}

var decoded = decodeURIComponent(input);
var inputDate = new Date(decoded);

var output = formatDate(inputDate);

console.log(output);


text:
Q: Get the error code from tweepy exception instance I'm new to python and I'm trying to use a library. It raises an exception, and I am trying to identify which one. This is what I am trying:
except tweepy.TweepError as e:
    print e
    print type(e)
    print e.__dict__
    print e.reason
    print type(e.reason)

This is what I am getting:
[{u'message': u'Sorry, that page does not exist', u'code': 34}]
<class 'tweepy.error.TweepError'>
{'reason': u"[{u'message': u'Sorry, that page does not exist', u'code': 34}]", 'response': <httplib.HTTPResponse instance at 0x00000000029CEAC8>}
[{u'message': u'Sorry, that page does not exist', u'code': 34}]
<type 'unicode'>

Im trying to get to that code. I have tried e.reason.code with no success and I have no idea what to try.

A: Things have changed quite a bit since 2013. The correct answer as of now is to use e.api_code.

A: Every well-behaved exception derived from the base Exception class has an args attribute (of type tuple) that contains arguments passed to that exception. Most of the time only one argument is passed to an exception and can be accessed using args[0].
The argument Tweepy passes to its exceptions has a structure of type List[dict]. You can get the error code (type int) and the error message (type str) from the argument using this code:
e.args[0][0]['code']
e.args[0][0]['message']

The TweepError exception class also provides several additional helpful attributes api_code, reason and response. They are not documented for some reason even though they are a part of public API.
So you can get the error code (type int) also using this code:
e.api_code

History:
The error code used to be accessed using e.message[0]['code'] which no longer works. The message attribute has been deprecated in Python 2.6 and removed in Python 3.0. Currently you get an error 'TweepError' object has no attribute 'message'.

A: How about this?
except tweepy.TweepError as e:
    print e.message[0]['code']  # prints 34
    print e.args[0][0]['code']  # prints 34

A: To get just the error code use the method monq posted.  The following example illustrates how to get both the error code and the message.  I had to extract the message from the e.reason string, if anyone has a better method to retrieve just the message, please share.
Note: This code should work for any error code/reason with the following format.
[{'code': 50, 'message': 'User not found.'}]
def getExceptionMessage(msg):
    words = msg.split(' ')

    errorMsg = ""
    for index, word in enumerate(words):
        if index not in [0,1,2]:
            errorMsg = errorMsg + ' ' + word
    errorMsg = errorMsg.rstrip("\'}]")
    errorMsg = errorMsg.lstrip(" \'")

    return errorMsg

And you can call it like so:
try:
    # Some tweepy api call, ex) api.get_user(screen_name = usrScreenName)
except tweepy.TweepError as e:
    print (e.api_code)
    print (getExceptionMessage(e.reason))

A: As of December 2021 (tweepy v4.4.0) the correct way is:
except tweepy.TweepyException as e:
    print(e)

source: https://docs.tweepy.org/en/v4.4.0/changelog.html?highlight=TweepError#new-features-improvements

A: Here is how I do it:
except tweepy.TweepError as e:
    print e.response.status


text:
Q: how to run tests as per respective suite in jmeter I have created some testcases in Jmeter.
Now I want to run them separately example smoke testcases only.
Is there any way in Jmeter so I can run my JMeter project for a particular group/collection/suite only.
Is Jmeter provide any annotation or containers mechanism from where I can achieve same.
I have written my cases in Jmeter in below assertions

*

*JSR223 Assertion

*Response Code

*Response Text

Any workaround will be helpful and appreciated in advance

A: The right way to module your JMeter scripts is to save small script in different JMXs and combined them by calling each or inside a bigger JMX file which uses Include Controller to execute different JMX files

The include controller is designed to use an external JMX file. To use it, create a Test Fragment underneath the Test Plan and add any desired samplers, controllers etc. below it. Then save the Test Plan. The file is now ready to be included as part of other Test Plans.

Inside JMX you can also use Module Controller to reduce code duplication

The Module Controller provides a mechanism for substituting test plan fragments into the current test plan at run-time.

If you want to execute specific test I suggest send specific properties and check the property inside an If Controller .
for example call with property jmeter -JexcludeTest1=true ...
And add an If Controller before test 1:
"${__P(excludeTest1)}" == "true"

A: The easiest way is using Taurus tool as a wrapper for your JMeter script, it has Modifications for Existing Scripts feature where you can define which test elements you want to enable/disable during test execution.
scenarios:
  modification_example:
    script: tests/jmx/dummy.jmx
    modifications:
      disable:  # Names of the tree elements to disable
      - Thread Group 1
      enable:  # Names of the tree elements to enable
      - Thread Group 2

See Navigating your First Steps Using Taurus to get started.

Another option is putting requests you would like to enable/disable on demand under If Controllers so you could set "run/not run" condition dynamically.


text:
Q: Linking Error Using HsLua on Windows I am having some issues using HsLua as a library.  Lua compiles just fine as a standalone.  And this version runs on my Linux box without a problem.  Here is the linking error I see.
GHCi, version 7.4.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> import Scripting.Lua as Lua
Prelude Lua> l <- Lua.newstate
Loading package hslua-0.3.4 ... linking ... <interactive>: C:\..\AppData\Roaming\cabal\hslua-0.3.4\ghc-7.4.1\HShslua-0.3.4.o: unknown symbol `___strtod'
ghc.exe: unable to load package `hslua-0.3.4'
Prelude Lua>

I did some poking around the libraries and found the call for strtod and I think I may have been close but obviously not close enough.
EDIT
This may or may not help.  I'll post the cabal file, I made a couple of changes such as adding the os(windows) portion.
Name: hslua
Version: 0.3.4
...
Extra-source-files: src/*.h

Library
  Build-depends: base==4.*
  Exposed-modules: Scripting.Lua, Scripting.Lua.ConfigFile
  Hs-source-dirs: src
  C-sources: src/lapi.c, src/lauxlib.c, src/lbaselib.c, src/lcode.c,
             src/ldblib.c, src/ldebug.c, src/ldo.c, src/ldump.c, src/lfunc.c,
             src/lgc.c, src/linit.c, src/liolib.c, src/llex.c, src/lmathlib.c,
             src/lmem.c, src/loadlib.c, src/lobject.c, src/lopcodes.c,
             src/loslib.c, src/lparser.c, src/lstate.c, src/lstring.c,
             src/lstrlib.c, src/ltable.c, src/ltablib.c, src/ltm.c,
             src/lundump.c, src/lvm.c, src/lzio.c, src/ntrljmp.c
  Include-dirs: src
  ghc-options: -Wall
  extensions: ForeignFunctionInterface

  if os(linux)
    CC-Options: "-DLUA_USE_LINUX"

  if os(darwin)
    CC-Options: "-DLUA_USE_MACOSX"

  if os(freebsd)
    CC-Options: "-DLUA_USE_POSIX"

  if os(windows)
    CC-Options: "-DLUA_BUILD_AS_DLL"
    includes: stdlib.h

I tried a couple of different ways to get the stdlib in the project, I've added it in main headers for the project and I've also specified it in the cabal file.  Makes me think that is barking up the wrong tree.
EDIT-2
Well I haven't been able to get this built yet on win32.  A couple of other things I tried to do that didn't work for me just in case someone else runs into the same problem.
I linked all of the built object files into a static archive and I got the same error as above.  I also tried to use a build DLL and I got a different error but I'm not sure if it were progress forwards or backwards.
C:\..\hslua-0.3.4>ghci liblua.dll -package hslua
GHCi, version 7.4.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package hslua-0.3.4 ... linking ... ghc.exe: C:\..\hslua-0.3.4\ghc-7.4.1\HShslua-0.3.4.o: unknown symbol `_lua_close'
ghc.exe: unable to load package `hslua-0.3.4'

A: Hey I was struggling with exactly the same thing on windows and what worked for me was adding the following to the cabal file
  if os(windows)
     CC-options:        "-D__NO_ISOCEXT"

that makes gcc not use the special __strtod but rather just the normal one.


text:
Q: Data Mining Minimum Support and Strong Association Rules If I have the following table:

And if A = {I1}, B = {I2}, and I find the support is 0.4 and confidence is 0.5 for the association rule A ⇒ B, then how can I determine if this is a strong association rule or not?
For example, if minimum support is 30% then it'd be strong I imagine, correct? Because our support is 0.4 calculated. But if minimum support is 50%, then it isn't strong because we have less than that.
Am I correct in thinking like this in regards to the image I posted?

A: Please read "Data Mining: Concepts and Techniques" written by J. Han, M. Kamber, and J. Pei.
Typically, an association rule is called strong if it satisfies both a minimum support threshold and a minimum confidence threshold that is determined by the user. In your case;
I1 ⇒ I2 [40%, 50%]

Using a minimum support of 30% and a minimum confidence of 60%, your association rule does not satisfy the minimum confidence threshold. Therefore, it's not a strong association rule.