text:
Q: Does net-snmp support AES-192 and AES-256 encryption? The network device has been configured with snmpv3 users which uses AES192 as the privacy protocol.But when the following command is executed
snmpwalk -v3 -l authPriv -u user -a SHA -A authpass -x AES256 -X privpass device_ip:161 oid

It throws the following error
Invalid privacy protocol specified after -x flag: AES256

but when i tried using AES128 encryption the snmpwalk worked perfectly fine,which made me think if AES192&256 features are supported if not why was it not included.

A: The original SNMP RFC documents do not require those.
Thus, along with other reasons Net-SNMP never supports them,
http://www.net-snmp.org/wiki/index.php/Strong_Authentication_or_Encryption
Update in 2019: In Aug 2018, net-snap 5.8 introduced support for such, please refer to the same link for more info.

A: Net-snmp does not support AES 192 or 256. There are many devices (including most Cisco devices) that do support both 192 and 256 bit AES. Manager side software supporting AES 192 and 256 is available from several sources including SNMP Research, LogMatrix, CA, and others.

A: Even though the original RFC does not require AES192 and AES256, some vendors have implemented them, for example Cisco.
Net-SNMP did not support this until release 5.8 (source):

Does Net-SNMP support AES192 or AES256? The short answer is Yes,
starting with release 5.8 AES193 and AES256 are an optional configure
option.

Other SNMP libraries, such as SNMP4J, also have support for AES256:

*

*https://www.snmp4j.org/doc/org/snmp4j/security/PrivAES256.html

*https://stackoverflow.com/a/41833176/1067124

A: Cisco supports a AES 192 and 256, but I have found no public software that supports the related client calls.  These versions are in actual use.


text:
Q: Why is my override method not being called in C++? So I have a base class that is made to hold a string value, and be able to add characters onto it:
class TextInput
{
public:
    std::string value;
    void add(char c)
    {
        if (!value.empty())
        {
            value += c;
        }
        else
        {
            value = c;
        }
    }

    std::string getValue()
    {
        return value;
    }
};

Then an inherited class, which is the same as parent but should only allow you to add numeric values to the string:
class NumericInput : public TextInput
{
public:
    TextInput input;
    void add(char c)
    {
        if (isdigit(c))
        {
            input.add(c);
        }
    }

    std::string getValue()
    {
        return value;
    }
};

What I want to know is, when called like this in my tests:
#ifndef RunTests
int main()
{
    TextInput* input = new NumericInput();
    input->add('1');
    input->add('a');
    input->add('0');
    std::cout << input->getValue();
}
#endif

Why does the call to add still only use the base add class? I would assume this to use the child NumericInout class since it is being created as one, but when debugging it still only uses the parent class and I don't understand why?

A: class NumericInput : public TextInput
{
public:
    TextInput input;

This is almost definitely not what you want. If you're inheriting, I can't think of a good reason you'd ever also want composition. Get rid of this input member variable. When you inherit, you already get everything from the parent class (including value in this case).
To specifically call the parent class's add(), you can do TextInput::add(), so your child add could look like:
void add(char c)
{
    if (isdigit(c))
    {
        TextInput::add(c); // Call parent add()
    }
}

Furthermore, if you want to call add() on a TextInput pointer that's pointing to a NumericInput, and you want it to resolve to call the NumericInput's add(), you must declare the base add() to be virtual:
virtual void add(char c) { // ...

Lastly, you can still append to a string even if there's nothing in it, so your check in the base add() does nothing.
Altogether, that'll make your code look like:
class TextInput
{
public:
    std::string value;
    virtual void add(char c)  { value += c; }
    std::string getValue() { return value; }
};

class NumericInput : public TextInput
{
public:
    void add(char c)
    {
        if (isdigit(c)) { TextInput::add(c); }
    }

    // You already get this for free from the inheritance
    // std::string getValue()
    // {
    //     return value;
    // }
};

Live example here: https://ideone.com/kQxAPo

redpajama_set_name: RedPajamaStackExchange


text:
Q: PowerBi measure and summarize row for report I am new to PowerBi.
What I am trying to do is summarize an email marketing report for open, clicks with the exported data. The data looks like
|   Campaign Name  |     Email Address     | Event Type |
|:---------------: |:---------------------:| :--------: |
| Test Campaign    | test@example.com      | Open       |
| Test Campaign    | test@example.com      | Open       |
| Test Campaign    | test123@example.com   | Open       |
| Test Campaign 2  | test@example.com      | Open       |
| Test Campaign 2  | test@example.com      | Open       |
| Test Campaign 2  | test1234@example.com  | Open       |
| Test Campaign 2  | test@example.com      | Clicked    |
| Test Campaign 2  | test@example.com      | Clicked    |

I want to calculate each event type that is unique for each email address and summarize it by the campaign name. There can be duplicate email address if someone opens email twice. And there are multiple different campaign names
I want PowerBI to be able to take the above data and summarize it as such with a measure formula :

Campaign Name
Open
Click

Test Campaign
2
0

Test Campaign 2
2
1

Any suggestions? I can't get it to summarize by campaign name.
Clicks = Calculate(DistinctCount('table'[column]),'table2 for event type'[event type] = "click"))

A: You can do it in DAX very quickly.
In PowerBI, you create two new measures:
Please note that I've used 'Table' as the table name, replace it with the actual name of your table.
'Table'[Open_Nb] =
CALCULATE(
    DISTINCTCOUNT('Table'[Email Address ]),
    'Table'[Event Type] = "Open"
)

and
'Table'[Clicked_Nb] =
CALCULATE(
    DISTINCTCOUNT('Table'[Email Address ]),
    'Table'[Event Type] = "Clicked"
)

Then you can use this table two ways. You can create a new Table visual and drag and drop :

*

*Campaign Name

*Measure Open_Nb

*Measure Clicked_Nb
Or, directly as a new table with the expression :
ADDCOLUMNS(
    SUMMARIZE(
        'Table',
        'Table'[Campaign Name ]
    ),
    "Open",
    'Table'[Open_Nb],
    "Click",
    'Table'[Clicked_Nb]
)


text:
Q: Matlab sin(pi) and its relation to machine epsilon I understand that the reason why sin(pi) is not equal to zero is because of the fact that there is not enough bits to store all the significant digits of "pi", but what does that have to do with machine epsilon?
I read online what machine epsilon was, but after an hour of reading various definitions worded differently I got confused and did not understand the concept of epsilon. I ended up getting really frustrated in my own foolishness...
This following example was given in the MATLAB documentation and I don't understand it, can someone explain to me what the example is trying to show?

Find the distance from 10.0 to the next largest double-precision number.
d = eps(10.0)

d =

   1.7764e-15

http://www.mathworks.com/help/matlab/ref/eps.html

A: At first order, sin(pi-epsilon)=epsilon+O(epsilon^3)
So, if we have an approximated value of pi instead of pi (with an error up to 1/2 unit of least precision), then we expect this error to be transferred directly to the sine result.
Machine epsilon is definitely related to the error we make with approximated value of pi.

A: There are a couple of different definitions of machine epsilon, but Matlab eps is fairly typical, being the gap between 1.0 and the next largest double precision floating point number.
We can actually make this more general: for any floating point number between 2k ≤ x < 2k+1, the gap between x and the next largest floating point number is 2k × eps (i.e. eps(x) in Matlab). Moreover, the gap between any real number and its nearest floating point approximation is half this.
Since 2 ≤ π < 4;, this means that the gap between pi (the numerical approximation) and π (the exact irrational number) is bounded by eps. In actual fact, it is just over half that:
eps ≈ 2.22 × 10-16
|pi - π| ≈ 1.22 × 10-16
Now using the result from @aka.nice answer, and that sin(π) = 0, we have that
sin(pi) = | sin(pi) - sin(π) | ≈ |pi - π| < eps
i.e. it is also bounded by eps.
Note: there is also some slight rounding between sin(pi) (the numeric result) and sin(pi) (the exact result), but this is of order eps2, so can be ignored in this case.


text:
Q: How Do I Connect Oracle To PostgreSQL over ODBC using the Oracle ODBC Gateway? I would like to select from a PostgreSQL instance on a server running openSUSE from an Oracle instance on a server running Oracle's custom Linux flavor.  I would like to do this using the Oracle ODBC gateway.  I have done this successfully in the past and continue to do it using the same Oracle box and other SUSE/Postgres boxes.
my ODBC manager on the SUSE (Postgres) side is: unixODBC
My odbc.ini is:
[postgresql]
Description         = Test to Postgres
Driver              = /usr/lib64/psqlodbcw.so
Trace               = Yes
TraceFile           = sql.log
Database            = host
Servername          = localhost
UserName            = *****
Password            = *****
Port                = 5432
Protocol            =
ReadOnly            = Yes
RowVersioning       = No
ShowSystemTables    = No
ShowOidColumn       = No
FakeOidIndex        = No
ConnSettings        =

My odbcinst.ini is
[postgresql]
    Description             = Postgresql driver for Linux
Driver          = /usr/lib64/psqlodbcw.so
UsageCount              = 1

my tnsnames.ora (with other ODBC entries omitted) is:
# tnsnames.ora Network Configuration File: /opt/oracle/product/11gR1/db/network/admin/tnsnames.ora
# Generated by Oracle configuration tools.

LISTENER_ORCL =
  (ADDRESS = (PROTOCOL = TCP)(HOST = dbs1)(PORT = 1522))

ORCL =
  (DESCRIPTION =
    (ADDRESS = (PROTOCOL = TCP)(HOST = dbs1)(PORT = 1522))
    (CONNECT_DATA =
      (SERVER = DEDICATED)
      (SERVICE_NAME = orcl)
    )
  )

ODBC_SERVER123=
  (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=dbs1)
      (PORT=1522)
    )
    (CONNECT_DATA=
       (SID=server123)
    )
    (HS=OK)
  )

my listener.ora (with other SID_DESC entries omitted) is:
# listener.ora Network Configuration File: /opt/oracle/product/11gR1/db/network/admin/listener.ora
# Generated by Oracle configuration tools.

LISTENER =
        (DESCRIPTION_LIST =
                (DESCRIPTION =
                        (ADDRESS_LIST=
                                (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1522))
                                (ADDRESS = (PROTOCOL = TCP)(HOST = dbs1)(PORT = 1522))
                        )
                )
        )

ADR_BASE_LISTENER = /opt/oracle

SID_LIST_LISTENER=
        (SID_LIST=
                (SID_DESC=
                        (SID_NAME=server123)
                        (ORACLE_HOME=/opt/oracle/product/11gR1/db)
                        (PROGRAM=dg4odbc)
                        (ENVS=LD_LIBRARY_PATH=/usr/lib64:/opt/oracle/product/11gR1/db/lib)
                )
        )

TRACE_LEVEL_LISTENER = 0
LOGGING_LISTENER = off

Also, here is the inithost123.ora file located in $ORACLE_HOME/hs/admin:
#
# HS init parameters
#
HS_FDS_CONNECT_INFO = server123
HS_FDS_TRACE_LEVEL = 0
#HS_FDS_TRACE_LEVEL=DEBUG
HS_FDS_SHAREABLE_NAME = /usr/lib64/libodbc.so

HS_FDS_SUPPORT_STATISTICS = FALSE

HS_LANGUAGE=AMERICAN_AMERICA.WE8ISO8859P1
#HS_LANGUAGE=AMERICAN_AMERICA.US7ASCII
HS_FDS_TIMESTAMP_MAPPING = "TIMESTAMP(6)"
HS_FDS_FETCH_ROWS=1
HS_FDS_SQLLEN_INTERPRETATION=32

#
# ODBC specific environment variables
#
set ODBCINI=/etc/unixODBC/odbc.ini

#
# Environment variables required for the non-Oracle system
#
#set <envvar>=<value>

And just for good measure, my sqlnet.ora is:
# sqlnet.ora Network Configuration File: /opt/oracle/product/11gR1/db/network/admin/sqlnet.ora
# Generated by Oracle configuration tools.

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)

ADR_BASE = /opt/oracle

I added a gateway link oracle-side using the following:
CREATE DATABASE LINK ODBC_SERVER123 CONNECT TO "*****" IDENTIFIED BY "*****" USING 'ODBC_SERVER123';

When I try to perform my select I receive the following error:
[SQL] select * from "legit_view"@ODBC_SERVER123
[Err] ORA-28500: connection from ORACLE to a non-Oracle system returned this message:
[unixODBC][Driver Manager]Data source name not found, and no default driver specified {IM002}
ORA-02063: preceding 2 lines from ODBC_SERVER123

I can successfully test ODBC locally on the SUSE/Postgres box with isql:
>isql -v postgresql ***** *****
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+
SQL>

What step have I forgotten?

A: Your odbc.ini file must be on the remote box!  That is, the one originating the query.  In the example above that would be the Oracle box.  Here is an entry that must go on the Oracle (remote) box:
[server123]
Driver = /usr/lib64/psqlodbcw.so
Description = ODBC to PostgreSQL on Server 123
Trace = No
Tracefile = /var/log/sql_host_123.log
Servername = ip.address.for.123
Username = *****
Password = *****
Port = 5432
Protocol = 6.4
Database = host
QuotedId = Yes
ReadOnly            = No
RowVersioning       = No
ShowSystemTables    = No
ShowOidColumn       = No
FakeOidIndex        = No


text:
Q: How to find out the name of the default page displayed by a webserver? I'm downloading various files through I/O-streaming in my Java application. Receiving and saving those files works well as long as I have a full URL-path including file name, but how can I find out the name of the index file (as defined in, for example, Apache's DirectoryIndex) of a domain? The HTTP header doesn't provide this information and neither does the URLConnection method.
Thanks alot!
Be well
S.

A: As far as I know there is no way of retrieving this information. The HTTP specification doesn't provide it, and I think this isn't a bad thing. Your clients requests the URL "/", it's up to the web server how to handle that, there is no obligation to return a filename too.
It's also worth pointing out (I'm sure you're aware of it but just in case) that just because a URL looks like /somedir/somefile.html, it doesn't mean that is the actual file being served. It could be being served via a proxy to another host, mod_rewrite etc - in other words, the name as arbitrary and doesn't necessarily bear any relation to the physical name on disk.
In short, I think your best bet would be to pick a default filename e.g. index.html for those cases and stick to it.

A: Only way out is to:

*

*Inspect Content-Disposition header and use it to generate filename. If server is serving a file, it would set this header. E.g. http://server:port/DownLoadServlet URL might set this header to indicate name as "statement.pdf".

*IF this header is missing, use Heuristics to generate filename. This is what browsers do to generate filenames like Doc[10].pdf Doc[12].pdf etc.

*Use content-type header (if available) to guess file extension.


text:
Q: Firebase Security rule not working as expected I have the following rule set for events:
  "events": {
  ".indexOn": ["startTime"],
    "$eventId" : {
      ".read":  "auth != null && data.child($eventId+'/startTime').val() < (now + 86400000)",
      ".write": "auth != null && data.exists() && auth.uid === data.child('uid').val() || auth != null && root.child('proUsers/'+auth.uid).exists()"
    }
}

My intention was to limit read for all events to events that have startTime less than tomorrow. Thus I set a listener using .on() with "value like so:
database.ref('events').orderByChild('startTime').on('value', (snapshot) => { console.log(snapshot.val())}
however I get nothing, error occurs. Whats wrong with my rule. I did not want to set the ".read":  "auth != null" right below events since rules cascade.
Update:
 According to Restricting child/field access with security rules, I need to store a separate list of all approved to view events and set a read rule on that, but the problem is that in my case approved list changes according to the startTime value, thus it needs to happen automatically thus that solution does not work for me.


text:
Q: Why two completely different strings are seen as equal by SQL Server? In my sql server this:
select case when  N'ܐܪܡܝܐ' = N'አማርኛ' then 1 else 0 end

produces 1. I could reproduce this here as well. Can anybody explain to me why?

A: A specific collation need not contain sorting information for every code point defined in Unicode.
If you only need to test for (binary) equality of strings, ignoring every sort order, use the Latin1_General_BIN collation (or any other collation ending in _BIN or _BIN2):
select case
    when N'ܐܪܡܝܐ' COLLATE Latin1_General_BIN = N'አማርኛ' COLLATE Latin1_General_BIN
    then 1 else 0 end

A: Too long for a comment, so I add another answer, referring to @JBrooks' answer:
What's going on if you execute
select ascii('ܐ') AA, ascii('አ') AB

Well first, the string literals, which are Unicode code points above the ASCII range, are converted to '?' because they are not marked as Unicode strings (N'').
Then, the function ASCII is executed on the non-Unicode string '?', which obviously results in 63.
So let's just add the Unicode string marker N'':
select ascii(N'ܐ') AA, ascii(N'አ') AB

Again, the result is 63 for both expressions, but by a different route: while strings are declared as Unicode, the ASCII() function treats its argument as Non-Unicode strings, leading to the result 63.
The get the actual code point of the two Unicode characters, you need to apply the UNICODE() function:
select unicode(N'ܐ') AA, unicode(N'አ') AB

which correctly results in 1808 and 4768.
Final question: Why a question mark?
From Wikipedia

The question mark character is also often used in place of missing or
  unknown data. In Unicode, it is encoded at U+003F ? question mark
  (HTML: ?).

and, further down in the article

In many web browsers and other computer programs, "?" is used to show
  a character not found in the program's character set. [...] Some fonts
  will instead use the Unicode Replacement Glyph (U+FFFD, �), which is
  commonly rendered as a white question mark in a black diamond (see
  replacement character).

So the '?' question mark can be seen as the ASCII equivalent of the Unicode Replacement Character U+FFFD, which itself cannot be expressed by an ASCII value.

A: If I run this they both come back with 63.
select ascii('ܐ') AA, ascii('አ') AB


text:
Q: How and where can I calculate constant $k\approx1,895$? We know, that
$$e=\lim\limits_{n\to\infty}^{}\left[1+\frac{1}{1}\left(1+\frac{1}{2}\left(1+\frac{1}{3}\left(1+\cdots\frac{1}{n}\right)\right)\cdots\right)\right]$$
If $x_{m}=m(x_{m-1}-1)$ and $x_{0}=e$, then
$$x_{1}=\lim\limits_{n\to\infty}^{}\left[1+\frac{1}{2}\left(1+\frac{1}{3}\left(1+\frac{1}{4}\left(1+\cdots\frac{1}{n}\right)\right)\cdots\right)\right]$$
$$x_{2}=\lim\limits_{n\to\infty}^{}\left[1+\frac{1}{3}\left(1+\frac{1}{4}\left(1+\frac{1}{5}\left(1+\cdots\frac{1}{n}\right)\right)\cdots\right)\right]$$
$$x_{m}=\lim\limits_{n\to\infty}^{}\left[1+\frac{1}{m+1}\left(1+\frac{1}{m+2}\left(1+\frac{1}{m+3}\left(1+\cdots\frac{1}{n}\right)\right)\cdots\right)\right]$$
$$\sum\limits_{m=0}^{n}\left(x_{m}-1\right)\approx\ln(n)+k$$
How and where can I calculate this constant? Is there relationship with this constant and $\gamma$?
If I made some mistakes, sorry for my English.

A: For general $m \in \mathbb{N}$, it is easy to see
$$x_m = m!\left(e - \sum_{k=0}^{m-1}\frac{1}{k!}\right)
\quad\implies\quad x_m - 1
= m!\left(e - \sum_{k=0}^{m} \frac{1}{k!}\right)
= \sum_{k=m+1}^\infty \frac{m!}{k!}$$
This leads to
$$\begin{align}x_m - 1
= \sum_{k=0}^\infty \frac{m!}{(m+k+1)!}
&= \frac{1}{m+1} + \sum_{k=1}^\infty \frac{1}{k!}\frac{\Gamma(m+1)\Gamma(k+1)}{\Gamma(m+k+2)}\\
&= \frac{1}{m+1} + \sum_{k=1}^\infty\int_0^1 (1-t)^m \frac{t^k}{k!} dt\\
&= \frac{1}{m+1} + \int_0^1 (1-t)^m (e^t-1)dt
\end{align}
$$
Summing $m$ from $0$ to $n$, we get
$$\begin{align}
\sum_{m=0}^n (x_m - 1)
&= H_{n+1} + \sum_{m=0}^n\int_0^1 (1-t)^m (e^t-1)dt\\
&= H_{n+1} + \int_0^1 \frac{1-(1-t)^{n+1}}{1-(1-t)} (e^t-1) dt\\
&= H_{n+1} + \int_0^1 (1 - (1-t)^{n+1}) \frac{e^t-1}{t}dt
\end{align}
$$
where $H_n = \sum_{m=1}^n \frac{1}{m}$ is the $n^{th}$ harmonic number.
Notice for $t \in (0,1)$, MVT tell us for some $\xi \in (0,t)$,
$\frac{e^t - 1}{t} = e^{\xi t} \in (1, e^t) \subset (1,e)$. This allows us
to bound the $n$ dependent piece in above integral as
$$\frac{1}{n+2} \le \int_0^1 (1-t)^{n+1} \frac{e^t - 1}{t} dt \le \frac{e}{n+2}$$
We also know for large $n$,
$$H_n = \log n + \gamma + O\left(\frac1n\right)$$
Combine these, we can conclude
$$\sum_{n=0}^n (x_m - 1) = \log n + k + O\left(\frac1n\right)
\quad\text{ where }\quad
k = \gamma + \int_0^1 \frac{e^t-1}{t} dt$$
Using an CAS, we find the integral above has a closed form in terms of
exponential integral
${\rm Ei}(x)$. The end result is
$$
k = \gamma + \left( {\rm Ei}(1) - \gamma\right) = {\rm Ei}(1)
\approx 1.89511781635593675546652...
$$


text:
Q: ext4 inodes in use for files that are missing Executive summary:

*

*Every tool I've tried confirms lots of inodes in use on this ext4 partition

*Every tool I've tried shows me that there are no files on the partition

*It's not files held open and it's not an overlay mount
Long story:
I have an SSD with a single ext4 partition.  This drive was being used to continually store video from cameras, in short clips, and a cron job would periodically delete the oldest clips (in a C application, which deleted them by calling remove()).  After a while someone noticed that while there should have been about 5 days' worth of video backed up, there was hardly any, but the drive was almost full.
I took a look and naively tried just removing lost+found, but the drive was still full.  So, I deleted everything (rm -rf *), but df -i tells me that 91230 inodes are in use, even though ls and du show nothing at all.
e2fsck -fv found no errors to fix (aside from creating lost+found again), and dumpe2fs and tune2fs -l both agree with df -i on the number of used inodes.  I've tried e2fsck -b with a couple of the backup super-blocks and it didn't seem to make any difference.
baobab shows the same used space as df in the summary view, but when I click on the partition to see where the space is used, it only shows the 4.1kB used by  the empty lost+found directory.
The problem is not that deleted file handles that are still open - nothing is open.  I've mounted and unmounted this partition multiple times, and even taken the drive out and put it in a completely different machine.
I know I could just re-format the partition and start fresh, but I would really like to understand what's going on here and whether there's any "proper" way to fix this - I don't care whether it brings the files for those inodes back or it makes them properly deleted so they don't use up all the space.
Edit:
Running dump creates a backup file roughly equal in size to the used space reported by df et al.  Then running restore to a different drive created a chain of directories that's clearly wrong (/media/usb0/20150426/10/1_20150426_100125.264/20150426/10/1_20150426_100125.264/ and it continues many levels deep, the same structure repeating), before printing a bunch of lines like:
expected next file 7823361, got 7610674
expected next file 7823361, got 7610675

(second number incrementing - it goes back well beyond my terminal's buffer) before finally:
cannot find directory inode 11
abort? [yn]

Choosing n results in more "cannot find directory node x", so I aborted.
Giving up and writing this off as a freak file-system corruption which hopefully won't happen again.


text: Q: Open an external page as an iframe within a docusaurus site I want to be able to provide a link on my docusaurus ToC pointing to an external page (in this case it's a particular method in an API docs portal), such that the page loads within an iframe on the docusaurus site, so the ToC is still present, but the external page is displayed. Is this possible in docusaurus or any of the well known markdown or rst based doc tools?


text:
Q: Is there any ways to extract the number of views a webpage recieved? Looking for any tools (preferably in python) to extract the number of views a particular webpage received. If not, it would be also handy to know if there is any other webpage specific analytics that I can obtain (such as the one listed)

A: Unless you own this particular webpage there is no way to see how much visitors/views/traffic it gets. Visits are measured with Analytics injected into the site (e.g. Google Analytics) or by reading the server logs. Both of which you cannot access unless you own the site.
There are some sites that make estimates available in an API. For example:

*

*https://www.sitetrafficapi.com/

*https://www.alexa.com/


text:
Q: PHP, "The requested URL was rejected. Please consult with your administrator." error when submitting I made an HTML form that retrieves data from a mysql database via a php code in a separate file. So far so god, everything works fine. Then after the user edits the data in that form it submits it via another php page and the data are written back to the database.
This used to work fine until last spring, where many users complanied "The requested URL was rejected. Please consult with your administrator." error. What might be causing this? Is it my code? It seems to happen only from those that use chrome. In the console I get no errors. Could you please help me?

A: My IT fixed the problem. Here is their response for the history:
something from the code of the request is violating HTTP Protocol with the message "Number of headers 21 exceeded maximum limit of: 20" which caused the Web Application Firewall to block the request. We have now increased the maximum number of headers allowed to 25 but you should also check your code to adhere to HTTP Protocol standards and security best practices.
A ton of thanks to you all for helping me out.
Best,


text:
Q: Free $R$-modules vs finitely supported maps I am reading something on the web talking about free modules over a ring $R$. At the very beginning there is this identity:
$$\displaystyle\oplus_{\alpha\in A}R=\{s:A\to R: s\text{ is finitely supported}\}$$
Here $A$ is any set. The text says that this is an example of free $R$-module. What I can't understand is:
1) What is the left hand side of the identity? Maybe the direct sum of finitely many copies of $R$?
2) Why left hand side is the same as right hand side? I mean, I have checked that RHS is an $R$-module, with obvious pointwise operations, but why is the same as LHS, whatever LHS is? I mean, that "=" is a strict equal or maybe an isomorphism?
3) Assuming that this is free, what is a basis for it?

A: 1) the left hand side is the direct sum of $|A|$ many copies of $R$. And it is not assumed that $A$ is finite.
One definition of the direct sum which you may be familiar with is that $A_1\oplus A_2 \oplus A_3 \oplus \dotsb$ is the set of all finitary sums of the form $a_1+a_2+a_3+\dotsb + a_{i_n}$ with each $a_i\in A_i$. Another definition is as tuples of elements (so it's a subset of $A_1\times A_2\times A_3\times\dotsb$) which are only finitely often nonzero.
The direct sum $A_1\oplus A_2 \oplus A_3 \oplus \dotsb$ comprises tuples, so it is a subset of the direct product $A_1\times A_2 \times A_3 \times \dotsb$ of all tuples. The direct sum should be thought of as actual formal sums, and summation is built inductively out of addition. Addition is a binary operation, so you can only inductively build up finite sums, so in an algebraic setting, only finite summations are considered. And taking infinite sums is not usually considered an algebraic operation; for example that operation often requires topological data (take a limit of partial sums, etc). This is why the direct sum only includes tuples which are finitely often nonzero, and the tuples in the direct product should not be thought of as sums of its components, unless you want to consider formal infinite sums.
2) The left-hand side is the same as the right-hand side because tuples and functions (or sequences) are the same thing. Why is this?
Consider a sequence $\{a_n\}_{n\in\mathbb{N}}$ such as the Fibonacci sequence with $a_1=1, a_2=1, a_3=2, a_4=3, a_5=5, a_6=8,\dotsc$. Just like a tuple it has a first, second, third, etc element, and this property characterizes tuples. A tuple is an ordered list like $(1,1,2,3,5,8,\dotsc)\in R\times R\times R\times\dotsb$. It can also be thought of as a function $a\colon \mathbb{N}\to R$ with $a(1)=1, a(2)=1, a(3)=2, a(4)=3, a(5)=5, a(6)=8,\dotsc$.
So we may think of our direct sum as a finite length sequence, or as a tuple, or as functions from the indexing set. They are the same.
I had written "a tuple is the same as a sequence is the same as a function", but that's not entirely true. A tuple like $(4,7)$ may live in a direct product like $2\mathbb{Z}\times(2\mathbb{Z}+1)$, where the two factors are not the same. Elements of such a product are not functions, because functions always take values in a fixed codomain. We cannot think of this tuple as a function with $f(1)=4, f(2)=7$, because what would be the codomain of this function?
However when all the factors (or summands, in case of direct sum) are the same (as in your example), then it is valid to state that tuples, sequences, and functions are the same thing.
3) yes it's free. A natural basis is the set of functions $\{e_a\}_{a\in A}$ where each $e_a$ is defined as the function which sends $a$ to $1$ and all other elements to $0$.
$$e_a(b)= \left\{ \begin{array}{cc}
             1  & a=b \\
             \\ 0 & a\neq b \\
             \end{array}
   \right.$$
Viewing elements as tuples, this basis is written as $(1,0,0,0,\dotsc), (0,1,0,0,\dotsc), (0,0,1,0,\dotsc),(0,0,0,1,\dotsc),\dotsc$. It is sometimes called the standard basis.
Note that the standard basis does not span the direct product. You need a strictly larger cardinality basis and some nonconstructive mathematics to get a basis for the direct product.


text:
Q: Kafka consumer doesn't consume more then 200 per second We subscribe to a kafka producer with our consumer and in our implementation we are stuck consuming at a maximum of 200 events per second.
For testing we receive bytes and don't do any deserialization and discard them immediately and still we are stuck at a maximum of ~200/s
Our consumer config is as follows:
sbt (v0.13.5): "org.apache.kafka" % "kafka-clients" % "1.0.1"
val props: Properties = new Properties()
props.put(ConsumerConfig.CLIENT_ID_CONFIG, "some-client")
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "<list-of-kafka-brokers:6668>")
props.put(ConsumerConfig.GROUP_ID_CONFIG, "test")
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true")
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000")
props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "3000")
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer")
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArrayDeserializer")
props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, "64")
props.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, "50")
props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, "2000")
props.put(CommonClientConfigs.RECEIVE_BUFFER_CONFIG, "102400")

Any idea what could cause our consumer to max process only 200 max?
PS: our machine is 16gb ram with 8 cores and 4gb JVM heap space


text:
Q: TypeScript – TypeError: Alice_1.Alice is not a constructor I've got a file alice.ts with the implementation of a class called Alice and an interface called IAlice:
export interface IAlice {
    readonly prop: number;
}

export class Alice {
    static fromJSON(json:string) {
        const par = ...
        return new Alice(par);
    }

    readonly prop: IAlice;

    constructor(prop: IAlice) {
        this.prop = prop;
    }
}

In my test when I run:
import { Alice, IAlice } from "filepath";
...
const alice: Alice = new Alice(object);
...

I got as output an error:
TypeError: alice_1.Alice is not a constructor

Does anybody have an idea why this error is raised?
Thanks!

A: You have a typo in your declaration:
const alice: new Alice(object);
// Should be:
const alice = new Alice(object);


text:
Q: Cake PHP, avoid and detect empty fields and duplicate primary key i'm not able to catch, inside Controller class, when a field is empty, or when user try to add a new row with duplicate primary key.
this is my model validation array:
public $validate = array(
    'username' => array(
        'notEmpty' => array(
            'rule' => 'notEmpty',
            'message' => 'username empty',
            'required' => true
        ),
        'alphaNumeric' => array(
            'rule' => 'alphaNumeric',
            'message' => 'not alphanumeric'
        ),
        'maxLength' => array(
            'rule' => array('maxLength', 50),
            'message' => 'too long'
        ),
        'minLength' => array(
            'rule' =>array('minLength', 1),
            'message' => 'too short'
        )
    ));

and this is my add action inside controller:
if ($this->request->is('post')) {
        $this->Admin->set($this->request->data);
        $this->Admin->create();
            // it validated logic
            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash(__('The admin has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $errors = $this->Admin->validationErrors;
                debug($errors);
                $this->Session->setFlash(__('The admin could not be saved. Please, try again.'));
            }
}

but,

*

*if i leave empty my field, my custom message is not showed, but is showed default cakephp message for empty field

*if i try to add a duplicate element into my database (so i violate primary key), no error message is showed too, and i'm redirect automaticalli to index() action of controller (the default index action that shows database elements)

A: To avoid duplicate primary key, set id as unique key in your database table .

if i leave empty my field, my custom message is not showed, but is showed default cakephp message for empty field

that's correct way for displaying validation messages.

if i try to add a duplicate element into my database (so i violate primary key), no error message is showed too, and i'm redirect automaticalli to index() action of controller (the default index action that shows database elements).

If submitted data contain field id and that value exist in database, your post will be updated.
I think this piece of line is unnecessary:
$this->Admin->set($this->request->data);

UPDATE:

i would show a message if user insert duplicate record. i don't want show default cake php message, but my custom message declared into rule.

public function add(){
if ($this->request->is('post')) {
        //
        if(isset($this->request->data['ModelName']['id'])){
           $id = $this->ModelName->findById($this->request->data['ModelName']['id']);
           if($id){
              // my custom message here
           }
        }
        //
        $this->Admin->create();
            // it validated logic
            if ($this->Admin->save($this->request->data)) {
                $this->Session->setFlash(__('The admin has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $errors = $this->Admin->validationErrors;
                debug($errors);
                $this->Session->setFlash(__('The admin could not be saved. Please, try again.'));
            }
}
}


text: Q: How to share socks5 for local network? How can I convert the socks5 service on my u untu into a virtual network interface without using proxy settings and then share this interface for my local network so that the entire network can be connected to socks5 vpn without changing the network settings?


text:
Q: Memory monitor in Android Studio reports different RAM usage than the device When investigating RAM usage in an app I am working on, I have been using the Memory Monitor tool in Android Studio (can be accessed in Android Studio by going to Tools>Android>Memory Monitor). I have noticed the RAM usage of my app that is reported in Memory Monitor, is always far lower than when viewing the RAM usage from the device (can be accessed by going to Settings>Apps>Running).  As you can see in the screenshots below, Memory Monitor is reporting about 18MB of RAM usage (23MB if you include free space), but the device is reporting 43MB.
Why the difference and also is one more accurate than the other?

A: I suspect that the memory monitor tool is talking to the dalvik virtual machine about heap allocations made by Java code, and the device manager is showing what the entire process is using for memory.  So the first does not include overhead or memory used by the virtual machine itself (or its text and libraries), or any off-heap allocations (sometimes native code can allocate memory that isn't directly visible to the VM).
See https://developer.android.com/tools/debugging/debugging-memory.html#ViewingAllocations and try running the command:
adb shell dumpsys meminfo <package_name>

to get a more precise breakdown of the run-time memory usage of your application.

A: I've tested the Android Studio's Memory Monitor's Allocated can be get this way programmatically:

long allocatedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();

But this only works to get information of the current app.


text:
Q: SignalR setup when separating out data access layer Current setup has a single webapi with controllers, services, SignalR Hubs/server, data entity models and view models (say Project.Main). The thought is to create a separate project (Project.Data - webapi) for Data entity model, view models and services.
Project.Main would reference Project.Data to access services. Now these services currently utilizes Server HubContext to send data to clients like:
var ChatCompanyHubContext = GlobalHost.ConnectionManager.GetHubContext<ChatCompanyHub>();
                ChatCompanyHubContext.Clients.Group("ChatCompanyHub-1").newMessage(msg, for_user);

*

*How should this part of code be setup in Project.Data ?

*Should SignalR be setup considering Project.Data as client?

*What would happen when call is made to Project.Data function from Project.Main incase Project.Data is setup as SignalR client?

Background:
To utilize Azure functions and to keep debugging easy we thought of just calling a service function from Azure functions trigger action. This is why we need to separate out the data access layer into a separate project (Project.Data) which can be referenced by both the Project.Main and Azure Functions Project.


text:
Q: javascript expand exponential Found this function here
http://jsfromhell.com/string/expand-exponential
String.prototype.expandExponential = function(){
return this.replace(/^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/, function(x, s, n, f, c){
    var l = +c < 0, i = n.length + +c, x = (l ? n : f).length,
    c = ((c = Math.abs(c)) >= x ? c - x + l : 0),
    z = (new Array(c + 1)).join("0"), r = n + f;
    return (s || "") + (l ? r = z + r : r += z).substr(0, i += l ? z.length : 0) + (i < r.length ? "." + r.substr(i) : "");
});
};

I sort of get the replace part, but I'm lost when I see the function(x,s,n,f,c) part. What am I missing?
Can someone help me break this down into more understandable components?

A: See this page
Basically, x is the matched substring. s corresponds to the part that was matched by the first pair of parentheses (([+-])), n corresponds to the part matched by the second parentheses ((\d+)), and so on.
The matched string is replaced by the value returned by this function.

A: You can pass a function as the second parameter of a replace() call.
The parameter list (from MDN):

*

*the matches substring - in your case x

*the n parenthesized submatch strings - in your case 2: s and n

*offset of the matched substring - in your case f

*the total string - in your case c


text:
Q: Is it possible to give preference to row returned based on column value when grouping by another column? I would like to specify which row to return first based on whether the uid value is equal to a value I specify, when using count with group by.
I have 5 tables. Two tables are 'intersection entity' tables that hold foreign keys to the 3rd and 4th tables  poster and albums, as well as the foreign key to the fifth table, link which holds the user_id.
if a user has created a link, I need that user_id to be the value in the user_id column, otherwise it doesn't matter which row is used. I have tried many different approaches and the only one that comes close is using group by imageId, uid = 9, but this breaks the count and I get duplicate rows with a count of 1, instead of the actual count. I apologize if I am missing something obvious as I haven't used mysql significantly in quite awhile.
SELECT  * FROM (
                SELECT poster.*,  l.user_id as uid,  count(*) as c
                FROM `poster_links` pl
                INNER JOIN poster ON poster.posterID = pl.poster_id
                inner join link l on pl.link_id = l.link_id
                WHERE pl.poster_id != 167 and l.link_id in(
SELECT pl.link_id from poster_links as pl where poster_id = 167)
    group by imageId, uid = 9
    UNION ALL
                SELECT albums.*,  l.user_id as uid,  count(*) as c
                FROM `album_links` al
                INNER JOIN albums ON albums.album_id = al.album_id
                inner join link l on al.link_id = l.link_id
                WHERE al.album_id != 'null' and l.link_id in(
SELECT pl.link_id from poster_links pl  where poster_id = 167)
    group by imageId, uid = 9
                    ) T

Using group by imageId, uid = 9(current user) is the only way I have found to force the uid to be equal to the current user if that user is one of the multiple users who have created the link. I am trying to avoid an additional query to get the current users 'links', then comparing both query results on the back end.
I am grouping by imageId because it is the only unique field. Also I have tried using case in the select-
CASE l.user_id
   WHEN 9 THEN 9
       ELSE null
   END  as uid,

but I only got null values probably because mysql only checks the first value returned which could be any uid.
CREATE TABLE `poster` (
  `posterID` int(11) NOT NULL,
  `imageId` varchar(255) DEFAULT NULL,
  `title` varchar(64) NOT NULL,
  `user` int(11) NOT NULL,

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `poster` (`posterID`, `imageId`, `title`, `user`) VALUES
(71, 'C44FB5C807FFC1768271D9988FF41270054D9B6F', 'Testarossa', 1),
(72, 'E009F63FD85E1EE98BE1EED77EA4F8A8E96BEA4F', 'Lambo', 1 ),
(73, 'E192493089403C89E9DAA8B64DDBED12FFF818E5', 'Ferrari', 1),
(74, '8AFFA17561689FCA48BB9000B81AE13CA46E9A05', 'Koenisegg', 1),
(167, 'E13CA46E98AFFA17561689FCA48BB9000B81AA05', 'egg', 1);

CREATE TABLE `albums` (
  `album_id` int(11) NOT NULL,
  `imageId` varchar(255) DEFAULT NULL,
  `title` varchar(255) NOT NULL,
  `user_id` int(11) NOT NULL,
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `albums` (`album_id`, `imageId`, `title`, `user_id`) VALUES
(45, '6FJIVC7L4OKNM8YAP1XGZ23DW5SUR0QEHB9', 'Cars', 3),
(46, 'FU6D7MVTZK85SRPLIE1CXGY2WO4QAN03JHB', 'Misc', 3),
(47, '5W498FRDAQGOZN2XUIP7VL3CKJTHSBM0E16', 'SCars', 3),
(48, 'SG8MVX1DLAUHENFOI5JB6W0C2RP379QYZ4K', 'MCars', 3);

 CREATE TABLE `link` (
      `link_id` int(11) NOT NULL,
      `user_id` int(11) NOT NULL,
        `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `link` (`link_id`, `user_id`, `timestamp`) VALUES

    (11, 6,  '2019-10-29 09:11:25'),
    (12, 3,  '2019-10-29 07:57:24'),
    (13, 9,  '2019-10-29 07:59:55'),
    (14, 9,  '2019-10-29 09:10:25'),
    (15, 7,  '2019-11-03 11:05:51'),
    (16, 9,  '2019-11-03 12:05:51');

CREATE TABLE `album_links` (
  `link_id` int(11) NOT NULL,
  `album_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `album_links` (`link_id`, `album_id`) VALUES
(12, 45),
(13, 45),
(13, 46),
(14, 47),
(15, 48);

CREATE TABLE `poster_links` (
  `link_id` int(11) NOT NULL,
  `poster_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `poster_links` (`link_id`, `poster_id`) VALUES
(11, 167),
(11, 71),
(12, 167),
(14, 167),
(12, 71),
(16, 167),
(16, 71),
(14, 72),

I expect to get all the posters and albums grouped by imageId with the addition of a count column and a uid column that should display the value 9, if that is one of the values in the link table. Instead it shows a different uid.
poster   | uid  | c  |
C44FB5..   9      3
E009F6..   9      1
6FJIVC..   3      1
5W498F..   9      1

A: I'm still having trouble to understand the logic behind your expected result, but here is a wild shot:
WITH tmp as (
    SELECT poster.imageId,  l.user_id as uid
    FROM poster_links t
    JOIN poster
        ON poster.posterID = t.poster_id
    JOIN link l
        ON t.link_id = l.link_id
    WHERE t.poster_id <> 167
      AND t.link_id IN (
          SELECT pl.link_id
          FROM poster_links as pl
          JOIN link AS l
              ON l.link_id = pl.link_id
          WHERE poster_id = 167
      )
    UNION ALL
    SELECT albums.imageId, l.user_id as uid
    FROM `album_links` s
    JOIN albums
        ON albums.album_id = s.album_id
    JOIN link l
        ON s.link_id = l.link_id
    WHERE s.album_id <> 'null'
      AND s.link_id in (
           SELECT pl.link_id
           FROM poster_links AS pl
           JOIN link AS l
               ON l.link_id = pl.link_id
           WHERE poster_id = 167
       )
)
SELECT imageId, uid, cnt
FROM (
    SELECT imageId, uid
         , COUNT(*) OVER (PARTITION BY imageId) as cnt
    FROM tmp t1
) as t
WHERE uid = 9
UNION ALL
SELECT imageId, uid
     , COUNT(*) OVER (PARTITION BY imageId) as cnt
FROM tmp t1
WHERE NOT EXISTS (
    SELECT 1 FROM tmp t2
    WHERE uid = 9
      AND t1.imageId = t2.imageId
);

I placed you original query in a Common Table Expression (CTE) and used a Window function for the count.
I split it into 2 cases, where the uid = 9 and images where uid = 9 does not have a link:
imageId                                  uid    cnt
5W498FRDAQGOZN2XUIP7VL3CKJTHSBM0E16        9    1
C44FB5C807FFC1768271D9988FF41270054D9B6F   9    3
E009F63FD85E1EE98BE1EED77EA4F8A8E96BEA4F   9    1
6FJIVC7L4OKNM8YAP1XGZ23DW5SUR0QEHB9        3    1

Fiddle

A: I took a 2 day break and when I checked back this morning I didn't see any additional alerts so I decided to give up and break the query into several different queries and perform the needed logic in my back end code. While working on this I made a few more attempts and found a solution! It seems all I needed to do was put an additional aggregate function in the field list and test for the needed uid.
SUM(CASE WHEN l.user_id = 9 THEN 9 ELSE 0 END) as uid

Here is what I did-
SELECT  * FROM (
                    SELECT poster.*, 1 AS type, SUM(CASE WHEN l.user_id = 9 THEN 9 ELSE 0 END) as uid, l.link_id, count(*) as c
                    FROM `poster_links` t
                    INNER JOIN poster ON poster.posterID = t.poster_id
                    inner join link l on t.link_id = l.link_id
                    WHERE t.poster_id != 167 and t.link_id in(
    SELECT pl.link_id from poster_links as pl join link as l on l.link_id = pl.link_id where poster_id = 167)
        group by imageId
    UNION ALL
                    SELECT albums.*, 2 AS type, SUM(CASE WHEN l.user_id = 9 THEN 9 ELSE 0 END) as uid, l.link_id, count(*) as c
                    FROM `album_links` s
                    INNER JOIN albums ON albums.album_id = s.album_id
                    inner join link l on s.link_id = l.link_id
                    WHERE s.album_id != 'null' and s.link_id in(
    SELECT pl.link_id from poster_links as pl join link as l on l.link_id = pl.link_id where poster_id = 167)
        group by imageId
                    ) T

Unfortunately I have no idea how efficient this is, or will be when the tables become enormous, but I am happy I found a simple solution to the problem.
I am also curious if there is a way to do this without running the exact same subquery twice as both select poster.* and select album.* queries are dependent on the same subquery. Any suggestions?
If anyone has any comments on my table structure or the efficiency of this query, or anything else, please provide feedback!


text:
Q: How can I store previous wizard pages? Actually i am trying to do a Wizard control. In which i have load 3 pages dynamically when click the next button. When i click the next button i need to store the page details so i have created a dictionary to store the usercontrol. Is there any other suggestions to store the previous page details.

A: There are many ways to achieve your requirements. This is what I would do, which I think is very inline with the MVVM design pattern.

*

*Define a ViewModel class that contains all the variables that you want to collect (regardless of the partition to pages.

*Add a public property named 'currentPage'.

*Define the frame of the wizard. Probably a <Window> element, with a StackPanel. The Window would have a title at the top, and an area at the bottom for the 'prev' and 'next' buttons (and 'finish' if you want to).

*In the main area of the StackPanel put a  and bind its DataContext to the ViewModel

*In the ViewModel create a Next and Pref commands (use Prism DelegateCommand, or implement your own lightweight version that derives from ICommand.
6/ Also, bind the 'Finish' button to a command, with the appropriate CanExecute logic (have you collected enough data?).

*The Next and Prev 'CanExectue' logic would look at currentPage. e.g. the Prev command CanExecute will return false when currentPage is 0.

*You'll have 3 different data templates, one for each page. Each data templates will present different subset of properties you want to collect at that page. Bind the UI controls to properties at the ViewModel, and have the binding mode two way.

*Derive your ViewModel from INotifyPropertyChanged, and have all the setters to fire the appropriate notification. It is required for at least the currentPage property, but for the completion of the solution do it for all properties.

*In the Next and Prev command Execute method will modify the currentPage property (the Setter should fire notification). The view will update automatically.

*For the main area ItemControl, implement a WizardTemplateSelector derived from DataTemplateSelector. Define it as a resource, and assign the ItemControl.ContentTemplateSelector using {StaticResource} binding.

*If you want to, you can also have a List control at the left side of the Window, with the Selected Item Index bound to the current page.

EDIT (Explainer): The basic idea is to have a single ViewModel, which can be Viewed in several different Data Template, depends on the current page.


text:
Q: Will C/C++ libraries work on Android Phone Does anyone have any experience using JNI to call native C/C++ libraries in Android? Is the environment suitable for running C/C++ libraries and if so is there anything specific about the environment which you need to accommodate?
Thanks

A: My understanding is that Android provides only a subset of the standard C++ runtime library. For example, Android does not support exceptions in native code. I think there are other restrictions as well.

One complication is that, while Android itself might include many native libraries, only some of them are considered stable enough to link against. The Android NDK page lists the libraries which are safe.

*

*libc (C library) headers

*libm (math library) headers

*JNI interface headers

*libz (Zlib compression) headers

*liblog (Android logging) header

*A Minimal set of headers for C++ support

If your C library only uses those, you should be fine. C++ support sounds a little spottier.

A: For a good example of C and Java integration, check this out:
https://github.com/jackpal/Android-Terminal-Emulator
Untar the files and you can find a jni/termExec.cpp - which uses normal C API like "exec()", "fork()", and "open(/dev/ptmx)" to implement terminal emulation (http://linux.die.net/man/4/ptmx).
Looking up the jni/Android.mk file, and u can see that the cpp is compiled as a library -  libandroidterm.
And then the java application (src/jackpal/androidterm/Exec.java) will load the library via System.loadLibrary("androidterm").
I think this application provide a small enough example for u to extend whichever way u like - either the cpp or the java file.   (The cpp file is basically C-based, not C plus plus).
And remember the mapping between them, for example here it is:
static JNINativeMethod method_table[]
= {
    { "createSubprocess", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[I)Ljava/io/FileDescriptor;",
        (void*) android_os_Exec_createSubProcess },
    { "setPtyWindowSize", "(Ljava/io/FileDescriptor;IIII)V",
        (void*) android_os_Exec_setPtyWindowSize},
    { "waitFor", "(I)I",
        (void*) android_os_Exec_waitFor},
    { "close", "(Ljava/io/FileDescriptor;)V",
        (void*) android_os_Exec_close} };

A: for a C library, you shouldn't have any trouble. a C++ library might be more fun if it uses much of the standard library, because most of the C++ standard library is missing, but you can always supply your own "mini-STL". that's basically how external/webkit works.
much of Android's java.util.regex, java.nio.charset, java.util, and java.text are implemented by calling ICU4C, for example. (the library's in external/icu4c and the JNI is in dalvik/libcore/icu/src/main/native.) a mix of ICU's C and C++ interfaces are used, so you can rest assured this stuff gets quite a good workout on a daily basis ;-)


text:
Q: message:ORA-00060: deadlock detected while waiting for resource in oracle transaction I have below code for running transaction. I keep getting error like   message:ORA-00060: deadlock detected while waiting for resource. But if same is executed second time, it works fine. Does code seem buggy at any place?
async transactionData(postData) {
        var options = {
            autoCommit: false
        };
        return new Promise(async (resolve, reject) => {
            try {
                let transactionError = false;
            let connection = await this.getConnection();
                let transactionErrorMsg = '';
                for (let i = 0; i < postData.length; i++) {
                    const sql = postData[i].query;
                    const binds = postData[i].binds;

                    try {
                        await connection.execute(sql, binds, options);
                    } catch (e) {
                        transactionErrorMsg = e.message;
                        transactionError = true;
                        console.log('Transaction error', transactionErrorMsg);
                        logger.error(transactionErrorMsg);
                        break;
                    }
                }
                if (transactionError) {
                    connection.rollback((err) => {
                        if (err) {
                            resolve({ "status": false, "message": err })
                        } else {
                            resolve({ "status": false, "message": `Transaction failed due to ${transactionErrorMsg}` })
                        }
                    });
                } else {
                    connection.commit((err) => {
                        if (err) {
                            resolve({ "status": false, "message": err })
                        } else {
                            resolve({ "status": true, "message": 'Transaction passed' })
                        }
                    });
                }
                connection.release();
            } catch (e) {
                resolve({ "status": false, "message": e.message })
            }
        })
    }


text:
Q: Fixed subspaces of a family of representations $\rho_t: F_2\to GL(n,\mathbb C)$ Suppose we have a real analytic family of matrices $A_t, B_t\in GL_n(\mathbb C)$, with $t\in \mathbb R$. Suppose that for $t\in (0,1)$ there is a common non-zero eigenvector $v_t\in \mathbb C^n\setminus 0$ such that $A_t(v_t)=B_t(v_t)=v_t$. Is it true that such a common (non-zero) vector exists for all $t\in \mathbb R$?

A: Define the sets
$$M = \{ (A,B,l)\in GL_n(\mathbb{C})\times GL_n(\mathbb{C})\times\mathbb{P}^{n-1}(\mathbb{C}) : Aw=Bw=w \text{ for all } w\in l \},$$
$$N = \{ (A,B)\in GL_n(\mathbb{C})\times GL_n(\mathbb{C}):\exists v\in\mathbb{C}^n\setminus\{0\}, Av=Bv=v\}, $$
where a point of $\mathbb{P}^{n-1}(\mathbb{C})$ is thought of as a line in $\mathbb{C}^n$. The set $M$ is closed and analytic (actually algebraic). Let
$$\pi: GL_n(\mathbb{C})\times GL_n(\mathbb{C})\times\mathbb{P}^{n-1}(\mathbb{C})\to GL_n(\mathbb{C})\times GL_n(\mathbb{C})$$ be the projection. Then $\pi(M)=N$, and since $\pi$ is proper, the set $N$ is closed and analytic.


text:
Q: Change color of selected element - React I'm new to React.
I'm trying to change the color of one particular "li" that was selected, but instead it changes color of all "li".
Also when another "li" is clicked I want the first "i" to be not active again.
here is the code:  http://codepen.io/polinaz/pen/zNJKqO
var List = React.createClass({
  getInitialState: function(){
    return { color: ''}
  },
  changeColor: function(){
    var newColor = this.state.color == '' ? 'blue' : '';
    this.setState({ color : newColor})
  },

  render: function () {
    return (

one

two

three

    );
  }
});
ReactDOM.render(
    <List/>,
    document.getElementById('app')
);

A: Since you don't have any identifiers on you list items you activate/deactivate them all every time. You need to reference each of them in a different way, then you can set the color individually. This is one example

var List = React.createClass({
  getInitialState: function(){
    return { active: null}
  },

  toggle: function(position){
    if (this.state.active === position) {
      this.setState({active : null})
    } else {
      this.setState({active : position})
    }
  },

  myColor: function(position) {
    if (this.state.active === position) {
      return "blue";
    }
    return "";
  },

  render: function () {
    return (

 {this.toggle(0)}}>one

 {this.toggle(1)}}>two

 {this.toggle(2)}}>three

    );
  }
});
ReactDOM.render(
    <List/>,
    document.getElementById('app')
);


text:
Q: Where I should save configuration data for backend Android sorry if it is a stupid question but I have little experience with development app.
I'm developing a native App that make ajax call to my backend (public API) , My question is:
Where I should save configuration for ajax call?
For now I have create a custom static class named ConfigData and in my app I call this class like
ConfigData.apiUrl

And in my ConfigData class I have
public static String apiUrl= "www.mysite.com/public/api";

But Is there a better method?

A: One possible method is to use buildConfigField in you build.gradle
productFlavors {
    development {
        ....
        buildConfigField "String", "API_URL", "\"www.mysite.com/public/api\""
    }
}

You can then access it via BuildConfig.API_URL in code
You can define different urls for different build flavors, staging, production etc.
https://developer.android.com/studio/build/gradle-tips.html#share-custom-fields-and-resource-values-with-your-app-code

A: If it is just simple key value set, you may save it to Shared Preference. Follow this url for details
https://developer.android.com/training/basics/data-storage/shared-preferences.html
In case, it is bit complex, you can save it to sqlite database

A: You can use string.xml to save backend server URLs, Please try to add separate strings for base URL and each endpoint. Like
<string name="base_url">www.mysite.com/public/api/</string>
<string name="login">login.php</string>
<string name="get_data">getData.php</string>

And you can get above strings in java file like
String url=getResources().getString(R.string.base_url)+getResources().getString(R.string.login);


text:
Q: Viewing command results page by page I use a command in AIX to view back-end nodes,etc..but they are too many so they don't fit in one page and when I run the command when it finises I can pnly scroll to last page and cannot read the rest of results in previous pages.
How can I either print the results of a command to a text file or be able to pause and see the results on other pages?

A:
How can I either print the results of a command to a text file

Use the redirection operators > (overwrites) or >> (appends), which are documented in your shell's manual.
mycommand > output.txt

If you also need to redirect stderr, use one of the following, depending on your shell:
mycommand >& output.txt

mycommand > output.txt 2>&1

or be able to pause and see the results on other pages?

Use a pager such as more, less, w3m, or pg.
mycommand | less

mycommand |& less

mycommand 2>&1 | less

less is more convenient, but might not be installed on all systems.
The | pipe operator is also described in your shell's manual.


text:
Q: CFRelease EXC_BAD_ACCESS when called with MDQueryRef StringArray NativeSearch::search(const String &filenameglob) {

    CFStringRef queryString = jcf_getMDQueryString(filenameglob);

    MDQueryRef query;
    query = MDQueryCreate(kCFAllocatorDefault, queryString,
                          nullptr, nullptr);
    CFRelease(queryString);

    if (query == NULL) return StringArray();

    MDQueryExecute(query, kMDQuerySynchronous);

    int resultCount = MDQueryGetResultCount(query);
    StringArray result;

    for (CFIndex i = 0; i < resultCount; ++i) {
        const MDItemRef r = (const MDItemRef) MDQueryGetResultAtIndex(query, i);
        CFStringRef filename = (CFStringRef) MDItemCopyAttribute(r,
                                                                 CFSTR("kMDItemFSName"));
        DBG("found: " + String::fromCFString(filename));
        CFRelease(r);
        CFRelease(filename);
    }

    CFRelease(query);  // <<< EXC_BAD_ACCESS
    return result;
}

Any suggestions on this problem.  I was expecting to have to called CFRelease() on query as query was created with MDQueryCreate.  The Apple documentation suggests that's the right thing to do with a result from a Create function.
However I get a crash.  Otherwise the code works as intended.
Any thoughts on this one?

A: Problem solved.
    CFRelease(r);

Is releasing an MDItem which is actually owned by the MDQuery.  This is a mistake.  It means later, when I call CFRelease(query) the MDItem is released for a second time.  This causes the crash.
The lessons?

*

*When debugging this I should have looked at every operation that could have affected my MDQuery. Instead I just focused on the operations which named the query object directly.

*Don't CFRelease(...) anything which you obtain through a function name called GetSomething.

To quote apple:

Core Foundation functions have names that indicate when you own a
  returned object:
Object-creation functions that have "Create" embedded in the name;
Object-duplication functions that have "Copy" embedded in the name.
If
  you own an object, it is your responsibility to relinquish ownership
  (using CFRelease) when you have finished with it.

But: not when you obtain a reference to an object through a function with Get in the name!


text:
Q: Slow loading of QGIS Project I have a number of standard projects set up for QGIS users. Some of them take more than 5 minutes to load. Things recently got much worse suddenly - and I want to track down why.
Are there any methods to check what stages of loading a project are slowing things down or/and how long QGIS is taking over each stage of loading a project?
In my particular case the issue may be related to internal network overload, and seems to be related to upgrades (at the same time) from Windows 7 to Windows 10 and QGIS 2.18 to QGIS 3.4. However, I think answers will be more useful for others/Stackexchange if they consider the wider question.

A: I had issues with slow loading of QGIS in a general sense. What helped me was the unchecking my installed plugins so that they don't load on startup. This helped independent of what version I was using.

A: One idea is to load it without rendering and check the load time. Then turn rendering on and try different layers one by one.
Also check for feature counting on layers as that can slows thing down.

A: Deleting complex print layouts really helped to reduce the loading time of my QGIS projects.

A: In my case I opened a fairly large QGIS 2.6 project in QGIS 3.16 and it took an extremely long time to load, almost an hour. In 2.6 the same project file takes a minute or so to load on the same Windows 7 machine.
I isolated the problem to an 81000 row CSV layer. The CSV file used newlines for the row delimiters, and QGIS 3 apparently needs cr-lf delimiters (at least on Windows). This caused it to treat the entire file as a single massive row.
After I saved the CSV file from Wordpad (which converted the delimiters to cr-lf), the load time in QGIS 3 was normal.

A: Based on this never being answered, I now assume that there must be no way to do what I asked about - which is to find out by some standard method what is taking the time.
Other answers provide a selection of ideas for tracking down some of the potential issues.

A: Did you try out the Debugging/Development Tools? They are availably since QGIS 3.16.
The tool analyses the time it takes to load each layer from a QGIS project.
Go to View --> Panels --> Debugging/Development Tools and click on the Profiler in the left menu.
Select Project Load from the category list.
Expand the entry called "Reading map layers" in the profiler tree. Now you can see the loading time of each layer.

It is also described in this post: Measuring loading time of each layer when opening a QGIS project


text:
Q: Not able to delete file from the server? I've a file called piture-list.php in my website.
When I see them through the ftp client it shows two files with different filesizes.
as
File name          filesize
picture-list.php   19818
picture-list.php   9063

When I select the file with filesize 9063 and delete using ftp, it deletes the file with the filesize 19818.
Then I used the command prompt to list files and happened to see actually there were two files one with the original name and other with a space before the filename (" picture-list.php").
I tried to move, delete the file but nothing is successful..
What may be the issue?

A: To interact with the file containing a leading space you will need to put a quotes around the file name e.g.
rm " picture-list.php"

You can also use the -i command line switch e.g.
rm -i *pict*
rm: remove regular file ` picture-list.php'?

and answer y to remove the one with the leading space.


text:
Q: Unable to setup connection between iPhone Proxy and Postman Proxy debug I want to track network traffic of mobile app in iPhone using Postman.
According to Postman article (https://learning.postman.com/docs/sending-requests/capturing-request-data/capturing-http-requests/) I setup it on between Postman App and my iPhone. But when I setup manual proxy in iPhone and try to access web application. Then my wifi disconnected and can't see any network traffic.
Anyone knows how to enable wifi connection and capture network traffic ?


text:
Q: Add fake column to Linq Entity Framework query I have 2 table : Singer and Song like this

I need to retrieve songs from 1 singer, or just retrieve a song by it id , I use this:
db.Songs.Find(id);                      // get song by its ID
db.Songs.Where(x => x.SingerID == id);  // get all songs by singer's ID

and it return that song
$id: "2",
Id: 1,
NAME: "....",
IMAGE: ".....jpg",
URL: ".....mp3",
SingerID: 1

but I want to hide the SingerID, instead I want to return a "SingerName" column.  I've used this:
db.Songs.Where(x => x.SingerID == id).Select(song => new { song, song.Singer.NAME });

but the result became:
song: {
    $id: "2",
    Id: 1,
    NAME: "....",
    IMAGE: ".....jpg",
    URL: ".....mp3",
    SingerID: 1
}
NAME: "SingerName"

So how can I get the result like this - all properties are equal (hide the SingerID and replace by SingerName):
$id: "2",
Id: 1,
NAME: "....",
IMAGE: ".....jpg",
URL: ".....mp3",
SingerName: "SingerName etc"

A: db.Songs.Where(x => x.SingerID == id).Select(song => new { song.Name, song.Image, etc... , SingerName = song.Singer.NAME });

A: You can just create new anonymous object and pass whatever you want.
db.Songs.Where(x => x.SingerID == id).Select(song => new {
  Id,
  NAME,
  IMAGE,
  URL,
  SingerName = song.Singer.NAME
});


text:
Q: Referring to the target name from the list of the prerequisites In a Makefile, I would like to refer to the target name from the list of prerequisites and to build something with it. Something of the form:
%.foo: $(addsuffix .bar, $(DATA_%))
  @echo $<

So that, supposing you have:
DATA_test = 1 2 3

When you call it as:
make test

That will expand to:
1.bar 2.bar 3.bar

Is this somehow possible? What would be a better approach to the problem?

A: If your version of Make has secondary expansion, this will probably work (I can't test it because today all I have handy is an old version).
.SECONDEXPANSION:

%.foo: $$(addsuffix .bar, $$(DATA_$$*))
    @echo $^

Without that, I don't see any better way to do it than this:
define FOO_RULE
$(1).foo: $(addsuffix .bar,$(DATA_$(1)))
endef

FOO_TYPES = test real whatever

$(foreach t,$(FOO_TYPES),$(eval $(call FOO_RULE,$(t))))

%.foo:
    @echo building $@ from $^


text:
Q: TableView Header Text Issue i have a bit of a problem with spacing as seen here : (Excuse my bad drawing skills :\ )

Can anyone tell me how to fix this spacing issue ? i can't find a solution to it ... Here is my code:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerText = UILabel()
        headerText.textColor = UIColor.darkGrayColor()
        switch section{
        case 0:
            headerText.textAlignment = .Right
            headerText.text = "הבר המועדף עליכם חסר? שתפו אותנו ונוסיף"
        case 1:
            headerText.textAlignment = .Right
            headerText.text = "יש לכם רעיון לשיפור האפליקציה? שתפו אותנו :)"
        default:
            headerText.textAlignment = .Right
            headerText.text = ""
        }
        //Any Other Customizations

        return headerText
    }
}

A: Implement the heightForHeaderInSection delegate method and return the desired height.
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 35.0//write here your desired value. This will be your table's header height
}


text:
Q: Loading Qt libs(different versions) inside an application We have our application developed in Qt 5.4 which is shipped as an SDK (dylib) for integration with other applications.  All the dependent libs are shipped along with the SDK(Qt 5.4.x binaries).
However we bumped into an issue when the customer tried to integrate our SDK in his application. That application is making use of a component which has a  Qt 5.3.x dependency. Our SDK has not worked with the application.  The issue is due to the fact the "libqcocoa" in platforms is shared, which is leading to a crash.
Can an application be able to load two different Qt binaries(with/without namespace) ?  If yes, how this can safely taken care  ? (application is in Mac)
I also need to address the point that,  the components which are using different Qt versions can be updated independently.  What are the best practices generally followed ? Please suggest.

A: Your use of Qt is usually an implementation detail. Hide it by using private frameworks or linking Qt statically.
Alternatively, if you need to interoperate with the user's Qt, add a small open-source interface that forwards relevant Qt APIs to your code. You'll be surprised at how little Qt most code uses. The interface is likely going to be a couple thousand lines at most and you can machine-generate it.


text:
Q: Creating new file association in Windows 10 by registry I'm working on Java application and I want to associate some file extensions with this app. While on older Windows systems (XP, 7) I had no problems - just creating two keys in HKEY_CLASSES_ROOT, for example:
[HKEY_CLASSES_ROOT\.fns]
@="strepFns"
[HKEY_CLASSES_ROOT\strepFns]
@="StrepFns File"
[HKEY_CLASSES_ROOT\strepFns\shell]
[HKEY_CLASSES_ROOT\strepFns\shell\open]
[HKEY_CLASSES_ROOT\strepFns\shell\open\command]
@="\"java -jar C:\\Users\\Norbert\\StrepFns.jar\" \"%1\""

(Of course I'm actually adding those keys into HKEY_CURRENT_USER\Software\Classes.)
Looks like there was some change in how HKCR works. I found many instructions about what's going on and what to do, including both adding HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.fns\UserChoice and removing it, but nothing seems to work.
I must add that I need to do that only through changes in registry and only in HKCU, as other ways will require things like requesting some privileges from users and I want it to work in background, without any user actions required.
Is anyone there who actually understand how file assosciation in Windows 10 works?


text:
Q: Detect circular relations in a distribution table I have the following two tables, that will define distribution rates from items on table A to other items on table A (I think I can say B defines a many-to-many relationship for A with itself).
create table A (
    code char(5) not null primary key,
    desc varchar(50) not null
)

create table B (
    code1 char(5) not null,
    code2 char(5) not null,
    perc numeric(6,2) not null,

    constraint pk_B primary key (code1, code2),
    constraint fk_B_1 foreign key (code1) references A (code) on update cascade on delete cascade,
    constraint fk_B_2 foreign key (code2) references A (code) on update cascade on delete cascade
)

I'd like to have a simple way to check if a new record being inserted on B will cause a circular reference to be created.
This example illustrates the problem:
insert into B (code1, code2, perc) values ('01.10', '02.10', 100);
insert into B (code1, code2, perc) values ('02.10', '02.11', 50);
insert into B (code1, code2, perc) values ('02.10', '02.12', 50);
insert into B (code1, code2, perc) values ('02.11', '04.10', 50);
insert into B (code1, code2, perc) values ('02.11', '02.12', 50);
insert into B (code1, code2, perc) values ('04.10', '01.10', 50);
insert into B (code1, code2, perc) values ('04.10', '04.11', 50);

This set of data would generate the following circular reference:

I'm using Firebird 2.5, but I'd prefer to use only standard sql, because portability is something I'm concerned. We might be changing DBMS soon.
Documentation on Firebird is a bit problematic though, but I believe CTEs in Firebird are documented here (search for Common Table Expressions): https://www.firebirdsql.org/refdocs/langrefupd21-select.html

A: Following @ypercube comment to the question, I came up with this solution:
with recursive A as (
    select code1, code2 from B
    where code1 = new.code2
    union all
    select a2.code1, a2.code2 from B a2
    join A on a2.code1 = A.code2
)

select * from A
where code2 = new.code1

If any records are returned, then new.code2 references new.code1 and there would be circular reference if this new record was inserted.
For Firebird specifically, this is what I used:
CREATE EXCEPTION EX1 'circular reference exception';

SET TERM ^ ;

CREATE TRIGGER TRIGGER_B_CIRCULAR FOR B
ACTIVE BEFORE INSERT OR UPDATE POSITION 0
AS
DECLARE CODE char(5);
BEGIN
    FOR with recursive A as (
            SELECT CODE1, CODE2 FROM B
            WHERE CODE1 = new.CODE2
            UNION ALL
            SELECT a2.CODE1, a2.CODE2 FROM B a2
            JOIN A ON a2.CODE1 = A.CODE2
        )

        SELECT CODE2 FROM A WHERE CODE2 = new.CODE1
        INTO :CODE DO
            exception EX1;
END^

SET TERM ; ^


text:
Q: SNOWFLAKE- Trying to run task on 2nd Tuesday of every month (USING CRON 0 15 8-14 * 2 UTC)- running for all days 8-14? Why? I am trying to run the Snowflake task on the 2nd Tuesday of every month using (USING CRON 0 15 8-14 * 2 UTC). But it is running for all the days between 8-14. Why this behavior? Is this a known issue in snowflake?

A: there are plenty of online cron generators that will create cron strings for you.
This string should do what you want:
0 0 15 ? 1/1 TUE#2 *


text:
Q: Methods to properly cut a large fits file to isolate certain galaxies into smaller fits files Currently I am working on analyzing several galaxies within a fits file image. The fits file is a 3D Hyperspectral cube, with x and y axes representing Right Ascension and Declination, and a z axis representing frequency. I also know the precise right ascension and declination of each galaxy. My goal is to cut the large fits file into smaller ones that isolate each of the galaxies so I can perform some further analysis on the individual galaxies. A crude and brute force method would simply be to manually cut the fits files around galaxy, and my currently algorithm is crude by simply cutting a square of a certain number of pixels around a galaxy, but I want to ask if theres some astropy method or some other numerical/mathematical method to identify and cut around the galaxies more efficiently?

A: Have a look at the spectral-cube and photutils Python packages.
spectral-cube has methods to cut out sub cubes (see e.g. here), and photutils has methods to detect sources (see here) and more, e.g. to measure and analyse your sources. For photutils, some of the methods will only work for 2D, and you will need to do some Numpy expressions to work with your 3D data.
In general, all Python astronomy packages (Astropy, spectral-cube, photutils) will work with pixel data in Numpy arrays (e.g. read with astropy.io.fits) and sky coordinates using astropy.wcs.WCS and astropy.coordinates.SkyCoord objects, so you will have to learn those a bit. For that a good place to start is the Astropy tutorials.
You asked for an efficient way to do the cutouts. This is achieved by using a Numpy array feature to "slice" into the large 3D pixel data array and to create a "view" of that cutout without making a copy. If you're new to Numpy, a good starting point to learn is the "basics of Numpy arrays" page of the Python data science handbook.

A: Astropy has a Cutout2D class that is useful for this. While it can read in FITS files with more than two axes, it can only produce a cutout based on two of the axes.


text:
Q: Facing issue with datetime.now in mvc5 i am using Dateime.Now in .net mvc and i deployed my website on europen web server when i use date someware in my website system always pick server datetime which is not best for me i want system always pick specific user coutry datettime if user locate in pakistan syetem always pick pakistan datetime or if user locate in japan system always pick japan datetime is this possiable?

A: save/create the datetime in the backend as DateTime.UtcNow to set it in utc and in the frontend convert it to local via javascript
new dateToLocal = new Date(dateTimeValueFromServer);
document.getElementById(idOfDateTimeElement).value = dateToLocal;


text:
Q: Can't get my custom control to serialize from the designer I am building a custom component, and it has a DataTable as one of the properties.
All is working well, except that I cannot get the designer to serialize the columns from the DataTable property.
I tried the solution in this answer but it does not solves my problem.
In other words, when I drop this custom component on a form in the designer, and then do the following steps

*

*fill in the DataBase property

*fill in the SelectText property

*choose the value true for the property DoRefreshSchema (it will remain false in the designer because it is only used to trigger the code to populate the DataTable's Columns)

then in the designer, in the property window, I can see all the columns of the DataTable filled as I expect.

But after a build or closing/opening the form, they are all gone again...
So what am I doing wrong here.
this is the code from the custom control (stripped to only show relevant code)
[Serializable]
public partial class gttDataTable : Component, ISerializable
{
    private DataTable _Table = new DataTable();
    private string _SelectText = "";
    private bool _DoRefreshSchema = false;

    public gttDataTable()
    { }

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DataTable Table
{
    get { return _Table; }
    set { _Table = value; }
}

[Editor("System.ComponentModel.Design.MultilineStringEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
public string SelectText
{
    get { return _SelectText; }
    set { _SelectText = value; }
}

public gttDataBase DataBase
{
    get { return _gttDataBase; }
    set { _gttDataBase = value; }
}

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool DoRefreshSchema
{
    get { return _DoRefreshSchema; }
    set
    {
        _DoRefreshSchema = false;
        if (value)
        {
            RefreshSchema();
            // After this the DataTable has all columns, they are all present in the proporty window of the designer.
            // So I hoped that this code below would tell the designer to serialize the DataTable ,but it does not
            this.GetChangeService().OnComponentChanged(this, null, null, null);
        }
    }
}

public void RefreshSchema()
{
    if (DataBase != null && SelectText != "")
    {
        using (DataTable tempTable = new DataTable())
        {
            // THE Code below fetches the table's schema from the database and returns them as columns in `tempTable`
            DataBase.FillDataTable(tempTable, Concat("SET FMTONLY ON", Environment.NewLine, SelectText, Environment.NewLine + "SET FMTONLY OFF"));
        }

        // This loop then create's a column in the DataTable property for
        // every column find in tempTable
        foreach (DataColumn col in tempTable.Columns)
        {
            // I would really like these columns to get serialized in
            // designer.cs
            _Table.Columns.Add(col.ColumnName, col.DataType);
        }
    }
}

// I added own serialization code, because I hoped that this would solve my issue, but it does not

private IComponentChangeService GetChangeService()
{
    return (IComponentChangeService)GetService(typeof(IComponentChangeService));
}

// Implement this method to serialize data. The method is called
// on serialization.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
    // Use the AddValue method to specify serialized values.
    info.AddValue("DataBase", DataBase, typeof(gttDataBase));
    info.AddValue("SelectText", SelectText, typeof(string));
    info.AddValue("Table", Table, typeof(DataTable));
}

// The special constructor is used to deserialize values.
public gttDataTable(SerializationInfo info, StreamingContext context)
{
    // Reset the property value using the GetValue method.
    DataBase = (gttDataBase)info.GetValue("DataBase", typeof(gttDataBase));
    SelectText = (string)info.GetValue("SelectText", typeof(string));
    Table = (DataTable)info.GetValue("Table", typeof(DataTable));
}

EDIT
I tried adding
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]

to the DataTable property as suggested in a comment, but it did not help
EDIT 2
if I add a column manually to the property Table and then change something in one it's properties, this column gets serialized and is persistent.
But all the other columns that are added in code are not.
Is there a way to also serialize them ?
EDIT 3
for clarity, the idea is to serialize the columns of the DataTable property in designtime into the Designer.cs file.
Not at runtime


text:
Q: Python Flask SocketIO Multiprocessing different Class Functions I am new to Flask and was wondering if we could run different processes belonging to different classes running in parallel to Flask app. My code structure is very similar to this:
from flask import Flask, render_template, flash, request, jsonify
from flask_socketio import SocketIO, emit
from flask_wtf import FlaskForm
from wtforms import *
import multiprocessing as mp
import os
import serial
import time, datetime

# App config.
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

class serial_read_Process():

    def __init__(self):
        self.delay = 0.2
        self.port = serial.Serial ( port='/dev/ttyTHS2', baudrate=115200,
                                    parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
                                    bytesize=serial.EIGHTBITS, timeout=1)

    def serial_read (self):
        # read UART and process the incoming serial data and send it to webpage
        currtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        socketio.emit('values', {'data1':data1, 'currtime':currtime}, namespace='/serial')
        time.sleep(self.delay)

class ProcessWebPageData():

    def __init__(self, name):
        self.person_name = name
        self.delay = 0.2

    def process_data(self):
        # process the data received from the webpage
        time.sleep(self.delay)

@socketio.on('my_event', namespace='/test')
def test_message(message):
    name_val= message.get('name')
    ProcessDataObj = ProcessWebPageData()
    process2 = mp.Process(target=ProcessDataObj.process_data, args=(name_val,)) # For Processing the data received from the web page
    if not process2.is_alive():
        thread2.daemon = True
        thread2.start()

@app.route("/", methods=['GET', 'POST'])
def load():
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    print('Client connected')
    uart_read = serial_read_Thread()
    process1 = mp.Process(target=uart_read.serial_read) # For Reading UART values
    process1.daemon = True
    if not process1.is_alive():
        process1.start()
        print("process started")

if __name__== "__main__":
    socketio.run(app)

I am continuously getting the values from UART when I print those in serial_read function I see them being printed. I do not see them on the web page which I send via socketio.emit(). I have  a Javascript code where I receive the values and use it to display on HTML webpage. Also is this the correct way to do?  Any inputs would be appreciated. TIA.


text:
Q: Override Dependency Injection per request I have two Net Core API Controllers: RealController and MockController, I want to inject differents services in the application based on which controller accept the request.
Example ,  if the request was accepted by the RealController I want to inject the RealSharedService (scoped) in all classes that it's needed, but if the request was accepted by MockController I want to inject the MockSharedService instead.
public class RealController : ControllerBase
{
    public RealController(...)
    {
        //I could do somethig here to change the ISharedService intance to RealSharedService
    }
}

public class MockController : ControllerBase
{
    public MockController(...)
    {
        //I could do somethig here to change the ISharedService intance to MockSharedService
    }
}

public class Service1
{
    public Service1(ISharedService sharedService)
    {
        //The ISharedService instance must be RealSharedService or MockSharedService based on
        // the request, if it was accepted by RealController or MockController
    }
}

public class RealSharedService : ISharedService
{
    ....
}
public class MockSharedService : ISharedService
{
    ....
}

A: You could use HttpContextAccessor to conditionally resolve your service:
services.AddHttpContextAccessor();

services.AddScoped<ISharedService>(sp => {
   var httpContext = sp.GetService<IHttpContextAccessor>().HttpContext;
   Endpoint endpoint = httpContext.Features.Get<IEndpointFeature>()?.Endpoint;
   if (endpoint.DisplayName.Contains("MockController"))
   {
      return new MockService();
   }
   else
   {
      return new RealService();
   }
});