text:
Q: How do I "flush" data to my RSQLite disk database? I'm creating a database using R package dbplyr, using RSQLite, but my database is zero-bytes in size on disk despite my writing (and reading back) a table. Here is my script:
library("RSQLite")
library("dbplyr")
library("dplyr")

data(mtcars)

con <- DBI::dbConnect(RSQLite::SQLite(), dbname = "./mtcars.db")
copy_to(con, mtcars, "mtcars")

print(tbl(con, "mtcars"))

But as you can see from the ls -l at the end my database size is 0, even though the script did read mtcars from the database (so it's in there). I want to use the database file to share data with another program, so how do I periodically "flush" the data to disk?
tbrowne@calculon:~/scratch$ R -f dplysqlite.r

R version 3.2.3 (2015-12-10) -- "Wooden Christmas-Tree"
Copyright (C) 2015 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

>
> library("RSQLite")
> library("dbplyr")
Warning messages:
1: replacing previous import by 'rlang::enquo' when loading 'dbplyr'
2: replacing previous import by 'rlang::quo' when loading 'dbplyr'
3: replacing previous import by 'rlang::quos' when loading 'dbplyr'
4: replacing previous import by 'rlang::quo_name' when loading 'dbplyr'
> library("dplyr")

Attaching package: 'dplyr'

The following objects are masked from 'package:dbplyr':

    ident, sql

The following objects are masked from 'package:stats':

    filter, lag

The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union

>
> data(mtcars)
>
> con <- DBI::dbConnect(RSQLite::SQLite(), dbname = "./mtcars.db")
> copy_to(con, mtcars, "mtcars")
>
> print(tbl(con, "mtcars"))
# Source:   table<mtcars> [?? x 11]
# Database: sqlite 3.19.3 [/home/tbrowne/scratch/mtcars.db]
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1  21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4
 2  21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4
 3  22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1
 4  21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1
 5  18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2
 6  18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1
 7  14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4
 8  24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2
 9  22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2
10  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4
# ... with more rows
>
>
tbrowne@calculon:~/scratch$ ls -l
total 4
-rw-rw-r-- 1 tbrowne tbrowne 194 Oct 31 11:04 dplysqlite.r
-rw-r--r-- 1 tbrowne tbrowne   0 Oct 31 11:04 mtcars.db

A: The copy_to() method for dbplyr sources (dbplyr:::copy_to.src_sql()) has a temporary argument which is set to TRUE by default. This means that the new table will be visible only for your active connection and disappear after you close the connection. The following should work as expected:
copy_to(con, mtcars, "mtcars", temporary = FALSE)

Alternatively, use dbWriteTable() as Tim suggests.

A: You're not using the pattern suggested by the RSQLite documentation.  That documentation uses dbWriteTable to copy a data frame into a SQLite table:
dbWriteTable(con, "mtcars", mtcars)

According to this documentation, your full code would look something like this:
con <- dbConnect(RSQLite::SQLite(), "./mtcars.db")
data(mtcars)
dbWriteTable(con, "mtcars", mtcars)
dbListTables(con)
# Fetch all query results into a data frame:
dbGetQuery(con, "SELECT * FROM mtcars")


text:
Q: Javascript ondrag, ondragstart, ondragend I've been trying to use ondrag() and some other functions on a div rendered dynamically on an HTML page.
None of these events seem to fire, nor do I get any errors.  I can't find much helpful documentation on it either.  Am I interpreting it wrongly, can you use these events to script functionality to drag a div around the screen?

A: Have a look at this documentation: https://developer.mozilla.org/En/DragDrop/Drag_and_Drop
Note: It does not work in every browser.
If you want a cross-browser support use jQuery: http://jqueryui.com/demos/draggable/
jQuery example:

Drag me around

Another example:

  This text may be dragged.

A: I haven't used drag myself much but I believe it's the drag "edit action" - eg selecting text and dragging it within a textbox/textarea.
You may need to implement your own onmousedown() onmouseup() and onmousemove() handlers for the functionality I think you're after

A: Short answer:
-s are not draggable by default, unlike -s. You must add draggable=true:

HTML

Works on Firefox 75 like that.

A: Is there content in the div? I don't think it's the element itself that gets dragged in this particular event.

A: An easy way to do this is with jQuery UI, make sure you use it after your dynamic div has been rendered.
$(document).ready(function () {
    $('.my_draggable_elements').draggable({
        drag: function(){
          // do something
        }
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to change the background image of the cell in didSelectRowAtIndexPath I want to change the background image of the cell when cell it is selected.
I have tried with this syntax:
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
 //for adding image
 cell.ImgCateg.image=[UIImage imageNamed:[ImgArr objectAtIndex:indexPath.row]];
     ...
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CRHomeCategCell *cell = (CRHomeCategCell*)[_tblCateg cellForRowAtIndexPath:indexPath];
    cell.ImgCateg.image = [UIImage imageNamed:@"DefaultBg.png"];
}

this changes image in the foreground not in the background.

Please help and thanks in advance.

A: You can set UITableviewCell's property setSelectedBackgroundView in cellForRowAtIndexPath method.
like ,
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
{
....
UIImageView *normalCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];

[normalCellBG setImage:[UIImage imageNamed:@"box_nonselected.png"]];//Set Image for Normal
[normalCellBG setBackgroundColor:[UIColor clearColor]];
[cell setBackgroundView:normalCellBG];

UIImageView *selecetedCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
[selecetedCellBG setImage:[UIImage imageNamed:@"box_selected.png"]];//Set Name for selected Cell
[selecetedCellBG setBackgroundColor:[UIColor clearColor]];
[cell setSelectedBackgroundView:selecetedCellBG ];

}

look this SO question.

A: You can do this on following way:
UIImage *cellImage = [UIImage imageNamed:@"myimage.png"];
UIImageView *cellView = [[UIImageView alloc] initWithImage:cellImage];
cellView.contentMode = UIContentViewModeScaleToFill;
cell.backgroundView = cellView;


text:
Q: Can get a full view of my car model on a Ray-tracer I currently have an ray-tracer that can read .obj models and then render the objects described on them. Until now, I was basically working with .obj models where the vertices where around the origin, generally closer than 10 of distance, at maximum being around 100.
Now, I downloaded a different model, where the vertices are far away from the origin, Always at least at hundreds of units from the origin, some vertices being about 5000 away in some axis.
The problem is that now I cannot focus the entire car!
One of my tests was with the distance from camera to origin of -3639.
And the result was this:

Then I step the camera away at -4639 and what was produced was this:

Changing my approach, decided to approach it, placing the camera at -2639
The result:

So at -2639 a I am being able to visualize the entire car but it does not fit in my field of view. At -3669 the light is already fading away by some reason.
I imagine that might be possible to see the full car proper lightened using a intermediate distance between -2669 and -3669 and also experimenting with the filed of view value, but there is something odd about the Light not covering the entire car at -3669 and I would like to find out the reason.
So I would appreciate suggestions about the cause of this issue and how to proceed in this kind of situation, how to focus the entire car.

A: Your question mentions you are changing the camera position. However, the images show the lighting area changing between the various cases. Just a spotlight in one case, and more of the car being lit in the other.
Most likely, in the third case, nothing of the car is lit, hence everything comes up black. Start by fixing the light staying the same when the camera moves, and see if it fixes your issue.

A: If you move the camera: It could help looking into the settings for the front and back clipping planes.
If you don't move the camera: The FOV show be larger if the object is larger. I would avoid doing this as this likely will lead to more problems when you read more than one object that are different.
Personally I would scale the input from the file. Ideally to some SI-unit that makes sense.


text:
Q: Ubuntu 12.04: why could it not read DVD? (Encryption) How to play commercial DVDs on lenovo t-500 laptop?
I have Ubuntu 12.04, all updates
Could not read dvd despite having restricted extras
I tried the following, but VLC does not play DVDs.
 sudo apt-get install libdvdnav4 libdvdread4 gstreamer0.10-plugins-bad gstreamer0.10-plugins-ugly

 sudo /usr/share/doc/libdvdread4/install-css.sh

A: Try this
sudo wget --output-document=/etc/apt/sources.list.d/medibuntu.list http://www.medibuntu.org/sources.list.d/$(lsb_release -cs).list && sudo apt-get --quiet update && sudo apt-get --yes --quiet --allow-unauthenticated install medibuntu-keyring && sudo apt-get --quiet update

And then
sudo apt-get install libdvdcss2

Followed by
sudo apt-get install w32codecs

If you are on 64 bit install w64codecs instead however.

A: Open VLC Player. Press on Ctrl+D (or choose Media --> Open DISC). From there choose your Media type then click on Play. See pic


text:
Q: Could someone tell me how this is derived? I am referring to the solution to Exercise 7.39(c) in the book Probability and Random Processes for Electrical and Computer Engineers, and find one step of derivation hard to understand.
The problem is here:

Use the law of total probability to solve the following problems:
(c) Evaluate $\text{E}[Xe^Y]$ if $X \sim \text{uniform}[3, 7]$, and given $X = x$, $Y \sim N(0, x^2)$.

The solution is here:

Begin in the usual way by writing
$$\begin{align}
\text{E}[Xe^Y] &=\int_{-\infty}^{\infty}\text{E}[Xe^Y \mid X = x]f_{X}(x)\text{ d}x = \int_{-\infty}^{\infty}\text{E}[xe^Y \mid X = x]f_{X}(x)\text{ d}x \\
&= \int_{-\infty}^{\infty}x\text{E}[e^Y \mid X = x]f_{X}(x)\text{ d}x
\end{align}$$
Now observe that
$$\text{E}[e^Y \mid X = x] = \left.\text{E}[e^{sY} \mid X = x]\right|_{s=1}= \left.e^{s^2x^2/2}\right|_{s=1} = e^{x^2/2}\text{.}$$

Can someone tell me how the step $E[e^{sY}|X=x]|_{s=1} =  e^{s^2x^2/2}|_{s=1}$ in part(c) is derived? Thanks a lot in advance!

A: Recall that the moment-generating function (MGF) of a random variable $Y$ is $\mathbb{E}[e^{tY}]$.
In this case, observe that the MGF of $Y \mid X = x$ is thus $\mathbb{E}[e^{tY} \mid X = x]$.
Recall also that if $Z \sim N(\mu, \sigma^2)$ that its MGF is given by
$$M_{Z}(s) = \exp\left(\mu s+ \dfrac{\sigma^2}{2}s^2 \right)\text{.}$$
Thus, since $Y \mid (X = x) \sim N(0, x^2)$,
$$\mathbb{E}[e^{sY} \mid X = x] = \exp\left(0s + \dfrac{x^2}{2}s^2 \right) = e^{s^2x^2/2}\text{.}$$

A: A different but equivalent approach is the following:
$$\mathbb{E}[Xe^Y]=\mathbb{E}[\mathbb{E}[Xe^Y|X]]=\mathbb{E}[X\mathbb{E}[e^Y|X]]$$
Now observe that
$$Z=(e^Y|X=x)\sim \text{Lognormal}(0;x^2)$$
(Here is the link to the lognormal)
Thus
$$\mathbb{E}[X\mathbb{E}[e^Y|X]]=\mathbb{E}[Xe^{\frac{X^2}{2}}]=\frac{1}{4}\int_3^7xe^{\frac{x^2}{2}}dx=\frac{e^{\frac{9}{2}}(e^{20}-1)}{4}$$


text:
Q: Write a CSV file asynchronously in Python I am writing a CSV file with the following function:
import csv
import os
import aiofiles

async def write_extract_file(output_filename: str, csv_list: list):
    """
    Write the extracted content into the file
    """
    try:
        async with aiofiles.open(output_filename, "w+") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
            writer.writeheader()
            writer.writerows(csv_list)
    except FileNotFoundError:
        print("Output file not present", output_filename)
        print("Current dir: ", os.getcwd())
        raise FileNotFoundError

However, as there is no await allowed over writerows method, there are no rows being written into the CSV file.
How to resolve this issue? Is there any workaround available?
Thank you.
Entire code can be found here.

A: You can use aiocsv. Here is a quick example of writing a row to a CSV file asynchronously:
import asyncio
import aiofiles
from aiocsv import AsyncWriter

async def main():
    async with aiofiles.open('your-path.csv', 'w') as f:
        writer = AsyncWriter(f)
        await writer.writerow(['name', 'age'])
        await writer.writerow(['John', 25])

asyncio.run(main())

For more examples follow: https://pypi.org/project/aiocsv/

A: In my opinion it's better not to try to use the aiofiles with the csv module and run the synchronous code using loop.run_in_executor and wait it asynchronously like below:
def write_extract_file(output_filename: str, csv_list: list):
    """
    Write the extracted content into the file
    """
    try:
        with open(output_filename, "w+") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames=columns.keys())
            writer.writeheader()
            writer.writerows(csv_list)
    except FileNotFoundError:
        print("Output file not present", output_filename)
        print("Current dir: ", os.getcwd())
        raise FileNotFoundError

async def main():
    loop = asyncio.get_running_loop()
    await loop.run_in_executor(None, write_extract_file, 'test.csv', csv_list)

A: You can use aiofiles, you just gotta convert the dict to a row :)
import aiofiles

async def write_extract_file(
    output_filename: str, csv_list: list
):

    cols = columns.keys()

    async with aiofiles.open(output_filename, mode='w+') as f_out:

        await f_out.write(','.join(cols)+'\n')

        for data in csv_list:

            line = []

            for c in cols:
                line.append(str(data[c]) if c in data else '')

            line = ','.join(line) + '\n'

            await f_out.write(line)


text:
Q: XSLT: access the xml configuration in the XSLT file I am trying to print the fruit names which is not in the data:fruit. In my case I expect Pineapple, Kiwi. I am accessing the data:fruit in the XSLT xml configuration by 'select="document('')/*/data:fruit/attribute/@value"'. Currently I am getting the following error.
Error:

Error executing XSLT at line 24 : Exception thrown by URIResolver
resolving `` against `'. Found while atomizing the first argument of
fn:string-join()

Please check the following xsltfiddle link:
https://xsltfiddle.liberty-development.net/jyfAiC7/4
xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:exsl="http://exslt.org/common"
                xmlns:set="http://exslt.org/sets"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                extension-element-prefixes="exsl"
                version="2.0">

    <xsl:output method="xml" indent="yes" encoding="UTF-8"/>
    <data:fruit>
        <attribute  value="Pineapple" />
        <attribute  value="Kiwi" />
        <attribute  value="Apple" />
        <attribute  value="Orange" />
        <attribute  value="Banana" />
        <attribute  value="Cherry" />
        <attribute  value="Peach" />
    </data:fruit>

    <xsl:template match="/">

            <xsl:variable name="fruitMissing">
                <xsl:for-each select="document('')/*/data:fruit/attribute/@value">
                    <xsl:variable name="fruit" select="."/>
                    <xsl:if test="count(//root/details/item/line[contains(.,$fruit)])=0"><xsl:value-of select="."/>,</xsl:if>
                </xsl:for-each>
            </xsl:variable>

            <xsl:value-of select="$fruitMissing"/>
    </xsl:template>
</xsl:stylesheet>

xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<root>
     <header/>
     <details>
          <item>
               <line>14.04.22 5:04:30;Apple;Finished</line>
          </item>
              <item>
               <line>14.04.22 3:36:42;Apple;Finished</line>
          </item>
          <item>
               <line>14.04.22 4:03:47;Orange;Finished</line>
          </item>
            <item>
               <line>14.04.22 2:40:33;Orange;Finished</line>
          </item>
          <item>
               <line>14.04.22 3:37:12;Banana;Finished</line>
          </item>
          <item>
               <line>14.04.22 3:36:59;Cherry;Finished</line>
          </item>
          <item>
               <line>14.04.22 3:36:57;Peach;Finished</line>
          </item>
     </details>
     <summary/>
     <statistics/>
     <exceptions/>
</root>

A: I would suggest you do it this way:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>

<xsl:key name="existing-fruit" match="item" use="tokenize(line, ';')[2]" />

<xsl:variable name="fruit">
    <attribute value="Pineapple" />
    <attribute value="Kiwi" />
    <attribute value="Apple" />
    <attribute value="Orange" />
    <attribute value="Banana" />
    <attribute value="Cherry" />
    <attribute value="Peach" />
</xsl:variable>

<xsl:template match="/" >
    <xsl:variable name="xml" select="." />
    <xsl:value-of select="$fruit/attribute[not(key('existing-fruit', @value, $xml))]/@value" separator=","/>
</xsl:template>

</xsl:stylesheet>

Beside being shorter and more efficient, it also avoids possible false positive match on other values included in line.

Demo: https://xsltfiddle.liberty-development.net/jyfAiC7/5

A: Try this XSLT2:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:exsl="http://exslt.org/common"
            xmlns:set="http://exslt.org/sets"
            xmlns:data="http://mulocal/host"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            extension-element-prefixes="exsl"
            version="2.0">

<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<data:fruit>
    <attribute  value="Pineapple" />
    <attribute  value="Kiwi" />
    <attribute  value="Apple" />
    <attribute  value="Orange" />
    <attribute  value="Banana" />
    <attribute  value="Cherry" />
    <attribute  value="Peach" />
</data:fruit>

<xsl:template match="/">
    <xsl:variable name="varInput" select="root"/>
        <xsl:for-each select="document('')/*/data:fruit/attribute/@value">
            <xsl:variable name="fruit" select="."/>
              <xsl:if test="count($varInput/details/item/line[contains(.,$fruit)])=0">
                <xsl:value-of select="."/><xsl:text>,</xsl:text>
            </xsl:if>
         </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Result:
<?xml version="1.0" encoding="UTF-8"?>Pineapple,Kiwi,


text:
Q: "Unaligned address in store" error when saving a word I'm writing a program in assembly that takes one character of user input at a time and inserts it into an alphabetized string using recursion. I've been staring at this for a long time now, but it still seems like it should work. Some other eyes on this will be greatly appreciated.
        .data
text1:  .asciiz "To begin, type a lower case letter.\n"
text2:  .asciiz "Any time you are prompted for an input, you may type a 'P' to print the alphabetized string.\n"
text3:  .asciiz "You can also type 'Q' to end the program.\n\n"
text4:  .asciiz "Input: "
text5:  .asciiz "End."
err:    .asciiz "Something broke\n"
str:    .asciiz "abcdefghijklmnopqrstuvwxyz"
buffer: .space 30
in:     .space 4

        .text
main:   la $a0, text1              #opening statements
        li $v0, 4
        syscall
        la $a0, text2
        syscall
        la $a0, text3
        syscall

input:  la $a0, text4
        li $v0, 4
        syscall
        li $v0, 12                 #get input character
        syscall
        move $t0, $v0
        li $a0, 0x0a                #print new line
        li $v0, 11
        syscall

        beq $t0, 0x50, print        #input is 'P'; print out string
        beq $t0, 0x51, end          #input is 'Q'; end

        la $t1, str
search: lb $t2, 0($t1)              #search for the starting location
        beqz $t2, error
        beq $t2, $t0, phase1
        addi $t1, $t1, 1
        j search

phase1: sw $t2, ($sp)           #store the letter on the stack
        sub $sp, $sp, 4
        sw $t1, ($sp)           #store address of the letter on the stack
        sub $sp, $sp, 4
        addi $t1, $t1, 1        #increment address
        lb $t2, 0($t1)          #getting next letter to prepare for next loop
        beqz $t2, phase2        #if end of string is reached, come out of loop
        jal phase1
        j input

phase2: lw $ra, ($sp)           #pull return location off stack
        addi $sp, $sp, 4
        lw $t3, ($sp)           #pull letter address off stack
        addi $sp, $sp 4
        lw $t4, ($sp)           #pull letter off stack
        addi $sp, $sp, 4
        addi $t3, $t3, 1        #increment old address to get new address
        sw $t4, 0($t3)          #store the letter in its new location
        jr $ra

error:  la $a0, err
        li $v0, 4
        syscall
        j input

print:  la $a0, str
        li $v0, 4
        syscall
        li $a0, 0x0a
        li $v0, 11
        syscall
        j input

end:    la $a0, text5
        li $v0, 4
        syscall
        li $v0, 10
        syscall

Specifically, I am getting errors on the line:
sw $t4, 0($t3)

It says: "Unaligned address in store: 0x100100e7"
After that, I get "Exception 5 [Address error in store] occurred and ignored"
followed by an unending chain of "Exception 6 [Bad instruction address] occurred and ignored"
I am using QtSpim.

A: You're attempting to write a word to a non-word-aligned address with sw (store word). words on MIPS32 are 4 bytes long, and must be aligned on an address that is a multiple of 4.You can store halfwords to halfword-aligned locations (address multiple of 2) by sh (store halfword), and bytes to byte-aligned addresses with sb (store byte, unsurprisingly).


text:
Q: View "cvs diff" output in two columns with vim I have "cvs diff" output (for all files in project) in unified diff format.
Format could be like this:
Index: somefile.cpp
===================================================================
RCS file: /CVS_repo/SomeProject/somefile.cpp,v
retrieving revision 1.19
diff -r1.19 somefile.cpp
31c31
<       return "Read line four times";
---
>       return "Read line five times";
36c36
<       return "Make a bad thing";
---
>       return "Make a good thing";
Index: otherfile.cpp
===================================================================
RCS file: /CVS_repo/SomeProject/otherfile.cpp,v
retrieving revision 1.19
<       ........
---
>       ........

or even like this:
Index: somefile.cpp
===================================================================
RCS file: /CVS_repo/SomeProject/somefile.cpp,v
retrieving revision 1.19
diff -u -r1.19 somefile.cpp
--- somefile.cpp 13 Mar 2013 08:45:18 -0000      1.19
+++ somefile.cpp 26 Mar 2013 08:10:33 -0000
@@ -28,12 +28,12 @@
 //---------------------------------------------------------------------------
 extern "C" char *FuncGetSomeText()
 {
-       return "Read line four times";
+       return "Read line five times";
 }
 //---------------------------------------------------------------------------
 extern "C" char *FuncGetAwesomeText()
 {
-       return "Make a bad thing";
+       return "Make a good thing";
 }
 //---------------------------------------------------------------------------
Index: otherfile.cpp
===================================================================
RCS file: /CVS_repo/SomeProject/otherfile.cpp,v
retrieving revision 1.19
diff -u -r1.19 otherfile.cpp
--- otherfile.cpp 13 Mar 2013 08:45:18 -0000      1.19
+++ otherfile.cpp 26 Mar 2013 08:10:33 -0000
@@ -28,12 +28,12 @@
 //---------------------------------------------------------------------------
 extern "C" char *Func()
 {
-       .......
+       .......
 }
 //---------------------------------------------------------------------------

Is there any way to view this text side-by-side with vim?
Or maybe it's possible to change default diff tool in cvs to vimdiff?

A: Some sed magic help me:
\cvs -n diff -u > ~diff.tmp; vim -O <(sed -r -e 's/^\+[^\+]+.*$//g;s/^\+$//g' ~diff.tmp) <(sed -r -e 's/^-[^-]+.*$//g;s/^-$//g' ~diff.tmp) +'set scb | set nowrap | wincmd w | set scb | set nowrap'

It is not perfect solution, but better then nothing. Here what this script doing:
\cvs -n diff -u > ~diff.tmp;

Write CVS diff output in unified format (-u option) to temp file ~diff.tmp. '\' char prevent from taking alias of "cvs" command.
(sed -r -e 's/^\+[^\+]+.*$//g;s/^\+$//g' ~diff.tmp)
(sed -r -e 's/^-[^-]+.*$//g;s/^-$//g' ~diff.tmp)

This commands output text from ~diff.tmp, replace lines beginning with '+' and '-' symbols with empty line.
vim -O <(sed...) <(sed...) +'set scb | set nowrap | wincmd w | set scb | set nowrap'

Open two windows (-O option) with sed's output in each. Command followed '+' set srollbind on and nowrap for first window, then switch to second window (with 'wincmd w') and do same things


text:
Q: filter pipe always logs undefined I am trying to filter data in a table using input. For that I have created a custom pipe named textFilter as follows:
import {Pipe, PipeTransform} from '@angular/core';
import { Person } from '../Models/person';

@Pipe({
    name: 'textFilter',
    pure: false
})
export class TextFilterPipe implements PipeTransform {
    transform(people: Person[], filter: string): any {
        if (!people || !filter) {
            return people;
        }
        people.forEach(person => {
           console.log(person.firstName); //<-- this line logs undefined
        });
        console.log(filter);
        return people.filter(person => person.firstName.indexOf(filter) !== -1);
    }
}

Then I am using it like this:

  <input type="text" [(ngModel)]="query" (keyup)="0" />

        First Name
        Last Name

        {{person.firstName}}
        {{person.lastName}}

Here is my Component.ts:
import { Component, OnInit } from '@angular/core';
import { Person } from '../../Models/person';

@Component({
  selector: 'app-auto-complete',
  templateUrl: './auto-complete.component.html',
  styleUrls: ['./auto-complete.component.css']

})
export class AutoCompleteComponent implements OnInit{

    constructor() {}

    query: string;
    people: Person[];

    ngOnInit() {
        this.query = '';
        this.people  = [
            new Person ("Shane", "Watson", "Australia"),
            new Person ("David", "Warner", "Australia"),
            new Person ("Ricky", "Ponting", "Australia"),
            new Person ("Adam", "Gilchrist", "Australia"),
            new Person ("Andrew", "Symonds", "Australia"),
            new Person ("Sachin", "Tendulkar", "India"),
            new Person ("Rahul", "Dravid", "India"),
            new Person ("Virender", "Sehwag", "India"),
            new Person ("Mahendra", "Dhoni", "India"),
            new Person ("Virat", "Kohli", "India"),
            new Person ("Gautam", "Gambhir", "India")
        ];
    }
}

Here is my person class:
export class Person {
    firstName: string;
    lastName: string;
    country: string;

    constructor(firstName: string, lastName: string, country: string) {}
}

Why person.firstName is always undefined inside TextFilterPipe?
Update:
If I log person instead of person.firstName then I get
Person {}

printed on console

A: export class Person {
    firstName: string;
    lastName: string;
    country: string;

    constructor(firstName: string, lastName: string, country: string) {}
}

If the above is the definition of your Person class, then that's your problem - in your constructor, you're receiving 3 string values, but you're not doing anything with them. You need to assign them to your properties.
So, you need to do:
constructor(firstName: string, lastName: string, country: string) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.country = country;
}

Or preferably:
constructor(public firstName: string, public lastName: string, public country: string) {}

which is a Typescript shortcut that does the same thing. Note that I had to put an access modifier on the parameter names to get the automatic assignment to work. You can use public or private, but you must use one.


text:
Q: IDbContextTransaction not working rollback I have a windows application with .net framework 4.6 and the repository using .net framework core 3.1. I can get the transaction correctly, but it seems that it is not saving the changes in the transaction and when it falls into the catch error, it goes through the Rollback but does not perform any reversal of the saved record. My code basically saves a new order and then I simulate the error to validate the rollback and not save the order.
private async Task ManageNFeConsultaLote(EventoNFe eventoNFe, retConsReciNFe retorno)
{
    _transactionRepository = (ITransactionRepository)_serviceProvider.GetService(typeof(ITransactionRepository));
    using (var transaction = _transactionRepository.GetTransaction())
    {
        try
        {
            _faturamentoService.CreateOrder();
            transaction.Commit();
        }
        catch (Exception e)
        {
            transaction.Rollback();
            throw e;
        }
    }
}

This works fine in the API application, but in the windows application it is not doing rollback. should i use a different approach because etar in .net framework 4.6 and context uses .net framework core 3.1?


text:
Q: The Web server is configured to not list the contents of this directory Using Visual Studio 2012:

*

*I created an "ASP.NET Empty Web Application" (using C#).

*I used NuGet to install the FubuMVC package.

*When I run the application (using IIS Express), I get the "Welcome to FubuMVC!" page which tells me to delete the FubuMVC.GettingStarted.dll file and to set the home page.

*So I do both of those things, implementing a HomeController that simply returns "Hello World" from Index.

Rather than the expected "Hello World", I get an IIS error: The Web server is configured to not list the contents of this directory.
What have I done wrong?

A: try this
cmd => don't forget to run as administrator
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

A: Did you activate FubuMVC in your Global.asax?  I usually see that error when there is no FubuMVC application.
So in Application_Start() (or whatever it's really called), you'll need something like:
FubuApplication.DefaultPolicies().StructureMap(new Container()).Bootstrap();
Where you're telling it:
1.) What are the policies/conventions to use
2.) What's your IoC container

A: Usually if I run into this it's because I've got a conflict with a route and a folder in the project. For example, I might have a folder called 'Unit' and inside it I have a class called 'UnitEndpoint' with a method 'get_unit' (which should map to '/unit' as a route, assuming I'm using the FubuMVC defaults).
In that case, browsing to '/unit' will result in this error because IIS thinks I'm trying to list the contents of the 'Unit' folder. Renaming the endpoint or the folder to remove the conflict will fix it (e.g., renaming the 'Unit' folder to 'Units').

A: Just tried reproducing your problem with a brand new project; it turns out that problem is that the instructions in the example haven't kept up with the changes in FubuMVC.
The instructions tell you to create a class called 'MyHomeController' and add the Index() method to it. This used to work, because one of the default rules for routes was to use any class with a name that ends in 'Controller'.
But the default has been changed in more recent versions, and the rule now looks for classes ending in 'EndPoint'.
So if you change the name of the class from 'MyHomeController' to 'MyHomeEndpoint', it should work.
Also, remember that the application pool needs to restart for the new configuration to take effect, so you might have to touch your web.config (or force IISExpress to restart).

A: I suggest that you recompile your application or at least touch your global.asax -- looks like you need to rerun the App_Start method.


text:
Q: How to send a variable route-to-route in Silex 2? Making my first Silex Application and I need some help, I'm writting a route to show an item and then edit it, so first of all this is my 'get' route which receive the code of the item to show its details.
$app->get('/cat/productos_edit/{key}', function($key) use($app){

$app['twig']->addGlobal('itemtoedit', $key); //This is how I'm trying to do it

return $app['twig']->render('catalogo/productos/edit.html',[
    'title' => 'Catálogo - Productos'
  ]);
});

So in 'post' route I need to get that variable to edit the item,
 $app->post('/cat/productos_edit/', function() use($app){
    echo $app['itemtoedit'];
 })->bind('cat.productos.edit');

But then I got this error:

So I think that maybe I'm missing something, Hope that ypu can help me.

A: PHP / Silex will not keep any context between your get and post so IMHO you should do that :
$app->post('/cat/productos_edit/{key}', function($key) use($app){
    // get your item from database with its key
    // update item with your post payload
})->bind('cat.productos.edit');


text:
Q: How to replace single-quote with double-quote in sql query - oracle 10g? How can I replace single-quote (') with double-quote (") in sql query - oracle 10g?

A: You can use Ansi-codes as well, to make it more crystal what is happening:
SELECT someString
      ,replace(someString, Chr(39), Chr(34)) as replacedString
FROM   (SELECT ' abc ' || Chr(39) || ' def ' as someString
        FROM   Dual)

39 is a single quote, 34 a double quote

A: This should work:
UPDATE myTable
SET myField = REPLACE(myField, '''', '"');

A: If you have a variable in single quotes with an apostrophe e.g. 'John's Book', simply insert 2 apostrophes. i.e. 'John''s Book'. NOTE: Do NOT use a double quotation "

A: This should work:
UPDATE myTable
SET field = replace(your_string,Chr(39),Chr(39)||Chr(39));

A: Ten bucks says this thing is wide-open to SQL injection and the correct answer is to use parameterization.


text:
Q: Unsafe.defineClass hangs - slow reflection calls I'm oberserving extreme long running requests (>30s) in a Java 8 / Spring 5 / Tomcat 8.5 web application. The majority of requests responds normally.
It's remarkable that the frequency of long runners increases after some days of uptime.
Threaddumps show that Unsafe.defineClass is hanging:
at sun.misc.Unsafe.defineClass(Native Method)
at sun.reflect.ClassDefiner.defineClass(ClassDefiner.java:63)
at sun.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:399)
at sun.reflect.MethodAccessorGenerator$1.run(MethodAccessorGenerator.java:394)
at java.security.AccessController.doPrivileged(Native Method)
at sun.reflect.MethodAccessorGenerator.generate(MethodAccessorGenerator.java:393)
at sun.reflect.MethodAccessorGenerator.generateMethod(MethodAccessorGenerator.java:75)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:53)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.core.annotation.AnnotationUtils.getValue(AnnotationUtils.java:1328)
at org.springframework.core.annotation.AnnotatedElementUtils$MergedAnnotationAttributesProcessor.getAdaptedValue(AnnotatedElementUtils.java:1627)
at org.springframework.core.annotation.AnnotatedElementUtils$MergedAnnotationAttributesProcessor.overrideAttributes(AnnotatedElementUtils.java:1610)
at org.springframework.core.annotation.AnnotatedElementUtils$MergedAnnotationAttributesProcessor.postProcess(AnnotatedElementUtils.java:1598)
at org.springframework.core.annotation.AnnotatedElementUtils$MergedAnnotationAttributesProcessor.postProcess(AnnotatedElementUtils.java:1515)
at org.springframework.core.annotation.AnnotatedElementUtils.searchWithFindSemantics(AnnotatedElementUtils.java:1145)
at org.springframework.core.annotation.AnnotatedElementUtils.searchWithFindSemantics(AnnotatedElementUtils.java:1066)
at org.springframework.core.annotation.AnnotatedElementUtils.searchWithFindSemantics(AnnotatedElementUtils.java:1038)
at org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotationAttributes(AnnotatedElementUtils.java:650)
at org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation(AnnotatedElementUtils.java:726)
....

Has anybody ever seen this problem?

A: Could it be that you are running out of Metaspace either by using a conservative -XX:MaxMetaspaceSize or not having enough RAM on the server? Since GC runs on Metaspace your slowness might be the result of it struggling to clean it. By default the Metaspace memory is collected if it reaches the MaxMetaspaceSize so this 30 sec pause might be the GC.
There is however a bigger question. What in your code is allocating these classes and why does it happen often enough to fill Metaspace. Normally classes are created during startup and after that much less frequently. Perhaps you are doing  hot deployments and the ClassLoader is leaking?
In pre Java 8 this could be caused by the GC and PermGen running out e.g. as asked in this question where it caused OutOfMemoryError.


text:
Q: How to safely insert a jsonb into a table? I wrote this prepared statement for inserting jsonb data into a table:
PREPARE posts_insert(jsonb) AS
  INSERT INTO posts(data) VALUES($1) RETURNING ID;

Though I'm concerned if this query has some kind of vulnerabilities. The json comes from the client side of my application, so it could basically contain anything. Is it dangerous to use jsonb (that comes from the user) within queries? What can I do to make it safe or more safe?

A:
Is it dangerous to use jsonb (that comes from the user) within queries?

Not it's not dangerous because that JSON is essentially just text as it comes from the client, and you've protected yourself by using prepared statements. This text will be transparently fed to the internal function jsonb_in, and you'll be totally safe.


text:
Q: how to convert this query in codeigniter method chaing format "SELECT invester_details.invester_name,invester_details.invester_contact,add_project.project_name,
add_project.project_id
FROM invester_details
JOIN investment ON invester_details.invester_id=investment.invester_id
JOIN add_project ON investment.project_id=add_project.project_id
WHERE CONCAT(invester_name,invester_contact,project_name)
LIKE '%$filtervalues%' AND add_project.project_id LIKE '$filtervalue'";


text:
Q: How to install the latest macOS on a used Mac easily? I am struggling to figure out the best route to take for this: I have several Macs that have been sent back to me within my organization that I need to reset and prepare for the next user but the one thing we want above all else is the ability for the devices to be able to reset and then have the current macOS installed.
I have tried installing from USB but that doesn't seem to be what we are looking for as this requires that I set up the whole device, enable USB, and then install macOS.
How can I install the latest macOS easily (assume the Mac supports it) and such that the next user starts using it fresh as if the Mac just came out of the box?

A: If these computers are Intel computers, use recovery mode. At startup press:

*

*⌘+R: Reinstall the operating system already installed

*⌘+⌥+R: Reinstall the latest macOS operating system available

*⌘+⌥+⇧+R: Reinstall the original macOS operating system for that device, if available

https://support.apple.com/guide/mac-help/use-macos-recovery-on-an-intel-based-mac-mchl338cf9a8/mac
If these devices are Apple Silicon, hold the power button at startup. You can only reinstall using this approach the latest OS.
Before reinstalling, you'll need to erase the disk. You can do that using the information in this support articles: https://support.apple.com/kb/HT208496

Some issues can arise if the user registered the device on Find My and didn't properly de-register it. If you are regularly following this process, users should sign out of Find My (ideally never sign in in the first place if it's a company device...) and ensure they've removed their account.
This document outlines everything Apple recommends before selling. In the future, Steps 2-6 should be done by the user before sending it to you, if possible.
https://support.apple.com/HT201065


text:
Q: Instances of CultureInfo (from same culture) changing based on OS I've a web site which writes a date like this:
CultureInfo cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures).FirstOrDefault(c => string.Equals(c.TwoLetterISOLanguageName, MvcApplication.Language));
return string.Concat(date.Day, ".", cultureInfo.DateTimeFormat.GetAbbreviatedMonthName(date.Month));

In both my PC (Windows 7, Service Pack 1, Spanish culture) and the server (Windows Server 2012, English Culture) the MvcApplication.Language is es so the culture I get from the list is: es-ES.
I'd expect they both write the same string (they have different cultures, but I'm not using CurrentCulture). However the results are abr in my PC and Abr. in the server.
I've tried this isolated from MvcApplication.Language using the LinqPAD but it is still different. I've printed the arrays of AbbreviatedDayNames and AbbreviatedMonthNames and they are different in each computer.
Am I doing something wrong or this is the expected behavior? How can I do to make it completely independent from Windows / User Culture?

A: A you can see in this link from MSDN, culture info can be different on some windows versions.

Remember that the culture names and identifiers represent only a subset of cultures that can be found on a particular computer. Windows versions or service packs can change the available cultures. Applications add custom cultures using the CultureAndRegionInfoBuilder class. Users add their own custom cultures using the Microsoft Locale Builder tool. Microsoft Locale Builder is written in managed code using the CultureAndRegionInfoBuilder class.

If you want some format to be static, you can build your own CultureInfo object and customize the behaviour of it, setting your own Date Time format, as an example


text:
Q: char array compilation error What is the problem in my code? It does not compile..
   class FileNames
   {
        public:
           static char* dir;
           static char name[100];

           static void Init3D()
           {
            FileNames::dir = "C://3D//";
            FileNames::name = "abc";
           }
   };

A: You cannot assign to an array, so FileNames::name = "abc" fails (char arr[4] = "abc" works, however, because this is a direct initialization, not assignment). Either use a char* here as well, or use strcpy to copy data to the array or better a std::string which avoids many of the downsides of raw strings.
Most importantly you need to define your static members somewhere at global scope, outside a function:
char FileNames::name[100];. At this time initialization syntax using = would be possible even with the array, but the string to be assigned needs to have the same length as the array.

A: There are two problems with your code:
1) You've duplicated the variable name (with two different types).
2) You can't initialise static members like that (see example below).
The last thing isn't a problem as such, but you should consider using std::string instead, as that encapsulates string functionality so that you don't need to deal with raw pointers. It's a lot less painful, especially if you're new to this sort of thing.
Change it to this:
// Header file
class FileNames
{
private:
    static char* name;
public:
    static char* dir;
};

CPP file
#include "FileNames.h"

char* FileNames::name = "abc";
char* FileNames::dir = "C://3D//";

// Now use your class...

A: Try initializing like this:
class FileNames
{
    public:
       static char* dir;
       static char name[];

};

char *FileNames::dir = "C://3D//";
char FileNames::name[100] = "abc";

A: Did you remember to actually define the static members outside of the class?  Also, I don't believe you need to resolve the scope unless you're actually outside of the class.

A: Use:
FileNames::dir = new char[strlen("C://3D//")];
strcpy(FileNames::dir, "C://3D//");
strcpy(FileNames::name, "abc");

Also, don't forget to #include <cstring> and to later delete[](FileNames::dir)


text:
Q: Application Freezes When Sorting 1000+ numbers I made a program that generates and sorts data but when I try generating about 1000 numbers the program freezes and wont respond. It also loads in data from a file but any big file freezes the program. Is there any way around this?
public void generateData(int number)
    {
        //Clear text boxes and initialize random
        Unsorted_Box.Clear();
        Sorted_Box.Clear();
        Random random = new Random();
        dataArray = new int[number];

        for (int i = 0; i < number; i++)
        {
            //Generate random numbers using max and min values, ammount and store in unsorted box
            dataArray[i] = random.Next((int)Min_UpDown.Value, (int)Max_UpDown.Value);
            Unsorted_Box.Text += dataArray[i] + ", ";
        }
    }

A: If the program is freezing because it's taking a long time to process, then you could consider doing that processing on a background thread.  This will allow the rest of the program to remain responsive.
If the program is freezing because of a dead lock, then you can use the tools in visual studio to identify where this is happening.  if it's reproducible then pause in debugger and see where the problem is.
If it's neither of these 2, can you share the code you're using?

A: Try to uncheck ContextSwitchDeadlock under Debug->Exceptions->Managed Debugging Assistants.


text:
Q: React Native fatal error: 'folly/Portability.h' file not found on XCode 12.5.1 When i try to run the code, it is giving an error as follows from SignalProtocolC.

In file included from /Users/tsuser/Desktop/user/MyProject/MyProject-MOBILE/ios/Pods/SignalProtocolC/src/curve25519/ed25519/tests/internal_slow_tests.c:10:
/Users/tsuser/Desktop/user/MyProject/MyProject-MOBILE/ios/Pods/Flipper-Folly/folly/synchronization/Utility.h:19:10: fatal error: 'folly/Portability.h' file not found

This was working properly before the xcode update. I have looked other similar questions in stack overflow. but all are giving solutions for older versions which are not working for issue in xcode 12.5.1. One of the answer I tried is in following link.
https://stackoverflow.com/a/57709111/10722603


text:
Q: Проблема с Gradle при работе с Flutter на Android Studio Обнаружил проблему при работе с Flutter-ом на Android Studio.
Начал проходить учебный курс на Udacity, установил Dart-плагин, Flutter-плагин,  и столкнулся с тем, что при импорте проекта полугодичной давности, которому нужен Gradle версии не ниже 4.6, Gradle-wrapper выбирает версию 4.4.
Проблема в том, что исправить это так, как описано здесь - не выходит. Т.е. когда заходишь в File -> Project Structure -> Project в Android Studio из java или kotlin-проекта, то все ОК - можно выбирать версию Gradle:

А когда идешь тем же путём из Flutter-проекта, то видишь следующее:

Похоже, что это баг Flutter-плагина для Android Studio и выбирать версию Gradle из интерфейса Android Studio не получится.

A: Проблему удалось решить только вручную, исправив в файле проекта C:\Users\...\android\gradle\wrapper\gradle-wrapper.properties используемую в проекте версию Gradle с 4.4 на 4.6.


text:
Q: Sqldeveloper to define variable of RAW type I'm using SQL developer (Oracle's SQL developer) and have a table with column of raw type. Example values in this column are:
ABE478C1388D9015875646AD16010B13
D78ABC797BC898AA9710BC090913B15C

I want to use these values inside my SELECT statement as variables, which I define beforehand:
define carHashId = 'ABE478C1388D9015875646AD16010B13'

When I use this variable inside the WHERE clause:
WHERE hid = &&carHashId
I always get the following error:
*Cause:    An identifier with more than 128 bytes was specified,
           or a password identifier longer than 30 bytes was specified.
*Action:   Specify at most 128 bytes for identifiers,
           and at most 30 bytes for password identifiers.

What can I do about this?

A: Use HEXTORAW()
select HEXTORAW('ABE478C1388D9015875646AD16010B13') from dual ;
Note that
utl_raw.cast_to_raw('ABE478C1388D9015875646AD16010B13')
will give
'4142453437384331333838443930313538373536343641443136303130423133'
which is probably not what you want.

A: This is a substitution variable, so you need to include quotes when using it:
define carHashId = ABE478C1388D9015875646AD16010B13

select '&carHashId' from dual

The quotation marks in the define statement don't do anything in SQL Developer. You could use any of the following and ge the same result:
define carHashId = ABE478C1388D9015875646AD16010B13

define carHashId = 'ABE478C1388D9015875646AD16010B13'

define carHashId = "ABE478C1388D9015875646AD16010B13"


text:
Q: How to inject java script in ios 5 I am working on UIWebView in which i am injecting java script like:
        [webview stringByEvaluatingJavaScriptFromString:@"java script"];

this was working fine in ios 4.3. but when it not working on ios 5?
how to inject java script on ios 5;

A: As far as I know, this has not changed in iOS 5. It is a little more finicky with naming, perhaps you need to specify self.webview to make sure you are calling it correctly.


text:
Q: Css 'elem > elem' selector not working in jquery I have the page of a music video in youtube. I'm trying to access the author name from the end of the description using jquery. To that, I've made this css selector div[id="content"] > yt-formatted-string > a[href^="/channel"] I've also made sure to trigger the "show more" button before using it in jquery.
This selector works perfectly fine in chrome's inspect tab, but in JQuery it returns an empty array. Why is this happening?

A: Update: Solved it.
Apparently, it was a timing solution. The code couldn't catch when the elements dynamically loaded, and instead looked too fast.
Fixed that with MutationObserver, and now it works perfectly.


text:
Q: Convert canvas in Symbol Edge Animate I have a <canvas> tag in edge animate. I need to convert this in a symbol to import in other projects, but I don't know how to do that.
This is the tag:
<canvas id="myCanvas" width="640" height="350" ></canvas>

A: Hi you got a file html where store you tag html canvas
< canvas id="myCanvas" width="640" height="350" >

In CC animate (abobe) import model (your html file).


text:
Q: Return to caller as a thread (Dont do it) I want a function that checks a file for changes.
Every time it finds a change, it starts a thread and returns flow to the caller.
def if_file_changes(file_loc):
    import threading, time
    with open(file_loc, 'r') as nctn:
        state = nctn.read()
    while True:
        time.sleep(5)
        with open(file_loc, 'r') as nctn:
            check_state = nctn.read()
        if check_state != state:
            state = check_state
            check_state = None
            t = threading.Thread(return) # How do I return in a thread?
            t.daemon = True
            t.start()

Edit:
I did not understand the problem. I was trying to create the threading at the function level when it should have been at the caller.
My solution is below.

A: You can implemented returning a thread by setting a global value in the new thread:
G_THREAD_RET = None

def thread_func():
    #do something here
    G_THERAD_RET = ret

def main():
    #this is the main thread function
    # wait for child thread here
    ret = G_THERAD_RET # get the return value of child thread

This is simplest if you only have a few threads to get return value from.
Also, you can pass a param to thread function and set it in the new thread before thread exits:
def func(ret=[]):
    time.sleep(2)
    ret.append(2)

def main():
    ret = []
    t = threading.Thread(target=func,args=(ret,))
    t.start()
    t.join()
    print ret

You have to use a list for value returning, because only list and dict are mutable in python.
PS: do you really need to read the whole file to check if there are some changes? Checking the time stamp is much more common for detecting file changes.

A: The correction I made was modularizing the caller into functions so that any portion could be repeated as necessary. Then importing the file checker and calling it where needed.
the function:
def on_file_change(func=None, file_loc=None, start_activated=False):
    import threading, time
    def s():
        with open(file_loc, 'r') as nctn:
            state = nctn.read()
        while True:
            time.sleep(5)
            with open(file_loc, 'r') as nctn:
                check_state = nctn.read()
            if check_state != state and check_state != None and check_state != '':
                state = check_state
                t = threading.Thread(target=func)
                t.start()
    if start_activated == True:
        t = threading.Thread(target=func)
        t.start()
    s()


text:
Q: Form that shows specific text when certain dropdown option and certain radio button is selected Basically I am creating a form and I have looked at onchange with the targetElement toggle but I can't seem to figure it out.
Dropdown: A, B, C
Radio: A, B
If Dropdown A and Radio A is selected then it shows a certain div with text. If Dropdown B and Radio A it shows another set. It will all show and hide with the different variations.

A: Not having the privilege of seeing your code, this is one approach that you can take:
$('#form_id').on('change', 'select, :radio', function(){
    if( $('select', '#form_id').val() == 'A' && $('input#radio_A', '#form_id').is(':checked') ){
        $('#my_text_div').show();
    }else if(  $('select', '#form_id').val() == 'B' && $('input#radio_B', '#form_id').is(':checked') ){
        $('#my_text_div').hide();
    }
});

A: Here is a simple exemple https://jsfiddle.net/L7bpx59w/1/
$("#dropdown , input").change(function()
{
    $(".result").text( "Dropdown '"+$("#dropdown").val()+"' AND Radio '"+$("input:radio").val()+"' are selected" );
});
$("#dropdown").trigger("change");

A: Thanks for the help!
I ended up using this:
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$('#test').change(function () {
    $('.regInfo').hide();
    if ($('#initial').is(':checked') && $('#spouse').is(':checked')) $('.initialSpouse.regInfo').show(); // Initial + Spouse
    if ($('#initial').is(':checked') && $('#employee').is(':checked')) $('.initialEmployee.regInfo').show(); // Initial + Employee

    if ($('#t').is(':checked') && $('#spouse').is(':checked')) $('.tSpouse.regInfo').show(); // t + Spouse
    if ($('#t').is(':checked') && $('#employee').is(':checked')) $('.tEmployee.regInfo').show(); // t + Employee

    if ($('#p').is(':checked') && $('#spouse').is(':checked')) $('.pSpouse.regInfo').show(); // p + Spouse
    if ($('#p').is(':checked') && $('#employee').is(':checked')) $('.pEmployee.regInfo').show(); // p + Employee
});
});//]]>

So i have 6 divs that show different text.


text:
Q: Objeto que referência outro pode ser coletado? A classe possui referências ao próximo objeto e ao objeto anterior (Lista). E possui um método para ser deletado
...
function delete(){
    if($this->previousColumn){
      $this->previousColumn->nextColumn = $this->nextColumn;
    }
    if(($this->previousRow)){
      $this->previousRow->nextRow = $this->nextRow;
    }
  }
...

Se eu não configurar os campos previous e next
...
public ?CellInfo $nextColumn, $nextRow,
 $previousColumn, $previousRow;
...

para null este objeto será coletado pelo lixeiro? Ou ele continuará existindo mesmo que nenhum outro objeto tenha referência a ele, mas ele tendo referência a outros objetos
Quando chamo delete os outros objetos da lista deixam de ter referência para o objeto, dessa forma, o código deixa de ter referência a ele.
Entretanto o objeto em que chamo delete ainda continua tendo referências a outros objetos
Então ele será coletado?
class CellInfo{
  public $x, $y;
  public $possible_values = [];
  public ?CellInfo $nextColumn = null, $nextRow = null;
  public ?CellInfo $previousColumn = null, $previousRow = null;
  public $is_unique;

  function addPossibleValue($value){
    $this->possible_value[] = $value;
  }
  function setNextColumn(CellInfo $ci){
    $this->nextColumn = $ci;
    $ci->previousColumn = $this;
  }
  function delete(){
    if($this->previousColumn){
      $this->previousColumn->nextColumn = $this->nextColumn;
      //Como $this->previousColumn não foi
//cofigurado para null ele continuará tendo
//referência a outro objeto, mas não terá
// mais referência dentro da lista
    }
    if(($this->previousRow)){
      $this->previousRow->nextRow = $this->nextRow;
    }
  }
}//*/
$t1 = new CellInfo();
$t1->x = 10;
$t2 = new CellInfo();
$t2->x = 15;
$t3 = new CellInfo();
$t3->x = 20;

$t1->setNextColumn($t2);
$t2->setNextColumn($t3);
//*/
$t2->delete();//O coletor irá coletar esse $t2?

A: O garbage collector do PHP coleta um objeto quando ele não tem mais referências. Se você deixar apenas uma referência, não importa onde, o objeto não será coletado até o fim da execução, ou no momento que a referência deixe de existir explicitamente em alguma parte do código, ou implicitamente se a referência vem de um objeto que é destruído automaticamente por alguma razão, por exemplo quando esse this deixa de existir.
Isso é detalhe de implementação e pode mudar, mas normalmente ele tem um contador de referências. E se falhar por entrar em um ciclo ainda tem um coletor extra.
Eu não tenho como responder de forma mais precisa porque a pergunta fala em campos previous e next e em nenhum lugar do código tem campos com esses nomes. E também porque não há maior contexto.
De qualquer forma a pergunta mudou, o código nem faz o que fazia antes e n~]ao parece fazer muito sentido mais.
Mas está fazendo o que com PHP? Scripts no backend web? Se é isso então não precisa se preocupar, o script durará um tempo muito curto, alocará bem poucos objetos e mesmo que tudo falhe o fim dele coletará os objetos que ficarem.
Se está usando PHP para outra coisa que mantém o objetos vivos por muito tempo então deveria repensar a linguagem, PHP não foi feita pra isso. E quem me disse pessoalmente foi o criador da linguagem.


text:
Q: Firebase Cloud Messaging notification not visible on device however onMessageReceived is executing I am not sure if this is a bug or there is something missing or device setting. However it looks fine to me and checked many posts. Let me try to explain from scratch.
My requirement is a customer (e.g. User A1) will do a service booking of a service provider(e.g. 'User B'). Whenever there is a booking from customer for service provider's ('User B') service, there should be a firebase notification to service provider (User B).
I am new to Android, so easy way to achieve this is also welcome. However I am trying to achieve this with firebase cloud messaging with topic subscription. Where service provider is always subscribed to a topic. Customer will subscribe to topic dynamically, send notification to topic using Retrofit, and unsubscribe from topic. So in result, customer and service provider both will get the notification.

*

*At this moment a static Topic subscription is defined from app which will be changed later to dynamic

*A Retrofit is calling https://fcm.googleapis.com/topics/myTopic to send notification

*A 200 response is also coming back and onMessageReceived method is also called on customer instance but there is no notification on any instance.

*notification to device from Firebase control is working fine. which means, device is not having any issue.

Activity code which is sending notification:
package www.temp.com.bookyourslot;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.messaging.FirebaseMessaging;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import www.temp.com.bookyourslot.Model.BookingNotificationData;
import www.temp.com.bookyourslot.Model.Posts;
import www.temp.com.bookyourslot.Model.PushBookingNotification;
import www.temp.com.bookyourslot.Retro.BookYourSlotNotiicationAPI;
import www.temp.com.bookyourslot.Retro.JsonPlaceHolderAPI;
import www.temp.com.bookyourslot.databinding.ActivityChooseSlotBinding;
import www.temp.com.bookyourslot.databinding.ActivityPostsBinding;

public class PostsActivity extends AppCompatActivity {

    String TAG = "PostsActivity";
    ActivityPostsBinding activityPostsBinding;
    JsonPlaceHolderAPI jsonPlaceHolderAPI;
    BookYourSlotNotiicationAPI bookYourSlotNotiicationAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_posts);

        activityPostsBinding = ActivityPostsBinding.inflate(getLayoutInflater());
        View view = activityPostsBinding.getRoot();
        setContentView(view);

        FirebaseMessaging.getInstance().subscribeToTopic("myTopic")
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        //String msg = getString(R.string.msg_subscribed);
                        if (!task.isSuccessful()) {
                            Log.d(TAG, "onComplete: Subscription is not successful");
                            //msg = getString(R.string.msg_subscribe_failed);
                            Toast.makeText(PostsActivity.this, "not successful", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            //Log.d(TAG, msg);
                            Toast.makeText(PostsActivity.this, "Successfully subscribed.", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://fcm.googleapis.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        bookYourSlotNotiicationAPI = retrofit.create(BookYourSlotNotiicationAPI.class);

        activityPostsBinding.postsSendRequestButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendNotification();
            }
        });

    }

     public void sendNotification(){

        PushBookingNotification pushBookingNotification=new PushBookingNotification(
                new BookingNotificationData("First Title","First Message"),
                "/topics/myTopic");
        Call<PushBookingNotification> call = bookYourSlotNotiicationAPI.sendNotification(pushBookingNotification);
        call.enqueue(new Callback<PushBookingNotification>() {
            @Override
            public void onResponse(Call<PushBookingNotification> call, Response<PushBookingNotification> response) {
                if (!response.isSuccessful()) {
                    activityPostsBinding.postResultsTV.setText("Code : " + response.code());
                    return;
                }
                //PushBookingNotification notificationResponse = response.body();
                String content = "";
                content += "Code: " + response.code() + "\n";
                content += "Code: " + response.raw().toString() + "\n";

                activityPostsBinding.postResultsTV.setText(content);
            }

            @Override
            public void onFailure(Call<PushBookingNotification> call, Throwable t) {
                activityPostsBinding.postResultsTV.setText(t.getMessage());
            }
        });
    }
}

Message Service class:
package www.temp.com.bookyourslot.FirebaseMessaging;

import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MessagingService extends FirebaseMessagingService {

    private String TAG = "MessagingService";
    @Override
    public void onNewToken(@NonNull String s) {
        super.onNewToken(s);

        Log.d(TAG, "onNewToken: " + s);

    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...

        // TODO(developer): Handle FCM messages here.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "onMessageReceived: " + remoteMessage.getData().toString());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            /* Check if data needs to be processed by long running job */
            if ( true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                //scheduleJob();
            } else {
                // Handle message within 10 seconds
                //handleNow();
            }
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            Toast.makeText(getApplicationContext(),remoteMessage.getNotification().getBody().toString(),Toast.LENGTH_SHORT).show();
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }

    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
        Log.d(TAG, "onDeletedMessages: Message is delete...");
    }
}

Data Classes
package www.temp.com.bookyourslot.Model;

public class BookingNotificationData {
    public String title;
    public String body;

    public BookingNotificationData(String title, String body) {
        this.title = title;
        this.body = body;
    }
}

package www.temp.com.bookyourslot.Model;

public class PushBookingNotification {
    public BookingNotificationData data;
    public String to;

    public PushBookingNotification(BookingNotificationData data, String to) {
        this.data = data;
        this.to = to;
    }
}

Retro Class
package www.temp.com.bookyourslot.Retro;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import www.temp.com.bookyourslot.Constants;
import www.temp.com.bookyourslot.Model.PushBookingNotification;

public interface BookYourSlotNotiicationAPI {

    //String BASE_URL="https://fcm.googleapi.com";
    String SERVER_KEY="AAAAXS1k7O4:XXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXxxxxxxxxxxxxxxxXXXXXXXXXXXXXXXxxxxxx_";
    String CONTENT_TYPE="application/json";

    @Headers({"Authorization: key="+ SERVER_KEY, "Content-Type:"+CONTENT_TYPE})
    @POST("fcm/send")
    Call<PushBookingNotification> sendNotification(@Body PushBookingNotification pushBookingNotification);
}

A: While the app is in the background the firebase will automatically handle the notification. If the app in the foreground state you need to call the Local Heads up Notification and pass the data (title, body) received from the onMessageRecieved() override function.
Something like this:
 private void handleNotification(String title, String message) {

    if (!DeviceInfo.isAppIsInBackground(this)) {
        Intent notificationIntent = new Intent(this, HomeActivity.class);
        notificationIntent.putExtra("text", message);
        notificationIntent.putExtra("title", title);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notificationBuilder.setContentIntent(contentIntent);
        Notification notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.defaults |= Notification.DEFAULT_SOUND;
        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        int notificationId = 1;
        if (notificationId == Integer.MAX_VALUE - 1)
            notificationId = 0;
        notificationManager.notify(notificationId, notification);
    }


text:
Q: how to do a MongoDB query and use it in a partial view I have a collection called events that I am currently using in my footer partial, however, I would like to show only the ones with a date greater than today. I have achieved this on mongo shell like this:
db.events.find({date: {$gte: new Date()}})

I don't understand how to use this query in footer partial where I am running a loop to show the events, I would like to save this query in a variable that I can use in the loop, and it would be visible in every page of the website as they all have the footer.
To be able to use this collection in every page I am using this code in my app.js
// passing courses to every EJS template
app.use(function (req, res, next) {

    Event.find({}, function (err, allEvents) {
        if (err) {
            console.log(err);
            res.locals.events = [];
            next();
        } else {
            res.locals.events = allEvents;
            next();
        }
    });
});

and this is where I am doing my loop in footer partial

PROXIMOS EVENTOS

      <% var count = 0; %>
      <% events.forEach(function(event) { %>
        <% if (count <= 2 ) { %>

<%=moment(event.date).format('dddd, D MMMM, h:mm a')%>

 <%= event.name %>

        <% } %>
      <% count++; }); %>

A: Try this ...
Event.find({date: {$gte: new Date()}}, function (err, allEvents) { ...


text:
Q: Units of a finite commutative ring Let $R$ be a finite commutative ring with unity and $p$ a prime integer.
Suppose that there is a primitive $p$th root of unity $u \in R$ such that $u - 1$ is a unit.
Is it true that $u^i - 1$ is also a unit for all $1 \leq i \leq p - 1$? and how to prove it?

A: What is always the case is $u-1$ and $u^i-1$ generate the same ideal:
$$u^i-1=(u-1)(u^{i-1}+\cdots+u+1)$$
and
$$u-1=(u^i-1)(u^{i(j-1)}+\cdots+u^i+1)$$
where $ij\equiv1\pmod p$. If then $u-1$ is a unit, then $(u-1)R=R$
and so $(u^i-1)R=R$. Then $u^i-1$ is a unit.


text:
Q: Get route from a coordinate to a random distance I have this specific use case I can't figure out how to implement.
I need to trace a route route from a starting point to a random distance from that point.
The goal is to for instance suggest a route to the users can take if they want to walk 10km from their starting point or any point on a map.
Any ideas? or is there any free/paid service for such usecase?
Thank you for your help

A: One approach you could try is creating an isodistance polygon, then randomly choosing a direction from the center and find the intersection with the shape.
This blog post generates an isodistance shape by calculating the distance to a grid of nearby points, then  producing a concave hull around the perimeter.
https://blog.mapbox.com/dive-deeper-into-isodistances-c90bd5df9215
You could then randomly select a direction and draw a line to intersection that shape. One approach to that is to draw a line from the center to north, and then http://turfjs.org/docs/#transformRotate a random angle.
Then use https://turfjs.org/docs/#lineIntersect to find the intersection point.


text:
Q: Laravel Simple Authorization - Sometimes not working - "Invalid credentials." I use "HTTP Basic Authentication" for my administration in Laravel 5.4
It is working correctly, but sometimes it shows "Invalid credentials." and I cannot login (the HTTP Basic Auth doesn't pop up).
I suspect that Chrome is sending some credentials it already stored and Laravel doesn't pair it and instead of showing another Auth pop up, it just dies with the text "Invalid credentials."
I tried erasing all cookies, caches, everything except "passwords" (don't want to lose them), and it still isn't showing Simple Auth popup to ask my credentials.
I have tried opening the site in Chrome Ghost/Guest mode and it is working there (asks for auth and then logs in).
Can you help?
I set this up by putting 'middleware' => 'auth.basic' in ROUTES and then Auth::routes();
And then just added this line in /app/Http/Kernel.php:
protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

So basically I have zero customization... just simple Auth addition.

UPDATE #1:
I debugged this to file \vendor\laravel\framework\src\Illuminate\Auth\SessionGuard.php
However even putting my own stuff:
header('WWW-Authenticate:Basic realm=test');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;

Doesn't invoke the popup!!!
From what I've read it seems like some Chrome issue.
I tried all kinds of variations, but the popup still isn't coming up.

A: So, basically I called this address:
https://username:password@mysite.com/
Important here is to use correct username and correct password!
After that it began working again, so it was Chrome issue :)
Any other method including chrome://restart or erasing cache, cookies etc. didn't work.


text:
Q: What's the meaning of `SUR`? I saw a slogan:
NO HELP WITH BIG SUR HERE.

what's the meaning of it? I just don't understand SUR.

EDIT-01

A: macOS Big Sur (version 11.0) is the next major release of macOS, Apple Inc.'s operating system for Macintosh computers. It is the successor to macOS Catalina (version 10.15) and was announced at Apple's Worldwide Developers Conference on June 22, 2020, with public beta release scheduled for July and general release projected for fall. It is named after the coastal region of Big Sur in the Central Coast of California. Clearly, no help was available for that version.

A: According to Wikipedia,
Wikipedia "Big Sur" etymology
"The Spanish referred to the vast and relatively unexplored coastal region to the south of Monterey as el país grande del sur, meaning "the big country of the south". This was often shortened to el sur grande (the big south)."
So, "sur" is Spanish for "south".
I don't know why that phrase would appear in a piece of software, except that it might refer to the name of another piece of software, since the example you posted shows three other location references: "Catalina", "Mojave", and "High Sierra".


text:
Q: Synergy client won't connect, despite open port? I want to use a Debian KDE desktop computer (network name bradbury) as the server, and a Windows 7 laptop (network name Clarke) as the client. I have used this setup before without problems, but then there was a Fedora on the server. Now the client only gives
WARNING: failed to connect to server: Timed out.

What I did:

*

*installed Synergy from the repository

*saved a config file under /etc/synergy.conf

    section: screens
        bradbury:
        Clarke:
    end

    section:aliases
      Clarke:
        192.168.178.39
    end

    section: links
        bradbury:
            down = Clarke
        Clarke:
            up = bradbury
    end

*

*opened port 24800 (at least I think I did, this is the first time I have used iptables)

sudo iptables -A INPUT -p tcp --dport 24800 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 24800 -j ACCEPT

It seems that the port is indeed open.
rumtscho@bradbury:~$ netstat -an |grep 24800 |grep -i listen
tcp        0      0 0.0.0.0:24800           0.0.0.0:*               LISTEN

*

*checked on the router that my computer's IP is indeed 192.168.187.22, and the laptop's IP is 192.168.178.39

*started synergy

rumtscho@bradbury:~$ synergys -f -n bradbury
2014-03-21T11:50:29 INFO: Synergy 1.3.8 Server on Linux 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64
        /tmp/buildd/synergy-1.3.8/src/cmd/synergys/synergys.cpp,1098
2014-03-21T11:50:29 DEBUG: opening configuration "/home/rumtscho/.synergy.conf"
        /tmp/buildd/synergy-1.3.8/src/cmd/synergys/synergys.cpp,1113
2014-03-21T11:50:29 DEBUG: cannot open configuration "/home/rumtscho/.synergy.conf"
        /tmp/buildd/synergy-1.3.8/src/cmd/synergys/synergys.cpp,1120
2014-03-21T11:50:29 DEBUG: opening configuration "/etc/synergy.conf"
        /tmp/buildd/synergy-1.3.8/src/cmd/synergys/synergys.cpp,1113
2014-03-21T11:50:29 DEBUG: configuration read successfully
        /tmp/buildd/synergy-1.3.8/src/cmd/synergys/synergys.cpp,1124
2014-03-21T11:50:29 DEBUG: XOpenDisplay(":0")
        /tmp/buildd/synergy-1.3.8/src/lib/platform/CXWindowsScreen.cpp,901
2014-03-21T11:50:30 DEBUG: xscreensaver window: 0x00000000
        /tmp/buildd/synergy-1.3.8/src/lib/platform/CXWindowsScreenSaver.cpp,342
2014-03-21T11:50:30 DEBUG: screen shape: 0,0 5120x1440 (xinerama)
        /tmp/buildd/synergy-1.3.8/src/lib/platform/CXWindowsScreen.cpp,136
2014-03-21T11:50:30 DEBUG: window is 0x04c00004
        /tmp/buildd/synergy-1.3.8/src/lib/platform/CXWindowsScreen.cpp,137
2014-03-21T11:50:30 DEBUG: opened display
        /tmp/buildd/synergy-1.3.8/src/lib/synergy/CScreen.cpp,41
2014-03-21T11:50:30 DEBUG: registered hotkey ScrollLock (id=ef14 mask=0000) as id=1
        /tmp/buildd/synergy-1.3.8/src/lib/platform/CXWindowsScreen.cpp,729
2014-03-21T11:50:30 NOTE: started server
        /tmp/buildd/synergy-1.3.8/src/cmd/synergys/synergys.cpp,515
2014-03-21T11:50:30 INFO: screen "bradbury" shape changed
        /tmp/buildd/synergy-1.3.8/src/lib/server/CServer.cpp,1194

But the client still won't connect.

A: *

*You have to run the same version of synergy for both version.

*Check    the hostname.

*Check if you do not have any firewall on windows/linux that is generating issues.

*Change the port 24800 by 8081. That works    for me.

*Remember both have to listen the same port.

Good luck!

A: I solved adding the port with this command in ubuntu:
(a bit different from previous posts)
iptables -I INPUT 1 -p tcp --dport 24800 -j ACCEPT

A: In linux, I needed to use this command like described earlier:
sudo iptables -A INPUT -p tcp --dport 24800 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 24800 -j ACCEPT

I also added the computer name (client and server) in configuration, exact same names at both of them. (Ex: computer-client, computer-server).

A: Except for having the correct iptables rules mentioned all around here, be sure you apply the rules in the correct order within your iptables configuration as well. Apply them BEFORE the rule that drops/rejects the packets. That was something I needed to figure out :-).


text:
Q: Borel sets of $\mathbb{R}$ are not partition generated I want to prove that the Borel $\sigma$-algebra $\mathcal{B}(\mathbb{R})$ can not  be generated by partition: There is not any family $\mathcal{C} = \{A_i : (A_i)_{i \in I}$ partition of $\mathbb{R} \}$ such that $\sigma (\mathcal{C})=\mathcal{B}(\mathbb{R})$ .
Can you give me a hint?

A: Hints:

*

*If $\mathcal C=\{A_i\mid i\in I\}$ is a partition then $A\in\sigma(\mathcal C)$ iff it can be written as $\bigcup_{i\in J}A_i$ where $J\subseteq I$ is countable or co-countable.

*singletons are Borel-measurable.

*There are Borel sets that are not countable and not cocountable.

A: Here's my suggestion: Let $\mathcal{C}$ be a class of subsets of a set $X$. Say  that two elements $x,y\in X$ are separated by $\mathcal{C}$ if there is $C\in\mathcal{C}$ containing only one of $x,y$.

*

*Show that elements of $X$ are separated by $\mathcal{C}$ iff they are separated by $\sigma(\mathcal{C})$.

*Show that if $\mathcal{C}$ is a partition generating the Borel $\sigma$-algebra of $\mathbb{R}$, then $\mathcal{C}$ consists of singleton sets.

*Show that $\sigma(C)$ consists of countable or co-countable sets, a contradiction.

A: In my thought, if such a family $\mathcal C$ existed, it must contain singletons(since they are closed). Thus $\mathcal C$ must consist of every singletons in $\mathbb R$, while any open interval cannot be written as a countable union of singletons.
I'm not sure whether this is right, though.


text:
Q: Windows authentication and multiple prompts I currently have two IIS websites with windows authentication turned on. Internally on my network when you connect to them you're authenticated seamlessly and logged on. Externally you are prompted to login. This is all fine and expected.
However the two sites reference assets on each other, so going to site A causes not only a prompt to login for site A but also a prompt to login for site B as well.
Is there any kind of server that I can stick in front of the two websites so that the user will only have to authenticate once against that server and then all subsequent authentication is handled by it?

A: What about setting virtual directory for the domain. Say you are creating virtual directory for website A which points to a folder for website B.


text:
Q: Error: No module named 'PyQt5.sip' - When installing eric6-19.03 I have noticed a number of similar questions on stackoverflow, but none that really helped me with my current challenge. I have been attempting to install eric6 on my Raspberry Pi setup. And then I encountered the following messages:
Checking dependencies
Python Version: 3.6.8
PyQt5 could not be detected.
Error: No module named 'PyQt5.sip'

Shall 'PyQt5' be installed using pip? (Y/n) Y
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Requirement already satisfied: PyQt5 in /usr/local/lib/python3.6/site-packages (5.12)
Sorry, please install PyQt5.
Error: No module named 'PyQt5.sip'

And when I attempt to use the pip list to look at what has been installed (as I previously already managed to make and install the PyQt5 from source code):
Package    Version
---------- -------
pip        19.0.3
PyQt5      5.12
setuptools 40.6.2
sip        4.19.14

So, how do I overcome the issue that I am currently facing? By the way, I am using the following command when attempting to install eric6:
python3 install.py

Thought you might need to know that if it helps.

A: Python 3.6 isn't available in any Raspbian distribution, so I assume you installed this yourself. You can't install an out-of-distribution Python version and expect distribution Python packages to work. You have PyQt5 installed, yes, but it's the version of PyQt built for Python 3.5 (I'm assuming you're on Raspbian Stretch).
Sometimes you can install Python libraries with pip, and in theory that could work to install the correct version of PyQt for your version of Python, but PyQt only provides wheels for x86 on PyPI, not for Arm, so PyQt is not pip installable on the Pi. The only way to get PyQt on Raspberry Pi is via apt, where your choices are Jessie (old stable - with Python 3.4), Stretch (current stable - with Python 3.5), and Buster (unstable/testing - with Python 3.7). If there's a need for Python >3.5, your best bet is to try upgrading to Buster, but bear in mind it's not ready for release yet.


text:
Q: Ruby SimpleCov 0.0 LOC with stand alone .rb code I am trying to use SimpleCov to gather code coverage information but I can't seem to understand how it works. It always give me 0.0% LOC. Do I need to do something to make it work?
require 'simplecov'
SimpleCov.start
SimpleCov.command_name 'Unit Tests'

def foo
  puts '12345'
end

foo

I see the following output:
$ ruby mytest.rb
12345
Coverage report generated for Unit Tests to /private/tmp/simpletest/coverage. 0.0 / 0.0 LOC (100.0%) covered.
Do I have to use it under rspec or some special environment? Can I not just enable code coverage for arbitrary code?

A: SimpleCov filters the original source file itself out of the coverage report. To make it work standalone like this, you need to put your test code into a separate file:
require 'simplecov'
SimpleCov.start
SimpleCov.command_name 'Unit Tests'

require_relative 'my_code'
foo

Then in my_code.rb:
def foo
  puts '12345'
end

Now you will get a proper report.


text:
Q: Radius of convergence for $\sum a_kz^{2k}$ Let $R$ be radius of convergence of $\sum a_kz^k$
How do I find the radius of convergence for $\sum a_kz^{2k}$
My guess is $\sqrt{R}$ but I am not sure if it's correct.

A: That's obviously correct. Forget that $|a_n|^{1/n}$ thing. By definition the series $\sum a_kz^k$ converges when $|z|<R$ and diverges when $|z|>R$, hence $\sum a_kz^{2k}$ converges when $|z^2|< R$ and diverges when $|z^2|> R$.

A: Your guess is correct.
If $|z|<\sqrt R$, then $|z^2|=|z|^2<R$ and therefore the series$$\sum_{k=0}^\infty a_nz^{2k}=\sum_{k=0}^\infty a_n(z^2)^k\tag1$$converges. And if $|z|>\sqrt R$, the series $(1)$ diverges, for a similar reason.

A: Since the radius of convergence of the series $\sum a_{k} z^{k}$ is $R$, we have
$$
\frac{1}{R}=\lim_{k\to\infty}\left|\frac{a_{k+1}}{a_{k}}\right|
$$
Also, the series $\sum a_{k}z^{2k}$ to be convergent, we need the limit
$$
\lim_{k\to\infty}\left|\frac{a_{k+1}z^{2(k+1)}}{a_{k}z^{2k}}\right|=\frac{|z|^2}{R}
$$
to be less than $1$. Hence, the series $\sum a_{k}z^{2k}$ converges provided $\frac{|z|^2}{R}<1$, that is $|z|< \sqrt{R}$. The radius of convergence of the series $\sum a_{k}z^{2k}$ is therefore $\sqrt{R}$.


text:
Q: Apache Ant - как переименовать файлы? Допустим у меня в папке
temp/flash/... <- флеш файлы с расширением .swf

как мне с помощью ант, получить список этих файлов, переименовать их, скажем в
flash_name.swf -> flash_name-1-.swf
flash_name2.swf -> flash_name2-1-.swf
...

и закинуть в папку
temp/flash1/...

Подскажите! Спасибо.
A: Например, так
<copy todir="${temp.dir}/flash1" verbose="true" overwrite="true">
  <fileset dir="${temp.dir}/flash" />
  <globmapper from="*.swf" to="*-1.swf" />
</copy>

Почитайте про glob-mapper и про regexp-mapper


text:
Q: IntelliJ No tests were found with exit code 0 Just started a QA Automation tester course and I am having some problems with IntelliJ. When I am trying to run a test I get Process finished with exit code 0 and no tests were found.
public class MyStoreTest {
private WebDriver driver;

@BeforeEach
public void beforeEach() {
    System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver.exe");
    this.driver = new ChromeDriver();
    this.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(16));
    this.driver.get("https://mystore-testlab.coderslab.pl/index.php");
}

@Test
public void MyStoreTest() {
    MyStoreMainPage MyStoreMainPage = new MyStoreMainPage(driver);
    MyStoreMainPage.clickSignIn();

    MyStoreAuthenticationPage authenticationPage = new MyStoreAuthenticationPage(driver);
    String email =  "oetuomldfaacfducoz@bvhrk.com";
    String password = "1992Dawid";
    authenticationPage.submitSignIn(email , password);

    MyStoreAddAnAddressPage AddAnAddress = new MyStoreAddAnAddressPage(driver);
    AddressData AddressData = new AddressData()
            .setAddress("Ul.Pulawska")
            .setZip("02-508")
            .setCity("Warszawa");

    AddAnAddress.AddAnAddress(AddressData);

    MyStoreMyAccountPage myAccountPage = new MyStoreMyAccountPage(driver);
    assertTrue(myAccountPage.isAddressSuccessfullyAdded());
}

}
How can I understand why it can find no test?
I am would be really grateful for any answers
Other than no tests found I get
org.junit.platform.launcher.core.DefaultLauncher handleThrowable
WARNING: TestEngine with ID 'junit-vintage' failed to discover tests
org.junit.platform.commons.JUnitException: Failed to parse version of junit:junit: 4.13.2
at org.junit.vintage.engine.JUnit4VersionCheck.parseVersion(JUnit4VersionCheck.java:54)
at org.junit.vintage.engine.JUnit4VersionCheck.checkSupported(JUnit4VersionCheck.java:37)
at org.junit.vintage.engine.JUnit4VersionCheck.checkSupported(JUnit4VersionCheck.java:32)
at org.junit.vintage.engine.VintageTestEngine.discover(VintageTestEngine.java:61)
at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:177)
at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:164)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
wrz 15, 2022 12:31:10 AM org.junit.platform.launcher.core.DefaultLauncher handleThrowable
WARNING: TestEngine with ID 'junit-jupiter' failed to discover tests
java.lang.NoClassDefFoundError: org/junit/jupiter/api/io/CleanupMode
at org.junit.jupiter.engine.JupiterTestEngine.discover(JupiterTestEngine.java:66)
at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:177)
at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:164)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.ClassNotFoundException: org.junit.jupiter.api.io.CleanupMode
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 10 more
Maybe the problem is in my java classes?
public class AddressData {

private String Address;
private String City;
private String Zip;

public String getAddress() {
    return Address;
}

public AddressData setAddress(String Address) {
    this.Address = Address;
    return this;
}

public String getCity() {
    return City;
}

public AddressData setCity(String City) {
    this.City = City;
    return this;
}

public String getZip() {
    return Zip;
}

public AddressData setZip(String Zip) {
    this.Zip = Zip;
    return this;
}

}
public class MyStoreAddAnAddressPage {
public WebDriver driver;
public MyStoreAddAnAddressPage(WebDriver driver) {
    this.driver = driver;
}
public void AddAnAddress(AddressData AddressData) {

    WebElement AddressInput = driver.findElement(By.name("address1"));
    AddressInput.sendKeys(AddressData.getAddress());
    WebElement CityInput = driver.findElement(By.name("city"));
    CityInput.sendKeys(AddressData.getCity());
    WebElement ZipInput = driver.findElement(By.name("postcode"));
    ZipInput.sendKeys(AddressData.getZip());

    WebElement saveButton = this.driver.findElement(
            By.name("submitAddress")
    );
    saveButton.click();
}

}
public class MyStoreAuthenticationPage {

@FindBy(css = "href#log.in.to.your.customer.account")
private WebElement signIn;

@FindBy(name = "email")
private WebElement emailInput;

@FindBy(name = "password")
private WebElement passwordInput;

@FindBy(id = "submit-login")
private WebElement signInButton;
private WebDriver driver;

public MyStoreAuthenticationPage(WebDriver driver) {
    PageFactory.initElements(driver, this);
}

public void submitSignIn(String email, String password) {
    emailInput.sendKeys(email);
    passwordInput.sendKeys(password);
    signInButton.click();
}

}
public class MyStoreMainPage {
public WebDriver driver;
public MyStoreMainPage(WebDriver driver) {
    this.driver = driver;
}
public void clickSignIn() {
    WebElement signIn = this.driver.findElement(
            By.cssSelector("href#log.in.to.your.customer.account")
    );
    signIn.click();
}

}
public class MyStoreMyAccountPage {
public WebDriver driver;

public MyStoreMyAccountPage(WebDriver driver) {
    this.driver = driver;
}

public boolean isAddressSuccessfullyAdded() {
    WebElement confirmationPanel = this.driver.findElement(
            By.cssSelector("article.alert.alert-success")
    );
    String panelText = confirmationPanel.getText();

   return panelText.equals("Address successfully added!");
}

}

A: Hard to say without more information but it's possible that your run configuration is incorrect. Beside the test in the editor, there should be a play button. Try running it that way for a brand new run configuration.

If the button isn't visible, try invalidating caches and restarting the IDE as you may be missing some imports that the editor should detect when it restarts.


text:
Q: Intent not working with if operator Android I try when it displays a message when I press a button to redirect me to a page, but it doesn't work. When successful, the message is displayed but does not forward me.
private void registerUser() {
    try {

        Account account = new Account();
        account.setpAddress(edt_adress.getText().toString());
        account.setpBloodGroup(edt_blood.getSelectedItem().toString());
        account.setpFirstName(edt_first.getText().toString());
        account.setpMidName(edt_mid.getText().toString());
        account.setpFamilyName(edt_fam.getText().toString());
        account.setpGender(edt_gender.getSelectedItem().toString());
        account.setpPhone(edt_phone.getText().toString());
        account.setpEgn(edt_egn.getText().toString());
        account.setuPassword(edt_password.getText().toString());
        account.setuUsername(edt_username.getText().toString());
        INodeJS accountservice = RetrofitClient.getInstance().create(INodeJS.class);
        Call call = accountservice.create(account);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                Account result = (Account) response.body();

                Toast.makeText(getApplicationContext(), result.getNotes(), Toast.LENGTH_LONG).show();
                if (result.getNotes().equals("Success")) {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                }
                // startActivity(intent);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Toast.makeText(getApplicationContext(), getString(R.string.createfield), Toast.LENGTH_SHORT).show();
            }
        });

    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

A: looks like result.getNotes().equals("Success") isnt true, are you shure it should be? equals is case-sensitive so "success" doesn't equal "Success" and also " Success " - note whitespaces
maybe you can try with this statement:
result.getNotes().toLowerCase(Locale.getDefault()).trim().equals("success")

toLowerCase will make all your letters small caps and trim will remove all whitespaces at beggining and end of String
also there is equalsIgnoreCase method so it may also looks like below:
result.getNotes().trim().equalsIgnoreCase("success")


text:
Q: What do the nodes, groups, and values mean in the JSON for a d3 force-directed graph? I am trying to create a d3 force-directed graph (http://mbostock.github.com/d3/ex/force.html). Here is the simple JSON file containing my data.
{"nodes":[{"name":"Node1","group":1}, {"name":"Node2","group":1}],

    "links":[{"source":1,"target":2,"value":2}]}

I have two nodes in the same group. I am trying to also create a link between the two nodes. However, my page remains blank (and I am sure that other parts other than the JSON are correct).
What is a "group"? Why do edges have both a "source" and a "target" - and what are these values? Why do links have a "value"? Aren't the links just unweighted edges? I'm having trouble understand the JSON structure of data storage.

A: In the d3 force-directed graph example, the 'value' of links is mapped to the stroke width of the edges and the 'group' of nodes is mapped to the color of the nodes. The integer value of 'source' and 'target' in links refers to the array index of the corresponding node in nodes (https://github.com/mbostock/d3/wiki/Force-Layout#wiki-links).
If you change source links to
 "links":[{"source":0,"target":1,"value":2}]}

it, d3 should render an edge between the two nodes.


text:
Q: Does Restsharp support Xamarin forms call when the app is in background I am trying to make an API call from RestSharp on a geofence event. So the app is in background and on iOS for instance the Http Client needs allow Background flags set. Does RestSharp support this mode ? Are there any examples ?
I tried setting the flag but of course it is an iOS variable so only available in the iOS Project