text:
Q: How to align nav items to the right in Bootstrap 5? I have copied a navbar HTML code from https://www.codeply.com/go/qhaBrcWp3v
Example 6:

        Navbar 6

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#myNavbar">

        </button>

            Our Solution

            How We Help

            Bdfdsfslog

            Contact

The code keeps the nav items to right but when I paste it and run my HTML code it doesn't work and all items are in the left place
here is my index.html

    <title>Website Template</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

                Navbar 6

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#myNavbar">

                </button>

                    Our Solution

                    How We Help

                    Blog

                    Contact

I have tried Navbar code from https://getbootstrap.com/docs/5.0/components/navbar/ but I don't know how can I move nav items (ml-auto didn't work)

A: The code from my example Codeply is using Bootstrap 4, but your code is using Bootstrap 5 beta. If you take a look at the new Bootstrap 5 spacing utility classes you'll see that...

*

*l (left) has been replaced with s (start)

*r (right) has been replaced with e (end)

Why margin left (ml-*) is not working in Bootstrap 5?
ml-auto no longer exists, and the Bootstrap 5 equivalent would be ms-auto:

         Navbar 6

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#myNavbar">

            </button>

                Our Solution

                How We Help

                Blog

                Contact

Demo: https://codeply.com/p/zzFC5XoyUm

Why margin right (mr-*) is not working in Bootstrap 5?
Additionally, mr-auto has been replaced with me-auto.
Here you can read why Bootstrap 5 uses the start and end approach to improve RTL support since left and right are absolute, while start and end are relative.
The flexbox utils such as justify-content-end can also be used as explained here

A: don't use justify-content-end use ms-auto
use for  m- margin  and  p-padding

*

*t - for classes that set margin-top or padding-top

*b - for classes that set margin-bottom or padding-bottom

*s - for classes that set margin-left or padding-left in LTR,
margin-right or padding-right in RTL

*e - for classes that set margin-right or padding-right in LTR,
margin-left or padding-left in RTL

*x - for classes that set both *-left and *-right

*y - for classes that set both *-top and *-bottom

A: I actually tried a different approach, although inspired by some of these posts previous to mine. I wanted to just align some buttons (the My Profile and Login buttons) on my navbar to the right while keeping all others left on the navbar.
Follow This Process

*

*Set the position of the navbar as relative using position-relative

*Put the buttons you want to right-align in a separate

*Set the
 positioned absolute and at the end like so:

*Create an empty
 before the
 you just made to maintain the spacing when shrinking the screen (as absolute elements will overlap with other static and relative elements).

*Set the width equal to the right-aligned
 (find this out using Chrome inspect element). E.g.

My code as an example
        {# Create Navbar #}

                    Company Name

                <button class="navbar-toggler" type="button" data-coreui-toggle="collapse" data-coreui-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Home

                            Guide

                            About us

                            Blog

                        {# Invisible div to prevent overlap of absolute positioned elements #}

                            {# Create a login or logout link depending whether a user is logged in or not #}
                            {% if app.user %}

                                    My Profile

                                    Logout

                            {% else %}

                                    Login/Register

                            {% endif %}

Overall
I found this a bit easier to wrap my head around compared to other solutions I've seen and was able to get it to work more easily. I hope this is useful for anyone else coming across this post. Please comment if you have any feedback about my method and if you have any improvements. Thanks! :)
Note: My example is done in a Symfony project using twig templates in case you find any of the syntax confusing. However, all the HTML is the same for any dev tools.

A: Try this:

Flex item 1

Flex item 2

Flex item 3

Where you have this:

 //modify this to include flex-row-reverse

A: For those who started using bootstrap 5 (beta version), there are little changes there in the class names.
"Left" is replaced by "start" and "right" is replaced with "end"  everywhere in bootstrap.
E.g,  In bootstrap 4, we had ml-auto but in bootstrap 5, we have to use ms-auto and similarly for mr, we have me.
And same applies for every class in bootstrap, whether "left" and "right" are represented by "l" and "r", they got replaced by "s" and "e" and if they are used anywhere as complete words (left and right) they got replaced by "start" and "end"

A: this work for me:
use this class en you "ui" tag:
"ms-auto" it mean "margin start" auto,, and this will align your nav-items to the right of the corner.
This is for:
l (left) has been replaced with s (start) in Bootstrap 5

A: You can make use of "justify-content-end" if nothing else helps.


text:
Q: JavaScript showing active div when scroll the page I searched almost everywhere but I couldn't find it. I have a feed like facebook or instagram. I put the advirtesment div after every 5 posts like other posts(like on instagram). The problem is that when I scroll the page if scroll position is at the advirtesment div I want to add a class like in-view with js. How can I do that? By the way, I load other posts when scroll is bottom of page.
Thank you in advance

A: You can use jquery getBoundingClientRect to check if element is in view and then add in-view class to it. Pass your div element to following method and it will return true if your div is in viewport
function isElementInView(element){
  var boundry = element.getBoundingClientRect();

  var isInView = boundry.top >= 0 && boundry.left >= 0 &&
                 boundry.bottom <= (window.innerHeight || $(window).height()) &&
                 boundry.right <= (window.innerWidth || $(window).width());

  return isInView;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Please provide a valid WRITE query I try to run minimum spanning tree algorithm inside Spark using Neo4j Connector. But when I try to call it I get an error: Please provide a valid WRITE query.
My code looks like this:
    val df = (1 to 10)/*...*/.toDF()
    df.write
      .format("org.neo4j.spark.DataSource")
      .option("url", "bolt://localhost:7687")
      .option("query", "CALL gds.alpha.spanningTree.minimum.write('graph', {  startNodeId: id(1), relationshipWeightProperty: 'cost'," +
        "  writeProperty: 'CONNECT',weightWriteProperty: 'writeCost'})")
      .save()

Can calling an algorithm can be done inside write function?


text:
Q: 100% CPU used in javapns i'm working for a project send notification to iPhone. and i used javapns. but when i invork the message:
pushManager.sendNotification(client, complexPayLoad);

i found the message cannot return correctly, and it cause cpu usage become 100%.
could anybody tell me where's wrong about my code? Thanks.
more completement code
try {
        // create a complex PayLoad with a custom alert
        PayLoad complexPayLoad = new PayLoad();
        PayLoadCustomAlert customAlert = new PayLoadCustomAlert();
        customAlert.addBody(message);
        complexPayLoad.addCustomAlert(customAlert);
        complexPayLoad.addSound("chime");
        for (String key : new HashSet<String>(data.keySet())) {
            complexPayLoad.addCustomDictionary(key, (String)data.get(key));
        }

        try {
            // Link iPhone's UDID (64-char device token) to a stringName
            pushManager.addDevice(token, token);
        } catch (Exception ex) {
            // Perhaps we added duplicate devices
            log.debug("Perhaps we added duplicate devices");
        }

        // Get iPhone client
        Device client = pushManager.getDevice(token);

        // Send message
        pushManager.sendNotification(client, complexPayLoad);
        log.info("Message sent!"); // i cannot get this message

    } catch (Exception e) {
        log.error(e.getMessage());
    }

A: What version?
Version 2 just came out, and fixed a number of issues.
It is also much easier to implement.


text:
Q: Time Series Covariance Matrix for multiple variables - R I want to create a covariance matrix of time series data for the purpose of Monte Carlo simulation however this matrix is between multiple assets.
I.e. I not only want to know the covariance between X(t), X(t+1), ... , X(t+n) but also the covariances between X(t), Y(t), Y(t+1), etc.
Is there a simple way to generate a covariance matrix in R that is the covariance between every element in an dataframe?
Thanks

A: This produces the covariances up to nl lags:
set.seed(123)
c1 <- data.frame(matrix(rnorm(90),ncol=3))
nl=2 # number of lags
c1wlags=embed(as.matrix(c1),nl+1)
nams=colnames(c1)
ndfs=paste(rep(nams,nl),rep(1:nl,each=ncol(c1)),sep="t-")
colnames(c1wlags)=c(nams,ndfs)
cov(c1wlags)

> cov(c1wlags)
               X1          X2           X3       X1t-1       X2t-1        X3t-1       X1t-2       X2t-2       X3t-2
X1     1.02206766 -0.13725252  0.153975857 -0.04152948  0.02664973 -0.123077418 -0.16800464  0.26851379 -0.25855822
X2    -0.13725252  0.73845275 -0.213758648  0.09490394 -0.11391726 -0.032365562  0.01863737  0.02661447 -0.11817727
X3     0.15397586 -0.21375865  0.797592802 -0.44057820  0.05532353 -0.007062553 -0.15315625  0.24462652 -0.19898668
X1t-1 -0.04152948  0.09490394 -0.440578196  0.96044907 -0.13594448  0.101988693  0.01357564  0.02734684 -0.11077465
X2t-1  0.02664973 -0.11391726  0.055323528 -0.13594448  0.74666015 -0.206596930  0.10511073 -0.11827071 -0.03883939
X3t-1 -0.12307742 -0.03236556 -0.007062553  0.10198869 -0.20659693  0.758188218 -0.38571731  0.05271998 -0.00125309
X1t-2 -0.16800464  0.01863737 -0.153156254  0.01357564  0.10511073 -0.385717313  0.92688519 -0.14256158  0.08240385
X2t-2  0.26851379  0.02661447  0.244626522  0.02734684 -0.11827071  0.052719977 -0.14256158  0.74893806 -0.20346301
X3t-2 -0.25855822 -0.11817727 -0.198986683 -0.11077465 -0.03883939 -0.001253090  0.08240385 -0.20346301  0.76041872


text:
Q: How to return a VkPhysicalDevice from vkEnumeratePhysicalDevices I'm following a game engine tutorial in Vulkan and came across an issue where vkEnumeratePhysicalDevices is populating my 'devices' vector with pointers to the stack. VkPhysicalDevice appears to be the typedef of a pointer, VkPhysicalDevice_T*. I get a warning on Visual Studio about this issue, and I'm wondering if there's a way to have the function allocate to heap instead.
Edit: At "return devices[i]" I get the warning "C26816: The pointer points to memory allocated on the stack."
VkPhysicalDevice VulkanRenderer::selectPhysicalDevice() {
    U32 deviceCount = 0;
    vkEnumeratePhysicalDevices(_instance, &deviceCount, nullptr);
    if (deviceCount == 0) {
        Logger::Fatal("No supported physical device was found.");
    }
    std::vector<VkPhysicalDevice> devices(deviceCount);
    vkEnumeratePhysicalDevices(_instance, &deviceCount, devices.data());

    for (U32 i = 0; i < deviceCount; ++i) {
        if (physicalDeviceMeetsRequirements(devices[i])) {
            return devices[i];
        }
    }

    Logger::Fatal("No devices found which meet application requirements.");
    return nullptr;
}

A: I get this one too. It comes from static analysis related to the newish C++ guidelines.
The dispatchable handles in Vulkan are pointer-like things. The modern C++ conventions do not like raw pointers though. The static analyzer seems to incorrectly think the std:vector is tied to the lifetime of whatever is under that pointer.
At the time of writing, this code seems to avoid the static analyzer warning:
const VkPhysicalDevice d = devices[0];
return d;

Additionally, the warning could just be specifically silenced:
#ifdef _MSC_VER
#pragma warning( suppress: 26816 )
#endif
return devices[0];


text:
Q: Can bosons have anti-particles? Can bosons have anti-particles? In the past, I would have answered this question with a yes,  primarily because I can imagine writing down a QFT for complex scalars that has a $U(1)$ symmetry that allows me to assign a conserved charge. That is, I expect to obtain a charged spin-0 boson with an additive quantum number. A $CP$-transformation would change these quantum numbers into their negatives and I would consider the corresponding particle an anti-particle.
Of course I know at the same time that Standard Model particles, such as the $Z$-boson and the Higgs boson, are considered not to have observable anti-particles (in the way that electrons have, for instance). On the other hand, mesons are considered (composite) bosons and are known to have anti-particles. I used to take the viewpoint that the mentioned elementary bosons are their own anti-particles, because they are charge-neutral.
After reading, by chance, an interview with Geoff Taylor (Melbourne)  I am a bit confused, however. He says that bosons can not have anti-particles, because this property is restricted to Fermions and explicitly refutes the idea that they are their own anti-particles:

"Really fermions are the things where we have this idea of a particle
  and anti-particle pair," says Taylor, "anti-particles at the
  fundamental level are fermions with the opposite charge."
"The $W+$ and $W-$ bosons only differ by charge so it's an easy mistake to
  talk about it that way [as particle and anti-particle], but it's just a pair of different charges."
"While they behave in some sense like particle and anti-particle, we
  don't think of one as the anti-particle counterpart of the other
  because they're force carriers," says Taylor
"Fermions have conservation laws associated with them, so for example
  they are created in particle-anti-particle pairs, the sum of their
  quantum numbers cancelling to maintain the conservation laws,"
  explains Taylor.
"Bosons operate under different laws and can be created singly. This
  is a crucial distinction and is in nature of being either matter
  particles or force carriers."

(It should perhaps be mentioned that he works in experimental HEP-data analysis and not theory, but still he could know more.)
Which, if any, of these viewpoints is correct?

A: In the standard model, there is no elementary spin 0 boson being electrically charged (but there are many charged spin 0 composite particles). However, in many extensions such as supersymmetry, there are such particles: the scalar partner of the electron, the selectron carries the same charge as the electron. The anti-selectron is the spin 0 partner of the positron. Thus the answer to your question is yes.

A: In the Rishon Model (still non-mainstream, but how knows what the future brings; the model has a lot of advantages), made up by the great mind of Haim Harari, the $Z^0$ particle is considered to be a composite particle which consists of three T-Rishons and three anti-T-Rishons. Each T-rishon is considered to have a charge of $+\frac 1 3$ and two other kinds of charges (the color force and the hyper color force). So all these charges are opposite for the anti-$Z^0$ particle. In other words, the $Z^0$ and the $\bar{Z}^0$ are the same.
In the same model, the $W^+$ is considered to be a combination of three T-rishons and three V-rishons (which have a zero electric charge). In the model, it is considered not to be the fundamental weak force transmitting particle, just like the pion, which was once thought to be the fundamental transmitter of the strong force, turned out not to be the fundamental transmitter, but the gluon. In the model this is the hyper color gluon, transmitting the hyper color force, a particle similar to the gluon, which reduces the weak force to a residue force (like the strong force transmitted by the pion turned out to be a residue force). The $W^-$ in this model is the antiparticle of the
$W^+$.
The gluons and similar hypercolor (see the article) gluons (both bosons) are force transmitting particles, though their antiparticles are clearly different particles.
Maybe you can think for yourself how the Higgs is represented in the model.
It's true though that the antiparticles of all quarks and leptons (fermions) are different particles (especially the neutrino, of which only the left handed one exists).


text:
Q: Eeeeek where is my slow performance‽‽‽ Over the past couple of days, I have noticed that Stack Overflow is faster than ever.  This is severely affecting my thumb twiddling time.  When am I supposed to practice my thumb twiddling if I don't have to wait for the pages to load??  Please think of the thumb twiddlers when considering future performance enhancements!
Eeeek what have you done‽‽‽

A: We looked closely at performance over the last few weeks, particularly in the last 4 or 5 business days.

*

*we reduced the total number of queries happening on a lot of pages (question show, question lists, user page, etc.)

*we deployed a page that shows us our worst query offenders in CPU time, total duration, reads, writes, etc. and optimized the stuff at the top of the lists

*we improved the way we call LINQ to SQL and moved to pre-compiled LINQ queries in certain hot code paths. This seems to have gotten much faster in .NET 4.0, we saw 8x gains over plain vanilla LINQ and 2x over SQL-queries-as-LINQ-returns.

*we reduced the number of columns we return in some hot code paths, where we had effectively select * from users and posts.

*we were getting sloppy about the way we handled search engines, which was causing a lot of undue load -- Google's crawler is now indexing us at, and I am not making this up, 10 requests per second which is the maximum. This is confirmed in Google Webmaster Tools. Google doesn't need all the same work done per page that, say, a user does -- and when Google hits thousands of pages in a few minutes, that can kick off a lot of background work, such as rebuilding related questions. Not expensive by itself, but when multiplied by a hundred at once.. can be quite painful.

*we optimized the way we retrieve site settings and configuration, which occurs sometimes hundreds of times per page.

*we had some shared lock blocking and other general inefficiencies in our Redis C# library which was causing Redis (network level cache) to be slower and more blocking that it should be. This has been rewritten to be faster and block far less.

*all our database calls were not quite going through the same central hub (almost, not quite) causing too many database connections in some circumstances. This has been correctly centralized now.

*lots of general profiling with .NET profiling tools to identify places where we had gotten sloppy and were doing something inefficient.

*we are restructuring and reorganizing our JavaScript to make the delineation between "only anonymous users need this" and "registered users need this" clear, so as to reduce the footprint of our site to an absolute minimum for anonymous users. This also significantly improves page load time (perceived and actual) for registered users as well.
Some Google details:

A: Move to New Zealand, you'll have plenty of network-induced delays! Especially if you happen to be behind a corporate firewall, that always helps.

A:
But really read this. And then just realize our devs are crazy.


text:
Q: Min-Width and Initial-Scale in Bootstrap I'm using Bootstrap for the first time. My design needs to have a minimum width of 400px. When I load the page on a device with a narrower width (my Nexus 5 has a width of 360px), it overflows the viewport, and horizontal scrolling is needed to view the content. I would like it to be automatically scaled to fit the viewport. How can I accomplish this?

A: As I suggested in the comment, you can use a responsive image in bootstrap.  See this link:http://getbootstrap.com/css/#images-responsive

A: you answered you own question, you need to set your body to have a min width.
body{
   min-width:1000px; /* suppose you want minimun width of 1000px */
   width: auto !important;  /* Firefox will set width as auto */
   width:1000px;             /* As IE ignores !important it will set width as 1000px; */
}


text:
Q: How to load corresponding data in a given Search I already make a program that save the entered data in the textfields. It's saving technique is like this
data0 = student number
data1 = name
data2 = section
data3 = cp
data4 = email
data5 = address

inside the saved file:
data0 | data1 | data2 | data3 | data4 | data5
data0 | data1 | data2 | data3 | data4 | data5
data0 | data1 | data2 | data3 | data4 | data5
data0 | data1 | data2 | data3 | data4 | data5
data0 | data1 | data2 | data3 | data4 | data5

data0 has is unique,
this is the code I use to search Student No. "data0"
if I search 12293 for example
data0 | data1 | data2 | data3 | data4 | data5
data0 | data1 | data2 | data3 | data4 | data5
12293 | blahh | blehh | blihh | blohh | bluhh
data0 | data1 | data2 | data3 | data4 | data5

and there's a match in line 3, blah,blehh,blihh,blohh,bluhh must be printed in different textarea
but I don't know how to slice data1|data2|data3|data4|data5| into a array when a search has a match
this my code:
import java.io.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Jfetizanan
 */
public class DATALOAD {

    /**
     * @param args the command line arguments
     * @throws UnsupportedEncodingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, IOException {
        try{
      FileInputStream fstream = new FileInputStream("data.dat");
            try (DataInputStream in = new DataInputStream(fstream)) {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String strLine;
                while ((strLine = br.readLine()) != null)   {

                 if (strLine.startsWith("JFETZ")){
                 System.out.println("Data Found");

                 }
                 else
                 {System.out.println("Nothing Found in this line");}
                }
            }
      }catch (Exception e){
          System.err.println("Error: " + e.getMessage());
      }
    }
}

A: split() it by | do
String values[] = strLine.split("\\|");

and compare the search key with first element of array values[0]
while ((strLine = br.readLine()) != null)   {
 String values[] = strLine.split("\\|");
 if ("JFETZ".equals(values[0]))){
   System.out.println("Data Found");
 }else{
   System.out.println("Nothing Found in this line");}
 }
}

A: You get str like :
String str = "12293 | blahh | blehh | blihh | blohh | bluhh";
String[] arr = str.split("\\| "); // give space after | to trim spaces


text:
Q: Is the element $(0,0,0)\in\mathbb{R}^3$ a divisor of zero? (I'm assuming that $\mathbb{R}^3=\mathbb{R}\times\mathbb{R}\times\mathbb{R}$)
In my assignment, I'm told to prove that exactly one of the following can be true for an element $(x,y,z)\in\mathbb{R}^3$

*

*$(x,y,z) = (0,0,0)$

*$(x,y,z)$ is invertible

*$(x,y,z)$ is a divisor of zero

I'm starting with the first. Given the definition of the operations on the ring $A=\mathbb{R}\times\mathbb{R}\times\mathbb{R}$ (we were given non-standard multiplication), the multiplicative identity is $(1,0,0)$.
There's no way that, given our definition, $(0,0,0)(0,0,0)^{-1}=(1,0,0)$ so it's not invertible.
However, my issue is with showing that it is not a zero divisor. Whenever I use algebra to find each component of another element in the ring $p$, such that $p\cdot(0,0,0)=(0,0,0)\cdot p= (0,0,0)$, this is always true. Any suggestion?

A: By "zero divisor," your book probably means that $v \in \Bbb{R}^3$ is a zero divisor if and only if there exists some $a \in \Bbb{R}^3$ such that $a, v \neq 0$ and $av=\textbf{0}$. Therefore, $(0, 0, 0)$ is not a zero divisor because $(0, 0, 0) \neq \textbf{0}$ is false.
It is important to note that $(0, 0, 0)$ is intentionally excluded from the definition of zero divisor because some mathematicians think that this is a more useful definition of zero divisor. This way, we can talk about rings without zero divisors called integral domains, where if $av=\textbf{0}$, then either $a=\textbf{0}$ or $v=\textbf{0}$. This would be rings like $\Bbb{R}$ or $\Bbb{R}^3$ where you can't get $\textbf{0}$ by multiplying two non-zero elements.
Thus, because of the definition of zero divisor used in your book, $(0, 0, 0)$ is not a zero divisor.

A: You can actually have zero divisors depending on how multiplication is defined. If addition is point-wise, then (1,0,1)(0,1,0)=(0,0,0).
You said you were given non-standard multiplication. Was it defined for you?


text:
Q: Maven assembly plugin fails to execute I'm getting this message after attempting to "mvn package". It seems like there's an issue with retrieving the google collections jar, but I'm not sure if that's the only problem.
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-assembly-plugin:2.3:single (make-assembly) on project recommender:
  Execution make-assembly of goal org.apache.maven.plugins:maven-assembly-plugin:2.3:single failed:
  Plugin org.apache.maven.plugins:maven-assembly-plugin:2.3 or one of its dependencies could not be resolved:
  Failed to collect dependencies for org.apache.maven.plugins:maven-assembly-plugin:jar:2.3 ():
  Failed to read artifact descriptor for com.google.collections:google-collections:jar:1.0:
  Could not transfer artifact com.google.collections:google-collections:pom:1.0 from/to central (http://repo1.maven.org/maven2):
  Specified destination directory cannot be created: /Users/danquach/.m2/repository/com/google/collections/google-collections/1.0 -> [Help 1]

A: The original error should be a local problem:
Specified destination directory cannot be created:
/Users/danquach/.m2/repository/com/google/collections/google-collections/1.0

*

*Is your drive full?

*Do you have write access to this path?

You can try to create /Users/danquach/.m2/repository/com/google/collections and call maven again.


text:
Q: Follow up medical study with missing data I am analyzing some patient data for a medical study that has a duration of several years.
Once a year, the patients are expected to visit the doctor, where they get four treatments, say A, B, C, D. Afterwards, to get an indication for the effect of each treatment the patient is scored on a numerical scale (same scale for each treatment).
For various reasons I have a lot of missing data because a patient may:
1. Miss the appointment, and I end up with missing data on specific years.
2. Not get all four treatments due to reasons related to the health of the patient or other technical reasons.
I am interested in both:
1. Finding whether there are differences in the mean score for each treatment separately over time.
2. Finding whether at specific point in time, there are differences in the mean score between the treatments.
Since the data for each year are not independent, the right tests to use to check whether there are differences in the mean scores for each treatment for different years is  e.g., paired t-test or repeated measures ANOVA.
To have complete sets of data over the years, I must have different samples, i.e., I can find X patients that had treatment A for n years and then Y different patients that had treatment B for n years. For each group I would then perform e.g., paired t-test and then draw conclusions from it.
Is this methodology sound? Or are there other factors that I need to take into account for having a correct comparison between different groups?

A: A better option compared to paired t-test and repeated measurements ANOVA (also with regard to the missing data you have), is to use a (linear) mixed-effects model. In this model, you should appropriately specify the time effect for the score variable (i.e., is it linear/nonlinear), and its interaction with treatment indicator (i.e., a factor with levels A-D). You will also need to appropriately model the correlation structure, using, for example, random intercepts and (potentially nonlinear) random slopes. Also because at each visit you have up to four score values per patient, it may also be required to consider a nested random effect for the visit.
This type of models provided that the mean and correlation structures are appropriately specified will provide you with correct inferences under the missing at random assumption (i.e., the reasons why patient miss visits may depend on their previously observed score values).
If you're interested in learning more about these models, you can have a look in my Repeated Measurements course notes.


text:
Q: DSO missing from command line I am trying to compile a C++ program like this:
$ g++ -o Sniffer_Train main.cpp Sniffer_train.cpp Sniffer_train.h -lmysqlclient -lpcap

However I get the following error:
/usr/bin/ld: /tmp/cct6xeXD.o: undefined reference to symbol
'pthread_join@@GLIBC_2.4' //lib/arm-linux-gnueabihf/libpthread.so.0:
error adding symbols: DSO missing from command line

collect2: error: ld returned 1 exit status

I have no idea what this error means. Any help will be greatly appreciated.

A: DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.
That is, try adding -lpthread to your command line.


text:
Q: Mutex across network - C#.NET I have a message queue on a shared system. This queue is accessed by 2 processes which run on 2 other machines. I need to control access to this queue by the 2 processes. So I need a "network mutex". How can I achieve this?
I don't think this is supported out of the box in C#.NET but if I have missed something very obvious, do point me in the right direction. This question has been asked before but the solutions suggested involved a database. I dont have any database in question.
How To Mutex Across a Network?

A: You need a third process, which actually owns the queued items.  The two workers each ask the third process for the next item, and it's this third process that polices access and acts as the lock.

A: Use MSMQ or other queuing system design for use across a network.
Win32 has no cross machine synchronisation primitives like a muxtex, you might be able to build something from file locking, but you would just be re-inventing MSMQ.

A: I think I found what I was looking for ... and it turns out to be a simple property setting!
http://msdn.microsoft.com/en-us/library/system.messaging.messagequeue.denysharedreceive%28VS.80%29.aspx
Should have explored this first!!
Jeff key has reported an issue with this and his experience:
http://weblogs.asp.net/jkey/archive/2004/05/12/130922.aspx
Thank you all for the help.


text:
Q: LaTeX Error: \begin{table} on input line XXX ended by \end{document} I am facing a problem with my LaTeX code.
I receive the error message \begin{table} on input line XXX ended by \end{document}.
But, I have no idea what went wrong as I actually have \end{table} in my code.
Any help?
Here's the code:
\begin{document}

\begin{table}[H]
\centering
\begin{tabular}{||c c c c c||}
 ...
\end{tabular}
\caption{YYY}
\label{table 7}
\end{table}

\end{document}

The used packages are the following:
\documentclass[fleqn,12pt,a4paper]{article}%leqno,fleqn,
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{array}
\usepackage[T1]{fontenc}
%\usepackage[ngerman]{babel}
%\usepackage{german}
%\usepackage{emlines}
%\usepackage{amssymb}
\pagestyle{myheadings}\setlength{\parindent}{0em} \sloppy
\mathindent10mm
\usepackage{xurl}

%packages for the table footnotes
\usepackage{footnote}
\makesavenoteenv{tabular}
\makesavenoteenv{table}
\usepackage{scrextend}

\usepackage{hyperref}

\usepackage{float}

\usepackage{color}
\usepackage{amsmath}
\usepackage{pdflscape}

\usepackage{graphicx}
\usepackage{graphics}
\usepackage{array}
\usepackage{xcolor}

\usepackage{hyperref}

\usepackage[
backend=biber,
style=apa
]{biblatex}

%\usepackage{german}
%\usepackage{emlines}
%\usepackage{amssymb}
\pagestyle{myheadings}
\setlength{\parindent}{0em}
\sloppy
\mathindent10mm

\graphicspath{ {./Images/} }

%\oddsidemargin+25mm
%\topmargin-5mm
%\textwidth145mm
%\textheight245mm
%\footskip20mm
%\renewcommand{\baselinestretch}{1.5}

A: You get this error because you can't use the H option with \makesavenoteenv{table}. There are other questions on this site about this, like this one or this one. If I take your code and remove the line
\makesavenoteenv{table}

from the preamble, the document compiles.
Now, do you really need (or even want) this line? It would be a good idea to make sure that you know what each line of the preamble is supposed to do, and something tells me you haven't been careful about that. For example:

*

*You load graphicx, array and hyperref twice,

*You load both graphicx and graphics and both color and xcolor, while in both cases you should really only use one of them.

Understanding what each line of the preamble is doing might certainly save you some trouble later.


text:
Q: transact sql temporal table and user-defined data type Sorry for my english.
I have the following definitions in a visual studio 2017 dacpac project (target platform = SQL SERVER 2016).
CREATE SCHEMA [Demo]
CREATE TYPE Demo.Code FROM NVARCHAR(16) NOT NULL
CREATE TABLE [Demo].[Gear] (
    [Id] int identity(1,1) primary key,
    [Name] nvarchar(25) not null,
    [Code] [Demo].[Code],
    [rowguid] uniqueidentifier constraint [DF_Gear_rowguid] default (newid()) rowguidcol not null,
    [ValidStart] DATETIME2 GENERATED ALWAYS AS ROW START NOT NULL,
    [ValidEnd] DATETIME2 GENERATED ALWAYS AS ROW END NOT NULL,
    PERIOD FOR SYSTEM_TIME([ValidStart], [ValidEnd])
)
WITH ( SYSTEM_VERSIONING = ON(HISTORY_TABLE = [Histo].[Gear]) )
GO

After build, I have this error :

SQL71609: System-versioned current and history tables do not have
  matching schemas. Mismatched column: '[Demo].[Gear].[Code]'.

Without user defined data type, it's okay. Is someone knowing that's the problem ?


text:
Q: How to limit the number of users in a group in Django-Admin I've been searching for an answer to this all over and I can't seem to find it. I created a group in django admin and I want to limit the number of users that can be added to it. What's the best way to do that?

A: this code should be what you need:
change the group name ('LIMITED' in the example and the value LIMIT for your needs.
Anyway this code does not guarantee 100% what you are looking for, as 2 different processes that run simultaneously can by-pass this check (both read group.user_set.count() < LIMIT and allow the operation)
there is no out of the box solution to prevent this in django
from django.contrib.auth.admin import UserAdmin as _UserAdmin, User
from django.contrib.auth.forms import UserChangeForm as _UserChangeForm

class UserChangeForm(_UserChangeForm):
    def clean_groups(self):
        groups = self.cleaned_data.get('groups', [])
        for group in groups:
            if group.name == 'LIMITED' and group.user_set.count() == LIMIT:
                raise ValidationError('Group %s does not accept more users' % group.name)
        return self.cleaned_data.get('groups')

class UserAdmin(_UserAdmin):
    form = UserChangeForm

admin.site.unregister(User)
admin.site.register(User, UserAdmin)


text:
Q: Solve the equation $\log_{1-2x}(6x^2-5x+1)-\log_{1-3x}(4x^2-4x+1)=2$ Solve the equation $$\log_{1-2x}(6x^2-5x+1)-\log_{1-3x}(4x^2-4x+1)=2$$
We have $$D_x:\begin{cases}1-2x>0\\6x^2-5x+1>0\\1-3x>0\\1-3x\ne1\\4x^2-4x+1>0\iff(2x-1)^2>0\iff x\ne\dfrac12\end{cases}\iff x\in(-\infty;0)\cup(0;\dfrac{1}{3})$$
Also the quadratic $6x^2-5x+1$ factors as $(2x-1)(3x-1)$. The equation then becomes $$\log_{1-2x}(2x-1)(3x-1)-\log_{1-3x}(2x-1)^2=2\\\log_{1-2x}(2x-1)(3x-1)-2\log_{1-3x}(1-2x)=2,$$ as $\log_{1-3x}(2x-1)^2=2\log_{1-3x}|2x-1|,$ but we know from $D_x$ that $2x-1<0$,
$$\log_{1-2x}(2x-1)+\log_{1-2x}(3x-1)-\dfrac{2}{\log_{1-2x}(1-3x)}=2$$ I don't know what to do next.

A: You're almost there, but you may use a simplified method such as this:
$$\log_{1-2x}(2x-1)(3x-1) - 2\log_{1-3x}(1-2x)=2$$
$$\log_{1-2x}(1-2x)(1-3x) - 2\log_{1-3x}(1-2x)=2$$
$$\log_{1-2x}(1-2x)+\log_{1-2x}(1-3x) - 2\log_{1-3x}(1-2x)=2$$
$$\log_{1-2x}(1-3x) - 2\log_{1-3x}(1-2x)=1$$
$$\frac{1}{\log_{1-3x}(1-2x)} - 2\log_{1-3x}(1-2x)=1$$
Now you can set $\log_{1-3x}(1-2x)=t$ and get:
$$\frac{1}{t}-2t=1$$
This will give you a quadratic in terms of $t$ which you can solve for and substitute back into the substitution and solve for $x$ that way.

A: We have that for $1-2x>0$, $1-3x>0$, $1-2x\neq 1$, $1-3x\neq 1$
$$\log_{1-2x}(6x^2-5x+1)-\log_{1-3x}(4x^2-4x+1)=2 $$
$$\iff \frac{\log((1-2x)(1-3x))}{\log (1-2x)}-2\frac{\log (1-2x)}{\log (1-3x)}=2$$
$$\iff \frac{\log (1-3x)}{\log (1-2x)}-2\frac{\log (1-2x)}{\log (1-3x)}=1$$
then by $u= \frac{\log (1-3x)}{\log (1-2x)}$ we obtain
$$u-\frac 2 u =1 \implies u = \frac{\log (1-3x)}{\log (1-2x)}=2 \implies x=\frac14$$

A: The key here is to use the change of base formula for logs: $\log_c(x)=\frac{\log_b(x)}{\log_b(c)}$.  Using this allows us to express everything in terms of a common base, which then lets us use other log rules.
$$\frac{\log (1-2x)(1-3x)}{\log (1-2x)}-\frac{\log[(1-2x)^2]}{\log(1-3x)}=2.$$
Using log properties, this simplifies to
$$1+\frac{\log (1-3x)}{\log (1-2x)}-2\frac{\log[(1-2x)]}{\log(1-3x)}=2.$$
For ease of notation, let us write $u=\log(1-2x), v=\log(1-3x)$.  Then $\frac{v}{u}-2\frac{u}{v}=1$.  The easiest approach is to notice that we reciprocals, so that if $t=u/v$, then $1/t - 2t=1$.  Multiplying through by $t$ yields a quadratic to solve for $t$, and then for $x$.  However, if we do not make that realization, we may proceed as follows.
Multiplying by $uv$ to clear denominators, and moving everything to one side, we get
$$v^2-uv-2u^2=0$$
This factors as $$(v+u)(v-2u)=0$$
and so either $v+u=0$, or $v-2u=0$, i.e., either $\log(1-2x)(1-3x)=0$ so $(1-2x)(1-3x)=1$, or $\log\left(\frac{1-3x}{(1-2x)^2}\right)=0$, so $\frac{1-3x}{(1-2x)^2}=1$.  This gives a linear and a quadratic equation to try to solve for $x$.


text:
Q: symfony translation doctrine empty object_id database field I'm trying to implement this translation example (https://gist.github.com/tristanbes/2116290) with SonataAdminBundle & DoctrineExtensions, but when I run the create action form, the database translation field object_id is empty. All other fields are filled correctly on database!
My database schema:
CREATE TABLE `Book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` longtext,
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_6BD70C0F5E237E06` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1

CREATE TABLE `book_translations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`object_id` int(11) DEFAULT NULL,
`locale` varchar(8) COLLATE utf8_unicode_ci NOT NULL,
`field` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`content` longtext COLLATE utf8_unicode_ci,
PRIMARY KEY (`id`),
UNIQUE KEY `lookup_unique_idx` (`locale`,`object_id`,`field`),
KEY `IDX_9F5610DF232D562B` (`object_id`),
CONSTRAINT `FK_9F5610DF232D562B` FOREIGN KEY (`object_id`) REFERENCES `Book` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Can anyone help me? I have the same source!!!
Thanks in advance,
Luis Miguens


text:
Q: Excel Html Automation I have an excel sheet which has data of the employee leave applications.
This sheet gets data from a userform which is filled by an employee.
The data then gets stored in the excel sheet for the review of manager.
What i want to do is that as soon as an entry is created it should generate a report of that particular leave application which contains all the details of the leave and save it in an html format.
Also once the manager reviews the leave application he writes comments in the application which should again get updated automatically in the html file.
I want to convert to html with a specific filename so that the file can be uploaded to my webserver and can be accessed by us anywhere and at anytime!
I also use this vba code to send email to the manager as soon as the entry is made.

Sub Leave_mail()

Dim aOutlook As Object
Dim aEmail As Object
Dim rngeAddresses As Range, rngeCell As Range, strRecipients As String

Set aOutlook = CreateObject("Outlook.Application")
Set aEmail = aOutlook.CreateItem(0)

'set Importance
aEmail.Importance = 2
'Set Subject
aEmail.Subject = "EMS- " & frmLeaveappl.txtname.Text & " IS REQUESTING FOR LEAVE for: " & frmLeaveappl.txtfrom.Text & "................................"
'Set Body for mail
aEmail.htmlbody = "

LEAVE REQUEST FROM AN EMPLOYEE

" & vbNewLine & vbNewLine & "NAME OF EMPLOYEE: " & frmLeaveappl.txtname.Text & "
" _
                & vbNewLine & "From: " & frmLeaveappl.txtfrom.Text & "
" _
                & vbNewLine & "To: " & frmLeaveappl.txtto.Text & "
" _
                & vbNewLine & "Reason for leave: " & frmLeaveappl.txtreason.Text & "
" _
                & vbNewLine & "Application Number: " & frmLeaveappl.txtapno.Text & "

" _
                & vbNewLine & vbNewLine & vbNewLine & "The Status for this leave is pending!"

aEmail.Recipients.Add ""

'Send Mail
aEmail.Send
End Sub

A: Record a macro doing a SaveAs HTML file????????????????????
Alt + T, M, R
then Home key then Up Arrow. Stop recording.
Gee look what Excel wrote
Selection.End(xlUp).Select

or if you had of recorded Go To dialog
Application.Goto Reference:="R1C1"

or if you had of recorded Ctrl + Home
Range("A1").Select

or Saving a Web Page
    ActiveWorkbook.SaveAs Filename:="C:\Users\User\Documents\Book1.htm", _
    FileFormat:=xlHtml, ReadOnlyRecommended:=False, CreateBackup:=False


text:
Q: Lost my github credentials; Now being prompted for username and getting an error I had to do a coding challenge last night that involved cloning a github repo. It was a hot mess and I frantically changed a bunch of settings trying to get it to work. Now, it appears that my personal account is broken as when I try to push code this morning, I get an authentication request and it fails.
Here is what happens:
git push origin master
(response from terminal)
Username for 'https://github.com':(I enter my email)
Password for '(my email)@github.com': (I enter my password)
remote: Invalid username or password.

I deleted the ssh key last night and uploaded a new one. I am sure that has something to do with it. I am also not sure why it is adding the @github to my email when I enter it.

A: You should use:

*

*your GitHub user account name, not email

*a PAT (Personal Access Token) as password, especially since Dec. 2020, and the Token authentication requirements for Git operations.

Check also your git config credential.helper: it could have cached another user/email/password.
If that setting is xxx, type:
printf "protocol=https\nhost=github.com"| git-credential-xxx get

You will check if there is any credential already stored.


text:
Q: Overlapping probability of two normal distribution tfp.distributions.Normal() How to calculate overlap probability of two tfp.distributions.Normal?
Like the one implemented within
https://docs.python.org/3.8/library/statistics.html?highlight=normaldist#statistics.NormalDist

A: here is my implementation based on statistics.NormalDiststatistics.NormalDist code:
    dv = Y.variance() - X.variance()
    dm = tf.math.abs(Y.mean() - X.mean())

    if tf.reduce_sum(dv) == 0:
         return 1.0 - tf.math.erf(
             tf.math.divide(dm,
                            tf.math.multiply(
                                tf.constant(2, dtype=tf.float32),
                                tf.math.multiply(
                                    X.stddev(),
                                    tf.math.sqrt(tf.constant(2, dtype=tf.float32))))))
    a = tf.math.multiply(X.mean(), Y.variance()) - tf.math.multiply(Y.mean(), X.variance())
    b = tf.math.multiply(
            tf.math.multiply(X.stddev(), Y.stddev()),
            tf.math.sqrt(tf.math.pow(dm, 2) + tf.math.multiply(
                dv,
                tf.math.log(Y.variance() / X.variance()))))
    x1 = (a + b) / dv
    x2 = (a - b) / dv

    return 1.0 - (tf.math.abs(Y.cdf(x1) - X.cdf(x1)) + tf.math.abs(Y.cdf(x2) - X.cdf(x2)))def norm_dist_overlap_prob_v1(X: tfp.distributions.Normal, Y: tfp.distributions.Normal):
    dv = Y.variance() - X.variance()
    dm = tf.math.abs(Y.mean() - X.mean())

    if tf.reduce_sum(dv) == 0:
         return 1.0 - tf.math.erf(
             tf.math.divide(dm,
                            tf.math.multiply(
                                tf.constant(2, dtype=tf.float32),
                                tf.math.multiply(
                                    X.stddev(),
                                    tf.math.sqrt(tf.constant(2, dtype=tf.float32))))))
    a = tf.math.multiply(X.mean(), Y.variance()) - tf.math.multiply(Y.mean(), X.variance())
    b = tf.math.multiply(
            tf.math.multiply(X.stddev(), Y.stddev()),
            tf.math.sqrt(tf.math.pow(dm, 2) + tf.math.multiply(
                dv,
                tf.math.log(Y.variance() / X.variance()))))
    x1 = (a + b) / dv
    x2 = (a - b) / dv

    return 1.0 - (tf.math.abs(Y.cdf(x1) - X.cdf(x1)) + tf.math.abs(Y.cdf(x2) - X.cdf(x2)))```

A: You might do well to watch Pierre Jacob's excellent series on couplings. If I understand correctly, the integral you want to compute here is connected to the total variation distance.
I have a little demo of sampling max-coupled distributions with TFP here https://colab.research.google.com/gist/brianwa84/2b78eb819ad9cfb910f9a6eb62b4a402/maximal-couplings.ipynb
I don't know off hand if the integral is analytically tractable or not.


text:
Q: Jquery Load external pages duplicate Id issue Our page loads two external pages (same url) using $("#div1").load(mypageurl) & $("#div2").load(mypageurl). Each div is opened as a Jquery UI dialog on click of their respective buttons
The external page has some initial load logic to select an internal element and set some value.
Issue is since the URL is same, the id gets duplicated and hence the setting of element does not work for the dialog opened second
If I clear the first div $("#div1").html("") everytime before loading the second div, it works alright
Is there any other alternative? Can I do something in my external page to restrict the jquery search of elements within the same page scope?
Pinakin

A: Wouldn't it be fine to empty it on close then, or am i missing something??
$( ".selector" ).dialog({
   close: function(event, ui) {
      $(this).empty();
   }
});

A: Could you simply avoid the problem by replacing all ids on the loaded page with class references instead?


text:
Q: Student's t-test versus Wilcoxon signed-rank test Trying to understand when to use which test, am I correct when saying both these tests, test whether two samples could be taken from the same distribution, but the difference is that the student's t-test assumes that the distributions that are tested have a normal distribution (Gauss distribution), while the Wilcoxon signed-rank test accept any type of distribution?

A: There are three t-tests:

*

*One sample

*Independent samples

*Paired samples

Since Wilcoxon signed rank is about paired samples, I will assume you are comparing it to a paired sample t-test.
The paired sample t-test does not assume the distributions are normal, it assumes the differences are normal. Then it sees if the differences are different from 0 (usually; it is possible to change this); essentially. Wilcoxon, on the other hand, tests whether the mean ranks are different.
Neither one tests the rather general proposition that you state: "from the same population". For instance, suppose you have two samples, both from populations with mean = 10, but one with sd = 2, the other with sd = 100. Neither t nor Wilcoxon will show a difference:
set.seed(1234)
x1 <- rnorm(1000, 10, 2)  #Normal, mean = 10, sd = 2, N = 1000
x2 <- rnorm(1000, 10, 10) #Normal, mean = 10, sd = 1-0, N = 1000

t.test(x1, x2, paired = TRUE) #t = -0.32, df = 999, p = 0.53
wilcox.test(x1, x2, paired = TRUE) #V = 243625 p = 0.40

You could even have much more different distributions:
x3 <- runif(1000, 0, 20)
t.test(x1, x3, paired = TRUE) #t = 1.25, df = 999, p = 0.21
wilcox.test(x1, x3, paired = TRUE) #V = 242525 p = 0.40

But if you do plot any pair of variables, you will see they are very different. E.g.
boxplot(x1, x2)
qqplot(x1,x2)
abline(a = 0, b = 1)


text:
Q: How do I update javascript variables with new values which are changing in my database? I'm building a multiplayer game which uses a mysql database to store coordinate positions of players, which are then used to display opponent models.
The game uses a javascript file (milktruck.js) on the client side, and then a php file (xml_http_request.php) on the server side.
My problem occurs when trying to get the javascript variables (which store the coordinate information of an opponent) updated as the database information is updated.
The javascript variables are declared within the php file with the following code:
  echo "<script> var lla0php = $lla0; </script>";
  echo "<script> var lla1php = $lla1; </script>";
  echo "<script> var lla2php = $lla2; </script>";

Then used in the javascript file, ticking function: prototype.tick, with:
  window['lla0_2']= lla0php;
  window['lla1_2']= lla1php;
  window['lla2_2']= lla2php;

How do I continuously update these variables with new database information?

A: The web model is stateless, and to do this you're going to have to think of a way to overcome this and may possibly consider writing an abstraction layer that takes care of this for you.
You'll either need to poll continuously or look into other web-based solutions that allow the server to "push" data back to the client and maintain an "open channel" of communication. An example of this would be Google Talk in your browser or FaceBook chat.

A: What you need to do is use ajax.

function requestCoord(){
    $.ajax({
        url: "your url",
        dataType : "json",
        type: "GET",
        success(val){
            //get your php script to echo out a json string
                        //and it will be in val
            window['lla0_2']= val.lla0php;
            window['lla1_2']= val.lla1php;
            window['lla2_2']= val.lla2php;

        }
    });
}

setInterval(requestCoord, 1000);

UPDATE
You can use html5 sockets.


text:
Q: Работа с таблицами в FireBase Как я могу редактировать/добавлять записи в таблицах Firebase?
Официальные документация предлагает делать так:
function writeUserData(name) {
  firebase.database().ref('users/' + '1').set({
    name: 'newUserName'
  });
}

В firebase я соответственно имею следующую структуру бд:
app738b
    -users
        -1
          -name: 'username'

После этого поле name должно измениться, но ничего не происходит.

A:

function writeUserData(username) {
  firebase.database().ref('users/' + '1').set({
    name: username
  });
}


text:
Q: Change background image using drop-down list? I have a quick question I am currently developing a website with a chat system and I want the background image of the website to change when the user selects the specific chat room from the drop-down box
Below is the current setup of the dropdown select's

    <form class="form-signin">

Chat Login

        Nickname <input type="text" placeholder="Nickname" id="nickname">

            Chatroom <select size="1" id="chatroom">
                                    <option>Gaming Soc</option>
                                    <option>Pokemon Soc</option>
            </select>

        <button type="submit" id="enterRoom">Sign in</button>
    </form>

I was thinking that it could be done using jQuery but I am at a loss when it comes to implementing it
Here's a an example of when I am trying to do
If the user selects Gaming Soc is changes to background 1 if they select Pookemon Soc is changes to background 2
Any help would great

A: Javascript
var bgChange = function() {
    var bgVal = $("#chatroom").val(), chatRoom = $("#chatRoom"); // chatRoom (chatRoom is object id)
    if( bgVal == "1" ) {
        chatRoom.css("background-image", "url(1.jpg)");
    } else if( bgVal == "2" ){
        chatRoom.css("background-image", "url(2.jpg)");
    }
};

HTML
<select onchange="bgChange()" size="1" id="chatroom">
    <option value="1">Gaming Soc</option>
    <option value="2">Pokemon Soc</option>
</select>

A: In this JS Fiddle, you pick the value of the option and pick the corresponding background-image from an array

var bgArray = [
  '//placehold.it/400x300?text=BG1',
  '//placehold.it/400x300?text=BG2'
]
$('#chatroom').on('change', function() {
  value = $(this).val() - 1;
  $('#bgDiv').css({
    'background-image': 'url(' + bgArray[value] + ')'
  });
});
#bgDiv {
  width: 400px;
  height: 300px;
  outline: 1px dotted gray;
  margin: 0 auto;
}

  <form class="form-signin">

Chat Login

    Nickname
    <input type="text" placeholder="Nickname" id="nickname">

      Chatroom
      <select size="1" id="chatroom">
        <option value="1">Gaming Soc</option>
        <option value="2">Pokemon Soc</option>
      </select>

    <button type="submit" id="enterRoom">Sign in</button>
  </form>

A: Try utilizing multiple background-image properties at css to request each image once , setting initial background-size to 0 0, 0 0 . If select option selectedIndex is 0 set background-size to 100vw 100vh, 00 , if selectedIndex is 1 set background-size to 0 0, 100vw 100vh.

var arr = ["100vw 100vh, 0 0", "0 0, 100vw 100vh"];
$("#chatroom").change(function(e) {
  $("body").css("backgroundSize", arr[this.selectedIndex])
})
body {
  background-image:url(http://lorempixel.com/400/300/technics)
    , url(http://lorempixel.com/400/300/cats);
  background-size: 0, 0;
  background-repeat: no-repeat, no-repeat;
}

  <form class="form-signin">

Chat Login

    Nickname
    <input type="text" placeholder="Nickname" id="nickname">

      Chatroom
      <select size="1" id="chatroom">
        <option>Gaming Soc</option>
        <option>Pokemon Soc</option>
      </select>

    <button type="submit" id="enterRoom">Sign in</button>
  </form>


text:
Q: facebook graph api 2.5 friendLists members empty I am calling
 2.5/firiend_list_id?fields=members
I always get an empty list back and not the members.
Does this still exist? Is there a way to get members of a friendList
Thanks

A: It will only return friends that are also using the app.
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.


text:
Q: Why is VideoView not playing Video? I am trying to play a video by starting it when the Activity starts.
However,I am just getting a black screen when the Activity starts.
I do not understand why this is occurring.
Is this not the proper way to configure and play a video?
HelloMoonFragment:
public class HelloMoonFragment extends Fragment {
private AudioPlayer mPlayer = new AudioPlayer();
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
private Button mResumeButton;
private Button mStartVideo;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_hello_moon,parent,false);

    mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
    mPlayButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPlayer.play(getActivity());

        }
    });
    mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
    mStopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPlayer.stop();
        }
    });

    mResumeButton = (Button)v.findViewById(R.id.helloMoon_startButton);
    mResumeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPlayer.resume();
        }
    });

    mPauseButton = (Button)v.findViewById(R.id.hellomoon_pauseButton);
    mPauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPlayer.pause();

        }
    });

    mStartVideo = (Button)v.findViewById(R.id.hellomoon_startVideo);
    mStartVideo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                Intent i = new Intent(getActivity(),VideoActivity.class);
                startActivity(i);
        }
    });

    return v;
}

@Override
public void onDestroy(){
    super.onDestroy();
    mPlayer.stop();
}

}

VideoActivity:
public class VideoActivity extends Activity {
private String mVideoPath = "android.resource://" + "com.tubbs.android.hellomoon" + "/" + "R.raw/apollo_17_stroll";
private Uri mVideo;
@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);
    mVideo = Uri.parse(mVideoPath);

    VideoView videoView = (VideoView)findViewById(R.id.hellomoon_startVideo);
    MediaController mc = new MediaController(VideoActivity.this);
    mc.setAnchorView(videoView);
    videoView.setMediaController(mc);
    videoView.start();

}
}

activity_video.xml file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<VideoView
    android:id="@+id/hellomoon_startVideo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>


text:
Q: How to write a query that can be run several times, but only insert once? I have this request
INSERT INTO SERVICEPAYANT_CLIENT (RE_ID, TYPE_DONNEES)
SELECT CLIENT_ID, 160 AS TYPE_DONNEES
FROM    REFERENTIEL r, CLIENT_APPLICATIF ca
WHERE r.ID = ca.ID_REFERENTIEL
AND r.TYPE=1
GROUP BY CLIENT_ID
HAVING COUNT(*)>0;

When I execute it several times I inserted my data several times but I would like my request I inserted my data once only. I would like to insert my data if they are not present in my table.

A: You can do:
INSERT INTO SERVICEPAYANT_CLIENT (RE_ID, TYPE_DONNEES)
SELECT CLIENT_ID, 160 AS TYPE_DONNEES
FROM    REFERENTIEL r, CLIENT_APPLICATIF ca
WHERE r.ID = ca.ID_REFERENTIEL
AND r.TYPE=1
AND NOT EXISTS (
    SELECT * FROM SERVICEPAYANT_CLIENT sp
    WHERE sp.RE_ID = CLIENT_ID AND TYPE_DONNEES = 160)
GROUP BY CLIENT_ID
HAVING COUNT(*)>0;

The "AND NOT EXISTS..." is what restricts it to returning rows that are not already in your target table.

A: There is a sentence MERGE in several mature DBMS for these cases.
MERGE is INSERT and UPDATE at same time.
General syntax example:
     MERGE INTO TABLE_NAME USING table_reference ON (condition)
       WHEN MATCHED THEN
       UPDATE SET column1 = value1 [, column2 = value2 ...]
       WHEN NOT MATCHED THEN
       INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...

Some DBMS like MySQL has its own syntax with the same idea.
See more in Wikipedia.
If your DBMS doesn't soppurt that then you can write a Stored Procedure with the same logic.
But a stored procedure or any kind of other check in your code before insertion will make a 'lag' and the operation will become 'non-atomic'. It means that it is possible that just after your check and before insertions another transaction can make a duplicate record and you will get unexpected duplicates or excpetions. To avoid this you will have to lock the table before this operation to obtain exclusive access to the table what has a porfomance penalty because of serialization of the access.
Or you can use INSERT with SELECT like this:
    INSERT (field1, ...) INTO table1
    SELECT value1, ...
    FROM DUAL -- put a name of analogue of Oracle's DUAL here
    WHERE NOT EXISTS (
       SELECT 1
       FROM table1
       WHERE key = :new_key
    )

But as you understand it will not update anything.

A: The typical solution would be to enforce it in the database with a unique constraint comprised of the fields that define a record. Your Java code would then get an error back from the database letting you know that it already exists.

A: You could do this:
INSERT INTO SERVICEPAYANT_CLIENT (RE_ID, TYPE_DONNEES)
SELECT CLIENT_ID, 160 AS TYPE_DONNEES
REFERENTIEL r
JOIN CLIENT_APPLICATIF ca
    ON r.ID = ca.ID_REFERENTIEL
WHERE
    r.TYPE=1
    AND NOT EXISTS
        (
            SELECT
                NULL
            FROM
                SERVICEPAYANT_CLIENT
            WHERE
                REFERENTIEL.CLIENT_ID=SERVICEPAYANT_CLIENT.RE_ID
        )
GROUP BY CLIENT_ID
HAVING COUNT(*)>0;


text:
Q: Cut an arabic string I have a string in the arabic language like:
على احمد يوسف

Now I need to cut this string and output it like:
...على احمد يو

I tried this function:
function short_name($str, $limit) {
    if ($limit < 3) {
        $limit = 3;
    }

    if (strlen($str) > $limit) {
        if (preg_match('/\p{Arabic}/u', $str)) {
            return substr($str, 0, $limit - 3) . '...';
        }
        else {
            return '...'.substr($str, 0, $limit - 3);
        }
    }
    else {
        return $str;
    }
}

The problem is that sometimes it displays a symbol like this at the end of the string:
...�على احمد يو

Why does this happen?

A: Answer:
return '...'.mb_substr($str, 0, $limit - 3, "UTF-8"); // UTF-8 is optional

Background:
In ISO 8859-1 Arabic is not a 8-bit character set. The substr() calls the internal libc functions which work on sets of 8-bit chars. To display characters higher then 255 (Arabic, Cyclic, Korean, etc..) there are more bits needed to display that character, for example 16 or sometimes even 32-bits. You subtract 3*8-bits which will result in some undisplayable character in UTF-8. Especially if you're going to use a lot of multibyte strings, make sure you use the correct string functions such as mb_strlen()

A: The symbol displayed after the cut is the result of substr() cutting in the middle of a character, resulting in an invalid character.
You need to use Multibyte String Functions to handle arabic strings, such as mb_strlen() and mb_substr().
You also need to make sure the internal encoding for those functions is set to UTF-8. You can set this globally at the top of your script:
mb_internal_encoding('UTF-8');

Which leads to this:

*

*strlen('على احمد يوسف') returns 24, the size in octets

*mb_strlen('على احمد يوسف') returns 13, the size in characters

Note that mb_strlen('على احمد يوسف') would also return 24 if the internal encoding was still set to the default ISO-8859-1.

A: Try this function;
 public static function shorten_arabic_text($text, $lenght)
        {
            mb_internal_encoding('UTF-8');
            $out = mb_strlen($text) > $lenght ? mb_substr($text, 0, $lenght) . " ..." : $text;
            return $out;
        }


text:
Q: Backslashes interpreted as control character in JavaScript I've got LaTex code from server and have no control over it. I would like to print the LaTex code as it is using JavaScript, but it interprets as control characters on assigning to variable.
var str = '\[\frac{{{d^2}y}}{{d{x^2}}} - \,3\,\left( {\frac{{dy}}{{dx}}} \right)\, + \,2y\, = \,0\]';

This interprets as follows
[rac{{{d^2}y}}{{d{x^2}}} - ,3,left( {rac{{dy}}{{dx}}} ight), + ,2y, = ,0]

And I want as follows:
\[\frac{{{d^2}y}}{{d{x^2}}} - \,3\,\left( {\frac{{dy}}{{dx}}} \right)\, + \,2y\, = \,0\]

I tried varies RegExps, and result of
var index = str.indexOf("\\")

is -1
JavaScript removes control characters like \f, \r and so on and there are thousands of backslash notations in TeX.

A: How is loaded in str var?
Anyway, there is a work around (working here):
var c=',[]flr';
for(var i=0;i<c.length;i++)
 eval("str=str.replace(/\\"+c.charAt(i)+"/g,'\\\\"+c.charAt(i)+"');");

What we do is for any char in c evaluate the following code (replacing X with the char):
str=str.replace(/\X/g,'\\X');

Anyway, there is a work around (working here):
var c=',[]flr';
for(var i=0;i<c.length;i++)
 eval("str=str.replace(/\\"+c.charAt(i)+"/g,'\\\\"+c.charAt(i)+"');");

What we do is for any char in c evaluate the following code (replacing X with the char):
str=str.replace(/\X/g,'\\X');

Ok, that's an odd (and maybe dangerous) bug at the site which delivers the JSON. If it does not turns the \' to \', maybe it does not turns the ' to \'. So, anything after a ' or a " (depending on how the string is quoted) will be executed on any site that includes that (i.e. your site). Maybe as JSON is a little more secure.


text:
Q: Error:(23, 13) Failed to resolve: com.intuit.sdp:sdp-android:1.0.2 My project was working fine but when I reinstalled android studio I am having errors in importing butterknife and sdp libraries. This is my gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "com.works.vipul.brainturner"
        minSdkVersion 13
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.intuit.sdp:sdp-android:1.0.2'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.android.support:support-v4:23.0.1'
    compile 'com.google.android.gms:play-services-ads:8.1.0'
}

and this is the error I am getting:
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not resolve com.intuit.sdp:sdp-android:1.0.2.
     Required by:
         BrainTurner:app:unspecified
      > Could not resolve com.intuit.sdp:sdp-android:1.0.2.
         > Could not get resource 'https://jcenter.bintray.com/com/intuit/sdp/sdp-android/1.0.2/sdp-android-1.0.2.pom'.
            > Could not GET 'https://jcenter.bintray.com/com/intuit/sdp/sdp-android/1.0.2/sdp-android-1.0.2.pom'.
               > peer not authenticated
   > Could not resolve com.jakewharton:butterknife:7.0.1.
     Required by:
         BrainTurner:app:unspecified
      > Could not resolve com.jakewharton:butterknife:7.0.1.
         > Could not get resource 'https://jcenter.bintray.com/com/jakewharton/butterknife/7.0.1/butterknife-7.0.1.pom'.
            > Could not GET 'https://jcenter.bintray.com/com/jakewharton/butterknife/7.0.1/butterknife-7.0.1.pom'.
               > peer not authenticated

A: It seems that jcenter has an invalid ssl.
As workaround try to add this to build.gradle
repositories {
    mavenCentral()
    jcenter {
         url "http://jcenter.bintray.com/"
    }
}


text:
Q: Examples on $\sigma$-finiteness of a $\sigma$-field versus the field that generates it I'm wondering if there's an example of a measure $\mu$ on a $\sigma$-algebra $\mathcal{F}$ that is $\sigma$-finite on $\mathcal{F}$ but not on $\mathcal{F}_0$, the field that generates $\mathcal{F} := \sigma\langle\mathcal{F}_0\rangle$?
Also, a related question: An example when $\mu$ is $\sigma$-finite on $\mathcal{F}_0 \cup \mathcal{N}$ where $\mathcal{N} = \{F \in \mathcal{F}: \mu[F] = 0\}$, but not on $\mathcal{F}_0$? And an example where $\mu$ is $\sigma$-finite on $\mathcal{F}$ but not on $\mathcal{F}_0 \cup \mathcal{N}$?

A: Yes, consider the case where $\mathcal{F}$ is the Borel $\sigma$-algebra on the reals, $\mathcal{F}_0$ is the collection of finite unions of half-open intervals $(a,b]$ ($a,b\in\mathbb{R}\cup\{\pm\infty\}$) and $\mu(S)$ just counts the number of rationals in a set $S$.


text:
Q: Almost everywhere pointwise convergence I am trying to solve this problem
Let $a_n$ be a sequence of numbers so that $\lim_{n \to \infty} \sin(a_nx)$ exists pointwise almost everywhere on  $\mathbb{R}$. Show that $\lim_{n \to \infty}a_n$ exists.
I tried to use Egoroff's theorem and other things, but I could not solve it.

A: There is a stronger result: Suppose $\sin(a_nx)$ converges pointwise on a set of positive measure. Then $a_n$ converges to a finite limit.
Proof: Let $E$ be a set of positive and finite measure where $\sin(a_{n})$ converges pointwise.
We first prove $(a_n)$ must be bounded. If not, then WLOG there exist $0<a_{n_1} < a_{n_2} < \cdots \to \infty.$ By DCT we have
$$\tag 1 \int_E \sin^2(a_{n_k}x)\,dx \to \int_E f(x)^2\,dx.$$
The left side of $(1)$ equals
$$\int_E \frac{1-\cos(2a_{n_k}x) }{2}\, dx = m(E)/2-\frac{1}{2}\int_E \cos(2a_{n_k}x)\, dx.$$
Because $a_{n_k}\to \infty,$ the Riemann-Lebesgue lemma shows the last integral $\to 0.$ Hence $m(E)/2=\int_E f(x)^2\,dx.$
On the other hand,
$$\int_0^1f(x)^2\,dx = \lim \int_0^1f(x)\sin(a_{n_k}x)\,dx.$$
The limit on the right is $0,$ again using RL.
We therefore have $m(E)/2=0,$ contradiction. This proves $(a_n)$ must be bounded.
So now assume the bounded sequence $(a_n)$ has the given limit property but $\lim a_n$ fails to exist. Then
$$L=\liminf a_n< \limsup a_n = M.$$
There exist subsequences $a_{l_k}\to L$ and $a_{m_k}\to M.$ It follows that
$$\sin (a_{l_k}x) \to \sin (Lx),\,\, \sin (a_{m_k}x) \to \sin (Mx)$$
for $x\in E.$ We conclude $\sin (Lx)=\sin(Mx)$ on $E.$ Since these are analytic functions, we have $\sin (Lx)=\sin(Mx)$ everywhere. Differentiating then gives$$L\cos (Lx) = M\cos (Mx)$$everywhere. Now plug in $x=0$ to get $L=M,$ contradiction.
Therefore $\lim a_n$ exists.


text:
Q: RLS from Azure SQL not working with Power BI or Excel I have put in RLS rules on SSMS - they are restricted by Azure AD security groups created for this purpose.  The Azure AD security groups have been added as user to the Azure SQL database through CREATE USER [Sec Group Name] FROM EXTERNAL PROVIDER.  They work fine as the testing in SSMS shows logging in as different users into SSMS and using SELECT * FROM [RLS Tbl Name] is working as expected.
When I connect this Azure SQL DB to Power BI there are no rows coming through in the PBIX file (there should be some rows but not all in line with the RLS in place).  Obviously, any report created from a blank table returns only blank visuals.  Further, when I try to "View As" in Power BI, there are no rows (a table with no rows is all I can see).  Further, when I publish the report to the service and log in as different users, it still shows blank rows in the report.  Please note that the logged in user for the PBIX file is a "permitted" user under the RLS mandate
In desperation, I opened a new Excel workbook (logged in as the same "permitted" user) and connect it to the database, there are no rows that come through.
As a final check, I made a quick Power Apps app and I connected the above Azure SQL Database and published it to powerapps.com and note that the correct number of rows come through depending upon which user has logged in.
In summary,

*

*The RLS is working fine in SSMS (as logging in through different users outputs filtered rows in line with the RLS specified)

*The RLS is NOT working in Power BI (either in the PBIX or the service)

*The RLS is NOT working in Excel as connecting the same to the Azure SQL database is outputting blank rows.  In connecting the Azure SQL DB the conventional route of Get Data > Azure > Azure SQL Database been used (and NOT Analyse in Excel

*The RLS is working in Power Apps as it is correctly outputting the filtered number of rows depending upon the logged in user and his priveleges

I am at a loss to understand the different outcomes on Power BI, Power Apps and Excel.
The following points may be of use to further understand the problem

*

*In stating all of the above, I am using the same user when I compare Power BI behaviour, Power Apps behaviour, SSMS behaviour and Excel behaviour

*Different users have different entitlements/privileges.  Care has however been taken that when a different user is selected for anything mentioned in point 1, the other platforms also have the exact same user logged in - so that the comparison is not apples to oranges

*In stating the full mail above, at no point has a user who doesnt have permission been referred to (as this would explain the blank rows)

Am I missing something entirely as I did not expect to encounter a different behaviour across different platforms (SSMS, Power BI Desktop, Power BI Service, Power Apps and Excel)
Edit - 13 Oct 22
To be precise - there are 3 AD security groups and any row in the SQL table "belongs" to only 1 AD sec group out of the 3.  The RLS dictates that a user logging in will be able to see only the rows created by the security group to which he belongs to.  Therefore, if A logs in - he will be able to see only the rows for X security group (since he is a part of that security group).  When you log into SSMS as different users, it is correctly filtering the rows of the SQL table in line with the RLS rules.  Further, when you connect the SQL table to Power Apps, it correctly takes only the filtered SQL table.
However, connecting the same SQL table to Power BI and Excel results in a blank table on both these platforms.


text:
Q: How to speed up requests in livewire? I've made a very simple profile card with two views once is showing me the profile id,name and email and the second view just show the input fields for this three attributes.
This is working but it is "very" slow. When i'm hitting the button Edit on the show view, it takes more than 650ms(in best scenario, sometimes it takes more than 1.2sec) to load the edit view and vice versa.
How can I make this a little bit faster ?
Profile Component:
namespace App\Http\Livewire\User;

use App\User;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Profile extends Component
{

    public $user, $user_id, $name, $email;
    public $updateMode = false;

    public function mount(User $user)
    {
        $this->user = $user;
        $this->user_id = $user->id;
        $this->name = $user->name;
        $this->email = $user->email;
    }

    public function render()
    {
        return view('livewire.user.profile.resource');
    }

    public function edit()
    {
        $this->updateMode = true;
    }

    public function cancel()
    {
        $this->updateMode = false;
    }

    public function submit()
    {
        $attributes = $this->validate([
            'name' => 'required|min:6',
            'email' => ['required', 'email', Rule::unique('users')->ignore($this->user->id)],
        ]);

        $this->user->update($attributes);

        $this->updateMode = false;
    }

}

And this are the views:
resource.blade.php:

  @includeWhen(!$updateMode,'livewire.user.profile.show')

  @includeWhen($updateMode,'livewire.user.profile.edit')

show.blade.php:

            Id:

            {{ $user_id }}

            Name:

            {{ $name }}

            Email:

            {{ $email }}

        <button type="button" wire:click.prevent="edit" class="py-1 px-2 rounded bg-blue-500 text-white font-semibold">Edit</button>

edit.blade.php:
<form wire:submit.prevent="submit">

            Id:

            {{ $user_id }}

            Name:

            <input type="text" class="w-1/2 border appearance-none py-1 px-2 rounded shadow focus:outline-none" wire:model="name">

            Email:

            <input type="text" class="w-1/2 border appearance-none py-1 px-2 rounded shadow focus:outline-none" wire:model="email">

        <button type="submit" class="py-1 px-2 rounded bg-blue-500 text-white font-semibold" >Save</button>
        Cancel

</form>

A: I ran into the same issue, with the same implementation approach. I also noticed that it was a bit slow when Livewire would change the state to show/hide the form, so what I did was use Alpine.js for determining whether to show the form or not.

        <button wire:click="update">
            Save
        </button>
        <button @click.prevent="mode = 'view'">
            Cancel
        </button>

        <button @click.prevent="mode = 'edit'">
            Edit
        </button>

Doing it this way resolved the issue with displaying the form, which feels really snappy and quick. I have run into a different issue since that I'm not sure how to address.
If I begin to type in the form to update the name, and quickly hit the save button before the requests to update the component properties complete, then what ever the properties were at the time that I hit the save button are what gets saved to the database, creating a race condition.
I'm still relatively new to the Livewire paradigm so I don't have a good answer for this yet.


text:
Q: Should this be mocked? I am writing a component that fits into a large web framework.  The framework itself is not covered by any form of test.
The framework when initialized loads a large xml config tree (in memory) which part of contains xml for each installed component.
In my component I want to test whether it is recognized by the system and therefore installed correctly.
Should this be mocked or is it acceptable to check with the framework that my module is installed by doing an xpath on the xml config tree?  Or should that config tree be mocked?

A: 1) you already have the code, so the tag tdd is not appropriate.
2) the scenario you've described fits under integration-testing rather than unit-testing - you want to verify that two components are working together. I imagine that the system does many other things beside using the configuration file, so you'd have to mock them all. That seems to be too much unnecessary work.


text:
Q: How to get the respective funtion to be triggered when the respective element is clicked when one element is a parent? When I click the icon the clickIcon() funtion should trigger and when I click the button the clickBtn() fuction should trigger. What is happening now is the icon click is being triggered as I want but when on button click both fuction is triggered.
What I want is only the respective function should trigger on click. How to get the respective funtion to be triggered when the respective element is clicked?

clickBtn = () => {
  console.log("btn click")
}

clickIcon = () => {
  console.log("img click")
}
.icon {
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.icon>.buttons {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  opacity: 0;
  padding: 10px;
  background-color: rgba(50, 50, 50, 0.7);
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  transition: all 0.3s ease;
}

.icon:hover>.buttons {
  opacity: 1;
}

Folder

    <button (click)="clickBtn()">Action 1</button>

A: Add event.stopPropagation() in your clickIcon().

A: If you pass the event to your button click handler, you can invoke event.stopPropagation() on it to prevent it from bubbling up to the containing element.

clickBtn = (e) => {
  e.stopPropagation(); // prevent event from bubbling up to container
  console.log("btn click")
}

clickIcon = () => {
  console.log("img click")
}
.icon {
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.icon>.buttons {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  opacity: 0;
  padding: 10px;
  background-color: rgba(50, 50, 50, 0.7);
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  transition: all 0.3s ease;
}

.icon:hover>.buttons {
  opacity: 1;
}

Folder

    <button onclick="clickBtn(event)">Action 1</button>

A: Yes that's true because button and icon are child and parent respectively. If a child is triggered the parent functions also triggers, but you can prevent parents functions to trigger by using event.stopPropagation()
For Button:
<button (click)="clickBtn(event)">Action 1</button>

For Event Trigger
clickBtn = (e) => {
  console.log("btn click");
  e.stopPropagation();
  e.stopImmediatePropagation();
}

A: Events propagate to the parent elements until they reach the html element. This is called event bubbling.
In your case, the event on button click is getting propagated to its parent and the parent click event is also getting triggered, this is default event behavior. If you don't want this to happen, you can call event.stopPropagation() on the innermost element which will stop the bubbling.

clickBtn = (e) => {
  e.stopPropagation();
  console.log("btn click")
}

clickIcon = () => {
  console.log("img click")
}
.icon {
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.icon>.buttons {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  opacity: 0;
  padding: 10px;
  background-color: rgba(50, 50, 50, 0.7);
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  transition: all 0.3s ease;
}

.icon:hover>.buttons {
  opacity: 1;
}

Folder

    <button (click)="clickBtn()">Action 1</button>


text:
Q: error in RAC clustering part in oracle 11 g on redhat 5 i have this error while configuring the rac node
You must enter unique values for the public node name, the private node name and the virtual hostname for all nodes in the cluster. The name, YOUR-HOSTNAME , that you entered is being used by more than once for the same node.
what is the origin of the problem i have configured three adresses public private and virtual
you found below the file /etc/hosts with the different adresses so how can i solve the problem ?*
public
10.128.0.0 rac1
10.128.0.1 rac2
private
192.168.10.2 rac1-priv
192.168.10.3 rac2-priv
virtual
10.128.0.2 rac1-vip
10.128.0.3 rac2-vip

A: You can't assign network address which is reserved for IP standard!
X.X.X.0 indicate network address!
Please choose another IP. You can select the IP address +1 or +2.
This example will dispel your doubts:

public
10.128.0.2 rac1 10.128.0.3 rac2

private
192.168.10.2 rac1-priv 192.168.10.3 rac2-priv

virtual
10.128.0.4 rac1-vip 10.128.0.5 rac2-vip
Please correct your IP's and /etc/hosts on all of your cluster nodes.


text:
Q: NodeJs / Mongoose - nested documents, how to update changed subdocuments and add new subdocuments I have a nested structure in my schemas. I have main Schema, Training, then each Training can have one or more Phase subdocumens, and then each Phase can have multiple Training Units.
const TrainingSchema = new Schema(
{
    title: { type: String, required: true },
    description: { type: String, required: false },
    tags: { type: [String], required: false },
    phases: [{ type: mongoose.Schema.Types.ObjectId, ref: "Phase" }],
    status: { type: Number, default: 0 }, // 5 active, 10 complete
    public: { type: Boolean, default: false },
    updateUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, // bind user information
    createUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, // bind user information
    clonedFrom: { type: mongoose.Schema.Types.ObjectId, ref: "Training" }, // bind training information
    trainingData: { type: Object, required: false },
},
{
    timestamps: true,
})

const TrainingPhaseSchema = new Schema(
{
    phaseTitle: { type: String, required: true },
    units: [{ type: Schema.Types.ObjectId, ref: 'Unit' }],
    training: { type: mongoose.Schema.Types.ObjectId, ref: 'Training' },
    updateUser: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, // bind user information
    createUser: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, // bind user information
},
{
    timestamps: true,
})

const trainingUnitSchema = new Schema(
{
    unitTitle: { type: String, required: true },
    date: { type: Date, required: true },
    duration: { type: Number },
    distance: { type: Number },
    training: { type: mongoose.Schema.Types.ObjectId, ref: "Training" },
    phase: { type: mongoose.Schema.Types.ObjectId, ref: "Phase" },
    status: { type: Number },
    category: { type: Number, default: 0 },
    updateUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, // bind user information
    createUser: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, // bind user information
},
{
    timestamps: true,
})

I have problem with update / patch method. I'd like to be able to update changed document properties or subdocuments (Phases and Units) and also add new Phases and new Units.
I have an actions that is working but is has plenty of drawback and would like to know how to use Mongoose methods better to accomplish this.
const updateTraining = async (req, res, next) => {
try {
    const match = { createUser: req.user }
    if (!req.params.id) {
        log.warn("There is no ID provided for updateTraining action")
        return res.status(422).send({ error: "Request cannot be processed" })
    }

    const updates = Object.keys(req.body)

    const training = await Training.findOne({ _id: req.params.id, createUser: req.user })
    if (!training) {
        log.warn("Cannot find the training for updateTraining action")
        return res.status(404).send({ error: "Cannot find the training!" })
    }

    let phases = []
    if (req.body.phases) {
        for (let phase of req.body.phases) {
            let units = []
            //existing phases
            if (phase._id) {
                const sortedUnits = _.sortBy(phase.units, "date")
                for (let unit of sortedUnits) {
                    if (unit._id) {
                        //existing units
                        await Unit.findOneAndUpdate(
                            { _id: unit._id, ...match },
                            {
                                unitTitle: unit.unitTitle,
                                date: unit.date,
                                duration: unit.duration,
                                distance: unit.distance,
                                status: unit.status ? unit.status : 0,
                                category: unit.category ? unit.category : 0,
                            }
                        ).then((u) => units.push(u))
                    } else {
                        // new units
                        const newUnit = new Unit({
                            unitTitle: unit.unitTitle,
                            date: unit.date,
                            duration: unit.duration,
                            distance: unit.distance,
                            status: unit.status ? unit.status : 0,
                            category: unit.category ? unit.category : 0,
                            training: training._id,
                            phase: phase._id,
                            createUser: req.user._id,
                            updateUser: req.user._id,
                        })

                        await newUnit.save()

                        units.push(newUnit)
                    }
                }

                const p = await Phase.findOneAndUpdate(
                    { _id: phase._id, ...match },
                    { phaseTitle: phase.phaseTitle, units: units }
                )
                phases.push(p)
            } else {
                //new phases
                const sortedUnits = _.sortBy(phase.units, "date")
                for (let unit of sortedUnits) {
                    const newUnit = new Unit({
                        unitTitle: unit.unitTitle,
                        date: unit.date,
                        duration: unit.duration,
                        distance: unit.distance,
                        status: unit.status ? unit.status : 0,
                        category: unit.category ? unit.category : 0,
                        training: training._id,
                        phase: phase._id,
                        createUser: req.user._id,
                        updateUser: req.user._id,
                    })
                    await newUnit.save()
                    units.push(newUnit)
                }

                const newPhase = new Phase({
                    phaseTitle: phase.phaseTitle,
                    training: training._id,
                    createUser: req.user._id,
                    updateUser: req.user._id,
                    units: units,
                })

                await newPhase.save({ units: units })
                phases.push(newPhase)
            }
        }
    }

    req.body.phases = phases
    updates.forEach((update) => (training[update] = req.body[update]))
    await training.save() // this line will trigger middleware pre/post save, you can pass additional data to middleware
    return res.send(training)
} catch (error) {
    log.error({ err: error }, "Error while updating training")
    return res.status(400).send({ error: error.message })
}

}
any hints how to rewrite this massive block of code to something simpler ?


text:
Q: Enable source mapping on CRA with typescript and webpack I recently converted my create-react-app to typescript. I've lost the feature where I could see the file name when viewing the console in developer tools.
My tsconfig.json is as follows:
"target": "ES2018",
"module": "commonjs",
"checkJs": false,
"jsx": "react",
"sourceMap": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true

I'm a bit overwhelmed by the size of my webpack.config.js file (I think it was generated when I created my CRA). Here are some sections:
{
    devtool: isEnvProduction
      ? shouldUseSourceMap
        ? 'source-map'
        : false
      : isEnvDevelopment && 'cheap-module-source-map',
...
 module: {
      strictExportPresence: true,
      rules: [
        { parser: { requireEnsure: false } },
        {
          test: /\.(ts|js)x?$/i,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: [
                "@babel/preset-env",
                "@babel/preset-react",
                "@babel/preset-typescript",
              ],
            },
          },
        },
      ],
    },
}

How do I get my dev tools to show the actual files where errors are coming from?

A: Suggest you to have 2 separate webpack configs. Then use webpack-merge to join them.

*

*Make sure to set mode in either of those:
dev:
{..., mode: 'development', ... }
prod:
{..., mode: 'production', ... }

*set devtools to eval-source-map in development, and to whatever you prefer in production

*sourceMap to true in tsconfig (as you do)

Check webpack 5(I presume this is what you have) docs on devtooling.


text:
Q: My script doesn't work as expected

This is the button
contact

This is the php script:
<?php
$p = isset($_GET['p']);

if($p == "artist")
{
    include 'artist.php';
}

if($p == "contact")
{
    include 'contact.php';
}

if($p == "releases")
{
    include 'releases.php';
}

if($p == "downloads")
{
    include 'downloads.php';
}

else
{
    include 'home.php';
}
?>

So my script should include contact.php when I hit the button, but instead of including only contact.php it includes all php files. (this happens also with the other buttons).

A: Right now your $p variable equals true (this is what isset returns).
Change $p = isset($_GET['p']); to $p = $_GET['p']; and you'll be good
Even better:
$p = isset($_GET['p']) ? $_GET['p'] : false;
in this case you're secured against p being null
EDIT:
There is also another issue with your code - last else statement. It is always true when $p is different than downloads. So either you change every if to else if like this:
if($p == 'artist')
{
    include 'artist.php';
}

else if($p == 'contact')
{
    include 'contact.php';
}
(...)
else
{
    include 'home.php';
}

or change this to switch statement:
switch($p)
{
case 'artist':
    include 'artist.php';
    break;
(...)
default:
    include 'home.php';
}

A: isset($_GET['p']) returns true or false, so the code comparing $p to some strings will always return true and run the code inside the if block.
Change $p = isset($_GET['p']) simply to $p = $_GET['p']

A: To make this (more) reusable, you should alter your script a bit. Create a simple whitelist, check it the parameter is allowed, and if yes, include the $_GET['p']'s value directly:
$allowed = false;

if (isset($_GET['p']))

{

switch $_GET['p'] {

  case 'contact':
     $allowed = true;
     break;

  case 'artist':
     $allowed = true;
     break;

   // and so on for all your IFs

}

  if ($allowed === true) {
    include $_GET['p'].'.php'
  }
  else
  {
    die('illegal parameter found')
  }
}


text:
Q: how to bold a text inside || || in latex? I have a problem bolding the text inside || || sign:
I tried to do this:
$\left\Vert \textbf{\lambda_{max}w} \right\Vert^{2}$

but I got || λmaxw2.
However, I was able to do:
$\left\Vert \textbf{Aw} \right\Vert^2$

, which gives something like || Aw ||2. so I am not sure where I am wrong.
I want to make it looks like this || λmaxw ||2, I just found out I can do this \textbf{w} to make w bold, but I cannot make λmax bold.
Probably a simple mistake, but I just cannot figure it out.

A: Because Lambda is a math symbol, you will need a special package that modifies math symbols. In my case, I have used \usepackage{bm} and replaced \textbf with \bm. This made the results that you want it.
\documentclass{...}
    ...
    \usepackage{bm}
    ...
\begin{document}
    ...
    $\left\Vert \bm{ \lambda_{max}w } \right\Vert^2$
    ...
\end{document}

For more information, please visit this answer.


text:
Q: Why does this explicit template specialization does not work? from this code:
// Example program
#include <iostream>
#include <string>

struct Z { static const int z = 1; };
struct Y { static const int y = 2; };

template <typename A> struct TE { int foo(); int bar(); };

template <> int TE<Y>::bar() { return foo(); }
template <typename A> int TE<A>::bar() { return foo(); }

template <> int TE<Y>::foo() { return Y::y; }
template <typename A> int TE<A>::foo() { return A::z; }

template struct TE<Z>;
template struct TE<Y>;

int main()
{
    TE<Z> z;
    TE<Y> y;

    std::cout << z.bar() << std::endl;
    std::cout << y.bar() << std::endl;
    return 0;
}

with this error
21:28: error: specialization of 'int TE<A>::foo() [with A = Y]' after instantiation
 In instantiation of 'int TE<A>::foo() [with A = Y]':
13:12:   required from here
28:15: error: 'z' is not a member of 'Y'
 In member function 'int TE<A>::foo() [with A = Y]':
29:1: warning: control reaches end of non-void function [-Wreturn-type]

these implementations are done in separate cpp file. and the structs are in a header, typical explicit template instantiation.
why did this
int TE<Y>::bar() { return foo(); }

tries to use this
template <typename A> int TE<A>::foo() { return A::z; }

instead of this
template <> int TE<Y>::foo() { return Y::y; }

A: http://en.cppreference.com/w/cpp/language/template_specialization
Explicit specialization can only appear in the same namespace as the primary template, and has to appear after the non-specialized template declaration.
Also, you need to follow the One-Definition-Rule (ODR). So usually you would provide your implementations along in the same header.

A: The problem is that your foo specialization isn't known at the time bar is instantiated, so foo in both bars refers to the foo base template.
As the first error message says, when the compiler gets to your Y specialization, the base template has already been instantiated, using A = Y.
The second error is a "cascade error" due to the specialization failure, in the grand C++ tradition.
If you rearrange the definitions, it works:
template <typename A> int TE<A>::foo() { return A::z; }
template <> int TE<Y>::foo() { return Y::y; }

template <typename A> int TE<A>::bar() { return foo(); }
template <> int TE<Y>::bar() { return foo(); }


text:
Q: Invalid length parameter passed to the substring function case I have an issue with substring function while using it inside case statement.
select
case when -1<0 then 'ok' else SUBSTRING('abcd',1,-1) end

gives me an issue:

Invalid length parameter passed to the substring function.

Why is the case "looking" at the else condition since the first condition is met?
On the other hand query:
declare @a int;
set @a=-1

select
@a,
case when @a<0 then 'ok' else SUBSTRING('abcd',1,@a) end

presents the right answer 'ok' without any errors.

A: The problem is that the literal value of -1 is parsed by the compiler before run-time for the length parameter. The compiler knows that -1 is invalid, as length must have a positive value, so the error is flagged before the SQL is even run.
In the latter statement, the length passed is a variable. At compile time, the variable has an "unknown" value, as it's not SET till run time, thus the syntax is fine.
Simply put, the compiler knows that a length of -1 for SUBSTRINGis invalid, regardless of if that SQL will actually run, and so errors.
Unlike other functions, such as STUFF and REPLICATE, which state "If length is negative, a null string is returned.", SUBSTRING, LEFT, and RIGHT all state: "If integer_expression is negative, an error is returned." For a literal value, it appears that the compiler is checking these values, even if they will never be used, and then flagging the error.
This isn't limited to logic within a CASE either. For example, the using logical flow operators such as IF generates the same behaviour:
IF 1 = 0
    SELECT LEFT('abc',-1)

As does the ISNULL function:
SELECT ISNULL('ok',RIGHT('abc',-1));

It only, however, occurs with literal values. If, for example, you were to use the values from a column, the behaviour is not seen:
IF 1 = 0
    SELECT SUBSTRING('abc',1,n) FROM (VALUES(1),(-1)) V(n);

This does not return an error, even though everything in VALUES is a literal. That is because the value of n has not been evaluated.

A: You can try this as it needed positive end values as length can not be in negative but can be 0.
select
case when -1 < 0 then 'ok' else SUBSTRING('abcd',1, 1) end