text:
Q: Queries on large database kill connection to the server, works with LIMIT I'm trying to run queries on a large-ish database without killing the connection to the server.
I'm using Postgres 12.1 on a mac with 16gb of memory, and about 40gb of free disk. The database is 78gb according to pg_database_size with the largest table being 20gb according do pg_total_relation_size.
The error I get (from the log), regardless of which non-working query I run, is:
server process (PID xxx) was terminated by signal 9: Killed: 9

In VS code the error is "lost connection to server".
Two examples that don't work are:
UPDATE table
SET column = NULL
WHERE column = 0;

select columnA
from table1
where columnA NOT IN (
select columnB
from table2
);

I can run some of the queries (the above one, for example) by adding a LIMIT of, say, 1,000,000.
I suspected that I was running out of disk due to temp files, but in the log (with log_temp_files = 0), I can't see any temp files being written.
I tried increasing and decreasing work_mem, maintenance_work_mem, shared_buffers, and temp_buffers. None worked, the performance was about the same.
I tried dropping all indexes, which brought down the "cost" on some of the queries, but they still killed the connection to the server.
What could be my problem and how can I troubleshoot this further?
Additionally, I read that temp files from timed-out queries are stored in pqsql_tmp. I checked the folder, and it does not have files of significant size. Could the temp files be stored somewhere else?

The posgtres log for running a failed query looks like:
2020-02-17 09:31:08.626 CET [94908] LOG:  server process (PID xxx) was terminated by signal 9: Killed: 9
2020-02-17 09:31:08.626 CET [94908] DETAIL:  Failed process was running: update table
        set columnname = NULL
        where columnname = 0;

2020-02-17 09:31:08.626 CET [94908] LOG:  terminating any other active server processes
2020-02-17 09:31:08.626 CET [94919] WARNING:  terminating connection because of crash of another server process
2020-02-17 09:31:08.626 CET [94919] DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exi$
2020-02-17 09:31:08.626 CET [94919] HINT:  In a moment you should be able to reconnect to the database and repeat your command.
2020-02-17 09:31:08.626 CET [94914] WARNING:  terminating connection because of crash of another server process
2020-02-17 09:31:08.626 CET [94914] DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exi$
2020-02-17 09:31:08.626 CET [94914] HINT:  In a moment you should be able to reconnect to the database and repeat your command.
2020-02-17 09:31:08.629 CET [94908] LOG:  all server processes terminated; reinitializing
2020-02-17 09:31:08.698 CET [94927] LOG:  database system was interrupted; last known up at 2020-02-17 09:30:57 CET
2020-02-17 09:31:08.901 CET [94927] LOG:  database system was not properly shut down; automatic recovery in progress
2020-02-17 09:31:08.906 CET [94927] LOG:  invalid record length at 17/894C438: wanted 24, got 0
2020-02-17 09:31:08.906 CET [94927] LOG:  redo is not required

Running EXPLAIN on the second example query returns:
Seq Scan on gas_prices_all p  (cost=459.93..5635583.33 rows=128975016 width=16)
  Filter: (NOT (hashed SubPlan 1))
  SubPlan 1
    ->  Seq Scan on gas_station g  (cost=0.00..423.14 rows=14714 width=16)
JIT:
  Functions: 13
  Options: Inlining true, Optimization true, Expressions true, Deforming true

FWIW I get the same error for queries with "cost" around zero.

Update: I found a crash report from earlier today:
Process:               postgres [41042]
Path:                  /Users/USER/*/postgres
Identifier:            postgres
Version:               0
Code Type:             X86-64 (Native)
Parent Process:        postgres [40107]
Responsible:           postgres [41042]
User ID:               502

Date/Time:             2020-02-18 11:16:26.210 +0100
OS Version:            Mac OS X 10.14.5 (18F132)
Report Version:        12
Anonymous UUID:        F41CCD21-C558-6CB0-316D-D1FF3E279576

Sleep/Wake UUID:       5F08EAEC-373A-4D19-A243-E812E68D2697

Time Awake Since Boot: 1600000 seconds
Time Since Wake:       5700 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (Code Signature Invalid)
Exception Codes:       0x0000000000000032, 0x00000001044c4060
Exception Note:        EXC_CORPSE_NOTIFY

Termination Reason:    Namespace CODESIGNING, Code 0x2

kernel messages:

VM Regions Near 0x1044c4060:
    __LINKEDIT             0000000104466000-00000001044c4000 [  376K] r--/rw- SM=COW  /Users/USER/*/*.dylib
--> VM_ALLOCATE            00000001044c4000-00000001044c5000 [    4K] r-x/rwx SM=ZER
    VM_ALLOCATE            00000001044c5000-00000001044c6000 [    4K] rw-/rwx SM=ZER

Application Specific Information:
crashed on child side of fork pre-exec

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   ???                             0x00000001044c4060 0 + 4367073376
1   postgres                        0x0000000103798851 ExecAgg + 1185 (executor.h:308)
2   postgres                        0x0000000103785d0f standard_ExecutorRun + 287 (execMain.c:1652)
3   postgres                        0x0000000103789c4e ParallelQueryMain + 670 (execParallel.c:1405)
4   postgres                        0x00000001036520ce ParallelWorkerMain + 1054 (parallel.c:1434)
5   postgres                        0x000000010385bec5 StartBackgroundWorker + 533 (bgworker.c:834)
6   postgres                        0x000000010386acb9 maybe_start_bgworkers + 1161
7   postgres                        0x00000001038696c5 sigusr1_handler + 357 (postmaster.c:5167)
8   libsystem_platform.dylib        0x00007fff76195b5d _sigtramp + 29
9   ???                             0x0000000000003200 0 + 12800
10  postgres                        0x00000001037d54ae main + 1678
11  libdyld.dylib                   0x00007fff75faa3d5 start + 1

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x00000001044c4060  rbx: 0x00007f98b9045600  rcx: 0x00000001072c48d8  rdx: 0x00007ffeec6242f4
  rdi: 0x00007f98b9047520  rsi: 0x00007f98b9045fc0  rbp: 0x00007ffeec624320  rsp: 0x00007ffeec624288
   r8: 0x00000000014bafca   r9: 0xffffffff00000000  r10: 0x00000001072c48d0  r11: 0x0000000000000005
  r12: 0x0000000103c51220  r13: 0x00007f98b9047510  r14: 0x00007f98b9045fc0  r15: 0x00007f98b90459a0
  rip: 0x00000001044c4060  rfl: 0x0000000000010246  cr2: 0x00000001044c4060

Logical CPU:     0
Error Code:      0x00000015
Trap Number:     14

Binary Images:
      **lots of stuff**

External Modification Summary:
  Calls made by other processes targeting this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by all processes on this machine:
    task_for_pid: 134420121
    thread_create: 0
    thread_set_state: 0

VM Region Summary:
ReadOnly portion of Libraries: Total=398.8M resident=0K(0%) swapped_out_or_unallocated=398.8M(100%)
Writable regions: Total=4.2G written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=4.2G(100%)

                                VIRTUAL   REGION
REGION TYPE                        SIZE    COUNT (non-coalesced)
===========                     =======  =======
Kernel Alloc Once                    8K        1
MALLOC                            81.0M       19
MALLOC guard page                   16K        3
MALLOC_LARGE (reserved)             72K        2         reserved VM address space (unallocated)
STACK GUARD                       56.0M        1
Stack                             8192K        1
VM_ALLOCATE                        4.1G        4
__DATA                            18.0M      200
__FONT_DATA                          4K        1
__LINKEDIT                       232.2M       11
__TEXT                           166.6M      199
__UNICODE                          564K        1
mapped file                         64K        1
shared memory                      552K        6
===========                     =======  =======
TOTAL                              4.7G      450
TOTAL, minus reserved VM space     4.7G      450

I can find two maybe-interesting things in the log:
2020-02-18 19:01:52.044375+0100  localhost kernel[0]: CODE SIGNING: process 51528[postgres]: rejecting invalid page at address 0x1100c1000 from offset 0x0 in file "<nil>" (cs_mtime:0.0 == mtime:0.0) (signed:0 validated:0 tainted:0 nx:0 wpmapped:1 dirty:0 depth:0)
2020-02-18 19:01:52.044805+0100  localhost ReportCrash[52560]: unknown nested kcdata type: 0x1004, size: 2108

2020-02-18 19:01:55.268060+0100  localhost ReportCrash[52560]: (CrashReporterSupport) Saved crash report for postgres[51528] version 0 to postgres_2020-02-18-190155_MacBook-Pro.crash
2020-02-18 19:01:55.273159+0100  localhost ReportCrash[52560]: (CrashReporterSupport) Removing excessive log: postgres_2020-02-18-190155_MacBook-Pro.crash
2020-02-18 19:01:55.274208+0100  localhost ReportCrash[52560]: shouldDisplayUnexpectedlyQuitNotification is NO

UPDATE: I ran the second exaple query (above) with LIMIT until it went from working (LIMIT of 2,200,000) to killing the connection to the server (LIMIT of 2,300,000). EXPLAIN ANALYZE on the LIMIT 2,200,000 query is:
Limit  (cost=459.93..96581.42 rows=2200000 width=16) (actual time=13.228..38573.440 rows=2200000 loops=1)
  ->  Seq Scan table1  (cost=459.93..5635583.33 rows=128975016 width=16) (actual time=13.227..38374.070 rows=2200000 loops=1)
        Filter: (NOT (hashed SubPlan 1))
        Rows Removed by Filter: 139729529
        SubPlan 1
          ->  Seq Scan on table2  (cost=0.00..423.14 rows=14714 width=16) (actual time=0.350..6.925 rows=14714 loops=1)
Planning Time: 0.138 ms
Execution Time: 38685.762 ms

EXPLAIN on the LIMIT 2,300,000 is: (EXPLAIN ANALYZE crashed here)
Limit  (cost=459.93..100950.58 rows=2300000 width=16)
  ->  Seq Scan on table1  (cost=459.93..5635583.33 rows=128975016 width=16)
        Filter: (NOT (hashed SubPlan 1))
        SubPlan 1
          ->  Seq Scan on table2  (cost=0.00..423.14 rows=14714 width=16)
JIT:
  Functions: 14
  Options: Inlining false, Optimization false, Expressions true, Deforming true

I'm reading this as JIT kicking in here, which makes sense given jit_above_cost is set (default) to 100,000. So perhaps the problem is with the JIT somehow?

UPDATE 2: With jit=off the second example query works and is also ca. twice as fast. How can that be and what could cause JIT to be a problem on my system?

A: "signal 9" indicates this is almost certainly the Out Of Memory killer.  You could look in /var/log/kern.log or whatever it is called on your system to verify. Running out of disk space on temp files would not result in this error.
You should do an EXPLAIN on the query to see what plan it is using.  I would usually guess it was a deranged HashAgg, except your first query should not be doing any aggregation, Hash or otherwise.
You could also try turning off overcommit. That way your processes would get ordinary out of memory errors which they could then report in a orderly fashion, rather than just getting nuked from orbit with no chance to report the problem.  There are instructions for Linux, maybe you can adapt them for MacOS.  If you can catch the process once memory usage has started growing a lot, but before it is killed, you can get a report of where the memory is being allocated.

A: Thanks for all your suggestions and comments.
I've played around with it for long enough to conclude that disabling JIT (jit = off) solved the problem.
I can see that JIT was only introduced in PostgreSQL 11, which is probably why there isn't much online about the issues it can cause.


text:
Q: Can't access Linux machine from the network, network from the machine is fine I'm having issues with a machine that stopped replicating with mysql.
It's managed by a guy on another continent but recently I've had to get involved.
The server is running Ubuntu server 9.10
I can't log in with SSH, there is no response.  On the server itself I can ssh to localhost fine.
I thought maybe it's the firewall rules.  I'm no expert on IP Tables, but I believe that's not the issue as I removed all the rules.  But it still won't let me in.
Any ideas?  it's acting from other machines as though the service isn't listening, but I know that it is.  It's like this for all services.

A: Is the default gateway set correctly on the server?

A: Try ssh on the local box to it's LAN IP as localhost most likely was 127.0.0.1.
Just in case sshd is configured to only listen on 127.0.0.1 for some reason.
You can check /etc/ssh/sshd_config for the ListenAddress setting to confirm.  It should either be commented out, 0.0.0.0 or the actual IP you want it to listen on.

A: You should run through the standard networking debugging steps
1. Do I have an ip address (ifconfig)
2. Can I ping my Gateway (ping x.x.x.x where x.x.x.x is the gateway)
3. is my service running and listening on a port accessable to the world(netstat -lnp | grep ssh )
4. is my firewall blocking this port (iptables -L)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows Phone Search box Tags on tapping search results Is there any library available for Windows Phone with the tags in a search box feature? So if I start typing age, the search box should predict agent and agent smith etc and on tapping the predicted results, the search box gets filled with the tags (example image attached). Handling events like, backkeypress highlights the tag and another backkeypress removes the tag etc. Predicting results is easy, what I am looking for is all the events handling for search box with tags. Any free/paid library for the same?

A: There are a few AutoCompleteBoxes (Telerik, Windows Phone Toolkit), but the just work for one item. If you want more items, you need to create the control by yourself.

A: A lot of third party controls are available but you should prefer to write your own control. I used http://wpfactb.codeplex.com/releases/view/42340 control but you have to customized it and bugs are there to be fixed .
So I will suggest you to get hint from this and write your own control.

A: For something as specialized as this, I would write it myself. And XAML suits really well for such tasks.
One horizontal stackpanel with custom styled buttons being added, and one LongListSelector for the results.

A: This is very simple to implement.

*

*Set the InputScope in your textbox.

*On typing , you will get the possible result.

*When you tap on the respective suggestion, you will get the value.

*Create a Grid or Stackpanel and create a ellipse which should hold the tag value.

*On tap of the value, add the value inside the created ellipse.


text:
Q: derivative of a function as the limit of derivatives I am trying to figure out a proof of this using the fundamental theorem of calculus. Is is:
Supoose $\lbrace f_n \rbrace$ is a sequence of differentiable function on $[a,b]$. If  $\lbrace f_n' \rbrace$ converges uniformly on $[a,b]$ and $\lbrace f_n(x_0) \rbrace$ converges for some $x_0 \in [a,b]$,  then $\lbrace f_n \rbrace$ converges uniformly to a function $f$ on $[a,b]$, with $f'(x)= \lim_{n \rightarrow \infty} f'_n(x)$.
I am just confused at this point... What  I am most confused on is how to show that $f_n$ converges uniformly.
What I have is this:
By FTC, we have $f_n(x)=f_n(x_0)+ \int_{x_0}^{x}f'_n(x)dx$ and taking the limit, by a previous theorem, we have $\lim {f_n(x)}= \lim({f_n(x_0)+ \int_{x_0}^{x}f'_n(x)dx)}=L+\int_{x_0}^{x}g(x)dx$ for some $L \in \mathbb{R}, g$. But how does this show that $f_n$ converges uniformly??

A: Hint: For any $x\in [a,b]$, one has
$$
f_n(x)=f_n(x_0)+\int_{x_0}^xf'_n(x)dx.
$$
Solution: Fix $x\in[a,b]$ and define $y_n=\int_{x_0}^xf'_n(x)dx$. Now note that
$$|y_n-y_m|\le\int_{x_0}^x|f'_n(x)-f'_m(x)|dx\le (b-a) \sup_{x\in [a,b]}|f'_n(x)-f'_m(x)|.$$
As $f'_n$ converges uniformly to some function $g$, sequence $\{y_n\}_n$ is a Cauchy sequence and converges to some value $y(x)$ such that
$$|y_n-y(x)|\le (b-a) \sup_{x\in [a,b]}|f'_n(x)-g(x)|.$$
Thus, differentiable functions $f_n$ converges uniformly to the function $y(x)$. Thus $y(x)$ is a differentiable function and from Weierstrass, one has $f'_n$ converges uniformly to $y'(x)$. Due to uniqueness of limit, it yields that $y'(x)=g(x)$. (here $y\equiv f$)

A: Hint: Use the fundamental theorem of calculus
$$f(x)-f(x_0)=\int_{x_0}^x f'(t)dt$$


text:
Q: series converges or diverges
Determine whether the series
  $$ \frac{1}{1^2}+\frac{1}{2^3}+\frac{1}{3^2} + \frac{1}{4^3} + \cdots$$
  converges or diverges.

Can I write this as $ \sum_{n=0}^{\infty} \frac{1}{(2n+1)^2} + \sum_{n=1}^{\infty} \frac{1}{(2n)^3}$ or is there another/better way of solving this?

A: You want $\sum\limits_{i=n}^\infty a_n$ with $0\leq a_n\leq \frac{1}{n^2}$. Since $\sum\limits_{i=1}^\infty \frac{1}{n^2}<\infty$ your sum also converges.


text:
Q: Same instance referred to by multiple constructors I have an instance of Class A that I want to refer to in the constructor of multiple instances of B. How can I refer to that particular instance of Class A in each new instance of B?

A: If you only ever want to have one instance of class A, use a Singleton Pattern.  You can then have class B's constructor refer to the singleton.  Otherwise, the best way to refer to an object of class A in the constructor of class B is to pass it as an argument.


text:
Q: Winforms ComboBox Height different to ItemHeight I am using a ComboBox in Text and DropDown mode (the default) and I want to have an ItemHeight of X (e.g. 40) but have the ComboBox's Height set to Y (e.g. 20).
The reason for this is that I am intending to use the ComboBox for a Quick Search feature in which the user keys in text and detailed results are rendered in the list items. Only one line of input is required.
Unfortunately, Winforms automatically locks the ComboBox's Height to the ItemHeight and I can see no way to change this.
How can I make the ComboBox's Height differ to the ItemHeight?

A: What you have to do is, first of all, change DrawMode from Normal to OwnerDrawVariable. Then you've got to handle 2 events: DrawItem and MeasureItem . They would be something like:
    private void comboBox1_MeasureItem(object sender, MeasureItemEventArgs e)
    {
        e.ItemHeight = 40; //Change this to your desired item height
    }

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        ComboBox box = sender as ComboBox;

        if (Object.ReferenceEquals(null, box))
            return;

        e.DrawBackground();

        if (e.Index >= 0)
        {
            Graphics g = e.Graphics;

            using (Brush brush = ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                                  ? new SolidBrush(SystemColors.Highlight)
                                  : new SolidBrush(e.BackColor))
            {
                using (Brush textBrush = new SolidBrush(e.ForeColor))
                {
                    g.FillRectangle(brush, e.Bounds);

                    g.DrawString(box.Items[e.Index].ToString(),
                                 e.Font,
                                 textBrush,
                                 e.Bounds,
                                 StringFormat.GenericDefault);
                }
            }
        }

        e.DrawFocusRectangle();
    }


text:
Q: how to push a video list to rtmp server and keep connect Current methods
ffmpeg -re -i 1.mp4 -f flv "rtmp://example.com/live"
ffmpeg -re -i 2.mp4 -f flv "rtmp://example.com/live"
ffmpeg -re -i 3.mp4 -f flv "rtmp://example.com/live"
...

but 1.mp4 push done later , client and server will be disconnected.
i hope keep connect.

A: Try concat demuxer.
Create a list (myfiles.txt):
file '1.mp4'
file '2.mp4'
file '3.mp4'
...

Then
ffmpeg -f concat -i myfiles.txt -f flv "rtmp://example.com/live"


text:
Q: How to get back the Original document back after aggregation I have a case where I want to query a collection of documents that have a number of items under a array field "forms". The problem to solve was wanting to return only the documents that have all of the documents contained in "forms" with a particular status of "closed".
So here is a sample of two different documents in the collection:
{
    "_id" : "Tvq444454j",
    "name" : "Jim",
    "forms" : [
        {
            "name" : "Jorney",
            "status" : "closed"
        },
        {
            "name" : "Women",
            "status" : "void"
        },
        {
            "name" : "Child",
            "status" : "closed"
        },
        {
            "name" : "Farm",
            "status" : "closed"
        }
    ]
},

{
    "_id" : "Tvq579754r",
    "name" : "Tom",
    "forms" : [
        {
            "name" : "PreOp",
            "status" : "closed"
        },
        {
            "name" : "Alert",
            "status" : "closed"
        },
        {
            "name" : "City",
            "status" : "closed"
        },
        {
            "name" : "Country",
            "status" : "closed"
        }
    ]
}

And the expected result:
{
    "_id" : "Tvq579754r",
    "name" : "Tom",
    "forms" : [
        {
            "name" : "PreOp",
            "status" : "closed"
        },
        {
            "name" : "Alert",
            "status" : "closed"
        },
        {
            "name" : "City",
            "status" : "closed"
        },
        {
            "name" : "Country",
            "status" : "closed"
        }
    ]
}

As there is no standard query operator to match all of the elements of the array under this condition, the solution was found by using aggregation. This would return the _id of the documents in the collection that have all of their "forms" elements set to the status of "closed".
db.forms.aggregate([
    {$unwind: "$forms" },
    {$group: { _id: "$_id", status: {$addToSet: "$forms.status" }}},
    {$unwind: "$status"},
    {$sort: { _id: 1, status: -1 }},
    {$group: {_id: "$_id", status: {$first: "$status"}}},
    {$match:{ status: "closed" }}
])

So as I would be expecting to return many documents in the results, I would like to avoid issuing another find, or series of finds just to get the documents that match the returned _id's.
Considering this, is there any way that I can get the original documents back from aggregation in exactly the same form as they are in the collection, while still doing this type of filtering?

A: Falling under the category of stupid aggregation tricks is a little technique that often gets overlooked.
The query doing all of it's grouping around the document _id, being the unique identifier for this document. So the main point to think of is the whole document is actually a unique identifier already. So instead of just stashing in the _id key, use the whole document.
    {$project: {
        _id: { _id: "$_id", name: "$name", forms: "$forms" }, forms: "$forms"}
    },

Where this is done anything that is rolled up by the _id retains the document in it's original form. At the end of all other aggregation stages, issue a final $project in order to restore the true original document form:
    {$project: { _id: "$_id._id", name: "$_id.name", forms: "$_id.forms"}}

Then you will have the filtered results that you want. This technique can be very handy when used with advanced filtering such as in the case of this query, as it removes the need to issue an additional find on all of the results.
Also, in such a case where you know you are only looking for a set of results that are going to match a certain set of conditions, use a $match operator as the first stage of the aggregation pipeline. This is not only useful in reducing the working set size, but it is also the only stage at which you can make use of an index and where you can significantly increase query performance.
The whole process together:
db.forms.aggregate([
    {$match: { "forms.status": "closed" } },
    {$project: {
        _id: { _id: "$_id", name: "$name", forms: "$forms" }, forms: "$forms"}
    },
    {$unwind: "$forms"},
    {$group: { _id: "$_id", status: {$addToSet: "$forms.status"}}},
    {$unwind: "$status"},
    {$sort: { _id: 1, status: -1} },
    {$group: { _id: "$_id", status: {$first: "$status"} }},
    {$match: { status: "closed"}},
    {$project: { _id: "$_id._id", name: "$_id.name", forms: "$_id.forms"}}
])

A: You can simply use find for this:
db.collection.find({
  forms: {$not: {$elemMatch: {status: "void"}}}
})

Playground example


text:
Q: Form.submit is not found in Javascript Code
html
<form id="myFrm" name="myFrm" action="/myApp/ProcessFrm" method="post">
    <input autofocus="autofocus" type="text" id="Location" name="Location" onkeydown="changetotab()" style="width: 4em" tabindex="1"  />
    <input type="Submit" value="Submit" id="submit" /> <br />
</form>

js
 function changetotab() {
            var charCode = (window.event.which) ? window.event.which : window.event.keyCode;

            if (charCode == 13 || charCode == 9) {
                if (document.myFrm.submit == undefined) {
                    alert("form submit can't be found")
                } else {
                    alert("form can be submitted");
                   document.myFrm.submit();
                }
            }
        }

What happens is that when the user pressed TAB or ENTER, document.myFrm.submit == undefined comes up false (so far so good); then something weird happens - when I get to document.myFrm.submit(); JS informs that this method is not found.

0x80020003 - JavaScript runtime error: Member not found.

What is happening here?
Note: I can't use Jquery, just in case you were wondering why I am using old style JS. This will run on the old devices that do not support Jquery.

A: See this JSfiddle. What's going on here? Well, in the pre-DOM times, JavaScript created one property foo for each input with name foo on the input's parent form:
form.foo.toString() === "HTMLInputElement";

This however, means, that, if you have an input element with name submit, the form's own submit method is overwritten. This behaviour has survived till today.
Now, your input has no name attribute. In this case, the behaviour is to deduce one from the input's ID, if one is set. So basically, change the ID of the input, that's the most straight-forward way to deal with it:
<input type="Submit" value="Submit" id="submit_" />

There are lots of such subtleties, unfortunately. See DOMLint for a good overview.
Edit: What to do, if you end up with a clobbered submit method and no way to change the HTML? Then fetch the submit method from the form's prototype and use that:
// form.submit() doesn't work, but this will:
HTMLFormElement.prototype.submit.call(form);

A: Try this (plain javascript):
document.getElementById('myFrm')


text:
Q: Difference between java doc and Android doc in method documents Some times I see problematic differences between Java doc and Android doc in about method documents.For example in about setReadable (boolean readable, boolean ownerOnly) method you can see java doc says that:

Throws: SecurityException - If a security manager exists and its
  SecurityManager.checkWrite(java.lang.String) method denies write
  access to the file

But Android docs does not say any thing about throwing exception.Also we know that Docs say:

Any Exception that can be thrown by a method is part of the method's
  public programming interface. Those who call a method must know about
  the exceptions that a method can throw so that they can decide what to
  do about them.

So when we do not see any throw condition in Android documents of a method,

*

*Does it mean method will not throw exception any way?Or it may be forgotten?

*Do we need to check documents for any simple method for probability difference between Java and Android?Is it possible?

A: As you may already know,exceptions may occur in your code at run time, due to the closure of the code. Simply put, you may be using a method safely and correctly, but that specific block of code that's surrounding it, may be vulnerable to some exceptions and conditions. Also android docs may suffer from poor references for native java libraries and apis.Because they assume that you are an experienced java developer and are familiar with using javadocs.

A: If you go to the declaration of setReadable(bool,bool) you'll see that the exception is caught and false is returned instead. So in this case the Android documentation supersedes the Javadoc.


text:
Q: Probability of choosing like partners If there are $x$ (where $x$ is even) people in an office and each person calls out name what is the probability that every worker calls the name of the worker that calls him.
Thanks.

A: $(x-1)\times(x-3)\times(x-5)\times...\times3\times1$ distinct pairs of people.
In each one of these pair instances, each specific pair call
one another's name by the probability of
$\frac {1}{(x-1)^x}$ assuming no one calls his own name.
$\frac{(x-1)\times(x-3)\times(x-5)\times...\times3\times1}{(x-1)^x}$
EDIT: adding some explanations.
$x$ people ($x$ is even) forming $(x-1)\times(x-3)\times(x-5)\times...\times3\times1$ distinct pairs:
In these pairs, any one of the $x$ people could have paired with $(x-1)$ others. An arbitrary other among those remaining can appear in this set of pairs with $(x-3)$ of the remaining persons and so forth.
Assuming each can call one another's name with equal probability, a person can call out anyone of the $(x-1)$ names except his own. The probability of each person calling
the name of the person he paired up
with is $1/(x-1)$. Each one of the $x$ people calling out the "right" names in a set of pairs is $1/(x-1)^x$. Multiply this by the number of such pair instances.


text:
Q: How to read from pubsub source in parallel using dataflow I am very new to dataflow, I am looking to build pipeline which will use pubsub as source.
I have worked on streaming pipeline which has flink as streaming engine and kafka as source, in that we can set parallelism in flink to read messages from kafka so that message processing can happen in parallel instead of sequential.
I am wondering if same can be possible in pubsub->dataflow, or it will only read message in sequential order.

A: Take a look at the PubSubToBigQuery pipeline. This uses PubSub as a source, this will read data in parallel. Multiple threads will be each reading a message off of pubsub and handing it off to downstream transforms for processing, by default.
Please note that the PubSubToBQ pipeline can also be run as a template pipeline, which works well for many users. Just launch the pipeline from the Template UI and set the appropriate parameters to point to your pub sub and BQ locations. Some users prefer to use it that way. But this depends on where you want to store your data.


text:
Q: 74HC688 magnitude comparator and enable pin I'm using a 74HC688 8-bit magnitude comparator (datasheet) with Arduino. My question is how to generate active LOW E (enable) signal with Arduino? Is there another possibility (I want to enable the 688 chip)? Currently, I have the enable pin connected to ground. Is that the correct solution or do I need a resistor between enable and ground?

A: If you want the 74HC688 permanently enabled, you should connect the enable pin directly to ground.  If you want the Arduino to control the enable pin, connect the enable pin directly to an Aduino output pin.


text:
Q: group rows based on partial strings from two columns and sum values df = pd.DataFrame({'c1':['Ax','Ay','Bx','By'], 'c2':['Ay','Ax','By','Bx'], 'c3':[1,2,3,4]})

   c1  c2  c3
0  Ax  Ay   1
1  Ay  Ax   2
2  Bx  By   3
3  By  Bx   4

I'd like to sum the c3 values by aggregating the same xy combinations from the c1 and c2 columns.
The expected output is
  c1  c2  c3
0  x   y   4   #[Ax Ay] + [Bx By]
1  y   x   6   #[Ay Ax] + [By Bx]

A: You can select values in c1 and c2 without first letters and aggregate sum:
df = df.groupby([df.c1.str[1:], df.c2.str[1:]]).sum().reset_index()
print (df)
  c1 c2  c3
0  x  y   4
1  y  x   6


text:
Q: Determining Azure SQL Database requirements I'm looking into moving an SQL Server database project to the cloud using Azure SQL Database. I'm just wondering what metrics I can use from SQL Server to help determine what my needs will be on Azure.
The size of the database is around 150GB, so I understand what my needs are in terms of storage, I'm just not sure what metrics I can use to translate my database usage to the DTU benchmark metrics that the various service tiers on Azure SQL use.

A: Some good links from Microsoft to help translate DTU to actual metrics:
http://msdn.microsoft.com/en-us/library/azure/dn741336.aspx
http://msdn.microsoft.com/en-us/library/azure/dn741336.aspx
Short version, look at a combination of concurrent user sessions, and the number of transactions over a unit of time.
Take a look at the perfmon counters:
SQL Server/SQL Statistics/Batch Requests/sec
...to get an idea of number of transactions
and
SQL Server/General Statistics/User Connections
...to get an idea of user sessions.

A: Dbwatch have just created a repport where we run various benchmarks on Azure SQL databses in various datasenters around the globe.
Our tests indicate a performance difference of up to 500% between locations.
The report can be found here:
http://dbwatch.com/azure
We also provide our tool for free for a small number of database instances if you would like to compare the performance of different mashines while considering to migrate.


text:
Q: How Can I Use The Value Of A Variable In One Class To Another? I've defined a variable withdraw in class Account. It performs the withdrawl function just fine that's defined inside the Account class. However, I wish to access the value of withdraw variable inside the interest function present in the Sav_acct class. It's taking the value of withdraw as 0. How can I use the value of withdraw from the withdrawl function inside the  interest function so I can perform the right mathematical operation?
public class Account {
    String customer_name;
    int account_number;
    String type_account;
    int balance = 2500;
    double deposit;

    public static double withdraw;

    void deposit() {
        Scanner sc = new Scanner(System.in);
        System.out.println("how much do you want to deposit?");
        int amo = sc.nextInt();
        deposit = balance + amo;

        System.out.println("Your current balance is " + balance);
    }

    void withdrawl() {
        Scanner sc = new Scanner(System.in);
        System.out.println("how much do you want to withdraw?");
        int amo = sc.nextInt();
        withdraw = balance - amo;
        if (withdraw < 0) {
            System.out.println("Your balance is insufficient");
        }
        else {
            System.out.println("Your current balance is " + withdraw);
        }
    }
}

class Curr_acct extends Account {

    @SuppressWarnings("empty-statement")
    void penalty() {
        double Service_charge = withdraw - 100;
        double falling = Service_charge;

        System.out.println("You've been charged" + " 100" + " due to low balance");
        System.out.println("Your current amount is " + falling);
    }
}

class Sav_acct extends Account {
    void interest() {
        double interest;
        interest = (1 % 100) * withdraw;
        double total_amount = interest + withdraw;
        System.out.println("Your new balance with interest is " + total_amount);
    }
}

class publish {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your name");
        String n = sc.nextLine();
        System.out.println("Enter your account type: Savings Account or Current Account");
        String t = sc.nextLine();
        if ("Savings Account".equals(t)) {
            System.out.println("Do you want to deposit or withdraw amount?");
            String d = sc.nextLine();
            if ("deposit".equals(d)) {
                Account de = new Account();
                de.deposit();
            }
            else if ("withdraw".equals(d)) {
                Account wi = new Account();
                wi.withdrawl();
                Sav_acct in = new Sav_acct();
                in.interest();
            }
        }
        else if ("Current Account".equals(t)) {
            System.out.println("Do you want to deposit or withdraw amount?");
            String d = sc.nextLine();
            if ("deposit".equals(d)) {
                Account de = new Account();
                de.deposit();
            }
            else if ("withdraw".equals(d)) {
                Account wi = new Account();
                wi.withdrawl();
                if (withdraw < 2000) {
                    Curr_acct pe = new Curr_acct();
                    pe.penalty();
                }
                else {

                }
            }
        }
        else {
            System.out.println("please enter the correct account type as per the options provided on the screen");
        }
    }
}

EDIT : Modified the code.But interest is still 0.
import java.util.Scanner;

class Account {

    String customer_name;
    int account_number;
    String type_account;
    int balance = 2500;
    double deposit;

    double withdraw;

    void deposit() {
        Scanner sc = new Scanner(System.in);
        System.out.println("how much do you want to deposit?");
        int amo = sc.nextInt();
        deposit = balance + amo;

        System.out.println("Your current balance is " + deposit);
    }

    void withdrawl() {

        Scanner sc = new Scanner(System.in);

        System.out.println("how much do you want to withdraw?");

        int amo = sc.nextInt();

        withdraw = balance - amo;

    }

}

class Curr_acct extends Account {

    @SuppressWarnings("empty-statement")

    void penalty() {

        if (withdraw < 2000 && withdraw > 0) {
            double Service_charge = withdraw - 100;
            double falling = Service_charge;
            System.out.println("Your balance is " + withdraw);
            System.out.println("You've been charged a service charge" + " 100" + " due to a below the limit balance");
            System.out.println("Your current amount is " + falling);
        } else if (withdraw <= 0) {
            System.out.println("Your balance is insufficient");
        } else {
            System.out.println("Your current balance is " + withdraw);
        }

    }

}

class Sav_acct extends Account {

    void interest() {
        if (withdraw < 0) {
            System.out.println("Your balance is insufficient");
        } else {
            double interests;

            interests = (1 / 100) * withdraw;
            double total_amount = interests + withdraw;
            System.out.println("Your new balance with interest is " + total_amount);
        }

    }

}

public class publish {

    @SuppressWarnings("empty-statement")

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter your name");

        String n = sc.nextLine();

        System.out.println("Enter your account type: Savings Account or Current Account");
        String t = sc.nextLine();

        if ("Savings Account".equals(t)) {
            Sav_acct ac = new Sav_acct();
            System.out.println("Do you want to deposit or withdraw amount?");
            String d = sc.nextLine();
            if ("deposit".equals(d)) {

                ac.deposit();
            } else if ("withdraw".equals(d)) {

                ac.withdrawl();

                ac.interest();

            }
        }

        else if ("Current Account".equals(t)) {
            Curr_acct ac = new Curr_acct();
            System.out.println("Do you want to deposit or withdraw amount?");
            String d = sc.nextLine();
            if ("deposit".equals(d)) {

                ac.deposit();
            } else if ("withdraw".equals(d)) {

                ac.withdrawl();

                ac.penalty();

            }
        } else {

            System.out.println("please enter the correct account type as per the options provided on the screen");

        }

    }
}

A: Don't use public static in a variable just to access it . Use getter setter to access variables of a class. Thats the right way of doing it.
In your case removingpublic static will do fine;
In Account class
public static double withdraw;

to

double withdraw;

You are not maintaining any state while creating object for Account and  Sav_acct class.You are creating two different objects to do 1 job.
You will never get withdraw value of Account in Sav_acct since both are different objects.
You are not maintaining any state while creating objects for the Account and  Sav_acct classes. You are creating two different objects here.
You will never get the withdraw value of Account in Sav_acct since both are different objects. Plus you are missing the basics of Inheritence in OOPS
Since Sav_acct is extending the Account class it is inheriting all the properties of Account, so there is no need of creating an object of the Account class.
Instead, create an object of Sav_acct and use this obj to perform your operations;
Account wi = new Account();
wi.withdrawl();
Sav_acct in = new Sav_acct();
in.interest();

to
Sav_acct wi = new Sav_acct();
wi.withdrawl();
wi.interest();

You need to know about how Inheritance works in OOPS. Refer here
The main problem
You are declaring objects multiple times whenever you needed.Eg:-
System.out.println("Enter your account type: Savings Account or Current Account");
String t = sc.nextLine();
if ("Savings Account".equals(t)) {
    System.out.println("Do you want to deposit or withdraw amount?");
    String d = sc.nextLine();
    if ("deposit".equals(d)) {
        Account de = new Account();        // creating Account object
        de.deposit();
    }
    else if ("withdraw".equals(d)) {
        Account wi = new Account();   // creating Account object  again
        wi.withdrawl();
        Sav_acct in = new Sav_acct();
        in.interest();
    }
}

In the above why create Account de = new Account(); separately for both deposit and withdraw just declare one object after getting the account type name and use it to perform respective jobs.
System.out.println("Enter your account type: Savings Account or Current Account");
String t = sc.nextLine();
if ("Savings Account".equals(t)) {

    Sav_acct acc = new Sav_acct(); //creating sav_acct object here and use

    System.out.println("Do you want to deposit or withdraw amount?");
    String d = sc.nextLine();
    if ("deposit".equals(d)) {
        // Account de = new Account(); no need
        acc.deposit();
    }
    else if ("withdraw".equals(d)) {
        //Account wi = new Account(); no need
        acc.withdrawl();
        //Sav_acct in = new Sav_acct(); no need again
        acc.interest();
    }
}

Redesign your code inside main method otherwise, most of the thing is fine


text:
Q: Prove image sheaf is the sheafification of image presheaf with universal properties This is an exercise given by Vakil's online notes on algebraic geometry. I wanted to solve the problem by universal properties, but I could not make it complete. I found a solution online as follows:

This solution cannot convince me when it says (in the second last paragraph), "if the starred dashed arrow is not the identity, then we have two different ways...". Aren't both of them zero morphisms? Is this a right solution?
I was also stuck at the last bit where I need to find a reversed arrow of the starred dashed one.
I know this exercise can be solved by other ways such as category theory or the exactness of sheafification, but I wonder how to make this approach work. Thanks!


text:
Q: .NET XmlReader on SslStream - reading multiple XMLs from stream - obtatining XmlDocument I have a TCP connection wrapped around by SslStream .NET object. The remote server sends spontanous XML messages that I need to receive and parse. I use XmlReader and parse the document manually. I have no schema, I parse the incoming messages one by using XmlReader interface. Is it possible to obtain somehow XmlDocument objects from this XmlStrem?
Regards

A: You may want to look at using XDocument from System.Xml.Linq. Since you already have an XmlReader, you can use the XDocument.Load(XmlReader) method to populate it.


text:
Q: Check variable in javascript with php variable I have the php page with javascript code inside it.
If I have php variable retrieved by back-end server, can it be passed in javascript code?
For instance, if I want to check the flag(php variable) inside the javascript code, do I need to hardcode it inside the javascript?
Below are the "checkServiceCategory"? (Should it be Dynamic or static)
<?php
foreach ($result as $id=>$value) {
if($value[0]->isServiceCategory)
return true;
}

OR
isEmptyUploadFile(function(r)
{
var checkServiceCategory=document.getElementById('category-group').value;
if(checkServiceCategory!=85 && (fileList == null || fileList.length == 0))
{
$("#uploadImgError").html('  Please Upload at least one image!');
location.href = "#uploadImgError";
return false;
}
else

A: You can write PHP data into JavaScript before that JavaScript is loaded. So, for example:

You can do this because the PHP is run on the page before it is ever sent to the client. However, once the code is sent to the client, JavaScript and PHP cannot talk to each other. What you can do at that point is make AJAX requests via JavaScript from your client back to your server, and use PHP to respond to the AJAX request.

A: Yes you can use php variables inside the javascript code and php variable is dynamic as
<?php $your_variable = "some value"; ?>

A: You can pass value from php to js like this.
var js_var = '<?php echo $some_php_variable; ?>';


text:
Q: .NET Website hosted on Azure Windows VM - IIS Web Server fails to work after Server (VM) restart Hosted a .NET 6 basic Web App in IIS Web Server inside the Azure Virtual Machine (Windows 2016 Data Center)
Commands:
dotnet new webapp
dotnet run
dotnet publish -c Release

3rd command is used for placing release folder files in the Site Physical Path created in IIS Web Server:

It shown the result as welcome page. After VM Stop and Start action, it is showing the localhost as "The Site can't be reached"
If I create new site on Connections of the IIS Manager, then it is working.
Every time after restarting the VM, Creating New Site is not the solution.
Why previously created Site is showing me "The Site can't be reached" error.
What I have tried:

*

*Tested by creating new Site in Connections of the IIS Manager, it worked for the new site but after restarting the VM, it also stopped working and showing above mentioned error.

*Checked VM Status, it is Healthy

*All required tools are installed in the VM (VS Code, .NET 6 SDK, Runtime, and Hosting Bundle)

Note: It is working successfully after I clear the cache in the browser after server restart (stop and start) but why I have to clear the browser cache every time after VM stop and start?
Update:
Forgot to mention this:
I have given HTTPS binding to the IIS Manager Website Hosted so if do localhost with port 80, it will shows IIS Web Served Home Page and localhost with Https (443), it will show the hosted website content.
After Server Stop and Start, localhost with port 80 gives the IIS Web Served Home Page and localhost with Https is not giving the website content, here it is giving error "The site is not reached".
Fix:
I have found the fix to this issue which is:
Hosting works with particular time period.
Every time when you launch the Website hosted in VM through IIS Web Server after Server restart (several hours), you need to re-host or create new site in IIS Manager Pool.

A: I tried to reproduce the same in my environment and I got the results like below:
I have created sample website and when I tried Stop and Start action, localhost reached successfully:

As suggested by samwu you can check event viewer like below:
In start -> select event viewer -> click Windows Logs node

Select application Event Log and Search for errors associated with the failing app like below

You can make use of Debug Diagnostics tool.


text:
Q: Attaching a disk $D^2$ along the boundary circle to a circle $S^1.$
Let $Y$ be the space obtained by attaching a disk $D^2$ along the boundary circle to a circle $S^1$ by a map that wraps the boundary circle around the other circle 3 times, i.e., the following square is a pushout.
$$\require{AMScd}
\begin{CD}
\mathbb{S}^1 @>{\text{inclusion}}>> \mathbb{D}^2\\
@VVV @VVV \\
\mathbb{S}^1 @>{}>> Y
\end{CD}$$
Calculate $\pi_{1}(Y).$

My questions

*

*I do not understand the statement: "by attaching a disk $D^2$ along the boundary circle" what do the question mean by $along the boundary$? does it mean tangentially? Also, are there other ways of attaching a disk?

*I feel like I should use Van Kampen theorem but I do not know how to divide my space $Y$ into union path-connected open sets each containing the basepoint $y_{0} \in Y$?

Could anyone help me in answering these questions please?

A: Let's start from the begining. $S^1$ is given and another, distinct $D^2$ is given. The boundary $\partial D^2$ of $D^2$ is $S^1$ as well, but since it is distinct I will denote it as $\partial D^2$.

1- I do not understand the statement: "by attaching a disk $D^2$ along the boundary circle" what do the question mean by $along the boundary$? does it mean tangentially?

The concept is the same as in CW complex construction. You start with a map $f:\partial D^2\to S^1$ (in your case the triple winding) and then you glue $D^2$ and $S^1$ along this map, i.e. you take the quotient space
$$(D^2\sqcup S^1)/\sim$$
where "$\sim$" is generated by $x\sim f(x)$ for $x\in\partial D^2$. In particular note that if $f(x)=f(y)$ then $x\sim y$.

Also, are there other ways of attaching a disk?

Of course. If you glue along say identity $f(x)=x$ then the result is simply $D^2$. The same goes for the antipodal map $f(x)=-x$. But in your case this is something different. Note that if you attach along a double winding you obtain the real projective space $\mathbb{R}P^2$.

2- I feel like I should use Van Kampen theorem but I do not know how to divide my space $Y$ into union path-connected open sets each containing the basepoint $y_{0} \in Y$?

So let's generalize this a bit and assume that the attaching map winds $n$ times. Calculating the fundamental group for general $n$ is very similar to calculating it for $\mathbb{R}P^2$. Here is the answer that goes through the process in details: An intuitive idea about fundamental group of $\mathbb{RP}^2$ The core idea there is that they use the path lifting property of coverings instead of Van Kampen.
Try to generalize it (the quotient is no longer $x\sim -x$ but $x$ is now related to $n-1$ other points on $\partial D^2$) and note that the result should be $\mathbb{Z}_n$.

A: Suppose we have a closed disc $\bar{D}^2$ whose boundary $\partial D^2$ is attached to a circle $S^1$ by a map $\gamma:\partial D^2\to S^1$ that wraps $\partial D^2$ in total $n$ times around $S^1$.  We call the resulting space $Y_n$.
Let $U$ and $V$ be open subsets of $Y_n$ defined as follows.  The set $U$ is given by $(U\cap D^2)\cup S^1$, where $D^2$ is the interior of $\bar{D}^2$, and $U\cap D^2$ is a narrow strip on the outer edge of $D^2$ (so that $\partial(U\cup D^2)$ contains $\partial D^2$).  The set $V$ is just $D^2$.

My awful picture may help explain this.  The space $Y_n$ (on the left, where the orange arrows denote the attaching map $\gamma$) is the union of $U$ (the yellow subset) and $V$ (the pink subset).
Note that each of $U$ and $U\cap V$ has a deformation retract to just $S^1$, but $V$ is contractible.  That is $\pi_1(U)\cong\Bbb Z$, $\pi_1(V)\cong\{1\}$, and $\pi_1(U\cap V)\cong \Bbb Z$.  Now observe that $\pi_1(U\cap V)\to \pi_1(U)$ is given by multiplication by $n$ because each simple loop in $U\cap V$ wraps $n$ times around $S^1$ (and $\pi(U\cap V)\to \pi_1(V)$ is trivial).  By van Kampen's theorem, $$\pi_1(Y_n)=\pi_1(U)\underset{\pi_1(U\cap V)}{*}\pi_1(V)\cong (\Bbb Z*\{1\})/(n\Bbb Z)\cong \Bbb Z/n\Bbb Z.$$
Indeed, we can see that $\pi_1(Y_n)$ is generated by a generator $g$ of $\pi_1(S^1)$.  When you have a loop homotopic to $ng$, it is homotopic to $\partial D^2$, and can then be contracted along $\bar{D}^2$ to a point.


text:
Q: Begins with string or not in regular expression I am trying simplify the rows below to a single row:
sed -i 's/-XX\:PermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh
sed -i 's/-XX\:MaxPermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh

I try use something similar of this -XX\:(?:Max|)PermSize=128m\s, but without any success.

A: Note that (?:Max|) is a non-capturing  group and it is not compliant with the POSIX regex engine that sed uses. You are using a BRE POSIX engine, so, to use a capturing group, you need to use \(...\) and to use an alternation operator, you need \|.
You may use
sed -i 's/-XX:\(Max\)\?PermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh

This is a BRE POSIX expression, thus \(Max\)\? matches an optional Max character sequence.
Or,
sed -i -E 's/-XX:(Max)?PermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh

The -E option enables the ERE POSIX syntax, an optional Max character sequence is defined with (Max)?.
See the online sed demo
s="ABC-XX:PermSize=128m DEF-XX:MaxPermSize=128m "
sed 's/-XX:\(Max\)\?PermSize=128m\s//g' <<< "$s"
# => ABCDEF
sed -E 's/-XX:(Max)?PermSize=128m\s//g' <<< "$s"
# => ABCDEF

A: You could make Max optional in an optional group (Max)? :
-XX\:(max)?PermSize=128m\s

For example:
sed -i 's/-XX\:(Max)?PermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh

A: Try
sed -i 's/-XX\:\(Max\)?PermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh

A: Try this:
sed -ir 's/-XX\:(Max)?PermSize=128m\s//g' /usr/share/hbase/conf/hbase-env.sh

Better add r than with all those escape. If you are using GNU sed.


text:
Q: OpenXML Writing Values to Empty Cells in Excel I have figured out how to write the contents of a string array to Excel in the format I want but now I'm having trouble making sure it doesn't write over cells that are already populated in an Excel file.
Currently I am trying to read the contents of the Excel file first then insert based off of where there are no values.  This is what I currently have.
private static void WriteToExcel(string[] contents, char[] desiredColumns)
{
    string filePath = @"D:\Folder\test.xlsx";
    try
    {
        using (SpreadsheetDocument StatsCollection = SpreadsheetDocument.Open(filePath, true))
        {
            WorkbookPart bookPart = StatsCollection.WorkbookPart;
            string sheetName = "Sheet1";
            SharedStringTablePart sstpart = bookPart.GetPartsOfType<SharedStringTablePart>().First();
            SharedStringTable sst = sstpart.SharedStringTable;
            Sheet mySheet = bookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
            WorksheetPart sheetPart = (WorksheetPart)(bookPart.GetPartById(mySheet.Id));
            Worksheet sheet = sheetPart.Worksheet;
            var rows = sheet.Descendants<Row>();
            foreach (Row row in rows)
            {
                foreach (Cell currentCell in row.Elements<Cell>())
                {
                    int totalRows = contents.Length / 15;
                    int contentsIndex = 0;
                    for (uint indexRow = 1; indexRow <= totalRows; indexRow++)
                    {
                        for (int indexCol = 1; indexCol < 16; indexCol++)
                        {
                            SharedStringTablePart shareStringPart;
                            if (StatsCollection.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Count() > 0)
                            {
                                shareStringPart = StatsCollection.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
                            }
                            else
                            {
                                shareStringPart = StatsCollection.WorkbookPart.AddNewPart<SharedStringTablePart>();
                            }
                            int index = InsertSharedStringItem(contents[contentsIndex], shareStringPart);
                            if (currentCell.CellValue.InnerText == "")
                            {
                                Cell newCell = InsertCellInWorksheet(desiredColumns[indexCol - 1].ToString(), indexRow, sheetPart);
                                if (IsNumeric(contents[contentsIndex]))
                                {
                                    newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
                                    newCell.CellValue = new CellValue(contents[contentsIndex]);
                                }
                                else
                                {
                                    newCell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
                                    newCell.CellValue = new CellValue(index.ToString());
                                }
                            }
                            else
                            {
                                break;
                            }
                            sheetPart.Worksheet.Save();
                            contentsIndex++;
                        }
                    }
                }
            }
        }
        Console.WriteLine("Copy Complete.");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Cannot find output Excel file.\n" + ex.Message);
    }
}

My thought process here was that if I could use the code to read in the information on my Excel sheet I found here I could then insert where that is null.  Once I've determined if something is null I then break from my most inner loop (which handles my columns) to increment my outer loop (which handles rows).  However that doesn't seem to be working.  I've verified that I am in fact reading the information from the sheet I just can't seem to write based off of that.
Why can I read the contents of my file but not write based on the cells that are there?
Update:
For anyone who comes across this question I ended up switching to Microsoft.Office.Interop to append my data onto the end of an excel file.  I'm hesitant to put that as an answer because it doesn't answer how to do it in OpenXML, which was my question.  However with an answer someone else might find this useful.

A: This function tries to grab a value from a cell
if the cell has a SharedStringValue it will return that or if its just a number
Or return " "  if no value
public static string GetCellV(Cell cell, SharedStringTable ss)
    {
        string cellV = null;

        try
        {
            cellV = cell.CellValue.InnerText;
            if (cell.DataType != null
              && cell.DataType.Value == CellValues.SharedString)
            {
                cellV = ss.ElementAt(Int32.Parse(cellV)).InnerText;
            }
            else
            {

                cellV = cell.CellValue.InnerText;
            }
        }
        catch (Exception)
        {
            cellV = " ";
        }

        return cellV;
    }

Im sure you could edit the last part for your needs.
NOTE:
Interop is not very resourceful and is really slow at executing, watch out for Excel processes that aren't closed once you've finished executing.
Open XML is much faster as it directly edits the XML code.


text:
Q: Problems with displaying .txt file (delimiters) I have a problem with one task where I have to load some data set, and I have to make sure that missing values are read in properly and that column names are unambiguous.
The format of .txt file:

At the end, data set should contain only country column and median age.
I tried using read.delim, precisely this chunk:
rawdata <- read.delim("rawdata_343.txt", sep = "", stringsAsFactors = FALSE, header = TRUE)

And when I run it, I get this:

It confuses me that if country has multiple words (Turks and Caicos Islands) it assigns every word to another column.
Since I am still a beginner in R, any suggestion would be very helpful for me. Thanks!

A: Three points to note about your input file: (1) the first two lines at the top are not tabular and should be skipped with skip = 2, (2) your column separators are tabs and this should be specified with sep = "\t", and (c) you have no headers, so header = FALSE.  Your command should be: -
rawdata <- read.delim("rawdata_343.txt", sep = "\t", stringsAsFactors = FALSE, header = FALSE, skip = 2)
UPDATE: A fourth point is that the first column includes row numbers, so row.names = 1.  This also addresses the follow-up comment.
rawdata <- read.delim("rawdata_343.txt", sep = "\t", stringsAsFactors = FALSE, header = FALSE, skip = 2, row.names = 1)

A: It looks like your delimiter that you are specifying in the sep= argument is telling R to consider spaces as the column delimiter. Looking at your data as a .txt file, there is no apparent delimiter (like commas that you would find in a typical .csv). If you can put the data in a tabular form in something like a .csv or .xlsx file, R is much better at reading that data as expected. As it is, you may struggle to get the .txt format to read in a tabular fashion, which is what I assume you want.
P.s. you can use read.csv() if you do end up putting the data in that format.


text:
Q: multiple instaces of Dynamic modalpopupextender I have modalpopupextender in user control. And I load user control dynamic and multiple instance of that user control meaning I have multiple instances of modalpopupextender loaded dynamically. How do I set behaviorid so I can call .add_shown method to call some javascript on modal popup load ?

A: This should do the trick:
function pageLoad() {
//Find all the Popups that deal with ZoomTo and add a add_shown handler.
var AllThem = Sys.Application.getComponents();

for (them in AllThem) {
    if (AllThem[them]._PopupControlID != undefined) {
        var d = AllThem[them]._PopupControlID;
        if (d.indexOf("ZoomToPanel") >= 0) {
            //Add the
            AllThem[them].add_shown(onZoomToPanelShown);
        }
    }
}
}

function onZoomToPanelShown() {
   //Clear the AutoComplete box.
   var t2 = $$get('txtAutoComplete');
   t2.value = "";
}


text:
Q: Error in Python when dealing with lists read from a text file Here is my code. I am newbie to Python:
    f=open('dt2.txt','r').read().split('\n')
    for i in range (len(f)):
        a=f[i].split('\t')
        print type(a)
        print str(a[1])," with roll no: ",str(a[0])," ",
        c=0
        d=0
        for j in range (0,100):
            try:
                if str(a[j])=="HU101":
                    c+=1
                if str(a[j])=="HU301":
                    c+=1
                if str(a[j])=="HU481":
                    c+=1
                if str(a[j])=="HU501":
                    c+=1
                if str(a[j])=="HU601":
                    c+=1
                if str(a[j])=="HU781":
                    c+=1
                if str(a[j])=="HU801A":
                    c+=1
                if str(a[j])=="HU801B":
                    c+=1
                if str(a[j])=="M101":
                    d+=1
            except IndexError:
                continue
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"

I am getting this error:
enter image description here

A: Let's see if I can help... In python the csv-library and with ... open is considered more "pythonic". The with ... open ensures the file is properly closed after being opened.
import csv
with open('dt2.txt') as f:
    mydata = [i for i in csv.reader(f, delimiter='\t')] # one-liner

Another tip... you can also shorten your code dramatically by writing:
if str(a[j]) in ["HU101","HU301",...,"HU801B"]:
   c+=1

A: Frankly, this code is terrible. If I understand correctly what you're trying to achieve, this is a much cleaner way of doing the same:
f = open('dt2.txt','r')
for line in f:
    a = line.split('\t')
    print "{} with roll no: {} ".format(a[1],a[0]),
    c = sum(1 for j in a if j in set("HU101", "HU301", "HU481", "HU501", "HU601", "HU781", "HU801A", "HU801B"))
    d = 1 if "M101" in a else 0
    if c>d:
        print "is good in Soft Skills"
    else:
        print "is good in Quantitative & Logical Ability"
f.close()


text:
Q: Window Close Listener And setDefaultCloseOperation I have a question about the relationship between swing window listener and default close operation. The question occurs when I am dealing with below scenario:
I add a window listener (WindowAdapter is used for the listener) for a JFrame, and override the windowClosing function: if the user closes the window, a dialog will pop up to confirm, if user chooses CANCEL option, then directly return. However, when I test the code and choose CANCEL when closing the window, the frame window is still closed (or maybe just invisible, because the Java icon is still in the task bar).
Then I add the default close option with DO_NOTHING_ON_CLOSE, with the same test behavior, the frame window is not closed, which is what I expected.
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

Then I change the default close option with EXIT_ON_CLOSE, with the same test behavior, the frame window is directly closed(this time Java icon also disappeared).
This makes me confused. Does it mean the window listener can just define what to do when the window is closing but can't determine whether to close the window? Or I need to override other function?

A: The window listener is just a listener. It does not affect the default close operation, unless you actually change the default close operation in the windowClosing() code.
I use:
frame.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

as the default when the frame is created. Then in the windowClosing(...) method, if the user confirms the closing of the frame I change the default:
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

Check out Closing an Application for more information and more complete example code.


text:
Q: HTA/VbScript - If statement from Dropdown list choice In my HTA using vbscript I am trying to read a choice from a DropDown list that will run specific code for each choice.
I've been poking around looking for some method to use the value of a DropDown list to run a specific VBSCRIPT subroutine but have not found anything helpful in my search.  The code below does work however it only displays a message box with the choice listed.  Any pointers would be extremely appreciated!!
<select name="BuildStepChoice" size="1">
 <option selected="selected" value=" "></option>
 <option value="1">1</option>
 <option value="2">2</option>
</select>

And the VBSCRIPT
Sub Copychecklist()
Dim VMBuildStep
VMBuildStep = document.getElementById("BuildStepChoice").Value
 If VMBuildStep = 1 Then MsgBox "Picked #1" Else
 If VMBuildStep = 2 Then MsgBox "Picked #2" End If
End Sub

A: Not sure where I picked this up, but this is what I ended up with.
Sub Copychecklist()
 Dim VMBuildStep
 VMBuildStep = document.getElementById("BuildStepChoice").Value
  If (IsNumeric(VMBuildStep)) Then
  VMBuildStep = Int(VMBuildStep)
  If (VMBuildStep >= 1 And VMBuildStep <= 17) Then CreateFile(VMBuildStep)
 End If
End Sub


text:
Q: Quickbook : name supplied already exists error We are facing some issue while we are syncing customer information with Quickbook API,
We are getting error like "The name supplied already exists. : Another customer, supplier, or employee is already using this name. Please use a different name."
We have checked All three (customer, supplier, employee) listings in quickbook online. but I can't find record which already inserted and can't show in lising.
how I can find , are there any other listing need to check ? We checked customer, supplier, employee already with Include Inactive option.


text:
Q: Representing files in an ordered Array using fs.readdir Basically I am trying to get files within a directory using Node.js's method readdir and its not doing what I actually want, I tried searching and found a module called lodash didn't work so well with itsorder method. Am trying to build a Music Streaming Application and want to present the music accordingly to the music's track number ID3 Tag, I seriously need HELP!
Heres the code that retrieves the music:
// The directory to search
var directory = path.join("some/directory");
global.results = [];
// Collect all the audio files in the user's music library
audioManager.getMusicFiles = (dir) => {
// Collection of the music files
// Read into the directory
fs.readdirSync(dir).forEach(function (file) {
  var fstats = {};
  // Add it to the results only if the file is an audio file
  if ( file.split(".").pop() == "mp3" ) {
    // The filename property of the file
    fstats.filename = path.basename(file);
    // The real directory of the file
    fstats.fpath = path.join(dir, file);
    // Append the findings to the results array
    results.push(fstats);
  }

  if ( fs.statSync(path.join(dir, file)).isDirectory() ) {
    return audioManager.getMusicFiles(path.join(dir, file)); // Also scan that directory for music files
  }
});
};
audioManager.getMusicFiles(directory);

/** Returns unordered on console
 [
 {"filename": "01. Intro.mp3", "fpath":
 "C:\\Users\\Libby\\Music\\Azizi Gibson - Memoirs Of The Reaper\\01. Intro
 (2).mp3"
  },
  { "filename": "02. Happy.mp3", "fpath":
 "C:\\Users\\Libby\\Music\\Azizi Gibson - Memoirs Of The Reaper\\01. Intro
 (3).mp3"
 }
 ]

 But putting them into a HTML ELement they become unordered **/


text:
Q: Multiple get methods for single restlet resource I have the following two queries:
/api/resource/{id}
/api/resource?id=x&id=y&id=z

They need to be served with two different resource methods:
@Get
public DTO getSingleDTO();
@Get
public List<DTO> getMultipleDTO();

Is it possible to put these two methods into a single restlet resource?
I tried using @Get("?id"), but this annotation isn't really powerful and not usable in my case.
What's the best way to implement this? I don't want to implement two controllers for every resource I have.

A: I don't know your model, but from what I'm seeing, I'd go with single route and single resource method:
in the Application class:
router.attach("/api/resource/{id_1}?id_2=y&id_3=z", MyResource.class)

In the MyResource class:
   public Representation doMyThing() {

      String id1 = getRequestAttributes("id_1").toString()getRequestAttributes();
      String id2 = getQueryValue("id_2");
      String id3 = getQueryValue("id_3");

      if (StringUtils.isEmpty(id2) && StringUtils.isEmpty(id3)) {
        DTO result = service.handleSingleId(id1);
        return JsonRepresentation(result);
      } else {
        List<DTO> result = service.handleMultipleIds(id1, id2, id3);
        return JsonRepresentation(result);
      }
   }

you can always return some other Representation and not JsonRepresentation as I suggested


text:
Q: Как определять переключение месяцев в календаре react-dates? Я использую react-dates для календаря в своём веб-приложении. И у меня возникла необходимость отслеживать переключение между месяцами. Т.е. мне надо знать, когда пользователь переключил календарь на определённый месяц.
Вот мой календарь.

<DayPickerSingleDateController
   numberOfMonths={1}
   date={this.state.dateForCalendar}
   isDayHighlighted={this.highlited}
   renderCalendarDay={this.renderDay}
   onDateChange={this.daySelected}
   firstDayOfWeek={0}
/>

Я нашёл в документации свойства onPrevMonthClick и onNextMonthClick, которые принимают на вход функцию. Я думал это как раз то что мне нужно, но при вставке этих свойств компилятор выдаёт ошибку

./src/features/schedule/index.js
  Line 178:  Parsing error: Unexpected token

  176 |                         {this.state.calendar_on &&
  177 |                         <DayPickerSingleDateController
> 178 |                             onPrevMonthClick: {text => {console.log(text)}}
      |                                               ^
  179 |                             numberOfMonths={1}
  180 |                             date={this.state.dateForCalendar}
  181 |                             isDayHighlighted={this.highlited}

Что я не так делаю? (даже если я передаю функцию, которая не принимает аргументов или возвращает булево значение)

A: Для передачи данных от родителя к ребенку, через props необходимо указывать передаваемые данные через знак равенства =, а не через двоеточие :. Собственно, props - это неизменяемый объект, предназначенный только для чтения, props - это просто аргумент функции, с которым мы можем работать внутри, но не изменять (его изменение может повлечь за собой проблемы). В Вашем случае достаточно внести мелкую правку в код (заменить двоеточие : на знак равенства =):
<DayPickerSingleDateController
   onPrevMonthClick={text=>{console.log(text)}}
   onNextMonthClick={text=>{console.log(text)}}
   numberOfMonths={1}
   date={this.state.dateForCalendar}
   isDayHighlighted={this.highlited}
   renderCalendarDay={this.renderDay}
   onDateChange={this.daySelected}
   firstDayOfWeek={0}
/>

Однако использование стрелочной функции в рендеринге не рекомендуюется. Потому что при использовании стрелочной функции в рендере, каждый раз при рендеринге компонента создается новая функция, которая может нарушить оптимизацию и добавить тормоза. Про это пишут в документации по React: Arrow Function in Render


text:
Q: How to sum TOP N docs with terms in elasticsearch? Following are the sample document at elasticsearch.
         {
            "_index": "social",
            "_type": "social",
            "_id": "1632560884596186633",
            "_score": 1,
            "_source": {
                "created_date": "2017-10-24",
                "reach": 1692,
                "social_id": 200
            }
        },
        {
            "_index": "social",
            "_type": "social",
            "_id": "1626693964184981799",
            "_score": 1,
            "_source": {
                "created_date": "2017-10-25",
                "reach": 1692,
                "social_id": 100
            }
        },
        {
            "_index": "social",
            "_type": "social",
            "_id": "162669396418498170",
            "_score": 1,
            "_source": {
                "created_date": "2017-10-25",
                "reach": 1692,
                "social_id": 50
            }
        },
        {
            "_index": "social",
            "_type": "social",
            "_id": "1626693964184981756",
            "_score": 1,
            "_source": {
                "created_date": "2017-10-25",
                "reach": 1692,
                "social_id": 25
            }
        }

Question: Sum of reach for top 2 documents based on the created date per social id.
What I have tried:
{
"size": 0,
"aggs": {
    "reach_bucket": {
        "terms": {
            "size": 200,
            "field": "social_id"
        },
        "aggs": {
            "media_reach_bucket": {
                "terms": {
                    "field": "created_date",
                    "size": 200
                },
                "aggs": {
                    "top_sales_hits": {
                        "top_hits": {
                            "sort": [
                                {
                                    "created_date": {
                                        "order": "desc"
                                    }
                                }
                            ],
                            "_source": {
                                "includes": [
                                    "created_date",
                                    "reach"
                                ]
                            },
                            "size": 2
                        }
                    }
                }
            }
        }
    }
}
}

Problem:
Not to do sub aggregation for top_hits.
Any suggestion will be grateful.

A: You may want to use date_histogram instead of terms when bucketing per day (I assume). But more importantly, you should sort your top_hits by reach, not created_date, since that's going to be the same in your per-day bucket.
{
  "size": 0,
  "aggs": {
    "reach_bucket": {
      "terms": {
        "size": 200,
        "field": "social_id"
      },
      "aggs": {
        "media_reach_bucket": {
          "date_histogram": {
            "field": "created_date",
            "calendar_interval": "day"
          },
          "aggs": {
            "top_sales_hits": {
              "top_hits": {
                "sort": [
                  {
                    "reach": {
                      "order": "desc"
                    }
                  }
                ],
                "_source": {
                  "includes": [
                    "reach"
                  ]
                },
                "size": 2
              }
            }
          }
        }
      }
    }
  }
}

yielding top hits like so
"aggregations" : {
    "reach_bucket" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 100,
          "doc_count" : 4,
          "media_reach_bucket" : {
            "buckets" : [
              {
                "key_as_string" : "2017-10-24T00:00:00.000Z",
                "key" : 1508803200000,
                "doc_count" : 4,
                "top_sales_hits" : {
                  "hits" : {
                    "total" : {
                      "value" : 4,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "kart",
                        "_type" : "_doc",
                        "_id" : "3iLJRnEBZbobBB0NiV8R",
                        "_score" : null,
                        "_source" : {
                          "reach" : 40
                        },
                        "sort" : [
                          40
                        ]
                      },
                      {
                        "_index" : "kart",
                        "_type" : "_doc",
                        "_id" : "3SLJRnEBZbobBB0Nhl-Y",
                        "_score" : null,
                        "_source" : {
                          "reach" : 30
                        },
                        "sort" : [
                          30
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }

whose reach you can then sum up in your post processing functions.

I'm not familiar with a top-n sum, only with sums of docs above a certain threshold -- in which case I'd use filter aggregations.


text:
Q: Python packages depending on libxml2 and libxslt Apart from lxml, is anyone aware of Python packages that depend on libxml2 and libxslt?

A: See e.g. the list here -- not exhaustive, as the page itself says, but a start.


text:
Q: Parameter to disable Azkaban job by default Given the following Azkaban configuration that has 1 flow containing 3 jobs, how do I disable Job2 by default? Is there a parameter/configuration for that?
I know that I could go in the UI and disable the job manually. However, I'd like to have the Job2 disabled by default and possibly enable it from the UI only when needed.
hadoop {

  def input = "..."

  workflow('MyWorkflow') {

    hadoopJavaJob('Job1') {
      uses 'my.package.Job1Runner'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    hadoopJavaJob('Job2') {
      uses 'my.package.Job2Runner'
      depends 'Job1'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    hadoopJavaJob('Job3') {
      uses 'my.package.Job3Runner'
      depends 'Job2'

      reads files: [ ... ]
      writes files: [ ... ]
    }

    targets 'Job3'
  }
}

A: You can use the optional disabled parameter. See "Execute A Flow" section of the documentation.


text:
Q: How would I create the following with jquery? Id like to create this using jquery.

List2

A: you can create using this:
 var element = $('

List2

')

check this fiddle for more details: http://jsfiddle.net/victorrseloy/vPsdz/


text:
Q: PHP redis session save_handler not being used I've installed the php7-redis extension in an alpine container running in k8s.
Added a conf ini file that enables redis and sets the host.
This shows up in phpinfo's output but the app being deployed (flarum) doesn't seem to be saving its sessions to redis.
Basically needed because we want to run multiple replicas of flarum.
phpinfo output
session
Session Support enabled
Registered save handlers    files user redis rediscluster
Registered serializer handlers  php_serialize php php_binary
Directive   Local Value Master Value
session.auto_start  Off Off
session.cache_expire    180 180
session.cache_limiter   nocache nocache
session.cookie_domain   no value    no value
session.cookie_httponly no value    no value
session.cookie_lifetime 0   0
session.cookie_path /   /
session.cookie_samesite no value    no value
session.cookie_secure   0   0
session.gc_divisor  1000    1000
session.gc_maxlifetime  1440    1440
session.gc_probability  1   1
session.lazy_write  On  On
session.name    PHPSESSID   PHPSESSID
session.referer_check   no value    no value
session.save_handler    redis   redis
session.save_path   tcp://flarum-redis-master:6379?auth=<redis-password>
session.serialize_handler   php php
session.sid_bits_per_character  5   5
session.sid_length  26  26
session.upload_progress.cleanup On  On
session.upload_progress.enabled On  On
session.upload_progress.freq    1%  1%
session.upload_progress.min_freq    1   1
session.upload_progress.name    PHP_SESSION_UPLOAD_PROGRESS PHP_SESSION_UPLOAD_PROGRESS
session.upload_progress.prefix  upload_progress_    upload_progress_
session.use_cookies 1   1
session.use_only_cookies    1   1
session.use_strict_mode 0   0
session.use_trans_sid   0   0

Can I deregister files user rediscluster leaving only redis or some other way force it to be used?
Can't see what option I've missed or why no sessions are being saved to redis.
I've tested it should be working by using this script
 <?php
session_start();
$count = isset($_SESSION['count']) ? $_SESSION['count'] : 1;
echo $count;
$_SESSION['count'] = ++$count;

After refreshing this test.php file session data shows up in redis. Is there something in flarum preventing its use?
FYI php-fpm in use with nginx

A: This isn't as simple as telling PHP to use Redis.
An extension is needed to overload the built in session storage.
See the discussion at https://discuss.flarum.org/d/25889-how-to-use-redis-for-session-storage
Since we're in Kubernetes I found flarum stores session files in /flarum/app/storage/sessions so I mounted a shared volume there that all replicas can use. Testing so far has shown this works well.


text:
Q: Ошибка при создании MVC Здравствуйте, в чем может быть ошибка. PHPStorm ругается на 2-ую строчку
и выводит:

Fatal error: Uncaught exception 'Exception' with message 'Failed to
  include class: Config' in C:\xampp\htdocs\MY_MVC\lib\init.php:21 Stack
  trace: #0 C:\xampp\htdocs\MY_MVC\config\config.php(3):
  __autoload('Config') #1 C:\xampp\htdocs\MY_MVC\lib\init.php(3): require_once('C:\xampp\htdocs...') #2
  C:\xampp\htdocs\MY_MVC\webroot\index.php(6):
  require_once('C:\xampp\htdocs...') #3 {main} thrown in
  C:\xampp\htdocs\MY_MVC\lib\init.php on line 21


text:
Q: How can I input the same number multiple times on an HTML page and within code? I have a very basic question regarding an HTML page.  I would like to create a template for an HTML webpage and on that page I need to reference a number (property ID) multiple times on the actual web page and in the code to link to image sources.  I would like to be able to type the property ID once into the template code and that code will be populated into all the places I need it for the page to display properly vs having to type the 5-8 digit number over and over and over.
Below is a basic example of the template page - instead of having to write property ID 123456 multiple times, I would like to be able to write it once into the template or JS and then have it populated into the areas where the property ID needs to repeat.  The property ID will also be a folder containing images for the webpage.  Each folder will contain 1-25 images named 1.jpg, 2.jpg, 3.jpg and so on so I'll need to be able to use the property ID to be a part of the source code.  Currently the template looks like this...

You are viewing Property #123456

Would you like more information regarding Property #123456?

I would like to be able to quickly make new pages using a template without needing to copy & paste the property ID into each page multiple times.
I envision something like this...

You are viewing Property #

Would you like more information regarding Property #?

With the ***** in the img src referencing the propID somehow using JS but I do not know how to do this.
What's the best/easiest way to go about doing this?
TIA

A: Use an element (such as ) to display your number. Consider following a JS tutorial (such as at w3schools.com) to learn more about manipulating HTML with JavaScript.

const property_number = 42;
elements = document.getElementsByClassName("property-number");
for(var i = 0; i < elements.length; i++)
  elements[i].innerText = property_number;
document.getElementById("img1").src = property_number + "/image_1.jpg";
You are viewing

A: Taken answer from Imagifight
You have to just give array value to run the function
Used for loops and some basics , if need to know something from code or want to ask a doubt feel free to comment

const property_number = ["12345", "35245", "45234"];
var mainCont = document.getElementsByClassName("mainContainer");

for (let i = 0; i < mainCont.length; i++) {

  var mainContId = mainCont[i].getElementsByTagName("SPAN")
  var mainContIdImg = mainCont[i].getElementsByTagName("IMG")

  for (let j = 0; j < mainContId.length; j++) {
    mainContId[j].innerHTML = property_number[i]
  }

  for (let k = 0; k < mainContIdImg.length; k++) {
    mainContIdImg[k].src = property_number[i] + k + "/image_1.jpg";
  }
}

You are viewing Property #

Would you like more information regarding Property #?

You are viewing Property #

Would you like more information regarding Property #?

You are viewing Property #

Would you like more information regarding Property #?

Updated the answer for single productId only
Here what I have done :

*

*Taken one time input of product Id in the const property_number

*Get value from .mainContainer class in a variable mainCont which will be called later on

*Now taken the value of all span tags (Can also call by className  and it is also recommended) and inputted the product ID to each span tag using the for loop.

Note to Remember: product ID value is only valid inside the .mainContainer conatiner and it is not defined outside of it , so keep this in mind . As span tag is called from variable mainCont  which .mainContainer

*Now all the img tag is taken from the .mainContainer class , whose src is entered using another for loop with src as productID/(count of img tag).jpg . So the first value is taken from variable property_number and second value is taken from the j value of for loop, as loop starts from 0 so added 1 to it.

Note to Remember : As https:// is not used so the domain will start from the folder where your html is saved . So try to start from https:// and give the path else save images in the sub-folders where html is saved .

That's all done :)

const property_number = 12345;
let mainCont = document.getElementsByClassName("mainContainer");

let mainContId = mainCont[0].getElementsByTagName("SPAN")
let mainContIdImg = mainCont[0].getElementsByTagName("IMG")

for (let i = 0; i < mainContId.length; i++) {
  mainContId[i].innerHTML = property_number
}

for (let j = 0; j < mainContIdImg.length; j++) {
  mainContIdImg[j].src = property_number + "/" + (j + 1) + ".jpg";
  document.getElementsByClassName("demo")[0].innerHTML = mainContIdImg[1].src;
  document.getElementsByClassName("demo1")[0].innerHTML = "https://hello/"+ property_number + "/" + (j + 1) + ".jpg";
   document.getElementsByClassName("demo2")[0].innerHTML = "F:/UsersPitures/Screenshoos"+ property_number + "/" + (j + 1) + ".jpg";
}

You are viewing Property #

Would you like more information regarding Property #?

My wish to write the productId 5 more times :

  # #
   #
   #
   #

Below the line is of no use content but for understanding only

My wish to write the productId 5 more times but outside the class ".mainContainer":

# #
 #
 #
 #

The src of one of the image is :

The src of any image with use of https://

The src of any image with use of https://


text:
Q: How to change props in a component passed into another component as props I have a Screens component being passed into a Modal component as the screens prop. Inside Modal I'm rendering it thusly...
{props.screens()}

This displays fine but I need a way to change the Screens components props from within Modal.

A: You could use React.cloneElement, which allows you to clone an element and add new props.
function myComponent(props) {

return <> {React.cloneElement(props.screens, {someNewProp:"value"}, children)} </>;

}


text:
Q: Component not being rendered in switch statement in onChange Listener I am new to react. I have a class called GroupSelectt. In this class I have a switch statement in the onChange listener for a Select dropdown menu. When a selection is made I want a different form to render for each dropdown selection., i.e conditional rendering using a switch statement. ADCform and NVMform are currently identical in code.My issue is that the forms do not render on screen. I'm unsure if this is the correct way to do it or if there is a more efficient way.Below are my code files. Thanks
GroupedSelectt.js
import { borderBottom } from '@mui/system';
import React, { Component } from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
import { ADCform } from './ADCform';
import { NVMform } from './NVMform';
/* eslint-disable */

const options = ["peter", "bob", "bill"]

export class GroupedSelectt extends React.Component {
  state = {
    value: "peter",
  };

  onChange = e => {

    this.setState({ value: e.target.value });
    var vap = e.target.value
    console.log(vap)
    switch (vap) {
      case 'peter':

        break;
      case 'bob':
        <NVMform/>
        break;
      case 'bill':

      <ADCform/>
        break;
      default:
        return 'foo';
    }

  }

  render() {
    const { value } = this.state;

    return (

        <FormControl sx={{ m: 1, minWidth: 1200 }}>

          <InputLabel htmlFor="grouped-select">Category</InputLabel>

          <Select id="options" value={value} onChange={this.onChange}>

            <ListSubheader >Name Options</ListSubheader>

            {options.map((val, index) => <MenuItem key={index} value={val}> {val} </MenuItem>)}

          </Select>

        </FormControl>

    )
  }
}

ADCform.js

import React from 'react';
import 'bootstrap/dist/css/bootstrap.css'
import './CSS/Home.css';
import {  Form, Col, Row, Button} from 'react-bootstrap';

export class ADCform extends React.Component{
render(){
    return (

        <Form>

    <Row className="mb-3">
    <Form.Group as={Col}>
      <Form.Label>Fruit</Form.Label>
      <Form.Control type="ms" placeholder="Enter Fruit" />

    </Form.Group>

    <Form.Label htmlFor="inputPassword5">Enter Drink</Form.Label>
  <Form.Control
    type="percentage"
    id="inputPassword6"
    aria-describedby="Test"
  />
  </Row>

    </Form>

    );
    }
}

Home.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.css'
import './CSS/Home.css';
import { Card, Form, } from 'react-bootstrap';

import { GroupedSelectt } from './GroupedSelectt';
import { ADCform } from './ADCform';

export class Home extends React.Component {
  render() {

    return (

        <Card className='cardSize'>

          <Form className='formWidth'>
            <Form.Label className='label'>Category</Form.Label>
            <GroupedSelectt />

          </Form>

        </Card>

    );
  }
}

A: You have to return the forms in your switch cases for them to be able to be rendered in the JSX, like so:
onChange = e => {
  this.setState({ value: e.target.value });
  var vap = e.target.value;
  switch (vap) {
    case 'peter':
      return;
    case 'bob':
      return <NVMform />;
    case 'bill':
      return <ADCform />;
    default:
      return 'foo';
  }
};

I see another problem, you are not rendering the components anywhere in the JSX. For this to work you'd need to call it in the JSX, something like:

{onChange}

But this doesnt make sense. What i'd do is move this logic to another function called renderForm:
renderForm = e => {
  switch (this.state.value) {
    case 'peter':
      return;
    case 'bob':
      return <NVMform />;
    case 'bill':
      return <ADCform />;
    default:
      return 'foo';
  }
};

And then call it in the JSX like explained above. Then modify your onChange component to just change the state:
onChange = e => {
  this.setState({ value: e.target.value });
};

And you should be good to go.

A: I have solved it with the following:
import { borderBottom } from '@mui/system';
import React, { Component } from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import ListSubheader from '@mui/material/ListSubheader';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
import { ADCform } from './ADCform';
import { NVMform } from './NVMform';
import { Card, Form, } from 'react-bootstrap';
import './CSS/Home.css';
/* eslint-disable */

const options = ["peter", "bob", "bill"]
var component = null;

export class GroupedSelectt extends React.Component {
  state = {
    value: "peter",
  };

  onChange = e => {
    this.setState({ value: e.target.value });
    var vap = e.target.value;
    switch (vap) {
      case 'peter':
        return;
      case 'bob':
        component = <NVMform />;
        break
      case 'bill':
        component = <ADCform />;
        break
      default:
        return 'foo';
    }
  };
  render() {
    const { value } = this.state;

    return (

            <FormControl sx={{ m: 5, minWidth: 1200, Height: 1200 }}>

              <InputLabel htmlFor="grouped-select">Category</InputLabel>

              <Select id="options" value={value} onChange={this.onChange}>

                <ListSubheader >Name Options</ListSubheader>

                {options.map((val, index) => <MenuItem key={index} value={val}> {val} </MenuItem>)}

              </Select>
              {component}
            </FormControl>

    )
  }
}


text:
Q: First row not added in the calc For some reason the first row of my gridview is not getting added in the sum of the column.
Code here:
double total = 0;
foreach (GridViewRow gvr in GridView4.Rows)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string sNum = e.Row.Cells[6].Text;
        double sum;
        if (double.TryParse(sNum, out sum))
        {
            total += sum;
        }

        TextBox21.Text = total.ToString("c");
        //GridView4.FooterRow.Cells[6].Text = total.ToString("c");
    }
}