text:
Q: Sessions are not getting declared This is my login code
global $connection;

if (isset($_POST['user_login'])) {

    $email = $_POST['email'];
    $password = $_POST['password'];
    $password= md5($password);

    $login = mysqli_query($connection, "SELECT * FROM user WHERE email ='{$email}' AND password = '{$password}' ");
    if(!$login) {
        die("QUERY FAILED" . mysqli_error($connection));
    }

    if(!$login || mysqli_num_rows($login) == 0) {

        echo "
 Your Username or Password is invalid!
";

    } else {
        $_SESSION['user_id'] = $user_id;
        $_SESSION['email'] = $email;
        $_SESSION['username'] = $username;

        header('Location: index.php');
    }
}

I used the print_r function to display all the sessions but only the session email is getting declared. Why isn't the user_id and username not getting declared? What did I do wrong?

A: *

*You might forget to declare session_start(); at the top.

*It seems like you are using user_id and username in your sessions but they are not fetched from anywhere in your PHP code. So, you might forget to get and then use them from your $login response.

This is an assumption because your code looks to use user_id and
  username on the basis of SELECT query.

So, you can try using this code which has all parameters used from select query:
session_start();
global $connection;

if (isset($_POST['user_login'])) {

    $email = $_POST['email'];
    $password = $_POST['password'];
    $password= md5($password);

    $login = mysqli_query($connection, "SELECT * FROM user WHERE email ='{$email}' AND password = '{$password}' LIMIT 1");
    if(!$login) {
        die("QUERY FAILED" . mysqli_error($connection));
    }

    if(!$login || mysqli_num_rows($login) == 0) {

        echo "
 Your Username or Password is invalid!
";

    } else {
        // get user_id and username fetched from your Select query
        while($row = $login->fetch_assoc()) {
          $_SESSION['user_id'] = $row['user_id']; // assuming user_id as a column
          $_SESSION['email'] = $email;
          $_SESSION['username'] = $row['username']; // assuming username as a column
        }
        header('Location: index.php');
    }
}

A: When you try to put not initilized variable or null value into session, session don't raise the exception. But key and value list, can not add not init variable or null value.


text:
Q: Write to file from a method with variables from Main I have variables that are  from my main, and I want to use a private (or public doesn't really matter I am keeping them in the same class) method to write them to a text file. I have accomplished writing them to a file from within the main... I just cant figure out how to call variables from the main into my  writeToFile() method.  Below is what I have attempted but Im not sure how to incorporate the two.
 //This portion is what I had in my main method that wrote the info to a file successfully

     //Write to File
             String fileName = "order.txt";
             try{
                 PrintWriter writer = new PrintWriter(fileName);
                 writer.println("Thank you for ordering from Diamond Cards");
                 writer.println("Name: " + customerName);
                 writer.println("Returning Customer: " + customerReturn );
                 writer.println("Phone: " + custNumber);
                 writer.println("Card Type: " + customerType);
                 writer.println("Card Color: " + customerColor);
                 writer.println("Card Coating: " + customerCoat);
                 writer.println("Item Amount: " + numItems);
                 writer.println("Total Cost: " + fmt1.format(totalCostMsg));
                 writer.flush();
                 writer.close();
                 JOptionPane.showMessageDialog(null, "Receipt has been printed");
             } catch (FileNotFoundException e)
                        {e.printStackTrace();
                        System.exit(0) ;
                        }
             }

// This is where I try to create a method to do the file writing.... not sure how to proceed..

   public static void writeToFile() {
            try{
                FileWriter fw = new FileWriter("order.text"); //File name to be created
                PrintWriter pw = new PrintWriter (fw);          // Prints to the file that was created
         //text to be printed to file

        // close the writer
                pw.close();
        // catch errors
                } catch (IOException e) {
                out.println("Error!");
                }
            }

I also need to figure out how to make a separate method to read the file back in but I think I can engineer that if I can just figure this part out.

A: You want to define writeToFile with arguments, and pass them in from main:
   // Add additional arguments.
   public static void writeToFile(String fileName, String customerName, ...){
       FileWriter fw = new FileWriter(fileName);
       writer.println("Thank you for ordering from Diamond Cards");
             writer.println("Name: " + customerName);
       // Use additional arguments.
   }

From main:
writeToFile(fileName, customerName, ...);

I agree with Mr. Polywhirl though. It will be cleaner if you create a wrapping object, although I am not so sure you even need getters and setters for this purpose.
// The types are all String because you did not mention the types in your
// question.
class Customer {
    public String Name;
    public String Return;
    public String Number;
    public String Type;
    public String Color;
    public String Coat;
    public Customer String(String Name, String Return, String Number, String Type, String Color, String Coat) {
        this.Name = Name;
        this.Return = Return;
        this.Number = Number;
        this.Type = Type;
        this.Color = Color;
        this.Coat = Coat;

    }
}

You could then do the following in main:
Customer c = new Customer(customerName, customerReturn, customerNumber, customerType, customerColor, customerCoat);

Inside the writeToFile method with the same signature as Mr. Polywhirl's answer, you could directly do customer.Name, etc.

A: You can pass objects around by adding parameters to your methods. If you need to reference something in another class or method, just add more parameters.
I suggest that you create a Customer object so that you can pass it around as a single entity instead a couple dozen parameters.
You can try something like this:
public class FileWriteExample {
    public static void main(String[] args) {
        String fileName = "order.txt";
        Customer customer; // Customer object...
        int itemCount;
        float totalCost;
        try {
            PrintWriter writer = new PrintWriter(fileName);
            writeToFile(writer, customer, itemCount, totalCost);
            writer.flush();
            writer.close();
            JOptionPane.showMessageDialog(null, "Receipt has been printed");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
    public static void writeToFile(PrintWriter writer, Customer customer,
            int itemCount, float totalCost) {
        Card card = customer.getCard();
        try {
            writer.println("Thank you for ordering from Diamond Cards");
            writer.println("Name: " + customer.getName());
            writer.println("Returning Customer: " + customer.getReturn());
            writer.println("Phone: " + customer.getPhone());
            writer.println("Card Type: " + card.getType());
            writer.println("Card Color: " + card.getColor());
            writer.println("Card Coating: " + card.getCoating());
            writer.println("Item Amount: " + itemCount);
            writer.println("Total Cost: " + fmt1.format(totalCost));
        } catch (IOException e) {
            System.out.println("Error!");
        }
    }
}

A: There might be some fields that are not required or unavailable, like contact number, etc. Rather than sending a long list to write to file, consider using a Builder Pattern as suggested by Joshua Bloch in Effective Java.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can not install zoom conferencing by dpkg I've download zoom_amd64.deb by
wget -c https://zoom.us/client/latest/zoom_amd64.deb

and trying to install it:
sudo dpkg -i zoom_amd64.deb

but getting:
dpkg-deb: error: archive 'zoom_amd64.deb' has premature member
 'control.tar.xz' before 'control.tar.gz', giving up
dpkg: error processing archive zoom_amd64.deb (--install):
 subprocess dpkg-deb --control returned error exit status 2
Errors were encountered while processing:
 zoom_amd64.deb

GDebi gives the same error.
Decision from https://askubuntu.com/a/1100361/327339 also does not help.
My OS: Linux vnbs 3.16.0-41-generic #57~14.04.1-Ubuntu SMP Thu Jun 18 18:01:13 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
Please help me to install Zoom Conferencing client on Ubuntu 14.04.

A: sudo apt-get install libxcb-xtest0

A: I have used the below command on Ubuntu 20.10 and works for me.

sudo apt install libgl1-mesa-glx libxcb-xtest0


text:
Q: Rails: how do I resolve the 'rake/rdoctask'' is deprecated' warning? Just a forewarning: I'm a rails noob.
When I run:
rake db:migrate

I get this deprecation warning:
WARNING: 'require 'rake/rdoctask'' is deprecated.  Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead.
    at /Users/username/Code/rails/appname/rake/ruby/1.9.1/gems/rake-0.9.2.2/lib/rake/rdoctask.rb

I'm using:

*

*Rails 3.0.1

*Rake 0.9.2.2

*RSpec 2.0.1

*RDoc 3.12

If I uninstall rake 0.9.2.2 and use 0.8.7 there's no warning, but I rather not count that as a solution.
After a google search, many sites say I need to update a line in my Rakefile (basically changing require 'rake/rdoctask'  to   require 'rdoc/task'). However, my Rakefile looks like this:
require File.expand_path('../config/application', __FILE__)
require 'rake'

AppName::Application.load_tasks

There's no require statement to replace. When I add require 'rdoc/task', it has no effect. When I search the project for the deprecated 'rake/rdoctask', there are no results. So why is rails complaining?
edit: Not sure if it matters, but here's my gemfile:
source 'http://rubygems.org'

gem 'rails', '3.0.1'
gem 'sqlite3-ruby', :require => 'sqlite3'

group :development, :test do
   gem 'rspec-rails', '2.0.1'
   gem 'annotate-models', '1.0.4'
end

group :test do
   gem 'rspec', '2.0.1'
   gem 'webrat', '0.7.1'
   gem 'spork', '0.8.4'
end

A: Note this is fixed in later Rails 3.0.x versions (e.g., Rails 3.0.9).
The fix isn't in the top-level Rakefile but rather in the file mentioned in the error; it's just a general purpose notification:
if Rake.application
  Rake.application.deprecate('require \'rake/rdoctask\'', 'require \'rdoc/task\' (in RDoc 2.4.2+)', __FILE__)
end

It's actually related to something else, though; see this.

A: this is my rakefile
require File.expand_path('../config/application', __FILE__)
require 'rake'
require 'rake/testtask'
require 'rdoc/task'

# add this (and perhaps make it conditional on Rails.version if you like):
Rake.application.options.ignore_deprecate = true

myapp::Application.load_tasks

that's working for bug notification.


text:
Q: JavaFX TextArea appendText works in initialize but not elsewhere Simple enough problem but it's been driving me crazy.
In my program I have a TextArea, defined as:
<TextArea fx:id="output" editable="false" prefHeight="300.0" prefWidth="200.0" text="Output" GridPane.columnSpan="2" GridPane.rowIndex="4" />

@FXML private TextArea output;

...

public void initialize(URL url, ResourceBundle rb) {
    output.setText("Test"); //Test appears correctly in output
    ...
}

@FXML
public void download() {
    String outputTemplate = templateField.getText();
    String url = urlField.getText();
    System.out.println("Downloading from " + url);
    try {
        Process down = Runtime.getRuntime().exec("youtube-dl -o \"" + outputTemplate + "\" " + url);
        BufferedReader reader = new BufferedReader(new InputStreamReader(down.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line); //Prints as expected
            output.appendText(line + "\n"); //Has no effect
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Any ideas on how to get the text to appear would be great, I've done this before on different programs, just for some reason, this time it's being cantankerous
EDIT: Upon further tinkering, it actually will print out the results, but only after the Process ends and it exits the loop.

A: The text shown in the UI changes on a layout pulse. Layout pulses are done on the JavaFX application thread. Event handlers, like your download method run on the same thread effectively preventing it from doing any layouting or processing and other events until it completes. This is why you shouldn't block this thread with longrunning tasks, but execute them on a different thread.
Since updates to the UI should be done from the application thread, use Platform.runLater to append the text:
@FXML
public void download() {
    String outputTemplate = templateField.getText();
    String url = urlField.getText();
    Runnable r  = () -> {
        System.out.println("Downloading from " + url);
        try {
            Process down = Runtime.getRuntime().exec("youtube-dl -o \"" + outputTemplate + "\" " + url);
            BufferedReader reader = new BufferedReader(new InputStreamReader(down.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line); //Prints as expected
                final String printText = line + "\n";

                // append the line on the application thread
                Platform.runLater(() -> output.appendText(printText));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
    // run task on different thread
    Thread t = new Thread(r);
    t.start();
}

A: The problem is that you're doing this in the main thread. So stage can not be updated, until the cycle is finished. Try it in new thread:
@FXML
public void download() {
    Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() {
            String outputTemplate = templateField.getText();
            String url = urlField.getText();
            System.out.println("Downloading from " + url);
            try {
                Process down = Runtime.getRuntime().exec("youtube-dl -o \"" + outputTemplate + "\" " + url);
                BufferedReader reader = new BufferedReader(new InputStreamReader(down.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line); // Prints as expected
                    output.appendText(line + "\n"); // Has no effect
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    };
    new Thread(task).start();
}


text:
Q: Different hover behaviour for linear gradient backgrounds on divs I have two div's for two different buttons. The only thing that changes between the two div's is that one has a background: #E82171; whereas another has a gradient background: linear-gradient(to right, #e82171 , #ef3e36);.
However, I want to understand why they both have different hover behaviour even though they both have the same styling?

body{
  background-color: blue;
}

/** BUTTON 1 **/

.formLink {
    text-align: center;
    display: inline-block;
    box-sizing: border-box;
    background: linear-gradient(to right, #e82171 , #ef3e36);
    padding: 24px 40px;
    border-radius: 100px;
    font-size: 18px;
    color: #fff;
    text-decoration: none;
    cursor: pointer;
    font-weight: 900;
    margin-right: 0;
    margin-left: 0;
    transition: all 0.6s;
    outline:none;
    }

.formLink:hover {
    box-shadow: 0 0 20px #ffffff;
    background: #404262;
}

/** BUTTON 2 **/

.btn {
    display: inline-block;
    padding: 20px;
    border-radius: 100px;
    text-align: center;
    border: 0;
    cursor: pointer;
    transition: all 0.6s;
    color: #ffffff;
    outline: none;
    background: #E82171;
    font-size: 90%;
}
.btn:hover {
    box-shadow: 0 0 20px #ffffff;
    background: #404262;
}

Button 1

Button 2

As you can see, hovering on button 1 is much more instant. I basically want button 1 to have a slow transition on hover, like in button 2.
For testing, I changed the linear gradient to background: #E82171; for button 1 and the transition works exactly how I want it. Unsure why linear gradient will effect this?
Edit:
After finding out there's no "direct" way to do this, I decided to find a workaround based off this solution.

body{
  background-color: blue;
}
.formLink {
    text-align: center;
    display: inline-block;
    background: linear-gradient(to right,#e82171,#ef3e36);
    padding: 24px 40px;
    border-radius: 100px;
    -webkit-border-radius: 100px;
    -moz-border-radius: 100px;
    font-size: 18px;
    color: #fff;
    text-decoration: none;
    cursor: pointer;
    font-weight: 900;
    transition: all .6s;
    background: -moz-linear-gradient(to right,#e82171,#ef3e36);
    background: -webkit-linear-gradient(to right,#e82171,#ef3e36);
    background: -o-linear-gradient(to right,#e82171,#ef3e36);
    background: linear-gradient(to right, #e82171, #ef3e36);
      background-repeat: repeat-x;
      background-repeat: repeat-y;
      background-size: 100%;
      background-position: 0 100% no-repeat;
      -webkit-transition: all 0.6s linear;
         -moz-transition: all 0.6s linear;
           -o-transition: all 0.6s linear;
              transition: all 0.6s linear;
}

.formLink:hover {
    box-shadow: 0 0 20px #fff;
    background: #404262;
    background-position: 0 0;
}

/*************/

/** BUTTON 2 **/

.btn {
    display: inline-block;
    padding: 20px;
    border-radius: 100px;
    text-align: center;
    border: 0;
    cursor: pointer;
    transition: all 0.6s;
    color: #ffffff;
    outline: none;
    background: #E82171;
    font-size: 90%;
}
.btn:hover {
    box-shadow: 0 0 20px #ffffff;
    background: #404262;
}

Download

Button 2

I think my download button is nearly the same as button 2? You guys can advice better. However, I'm not sure why my download button "blinks" when hovering over it? The background disappears for a second and then reappears? Ideas on why? I need it to function exactly like button 2.

A: To avoid the blinking behaviour, you need to use a copy of the button behind it - otherwise the background will be transparent during the opacity animation. You do not have to use a second div, you can use the pseudo element after instead:
https://jsfiddle.net/qLmpxgd8/2/

body{
  background-color: blue;
}

.formLink, .formLink:after {
    position: relative;
    text-align: center;
    display: inline-block;
    background: linear-gradient(to right,#e82171,#ef3e36);
    padding: 24px 40px;
    border-radius: 100px;
    -webkit-border-radius: 100px;
    -moz-border-radius: 100px;
    font-size: 18px;
    color: #fff;
    text-decoration: none;
    cursor: pointer;
    font-weight: 900;
    transition: all .6s;
    background: -moz-linear-gradient(to right,#e82171,#ef3e36);
    background: -webkit-linear-gradient(to right,#e82171,#ef3e36);
    background: -o-linear-gradient(to right,#e82171,#ef3e36);
    background: linear-gradient(to bottom, #e82171, #ef3e36);
      background-repeat: repeat-x;
      background-repeat: repeat-y;
      background-size: 100%;
      background-position: 0 100% no-repeat;
      -webkit-transition: all 0.6s linear;
         -moz-transition: all 0.6s linear;
           -o-transition: all 0.6s linear;
              transition: all 0.6s linear;
}

.formLink:after {
  content: "Download";
  position: absolute;
  left: 0;
  top: 0;
}

.formLink:hover:after {
    box-shadow: 0 0 20px #fff;
    background: #404262;
    background-position: 0 0;
}

/*************/

/** BUTTON 2 **/

.btn {
    display: inline-block;
    padding: 20px;
    border-radius: 100px;
    text-align: center;
    border: 0;
    cursor: pointer;
    transition: all 0.6s;
    color: #ffffff;
    outline: none;
    background: #E82171;
    font-size: 90%;
}
.btn:hover {
    box-shadow: 0 0 20px #ffffff;
    background: #404262;
}

Download

Button 2


text:
Q: Unable to update the xamarin.support.v4 packages while updating my NuGet packages I am getting this issue
Unable to resolve dependencies. 'Xamarin.Android.Support.v4 25.4.0-rc1' is not compatible with 'Xamarin.Forms 2.3.5.253-pre5 constraint: Xamarin.Android.Support.v4 (= 23.3.0)'.
Can any one guide me for this issue
Thank You

A: You should not update Support libraries by your self. Instead update only Xamarin.Forms package and it updates his dependencies automatically.
Now, try to uninstall all Support libraries and Xamarin.Forms, install Xamarin.Forms again and it would add all dependencies needed.
As a reference, take a look at this.

A: I ran into similar the other week (blindly clicked update and it all went wrong), my solution was to downgrade Xamarin Android Support (I'm on 23.3.0) although I'm only using Xamarin Forms 2.3.4.247 I believe the issues is common.
From memory this was a bit of a pain and had to actually remove them one by one and add them back in (maybe take a screenshot of what packages are installed so you don't forget!), but 23.3.0 was the magic support version.
HTH

A: Solution 1.
Update xamarin forms to latest version.
Xamarin.Android.Support.v4 25.4.0-rc1 is having some dependence on latest xamarin.forms
Solution 2.
Install older version of Xamarin.Android.Support.v4 .
Check the version dependence before installing and ensure that older version do not have dependence on xamarin forms.


text:
Q: What's the best way to visualize sequence of events within pandas in Python? I have a dataframe showing sequence of events per session on weblog data, looking like this
SessionID     EventSequence   UrlPath
00001           1              Login
00001           2              Overview
00001           3              Account
00001           4              LogOff
00002           1              Login
00002           2              LogOff
00003           1              Login
00003           2              Account
00003           3              Overview
00003           4              Overview
00003           5              LogOff
....

I want to visualize this data in the most efficient, user-friendly way to show the most common paths within sessions in general (thinking of the tree mainly, but can be something else). What would be the most optimal way to visualize sequence of events within data? Can you please share any examples in different domains?

A: I think the best fine here:
Stacked Bar Graph:

from here
Or
3D bar charts

from here
In case you looking for common traffic you can you:

Sankey Diagram like here


text:
Q: Items doesn't display in list box when I run the program I was doing a program about Bisection Method. I haven't encountered any errors while doing the program, but when I run it, input the data, and press the compute button, no answer is displayed, but a scroll bar appears and freezes the program.
I don't know what is wrong but I guess it has something to do with logical error.
Public Class Form1
    Dim a As Double
    Dim b As Double
    Dim c As Double
    Dim fa As Double
    Dim fb As Double
    Dim fc As Double
    Dim err As Double
    Dim n As Integer = 1
    Dim x As Double
    Dim diserr As String
    Dim fas As String
    Dim fbs As String
    Dim fcs As String

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        a = TextBox1.Text
        b = TextBox2.Text
        err = TextBox3.Text

        fa = a ^ 3 - a - 3
        fb = b ^ 3 - b - 3
        c = (a + b) / 2
        fc = c ^ 3 - c - 3
        x = Math.Abs(a - b)

        Do While x > err
            fa = a ^ 3 - a - 3
            fb = b ^ 3 - b - 3
            c = (a + b) / 2
            fc = c ^ 3 - c - 3
            x = Math.Abs(a - b)

            If err < x Then
                diserr = "No"
            Else
                diserr = "Yes"
            End If

            If fa > 0 Then
                fas = "+"
            Else
                fas = "-"
            End If

            If fb > 0 Then
                fbs = "+"
            Else
                fbs = "-"
            End If

            If fc > 0 Then
                fcs = "+"
            Else
                fcs = "-"
            End If

            If diserr = "Yes" Then
                fcs = Str(x)
            End If

            ListBox1.Items.Add(Str(n))
            ListBox2.Items.Add(Str(a))
            ListBox3.Items.Add(Str(b))
            ListBox4.Items.Add(Str(c))
            ListBox5.Items.Add(Str(x))
            ListBox6.Items.Add(diserr)
            ListBox7.Items.Add(fas)
            ListBox8.Items.Add(fbs)
            ListBox9.Items.Add(fcs)
            n = n + 1

            If fas = "-" And fcs = "+" Then
                b = c
            End If
            If fbs = "-" And fcs = "+" Then
                a = b
                b = c
            End If

        Loop

    End Sub
End Class

A: You need to consider the cases where fcs is "-".
If I'm not misunderstanding the method you can just replace the last two ifs with
If fas <> fcs Then
    b = c
Else
    a = b
    b = c
End If


text:
Q: Porting network auditing software to Windows I am attempting to port a network auditing program called Argus to Windows using gnulib. It is my first time using gnulib, or porting software at all for that matter, and I've gotten stuck because the source code for Argus does not contain a Makefile.am which gnulib seems to need (the configure.ac is available, though). Is it possible to continue without an automake file? Is gnulib even the best option for this? What alternatives do I have? I have very little experience with this so any guidance on the matter is appreciated.
Thanks!


text:
Q: Intercepting Syslog log Traffic to a Custom UDP Server I'm trying to intercept application specific syslog log traffic from a custom UDP server in ubuntu. For testing purposes, I stopped the default syslogd daemon running in port 514 and configured a UDP server to listen to UDP traffic on port 514. I have faced the following questions in doing so:

*

*The remote logging feature has to be enabled in /etc/default/syslogd file using SYSLOGD="-r". However, since I stopped the syslogd daemon and am running my own UDP server on port 514, is there any other way to enable remote logging (programmatically, etc.) without using syslog.conf file so that log traffic is sent to the port 514?

*Is there a way to direct syslog log traffic to another port with the default port 514 (traffic must be sent to both ports)? If this is the case, I can easily run a custom UDP daemon in the second port and intercept log traffic.
Thanks.

A: You can't have two daemons listening on the same port. Set up your UDP test server (e.g. netcat) to listen on another port (e.g. 1514) and configure your ubuntu server to send logs to this port.


text:
Q: Calculating confidence intervals in two sample analysis with extremely skewed count data I want to identify the effect of a feature on a number of events. Each observation has >= 0 events and is assigned to one group, A or B. Each observation was assigned to a group by random sampling, and observations in group A were exposed to a treatment that group B was not exposed to.
I have a very large amount of observations (> 300K). This is an idea of what my table looks like:
Obs   Nb_events  Group
1     0          A
1     0          B
1     0          B
1     2          A
1     0          A
...

The overall probability of having at least one event is 0.04. If the observation is in group A, it's 0.00442, and if it's in group B, it's 0.00436.
The mean for group A is 0.01 and for group B it is 0.012.
The standard deviation of the number of events is 0.292 for group A and 0.234 for group B.
I want to estimate, as simply as possible, a confidence interval of the effect of being in group B on the number of events and the probability of having at least one event.
I have read that my data seems to follow a negative binomial distribution model, or a highly dispersed Poisson model because sample variance > sample mean.
However, I don't know how to find a confidence interval given this. It seems like I can't use a normal approximation, and a Poisson approximation does not seem to fit my data either. Given this, how can I estimate a standard 95% confidence interval as simply as possible for my data?
I also want to find a confidence interval for the probability of having at least one event. I wanted to use the usual confidence interval based on normal approximations, for two samples.
But this also posits a normal approximation using Central Limit Theorem and that does not seem to be verified because my p is extremely low.
Edit: I haven't found an answer to this yet besides using an exact test, which is, I believe, computationally intensive given my sample sizes.
Instead of finding a confidence interval, I think simply measuring whether the difference between my proportions is significant would be approproate.
I believe a chi square goodness of fit test would work well here, based on [this question][1]. However, I think it would not be applicable to my count data. Can you confirm this?


text:
Q: Homogeneity of a variant of Prikry forcing Prikry forcing is easily seen to be cone homogeneous (for any $p, q \in \mathbb{P}$, there are $p' \leq p, q' \leq q$ and an isomorphism $\Phi: \mathbb{P}/p' \simeq \mathbb{P}/q'$); in particular for any generic filter $G$,
$HOD^{V[G]} \subseteq V.$
Now consider the following variation of the Prikry forcing. Let $\kappa$ be measurable and suppose $(U_i: i<\kappa)$ are normal measures on $\kappa$ such that there are $A_i \in U_i,$ which are pairwise disjoint. Let $\mathbb{P}_{\bar{U}}$ consists
of all pairs $(t, T)$ where $T \subseteq [\kappa]^{<\omega}$ is a tree with trunk
$t$, and for all $t \unlhd u\in T, suc_T(v) \in U_i, suc_T(v) \subseteq A_i,$
where $i=max(v).$ The order is defined in the natural way.
It doesn't seem that the forcing has to be cone homogeneous, except we assume some connection between the measures $U_i$ (they are Rudin-Keisler equivalent, or ...).
Now my question is the following:
Question. Assume $G$ is $\mathbb{P}_{\bar{U}}$-generic over $V$. Does
$HOD^{V[G]} \subseteq V?$


text:
Q: Inserting an object in ascending order with an ArrayList in Java So I've went back and forth quite a few times trying multiple different methods but I just can't seem to wrap my head around the appropriate algorithm for this method. I am creating a Polynomial class that uses an ArrayList where Term(int coeff, int expo) The coeff is the coefficient of the polynomial and the expo is the exponent. In the test class I have to insert multiple different Term objects but they need to be inserted in ascending order by their exponents (for example, 4x^1 + 2x^3 + x^4 + 5x^7)
This is the code I have up to the end of the insert() method which takes two parameters, the coeff and expo:
public class Polynomial
{

   private ArrayList<Term> polynomials ;

   /**
     * Creates a new Polynomial object with no terms
     */
  public Polynomial()
  {
       polynomials = new ArrayList<>() ;
  }

  /**
    * Inserts a new term into its proper place in a Polynomial
    * @param coeff the coefficient of the new term
    * @param expo the exponent of the new term
    */
   public void insert(int coeff, int expo)
   {

      Term newTerm = new Term (coeff, expo) ;

      if (polynomials.isEmpty())
      {
          polynomials.add(newTerm);
          return;
      }

      int polySize = polynomials.size() - 1 ;

      for (int i = 0 ; i <= polySize ; i++)
      {
            Term listTerm = polynomials.get(i) ;
            int listTermExpo = listTerm.getExpo() ;

            if ( expo <= listTermExpo )
            {
                 polynomials.add(i, newTerm);
                 return;
            }

            else if ( expo > listTermExpo )
           {
                 polynomials.add(newTerm) ;
                 return ;
           }

    }

}

The problem arises near the end of the code. Once I put in a Term whose coefficient isn't <= the Term at the index it goes to the else if statement and adds it to the end of the list. Which is wrong, since it needs to be added where it JUST becomes bigger than the next coefficient. Just because it's larger than that coefficient doesn't mean its the LARGEST coefficient. I've tried doing the for statement backwards where:
for (i = polySize ; i >= 0 ; i--)
{
  etc.
}

But that didn't work either since it raises the same issue just the other way around. If anyone could provide some solution or answer it would be much appreciated since I am very confused. At this point I'm sure I'm just making it too complicated. I just want to know how to recognize that the exponent is larger but then go back into the for loop until it is smaller than or equal to the index's exponent.
Also, I should mention, I am not allowed to use any other collection or class, so I must do this using a for, if, else, or do while statement.
Thanks in advance!

A: Remove this from the for loop:
       else if (expo > listTermExpo)
       {
             polynomials.add(newTerm);
             return;
       }

Place this after the for loop:
polynomials.add(newTerm);
return;

Reasoning: You want to add the term to the end of the list only if it is not less than ANY term in it - not just the first term.
Also, it is good formatting to have the ; immediately after the statement it is for with no space in between, and for ()s to not have any spaces immediately inside them. I've edited the code I copied from you to show what I mean.

A: This should have the exact behaviour you specified:
public void insert(int coeff, int expo) {
    Term newTerm = new Term(coeff, expo);
    int max = polynomials.size();
    int min = 0;
    int pivot;
    while (max > min) {
        pivot = (min + max) / 2;
        if (expo > polynomials.get(pivot).getExpo()){
            min = pivot + 1;
        }
        else {
            max = pivot;
        }
    }
    polynomials.add(min, newTerm);
}

This algorithm will add new Terms right in front of the first term with the same exponent if any such Term is already in the list.


text:
Q: Gradle sync failed: Build tools download failed with code 2 I just install the latest version of Android SDK but my project was made in  a old version
This is my code:

This is the error that is shown on my Event Log:

A: I changed the build Gradle version in Project: appname.gradle to the latest version and added the latest google version.
dependencies {
     classpath 'com.android.tools.build:gradle:3.2.1'
     classpath 'com.google.gms:google-services:4.1.0'
}
You can find the latest versions here: https://developer.android.com/studio/releases/gradle-plugin
I also updated the distrubution Url in gradle.wrapper to the latest version:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.1-all.zip


text:
Q: How to build OpenCV for PNaCl on Windows I'm beginner to PNaCl/NaCl and have a problem.
I want to use "openCV" on Web Native Client. So I tried to build "naclports" on cygwin.
But it was failed..
below is my workflow and result. Please tell me what is wrong or alternative idea to use "openCV".
*I use windows8.1 and cygwin.
1. Download and install the [Native Client SDK][1].
     - installed pepper version is 35. PATH is C:/cygwin64/home/*user*/nacl_sdk/pepper_35 (set the environment variable).

2. Clone the "[naclports][2]" in  C:/cygwin64/home/*user*/naclports/src/

3. Done the build on cygwin.
**@** ~/naclports/src
$make opencv

4. error is coming:
######################################################################
Testing zlib
######################################################################
chdir /home/ryosuke/naclports/src/out/build/zlib/zlib-1.2.8
DEBUG MODE ENABLED (bypass acl)
fread: Broken pipe
DEBUG MODE ENABLED (bypass acl)
NaClMain: <fd:0>: Broken pipe
  *** minigzip test FAILED ***
naclports: Building 'zlib' failed.
Makefile:68: recipe for target 'opencv' failed
make: *** [opencv] Error 1

Do you have any good idea?

A: Unfortunately many of the ports in naclports don't currently building cygwin.  In this case you can see that its actually zlib that is failing to build.
If possible you can build the ports a mac or linux machine and copy the resulting packages over.
A system for installing binary package is currently being developed to make it easier to install pre-built packages rather than building them from source.


text:
Q: ElasticSearch - How perform a query using multi_match without using "dis_max"? Is there any way to use the multi_match interface using these more complex matchs?
Obs: I believe that multi_match: best_fields works as if it were an alias pro dis_max in this situation mentioned
I am trying to use multi_match to execute some queries, but as I read in the documentation, I noticed that within the multi_match context I can not make explicit the whole complex structure of each field, for example:
{
    "multi_match": {
        "query":    "quick brown fox",
        "fields": [ "title", "body" ],
        "type":     "best_fields"      # default
    }
}

This structure above represents a simple multi_match where it was not parameterized anything besides the fields used in the match and the value of the query, if I were for example want to put zero_terms_query already could not because multi_match does not support this parameter, having as a following way:
{
    "dis_max": {
        "queries": [
            { "match": { "title": {
                             "query" : "quick brown fox",
                             "zero_terms_query" : 'all'
                       }}
            },
            { "match": { "body":  "quick brown fox" }}
        ]
    }
}


text:
Q: Casting generic class types to non-generic or calling methods of their instances? I am trying to do one of the following:
Dummy d = (Class<Dummy>)super.getEntity();  // incompatible Types - cannot cast
Dummy d = (Dummy)super.getEntity();  // incompatible Types - cannot cast
d.foo();

or
Class<Dummy> d = (Class<Dummy>)super.getEntity(); // works
d.foo(); // method cannot be found

Dummy d is defined in an abstract superclass as follows:
Class<T> dummy;
public Class<T> getEntity() { return dummy; }

Is there any way to call a method (foo) in an object of Generic class type? The point is that the superclass should NOT care about the type of the object, so that functionality can vary by the extending classes.

A: Your getEntity() method returns a class token, not an instance of that class, so you can't call foo() on it, only the methods defined in the interface of java.lang.Class. You need to instantiate that class first (by calling newInstance() - it requires that the class has a public default constructor), then you have a class object, upon which you may call foo():
Class<Dummy> clazz = super.getEntity();
try {
  Dummy d = clazz.newInstance();
  d.foo();
} catch (...) {
}

Notes:

*

*since getEntity() is generic, it will return the proper class type, thus the cast to Class<Dummy> is not needed,

*Class.newInstance() may throw various exceptions, which you must handle, hence the try-catch block. This is one of the reasons reflection is not a preferred way of solving such issues,

*since in the derived class you know the exact type parameter used in the base class, this code is unnecessarily verbose and rather contrived.

Alternatively, you may prefer returning T from getEntity() instead of Class<T> - this way you can call foo() directly on the object returned. Note that since you can't instantiate generic types directly, you need to either pass an instance of the class to the superclass (e.g. as a constructor parameter, or through an overridden virtual method), or create it using reflection as described above.
Here is how to do it using a constructor parameter:
public abstract class ABC<T> {
  private T dummy;
  public ABC(T dummy) { this.dummy = dummy; }
  ...
  public T getEntity() { return dummy; }

}

public class DEF extends ABC<Dummy> {
  public DEF() {
    super(new Dummy(); }
  }
  public void doSomething() {
    Dummy dummy = getEntity();
    dummy.foo();
  }
}


text:
Q: How to print Yes/No after inputting all values? input is :
        5
        P204BT
        X182YZ
        a216bc
        A216BC
        ABC216

but after every inputted value i call def _check and it prints Yes/No. How to make output after inputting all values, but not after each value?
def _check():
    Alphabet = ['A', 'B', 'C', 'E', 'H', 'K', 'M', 'O', 'P', 'T', 'X', 'Y']
    w1 = busId[0]
    n1, n2, n3 = busId[1], busId[2], busId[3]
    w2 = busId[4]
    w3 = busId[5]
    if w1 in Alphabet and w2 in Alphabet and w3 in Alphabet and n1.isnumeric() and n2.isnumeric() and n3.isnumeric():
        print('Yes')
    else:
        print('No')

n = int(input())
for i in range(n):
    busId = [x for x in input()]
    _check()

A: There are several ways you could complete this code. The most simple solution in my opinion would be to take all the variables and put them into a list or an array. Then iterate through the entire list using a for loop and i to check if the values inside the list are what you want. This should allow the program to keep all the values together instead of reading them separately.


text:
Q: update cell with drop down selected value I need to update the cells in a column based on the next columns dropdown value. but i still couldn't achieve it .
could somebody help me with this.
Thank you in advance

$(document).ready(function() {
  var table = $('#example').DataTable({
    data: array,
    "columnDefs": [{

      "targets": -1,
      "render": function(meta) {
        return "<select id='optsl' onchange='getselect(this)'><option value='0'>Select Header</option><option value='1'>Client</option><option value='2'>Date</option><option value='3'>Date period</option><option value='4'>Topic</option><option value='5'>Full Total</option><option value='6'>Tax Total</option><option value='7'>Comment1</option><option value='3'>Comment2</option></select>";

      }
    }],

  });
});

var table = document.getElementById("#example");
//var cells = table.getElementsByTagName('th');

function getselect(table) {
  var d = $("#optsl option:selected").val();
  table.row('selected', 4).data(d).draw();
}

var array = [
  [null, null, null, null, null],
  [null, "Rough Costing", null, null, null],
  [null, null, null, null, null],
  [null, "Client", "Ua Limited", null, null],
  [null, "Product", null, null, null],
  [null, "Pro: Name", "Idam ", null, null],
  [null, "Est.: No", null, null, null],
  [null, "Time: period ", "43299", null, null],
  [null, "Date", "15th July - 2018", null, null],
  [null, null, null, null, null]
];

getselect($('#example'));
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}

<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" />

        Col 1
        Col 2
        Col 3
        Col 4
        Col 5
        select

my fiddle

A: Following should get you well on your way

$(document).ready(function() {

  function getSelectOptions(value) {
    var select = $("<select><option value='0'>Select Header</option><option value='1'>Client</option><option value='2'>Date</option><option value='3'>Date period</option><option value='4'>Topic</option><option value='5'>Full Total</option><option value='6'>Tax Total</option><option value='7'>Comment1</option><option value='3'>Comment2</option></select>");
    if (value) {
      select.val(value).find(':selected').attr('selected', true);
    }
    return select.html()
  }

  var table = $('#example').DataTable({
    data: array,
    "columnDefs": [{

      "targets": -1,
      "render": function(data, type, row, meta) {
        return "<select class='mySelect' data-col='" + meta.col + "'>" +
                getSelectOptions(data) + "</select>";
      }
    }],

  });

  $('#example').on('change', 'select.mySelect', function() {
    var colIndex = +$(this).data('col')
    var row = $(this).closest('tr')[0];
    var data = table.row(row).data();
    data[colIndex] = this.value
    data[colIndex-1] = $(this).find(':selected').text();
    table.row(row).data(data).draw();
  })
});

var array = [
  [null, null, null, null, null],
  [null, "Rough Costing", null, null, null],
  [null, null, null, null, null],
  [null, "Client", "Ua Limited", null, null],
  [null, "Product", null, null, null],
  [null, "Pro: Name", "Idam ", null, null],
  [null, "Est.: No", null, null, null],
  [null, "Time: period ", "43299", null, null],
  [null, "Date", "15th July - 2018", null, null],
  [null, null, null, null, null]
];
body {
  font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
  margin: 0;
  padding: 0;
  color: #333;
  background-color: #fff;
}

<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" />

        Col 1
        Col 2
        Col 3
        Col 4
        Col 5
        select


text:
Q: Cross Domain AJAX Post using easyXdm I am trying to get a cross domain AJAX post to work using the easyXdm library.
In my local development environment I have two sites:

1. http://localhost/MySite/ws/easyXDM/cors/index.html (EasyXdm file)
2. http://localhost/MyClientSite/TestPage.html (AJAX post from here)

TestPage.html (AJAX Post)
var rpc = new easyXDM.Rpc({
        remote: "http://localhost/MySite/ws/easyXDM/cors/index.html"
    },
    {
        remote: {
            request: {}
        }
    });

rpc.request({
        url: "http://localhost/MySite/ws/MyService.asmx/DoSomething",
        method: "POST",
        data: jsonData
    }, function(response) {
        console.log(JSON.parse(response.data));

        $('#thanksDiv').fadeIn(2000, function () {
            $('#thanksDiv').fadeOut(4000);
        });
    });

When I do the AJAX post I get the following in my browser's console:
easyXDM present on 'http://localhost/MySite/ws/easyXDM/cors/index.html?xdm_e=http%3A%2F%2Flocalhost%2FMyClientSite%2FTestPage.html&xdm_c=default884&xdm_p=4
native JSON found
easyXDM.Rpc: constructor
{Private}: preparing transport stack
{Private}: using parameters from query
easyXDM.stack.SameOriginTransport: constructor
easyXDM.stack.QueueBehavior: constructor
easyXDM.stack.RpcBehavior: init
{Private}: firing dom_onReady
... deferred messages ...
easyXDM.Rpc: constructor
{Private}: preparing transport stack
{Private}: using parameters from query
easyXDM.stack.SameOriginTransport: constructor
easyXDM.stack.QueueBehavior: constructor
easyXDM.stack.RpcBehavior: init
... end of deferred messages ...
easyXDM.stack.SameOriginTransport: init
easyXDM.stack.RpcBehavior: received request to execute method request using callback id 1
easyXDM.stack.RpcBehavior: requested to execute procedure request
easyXDM.stack.QueueBehavior: removing myself from the stack

Problem: The web service never actually receives the data. This is obvious as my AJAX post success function should show a thanksDiv and also a record should be created in the *database.
Note: I am replacing my existing AJAX post code as I need to use easyXdm to overcome an issue with Internet Explorer 6 and 7 on a client's site.
Additional Information:
The file-structure where my easyXdm files are located is as follows:
/ws/easyXDM/easyXDM.debug.js
/ws/easyXDM/easyXdm.swf
/ws/easyXDM/json2.js
/ws/easyXDM/name.html
/ws/easyXDM/cors/index.html

A: My web service was throwing a HTTP 500 server error as jsonData was not being sent correctly via easyXdm.
The json data looks like this before it was posted:

{ "param1": "value1", "param2": "value2"...... }

However, the web service was receiving the data one character per line e.g.
{
"
p
a
r
a
m
"
....

I was not serialising the json data prior to my post. So, based on the original code I posted in the original question:
To get it working I changed the line
data: jsonData

to
data: JSON.parse(jsonData)


text:
Q: Is glClear(GL_COLOR_BUFFER_BIT) necessary when I already glDisable(GL_BLEND)? In my understanding, if I disable GL_BLEND, then no blending happens at all.
So I don't need do glClear(GL_COLOR_BUFFER_BIT).
I am working on GLES20 for Android programming. I have added the line below.
GLES20.glDisable(GLES20.GL_BLEND);

If I don't add glClear(GL_COLOR_BUFFER_BIT), all other devices work well except Nexus 4.
On Nexus 4, on one pass (other passes work normally), only partial area is rendered.
If I add glClear(GL_COLOR_BUFFER_BIT), then now Nexus 4 works well.

A: If GL_BLEND is disabled, then a fragment of the draw buffer will be overwritten, if it is drawn to.
If you disable blending and you write on every fragment of the draw buffer in every frame, then it is useless to clear the draw buffer, because each fragment will be set during the drawing process.
glClear(GL_COLOR_BUFFER_BIT) does nothing else than to write to every fragment with a constant color set by glClearColor.
Note, you have to ensure, that every fragment is written in each frame. For example if GL_DEPTH_TEST is enabled you'll have to glClear(GL_DEPTH_BUFFER_BIT anyway.


text:
Q: C++ Vector Crashing Evening All,
My following code:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

const char NEWLINE = 0x0D + 0x0A;

int main() {

  int headerCount;
  char response;
  int x = 0;
  int i = 0;
  string header[headerCount];

  cout << "How many columns appear in you file: ";
  cin >> headerCount;
  cout << "There are " << headerCount << " columns in your file? (Y/N): ";
  cin >> response;
  if(response == 'Y'){
    cout << endl << "Okay" << endl;

    ofstream myfile;
    myfile.open("example.csv", ios::binary | ios::out);
    string vals;
    vector< vector<string> > buff;

    // To set values
    while(i != 3){
      vector<string> temp;

      while(x != headerCount){
        if (i == 0){
          cout << "What is header number " << (x + 1) << endl;
        } else {
          cout << "What is person " << i << "'s " << header[x] << ":";
        }
        cin >> vals;
        if (i == 0) header[x] = vals;
        temp.push_back("\"" + vals + "\"");
        if (x != (headerCount - 1)) { temp.push_back(","); }
        x++;
      }
      buff.push_back(temp); // Store the array in the buffer
      x = 0;
      i++;
    }

    //To access values
    for(vector<vector<string> >::iterator it = buff.begin(); it != buff.end(); ++it){
      //it is now a pointer to a vector<int>
      for(vector<string>::iterator jt = it->begin(); jt != it->end(); ++jt){
        // jt is now a pointer to an integer.
        myfile << *jt;
      }
      myfile << "\r\n";
    }

    myfile.close();

  } else {
    cout << endl << "oh";
  }

  return 0;
}

Crashes on its fourth iteration.
E.g. value[0][4]
Any ideas? I am reasonably new to vectors. This code causes Code::Blocks to display my application as "not responding". Really Lost at the moment!
I know there are probably plenty of similar posts but I have been trawling the web for hours.

A: First, you must thank  @40two who quickly spotted the main issues.
So add the missing include. Then, define your variable header as a vector to allow for dynamic sizing.  However, do this AFTER your cin reading,  in order to make sure the variable is initialised and not random:
  cin >> headerCount;                   // existing line
  vector<string> header(headerCount);   // definition in a new place

Then it should run without crashing (tested with VC2013)

A: As @40two mentioned, the real issue is that you cannot variable sized arrays in C++. There is huge scope to improve the code significantly. To get you going quickly, see the fixed up code below.
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

const char NEWLINE = 0x0D + 0x0A;

int main() {

  int headerCount;
  char response;
  int x = 0;
  int i = 0;

  cout << "How many columns appear in you file: ";
  cin >> headerCount;
  cout << "There are " << headerCount << " columns in your file? (Y/N): ";
  cin >> response;
  if(response == 'Y'){
    cout << endl << "Okay" << endl;

    ofstream myfile;
    myfile.open("example.csv", ios::binary | ios::out);
    string vals;
    vector< vector<string> > buff;

    // To set values
    while(i != 3){
      vector<string> temp;

      while(x != headerCount)
      {
        string header;
        if (i == 0){
          cout << "What is header number " << (x + 1) << endl;
        } else {
          cout << "What is person " << i << "'s " << header << ":";
        }
        cin >> vals;
        if (i == 0)
            header = vals;
        temp.push_back("\"" + vals + "\"");
        if (x != (headerCount - 1)) { temp.push_back(","); }
        x++;
      }
      buff.push_back(temp); // Store the array in the buffer
      x = 0;
      i++;
    }

    //To access values
    for(vector<vector<string> >::iterator it = buff.begin(); it != buff.end(); ++it){
      //it is now a pointer to a vector<int>
      for(vector<string>::iterator jt = it->begin(); jt != it->end(); ++jt){
        // jt is now a pointer to an integer.
        myfile << *jt;
      }
      myfile << "\r\n";
    }

    myfile.close();

  } else {
    cout << endl << "oh";
  }

  return 0;
}


text:
Q: How to get the current status of a Microsoft Teams user Is there an API where I can get the current Status of a Team User ? Like "Available", "In Meeting" etc ?
I have used the user's presence on Skype For Business using the 2013 lync SDK. I am not finding anything similar for Teams. Ultimately my goal is to find the current status and display it on an IOT Device.
Any code snippet, links will be much appreciated.

A: Graph API endpoints to get presence information is now available in beta version. Please check Graph API - Presence resource type

A: I don't think it is available yet.
Please check the following post:
[Accessing user presence with REST API for Microsoft Teams

A: We are working on it to get the Presence API for all our customers. We don't have timeline to share with you. Stay Tuned...


text:
Q: Cannot call method from view I cannot call the method from the controller
This is the view
<% songartist = change_artist(songartist) %>
<%= @artistnum  %></b> total songs.

This is my controller
 def mylist_artist
    @songs = current_user.songs.all
    @songartists = @songs.pluck(:artist).uniq

    def change_artist(link)

        require 'uri'
        require 'open-uri'
        require 'nokogiri'

        @changed = URI::encode(params[:link])
        linkurl = "https://www.ufret.jp/artist.php?data="+@changed
        doc = Nokogiri::HTML(open(linkurl))
        @artistnum = doc.xpath(" //a [@class= 'list-group-item list-group-item-action normal-chord']/strong").children.count
        return @artistnum
    end
end

A: I'm going to focus only on the problem stated in the question "Cannot call method from view";
You can't invoke that method because in the context you're (the view), that method is inaccessible without initializing the controller where it's defined. You can achieve that as follows:
<%= songartist = SomeController.new.mylist_artist('foo') %>

By previously updating the mylist_artist method by adding an argument:
def mylist_artist(link)
  ...
end

But you should never do that because we don't usually write nested methods in Ruby that way. As you can see, the only thing it returns is the name of the change_artist as a symbol, which happens to be the return value of that method.
If you plan to use change_artist in the View layer, you should move it to a helper. Since that's the norm and Rails allows you to invoke them without having to do much.
Just add a new file to your app/helpers/ directory, and move the method there:
# app/helpers/some_helper.rb
module SomeHelper
  def change_artist(link)
    ...
  end
end

Now in your view you can simply do:
<% songartist = change_artist('foo') %>

A: This is not supposed to work. If you really want to call such a method in your views, you'll have to put it into a app/helpers/foo_helper.rb.

A: You're defining a method inside another method...
Anyway if you want to call a method from the view you should define it in a helper class not in the controller.


text:
Q: Any way to efficiently sync two databases? I am planning to make a software which requires two or more databases to be in sync with a main server database ( located on a web server ). Suppose one user have installed my software on more than one computers. Suppose he updates some info on PC-1 then the change should be locally updated and if he is connected with the internet, it should get in sync with the main web server. When he opens the software on PC-2, latest into must be shown there ( assuming he is connected with the internet ).
Now suppose both PC-1 and PC-2 have same data, and both are offline. User deletes the data from PC-1 but don't deletes it from PC-2 ( he assumes it'll get managed automatically ), now when both of the systems go online, the record must be deleted from PC-2 too.
Basically, I am trying to find the database which was most recently updated or modified and sync it with the main database ( on the server ). How can I do it ?

A: It sounds like you want to synchronize some user data whenever the users or application becomes "online" again.
A couple of suitable services are:

*

*Amazon Cognito Sync is an AWS service and client library that enables cross-device syncing of application-related user data. You can use it to synchronize user profile data across mobile devices and the web without requiring your own backend. The client libraries cache data locally so your app can read and write data regardless of device connectivity status. When the device is online, you can synchronize data, and if you set up push sync, notify other devices immediately that an update is available.

*AWS AppSync enables developers to interact with their data by using a managed GraphQL service. GraphQL offers many benefits over traditional gateways, encourages declarative coding style, and works seamlessly with modern tools and frameworks, including React, React Native, iOS, and Android. GraphQL is a data language that was developed to enable apps to fetch data from servers. It has a declarative, self-documenting style. In a GraphQL operation, the client specifies how to structure the data when it is returned by the server. This makes it possible for the client to query only for the data it needs, in the format that it needs it in.


text:
Q: SQL insert into and DEFAULT values I have an INSERT INTO statement as
INSERT INTO tablename (var1, var2)
SELECT othervar1, othervar2
FROM othertablename

The problem is that the table "tablename" have more variable than just var1 and var2. The insert statement will set Null to the other variables that are not assign values by default. The problem is that the "tablename" do not accept null values.
I could set the default value to zero for the all the relevant variables in "tablename" but I do not have access to modify the DB.

A: Add the columns and the values to INSERT and SELECT statements
INSERT INTO tablename (var1, var2, col1, col2, col3)
SELECT othervar1, othervar2, 'default','default','default'
FROM othertablename

BTW: a table do not have variables, it has columns

A: IF you do not have access or can't update table columns default value,
so try to change the query and insert desire values...
like that:
INSERT INTO tablename (var1, var2, field3, field4)
SELECT othervar1, othervar2, 0, 0
FROM othertablename

A: you have to set default value for each field as per below picture i have shared.
you have to give default  value in that textbox.


text:
Q: How to Hoist Mutiple States in compose? I have been trying to figure out how to hoist multiple states in 1 single composable/ viewModel but without any luck.
Whenever I type in one of the fields, it types in all fields at the same time. Like this:
https://gyazo.com/b3aae51a92a00478dd228f69dc8c12ac
Also, if I add  extra parameters to the UI composable (UserProfile), it gives me an error in the hoisted composable since its missing in both Userprofile inside UserProfileState. I know how to hoist 1 state but with mutiple it seems to become more complex. How can I hoist mutiple states in the same composable/ ViewModel ?
My Hoisted state composable:

@Composable
fun UserProfileState() {

    var username by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }

    UserProfile(
        currentUserName = username,
        newTextFieldValueUserName = { username = it })

    UserProfile(
        currentUserName = email,
        newTextFieldValueUserName = { email = it},

    )

}

UserProfile containing both Username and Email textfields:
@Composable
fun UserProfile(
    currentUserName: String,
    newTextFieldValueUserName: (String) -> Unit,

) { // Username and Email is placed here, as seen below!}

Username:
 Spacer(modifier = Modifier.height(20.dp))

 OutlinedTextField(
 value = currentUserName,
 onValueChange = newTextFieldValueUserName,

 label = { Text(text = "Name") },
 singleLine = true,
 leadingIcon = {
             Icon(
                  imageVector = Icons.Default.Email,
                  contentDescription = null
                  )
                   },
modifier = Modifier
.fillMaxWidth(180F),

)

Email:
Spacer(modifier = Modifier.height(20.dp))

OutlinedTextField(
   value = currentUserName,
   onValueChange = newTextFieldValueUserName,

label = { Text(text = "Email") },
singleLine = true,
leadingIcon = {
                Icon(
                     imageVector = Icons.Default.Email,
                     contentDescription = null
                    )
                    },
modifier = Modifier
.fillMaxWidth(180F),
)

A: You just add all the data you want to pass in as inputs, and you also add callback functions for all the data that can change inside the composable, for your example it would be like this
@Composable
fun UserProfile(
    username: String,
    email: String,
    onUsernameChange: (String) -> Unit,
    onEmailChange: (String) -> Unit,
) {
    Column {
        Spacer(modifier = Modifier.height(20.dp))

        OutlinedTextField(
            value = username,
            onValueChange = onUsernameChange,

            label = { Text(text = "Name") },
            singleLine = true,
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Email,
                    contentDescription = null
                )
            },
            modifier = Modifier
                .fillMaxWidth(180F),

            )

        Spacer(modifier = Modifier.height(20.dp))

        OutlinedTextField(
            value = email,
            onValueChange = onEmailChange,

            label = { Text(text = "Email") },
            singleLine = true,
            leadingIcon = {
                Icon(
                    imageVector = Icons.Default.Email,
                    contentDescription = null
                )
            },
            modifier = Modifier
                .fillMaxWidth(180F),
        )
    }
}

Then in the parent screen you simply pass all the state in and you wire-up all the change callbacks
@Composable
fun UserProfileState() {
    var username by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }

    UserProfile(
        username = username,
        email = email,
        onUsernameChange = { username = it },
        onEmailChange = { email = it }
    )
}

Or if you prefer it this way
@Composable
fun UserProfileState() {
    val (username, setUsername) = remember { mutableStateOf("") }
    val (email, setEmail) = remember { mutableStateOf("") }

    UserProfile(
        username = username,
        email = email,
        onUsernameChange = setUsername,
        onEmailChange = setEmail
    )
}


text:
Q: what's the complexity of Exists C#? What's the complexity of the method Exists in a list, I have this:
List<ComplexData> list = new List<ComplexData>()
list.Exists( r => r.Name == someValue );

My class has the values:
public class ComplexData
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Descripcion { get; set; }
}

I've looking for the complexity and I've tried executing some loops but the time doesn't change so much. I don't know if the list create an "index" like a database or if make some order by the comparator and then do a binarySearch.

A: According to the C# Documentation on Microsoft's website:
Remarks

The Predicate is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List are individually passed to the Predicate delegate, and processing is stopped when a match is found.
This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

See it here: List.Exists

A: Source code is open, you can find it here
The method basically goes through every element in collection till it finds a match.
public bool Exists(Predicate<T> match)
{
    return FindIndex(match) != -1;
}

public int FindIndex(Predicate<T> match)
{
    Contract.Ensures(Contract.Result<int>() >= -1);
    Contract.Ensures(Contract.Result<int>() < Count);
    return FindIndex(0, _size, match);
}

public int FindIndex(int startIndex, int count, Predicate<T> match)
{
    if ((uint) startIndex > (uint) _size)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex,
            ExceptionResource.ArgumentOutOfRange_Index);
    }

    if (count < 0 || startIndex > _size - count)
    {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count,
            ExceptionResource.ArgumentOutOfRange_Count);
    }

    if (match == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    Contract.Ensures(Contract.Result<int>() >= -1);
    Contract.Ensures(Contract.Result<int>() < startIndex + count);
    Contract.EndContractBlock();

    int endIndex = startIndex + count;
    for (int i = startIndex; i < endIndex; i++)
    {
        if (match(_items[i])) return i;
    }
    return -1;
}

A: The complexity is O(n).
Exists internally uses FindIndex.
There's no index creation, basically Exists loops all items in a collection until it finds one that matches your predicate.
Try 10 million elements and you'll see how slow it gets when compared with a Hashset with the same number of elements.
Hashset has O(1) complexity


text:
Q: Scale font to size when text exceeds container? I want font size to be 54px if the text fits inside the container, otherwise it should be 36px.
I was considering whether I can achieve this with a pure CSS solution, using the scale function to collapse to either of the two. If the container can be assumed to be full with, I guess I could use vw as a base for a calculation?
But I am very much stuck on this. Could anyone give me a hint, as to how I can achieve this or something close to it.

A: If you would like to put some text inside a container and have it size itself to fill that container, then CSS Tricks has an article on Fitting Text to a Container that will cover your options.
You could also use Viewport Sized Typography which take advantage of viewport units such as:

*

*1vw = 1% of viewport width

*1vh = 1% of viewport height

*1vmin = 1vw or 1vh, whichever is smaller

*1vmax = 1vw or 1vh, whichever is larger

One unit of any v* is 1% of the viewport axis. Where the "Viewport" == browser window size == window object. If the viewport is 50cm wide, 1vw == 0.5cm. Using viewport units alone such as font-size: 4vw; can make the text appear too big or too small when varying the window width and bring accessibility issues (as the user preferences are not taken into account).
Lastly, you could use clamp() to achieve Simplified Fluid Typography. Clamp takes three values, a min, max, and a flexible unit in the middle that it will use in case the value is between the min and max.
If you want the font size to be a minimum of 36px and maximum 54px, you could use clamp() like this and vary the "flexible unit" to your liking. Here is an example of fluid typography for an
 element inside a container.

body {
  font-size: 1rem;
  margin: 0 auto;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.container {
  border: .2rem solid #f06;
  padding: .5rem;
  height: 100%;
  width: auto;
}

.container h1 {
  font-size: 36px; /* fallback */
  font-size: clamp(36px, 10vw, 54px);
}

Heading text

Browser support for clamp() is pretty good, but you'd probably want to put a font-size declaration before it to set an acceptable fallback value.
In conclusion, if you needed to set an explicit width and height for said container, you might want to use media queries along with viewport units, calc(), or clamp() depending on the size of the content box in which the text resides.

A: i think it's nearly impossible to calculate it without js.
below is an code example how i would do it in jquery or you could use the following jquery plugin, but i never tested this plugin before: FitText.js

for (let container of $('.text-container')){
    container = $(container);
    let textInner = $(container).find('.text-inner');

    console.log(container.width());
    console.log(textInner.width());

    if (container.width()<textInner.width()){
        textInner.addClass('fs-36');
        textInner.removeClass('fs-54');
    } else {
        textInner.addClass('fs-54');
        textInner.removeClass('fs-36');
    }
}
.text-container,
.text-container-before{
    position: relative;
    width: 250px;
    height: 60px;
    background: #333;
    color: #090;
    overflow: visible;
    margin: 20px 0;
}
.text-inner,
.text-before{
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    background: #0399;
    word-break: keep-all;
    white-space: nowrap;
}
.fs-54{
    font-size: 54px;
}
.fs-36{
    font-size: 36px;
}

/* just added because console window is hiding running code snipped */
.spacer{
    height: 80px;
}

before

a bit longer text

shorter text

after

a bit longer text

shorter text

A: This question awsers was not exactly what I was looking for, so here is a solution to scale down the text if it would exceed the size of the parent container, by making it smaller until it fits the container.

for(const element of document.getElementsByClassName("shrink"))
{
        var size = parseInt(getComputedStyle(element).getPropertyValue('font-size'));
        const parent_width = parseInt(getComputedStyle(element.parentElement).getPropertyValue('width'))
        while(element.offsetWidth > parent_width)
        {
            element.style.fontSize = size + "px"
            size -= 1
        }
}
.container{
  border:1px dashed #ccc;
  display:flex;
  align-items:center;
  justify-content:center;
  width:200px;
  height:50px;
  margin:10px;
}
.shrink{
    white-space: nowrap;
    font-size:80px;
}

long text to shrink

small text

A: Try this

.thingy {
font-size:54px;
overflow-wrap: break-word;
}

Hel000000000000000000ooo

A: Not, Sure about CSS solution. But, My JS solution can resolve your problem.
Refer below code. Class class-54 and class-36 will change based on content:

// creating node
function createNode(element) {
  return document.createElement(element);
}

// creating append
function append(parent, el) {
  return parent.appendChild(el);
}

var getPageTitle = document.getElementById("pageTitle"),
  textLengthWidth = 0;
const getPageTitleText = getPageTitle.textContent;
getPageTitle.innerHTML = "";
for (let index = 0; index < getPageTitleText.length; index++) {
  const span = createNode("span");
  span.innerHTML = getPageTitleText.charAt(index);
  append(getPageTitle, span);
  if (index == getPageTitleText.length - 1) {
    calcFontSize();
  }
}

function calcFontSize() {
  var listOfSpan = document.querySelectorAll("#pageTitle span");
  listOfSpan.forEach(element => {
    textLengthWidth += element.offsetWidth;
  });
  console.log("total DIV width: " + getPageTitle.offsetWidth);
  console.log("total Content width: " + textLengthWidth);
  getPageTitle.offsetWidth < textLengthWidth ? getPageTitle.classList.add("class-36") : getPageTitle.classList.add("class-54");
}
 * {
            padding: 0;
            margin: 0;
            font-size: 14px;
        }

        .title {
            display: block;
            width: 100vw;
        }

        h1, h1 span {
            font-size: 54px;
        }

        .class-54 span {
            font-size: 54px;
        }

        .class-36 span {
            font-size: 36px;
        }

Hello World! Hello World!

A: try word-break: break-all;, I think this will solve your problem


text:
Q: Run Meteor from within a folder I've run meteor build to create my bundle, uploaded to the server, it runs fine, however the .css and .js paths are wrong, as it's using the root url. I need to run this from within a /project folder. Again it's running, but 404 on the files as they're not prefixed with /project.

eg. http://domain.com/65d054cb90ff094804072528d222178ddbf625e22.js?meteor_js_resource=true 404 (Not Found)
needs to be http://domain.com/project/65d054cb90ff094804072528d222178ddbf625e22.js?meteor_js_resource=true

I've tried using ROOT_URL=http://domain.com/project node main.js, that gives an unknown path error, i've also tried using Meteor.absoluteUrl('project', {}); in conjuntion with rooturl but again, no avail.
Any of you fine people have any ideas? :) Thanks!
PS. It's running on an apache server with ProxyPass, if that's of relevance.

A: You could instruct your apache to redirect those calls with a ProxyPassMatch, such as:
<LocationMatch ^/(.*)meteor_js_resource=true$>
    ProxyPassMatch http://localhost/project/$1meteor_js_resource=true
</LocationMatch>


text:
Q: p:remoteCommand only update="@all" PF5 On below code <p:remoteCommand> just update whole view when I use @all, but I've tried update @this,@form or wizardEventContainer without success. Even though @all work as I wish I would prefer just update the specific container wizardEventContainer
In the PrimeFaces website the example works using id attribute therefore I don't know why I can't get it too.
I work with PF5, JSF 2.2 and SWF 2.4. I changed JSF separator char to - instead of :
<h:form id="formEditor" styleClass="eventEditorForm" prependId="true">
            <p:editor id="editorEvent" height="150" width="900" maxlength="500" onchange="writeTextonPanel()" widgetVar="editorWidget"  />

            <h:panelGroup layout="block" id="eventEditorButtons" styleClass="eventEditorButtons">
                <h:commandButton value="#{msg['saveLayer.btn']}" actionListener="#{eventProvider.saveTextLayer()}" alt="#{msg['saveLayer.btn.alt']}" title="#{msg['saveLayer.btn.title']}" onclick="showEditor('save')">
                    <f:ajax execute="@form" render="-formBotones-wizardEventContainer" />
                </h:commandButton>
                <h:commandButton value="#{msg['omitLayer.btn']}" alt="#{msg['omitLayer.btn.alt']}" title="#{msg['omitLayer.btn.title']}" onclick="showEditor('delete')">
                    <f:ajax execute="@form" render="-formBotones-wizardEventContainer" />
                </h:commandButton>
            </h:panelGroup>

            <h:inputHidden id="tempCSS" value="#{eventProvider.tempCSS}" />
            <h:inputHidden id="tempHTML" value="#{eventProvider.tempHTML}" />
</h:form>

<h:form id="formBotones" prependId="true">

    <p:remoteCommand name="omitTextLayer" process="@this" update="formBotones-wizardEventContainer" actionListener="#{eventProvider.omitTextLayer()}" />
    <p:remoteCommand name="modifyTextLayer" actionListener="#{eventProvider.modifyTextLayer()}" />
    <h:inputHidden id="tempCSSforModify" value="#{eventProvider.tempCSSModified}" />

    <h:panelGroup layout="block" id="wizardEventContainer" styleClass="wizardEventContainer">
        <h:inputHidden id="tempTextIdLayer" value="#{eventProvider.tempTextIdLayer}" />
    </h:panelGroup>
</h:form>

JS code linked with JAVA method
function showEditor(mode){
if(mode=='save')
    saveLayer();

if(mode=='delete')
    deleteLayer();

if($('#eventEditorContainer').css('visibility')=="hidden"){
    $('#eventEditorContainer').css('visibility','visible');
    $('#formControl-textLayerBtn').prop("disabled",true);
}
else{
    $('#eventEditorContainer').css('visibility','hidden');
    $('#formControl-textLayerBtn').prop("disabled",false);
}

}

function deleteLayer(layer){

if(layer==null){
    var idLayer='formBotones-' + $('#formBotones-tempTextIdLayer').val();

    $('#' + idLayer).remove();

    $('#formEditor-tempCSS').val('');
    $('#formEditor-tempHTML').val('');

}
else{
    var idLayer=layer.parent().attr('id');

    layer.parent().remove();

    $('#formBotones-tempTextIdLayer').val(idLayer.substring(idLayer.indexOf("-")+1));
    $('#formEditor-tempCSS').val('');
    $('#formEditor-tempHTML').val('');

}

omitTextLayer(); // p:remoteCommand function

}

P.D: I'v edited adding full code sample and js code which link to java method on p:remoteCommand
Thanks!

A: Update works right using IDs if p:remoteCommad if thrown from p:commandButton instead of h:commandButton.
So, code must change to
<p:commandButton value="#{msg['omitLayer.btn']}" alt="#{msg['omitLayer.btn.alt']}" title="#{msg['omitLayer.btn.title']}" onclick="showEditor('delete')" />


text:
Q: How display xml content with nodes from a jsp I have a jsp which calls a servlet which inturn calls a webservice. The response xml of webservice is returned to the jsp. Now in the front end the xml content is displayed with out the nodes..How to display the xml as xml(with nodes)? can anyone pls help?

A: Verrry simple solution...I replaced all "<" with & lt; and all ">" with & gt; before returning the xml :).
I could see the xml as it is in the browser .


text:
Q: calling a sub using checkboxes excel vba I'm trying to call a sub using this code
If CheckBox2 = True Then Call Qorep

Heres the sub :
Public Sub Qorep()

For i = 0 To cap
    Hoja9.Cells(i + 2, 3).Value = Empty
    array_Qorep(i, 0) = Hoja1.Range("B" & i + 2)

    Select Case Hoja9.Cells(3, 5)
    Case Is > 0
    If array_Qorep(i, 0) < Hoja9.Cells(3, 5) Then Hoja9.Cells(i + 2, 3) = array_Qorep(i, 0)
    End Select

    Select Case Hoja9.Cells(3, 4)
    Case Is > 0
    If array_Qorep(i, 0) > Hoja9.Cells(3, 4) Then Hoja9.Cells(i + 2, 3) = array_Qorep(i, 0)
    End Select
    If Hoja9.Cells(i + 2, 3) = Empty Then Hoja9.Cells(i + 2, 3) = "#N/A"
    Next
End Sub

The problem is that with the checkbox checked it doesn't do anything, is there a problem trying to call the sub?
im a beginner and i might not be able to see whats wrong, any help?

A: In the worksheet you need
 Private Sub  CheckBox2_Click()

       If CheckBox2 = True Then Call Qorep

   End Sub

If your sub is not in the same worksheet then you need to use
Modulename.Qorep


text:
Q: parsing JSON inside of ajax sucess function I am trying to parse and display this JSON data that gets returned. Basically I have an ajax call which reads an input, sends it via POST to a PHP page and the php page var_dump's the array which contains the data.
      array(1) {
      [0]=>
      string(21) "jsmith@yahoo.com"
    }

My AJAX Call looks like..
            <script>
                        function searchDB()
                        {
                              var lookupemail = $('#lookupemail').val();
                              $.ajax({
                              type: "POST",
                              url: "includes/dbsearch.php",
                              data: {wordpress: lookupemail},
                              success: function(server_response)
                              {
                                var response = server.response.1;
                                alert(response);
                              }
                              });
                        }
            </script>

How do I retrieve the string that is returned and assign it to a javascript variable?

A: Your PHP code would have to output JSON in the first place:
$array = array('jsmith@yahoo.com');
echo json_encode($array);

A: To make it into an array in JavaScript you can use
var newArray = $.map(server_response, function(el) { return el; });

However, you can access the JSON directly using the json_encode in PHP.
json_encode($phparray);

and then...
server_response.arraykey


text:
Q: LD Player adb port number? I am a React Native developer.
I used to run my app on Nox.
adb connect localhost:62001
react-native run-android --deviceId localhost:62001

Now, I want to run my app on LD Player.
However, I don't know what the port number of the LD Player is.
adb connect localhost:?????

Please help me with how to connect and run my react-native app on LD Player.

A: LDPlayer doesn't have port naturally.


text:
Q: How to keep text format from a getElementById in javascript? I store a text in a mysql database, and then I call it back and show it in a div with the following:
document.getElementById("mensaje").innerHTML = html;

But when it displays the text it doesn't keep the brake lines.
How can I fix it?

A: You need to encode and encode:
With JavaScript:
Option1:
encodeURI('string to database');
decodeURI('string from database');

Option2:
encodeURIComponent('string to database');
decodeURIComponent('string from database');

With PHP:
Option3:
<?php
htmlentities($strToDB);
echo html_entity_decode($strFromDB);
?>

A: If you are storing data from textarea then before storing data in database you can do
<?php
message = nl2br(message);
?>

It'll add HTML line breaks where it detects any line break.


text:
Q: How to install python packages to a running snap package? As I understand it, Ubuntu Snap encapsulates and manages versions and dependencies.  So if I'm using a python application which is installed as a classic snap, how do I pip install additional packages for the application to use inside the snap, without polluting my non-snap environment?
In this instance I want to add some packages to the 'atom' editor which have a bunch of python package dependencies.


text:
Q: Including JSTL implementation jar only Following this answer, below is a simple JSP demo that includes only JSTL implementation jar(javax.servlet.jsp.jstl-1.2.1.jar), but not JSTL API jar(javax.servlet.jsp.jstl-api-1.2.1.jar),

My understanding is, JSTL implementation jar holds both API(mostly Java interfaces) and it's implementation. This is the reason test.jsp got compiled and executed successfully.
Further, same approach would work with servlets using  API implementation jar provided by Tomcat container without using API(servlet-api.jar).

Is this the right understanding?

A: Api contains only interfaces you need to compile your code. The implementation could be in different library.
Tomcat and any other Java web servers provide implementation at runtime, so you don't need to package implemented classed and carry on them with your app.
You could see in the logs if implementation is already loaded if you deploy your application that contains classes impl.


text:
Q: How to decide function in which component? (React) I start to learn React. I try to create a little blog. The blog's part of structure likes this.
--blog
  --Artiecle
  --button

Now, I want to post an article. I get textarea's value from article component. But, onClick action is in button component.
I have two thoughts.

*

*put in button component. Because, that is the actual trigger position.

*put in blog component. Because, blog is common parent component.

I find some information about Hook Rule, layers or decomposition and try to read some side project.
Maybe I should not isolate button component. Or it's just personal style,


text:
Q: Enum Pairing and Searching C# Unity I am trying to pair an Enum to another. I have an Enum that has 35 different emote names like "angry","sad","happy"... The enum values are in a dropdown and I can search through them. So I want to create another enum that has values for the first enum like "smile" is ":)", "laugh" is ":D". So when I type ":D" in searchbar I want it to give me the laugh option in dropdown.

A: You could use Enumerable.Zip
Something like
var output
    = names.Zip( // zip names
            emotes, // with the emotes
            (first, second) => new {first, second}) // create a two element object
        .ToDictionary(kv => kv.first, kv=> kv.second ); // turn that into a dictionary key-value pair

This will create a dictionary where you can use the emoji as a key and it'll return your word, or you can swap round the names and emotes for the oposite key-value.


text:
Q: How many boys should be selected? A school has $545$ boys and $455$ girls. $200$ students are selected randomly in proportion to the number of boys and the number of girls for an interview. How many boys should be selected?
A. $91$
B. $109$
C. $140$
D. $100$

A: Hint: Set up a proportion of the number of boys to total number of people and set it equal to the proportion of the boys picked and 200 people picked.
$\frac{545}{1000}=\frac{x}{200}$


text:
Q: Python Jackknife Approach: Apply a function to a dataframe with one row removed each time Trying to create a simple jackknife of some regression coefficients. For simplicity, I am including sample data and code I am using. My issue is that the regression coefficients produced by the jackknife are the same, without any variation. Not sure what I am missing out.
# the libraries
import pandas as pd
import numpy as np
import statsmodels.api as sm

# generate dataset
df = np.random.randint(5, size=(20,4))
df[:10:]

# the regression function
def smREG(data):
    X = df[:, 1:]
    y = df[:, 0]
    mod = sm.OLS(y, sm.add_constant(X)).fit()
    return mod.params
# call reg function
smREG(df)

# the jackknife function
def simple_jackknife(data, fn):
    jack_sample = {}
    jack_reps = {}
    for i in range(len(data)):
        # delete row 'i' from df
        jack_sample[i] = np.delete(arr=data, obj=i, axis=0)
        # run function with row 'i' deleted
        jack_reps[i] = fn(jack_sample[i])
    return jack_reps
# call jackknife function
out = simple_jackknife(data=df, fn=smREG)
out

# just showing the first three of sample output
{0: array([ 2.33483583, -0.06541933, -0.00764364, -0.16846914]),
 1: array([ 2.33483583, -0.06541933, -0.00764364, -0.16846914]),
 2: array([ 2.33483583, -0.06541933, -0.00764364, -0.16846914])}

My issue is that, I am not sure why the regression coefficients are not changing, even if infinitesimally, after a row is deleted.


text:
Q: Show custom post install message I've create a managed package and based on my question here I'm performing a check on whether My Domain feature is enabled or not. Assuming the check is implemented, I now need to let user know that My Domain is not enabled. But if I try to throw exception with custom error message everything user sees is a message about unhandled exception which looks like this The package installation failed. Please provide the following information to the publisher: *here goes my package source org ingo* Error Message: The post install script failed. So my custom error message doesn't even appear. Is there any way I can actually show it on script failure?
UPD: generally I would like to achieve something like this


text:
Q: What parts of a .vs project do I need to check into GitHub for other people to use it? I'm porting my small unix/macOS CLI project to Windows. I have built a simple VS project to host it.
I am not familiar with the project file layout though - what parts of the project do I need to check into GitHub? The .sln of course, and I assume the .vcxproj as well, but anything else?


text:
Q: Angular 2: Have Child Route Component Replace Parent in router-outlet Is there a way to display a child route in the parent route's <router-outlet>?
For example, let's say we have two routes:
/users/12345

/users/12345/orders/12345

I need the second to be a child of the first, but I also need to completely replace the contents of /users/12345 with the contents of /users/12345/orders/12345 opposed to having /users/12345/orders/12345 in the /users/12345 sub router-outlet.
I thought I could do this by just naming the parent level router-outlet and have both routes target it, but from the research I've been doing (and the errors it caused) I get the feeling the names were intended for secondary uses when there already exists a primary router-outlet

A: edit:  I've come up with a new solution revolving around using template directives that allows for setting up routes hierarchically opposed to at the same level.
The sample code/demo can be found here: https://stackblitz.com/edit/angular-routing-page-layout
Updated version (2019):
https://stackblitz.com/edit/angular-routing-page-layout-cnjpz8

A: I had the same issue. This is how I fixed it:
const routes: Routes = [
   {
    path: '',
    children: [
         {
           path: '',
           component: ParentComponent,
         },
         {
           path: 'child',
           component: ChildComponent,
         }
     ]
   }
];

A:  let routes = [
  {
    path: 'users/:id',
    component: UsersComponent
  },
  {
    path: 'users/:id/orders/:id',
    component: OrdersComponent
  }
 ];

A: You can do it by setting your routes like this :
const routes : Routes = [
  {
    path : 'user/:id',
    component : ParentComponent,
    children : [
      { path : '', component : UserComponent },
      { path : 'order/:id', component : OrderComponent }
    ]
  }
]

ParentComponent's template will have only the <router-outlet> to load its children.

A: If you need to hide something (like a datagrid, or instruction panel) based upon a child route being active you can simply use this:
<div *ngIf="outlet.isActivated == false">
   Please select a child route!
</div>

<router-outlet #outlet="outlet"></router-outlet>

It is important to include #outlet="outlet" with the quotes because you're exporting a template variable reference.
There are also events on router-outlet for activation and deactivation.
An alternative is to get the child route when the NavigationEnd event occurs, and then make decisions what to show or hide. For simpler cases the first approach should work fine.
Also not relevant to your question I don't think, but you can completely hide a router-outlet with an *ngIf as you would anything else.


text:
Q: Custom List View with OnClickListener I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;

public class SMSPlanner extends ListActivity      {

    ListView contactsListView;

    private String TAG = "SMSPlanner";    CheckBox check;
    int count;

    List<ContactInfo> list = new ArrayList<ContactInfo>();
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        ph = new String[3];
        phType = new String[3];
        LoadContactListFromPhone();
        ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        setListAdapter(contactadAdapter);
    }
    @Override
    public void onListItemClick(ListView parent, View v, int position, long id)
    {
        TextView tx =(TextView)v.findViewById(R.id.firstname);
        TextView ph =(TextView)v.findViewById(R.id.phone);
        Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();

    }
    final class ContactHolder{
        TextView txtviewfirstname;
        CheckBox chkselected;
        TextView txtviewphone;
    }
    void LoadContactListFromPhone()
    {
        loadlistandreturns();
    }

    void call()
    {
        Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
        toast.show();
    }
}

CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{

    private final Activity context;
    int resourceid;

    List<ContactInfo> list = null;
    public ContactsAdapter(Activity context, List<ContactInfo> list) {
        super(context, R.layout.contactrow, list);
        this.context = context;
        this.list = list;
    }

    @Override
    public View getView(int position, View convertview, ViewGroup viewgroup){
        View view = null;
        if(convertview == null){
            LayoutInflater inflater = context.getLayoutInflater();
            view = inflater.inflate(R.layout.contactrow, null);

            ContactHolder holder = new ContactHolder();

            holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
            holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
            holder.chkselected = (CheckBox)view.findViewById(R.id.check);
            view.setTag(holder);
        }
        else{
            view = convertview;
        }
        ContactHolder holder2 = (ContactHolder) view.getTag();
        holder2.txtviewfirstname.setText(list.get(position).firstname);
        holder2.txtviewphone.setText(list.get(position).phonenumber);
        holder2.chkselected.setChecked(list.get(position).selected);
        return view;
    }

    final class ContactHolder{
        TextView txtviewfirstname;
        CheckBox chkselected;
        TextView txtviewphone;
    }
}

LAYOUT
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="100" >

    <RadioGroup
        android:id="@+id/rgStyle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="15"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/firstname"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/phone"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </RadioGroup>

    <RadioGroup
        android:id="@+id/rgStyle2"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="85"
        android:orientation="vertical" >

        <CheckBox
            android:id="@+id/check"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:checked="false"
            android:focusable="false"
            android:focusableInTouchMode="false" >

        </CheckBox>
    </RadioGroup>
</LinearLayout>

A: 1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/

A: you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/

A:    i think you should make adapter as

 public class ContactsAdapter extends BaseAdapter {

    ArrayList<ContactInfo> mlist;
    Context mcontext;

public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
        mlist =  mchtlist;
        mcontext = context;

    }

    @Override
    public int getCount() {
        return mlist.size();
    }

    @Override
    public Object getItem(int postion) {
        return mlist.get(postion);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
        public View getView(int position, View convertview, ViewGroup viewgroup){
            View view = null;
            if(convertview == null){
                LayoutInflater inflater = context.getLayoutInflater();
                view = inflater.inflate(R.layout.contactrow, null);

                ContactHolder holder = new ContactHolder();

                holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
                holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
                holder.chkselected = (CheckBox)view.findViewById(R.id.check);

                setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View arg0) {
            // to open the selected file in resp

                  // do your work here
                 }});

    chkselected .setOnClickListener(new OnClickListener() {
        @Override
    public void onClick(View v) {
    // Toast.makeText(context,// "checked is clicke="+pos, 12).show();
            if (chkselected.isChecked())
                       {

                        // do your work here
            } else {

     // do your work here
            }
        }
});

            view.setTag(holder);

        }
            else{
                view = convertview;
            }
            ContactHolder holder2 = (ContactHolder) view.getTag();
            holder2.txtviewfirstname.setText(list.get(position).firstname);
            holder2.txtviewphone.setText(list.get(position).phonenumber);
            holder2.chkselected.setChecked(list.get(position).selected);
            return view;
        }

}


text:
Q: Why needs a cross-compiler when install OpenCV in Ubuntu 16.04 ARM I want to install OpenCV on arm board installed ubuntu 16.04 arm OS.
Most of the docs. install OpenCV using a cross-compiler.
I've never used cross-compiler, I have a few question about it

*

*Why do I need use cross-compiler to install OpenCV?

*If I install using a cross-compiler, then always host-computer need when any of source code using OpenCV running?


text:
Q: Error while running app in debug mode and while building release apk in flutter My flutter sdk version is 2.2.1 and dart sdk version is 2.13 . Flutter doctor shows everything is fine. Problem occurred while building release apk for the first time. After that running in debug mode shows error also! here is the pic

A: please change your java SDK 7 to Java 8 to support lambda expressions.