text:
Q: csv to dynamic html refresh I have a backyard koi/goldfish pond I like to monitor.  I have a raspberry pi doing the monitoring and sending to my website.  I am trying to get the csv data to load into my index.html file.  I do not need to keep the data.  I have index 3 created the parses the data and puts in a  table.  I am having a hard time understand how to add a variable to a csv field and put that variable in the html file.
 <!DOCTYPE html>

Pond Temperature & Camera

<meta name="viewport" content="width=device-width, initial-scale=1">

Bio Falls Temperature

 ° F

Stream Temperature

 ° F

Waterfall Temperature

 ° F

Deep End Temperature

 ° F

Skimmer Temperature

 ° F

Outside Air Temperature

 ° F

 ```
 ```
<!DOCTYPE html>

<title>Pond Temperature & Camera</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

 <META HTTP-EQUIV="refresh" CONTENT="15">

Pond Temperature & Camera

 ```
First probe temp is 66.4
Second probe temp is 66.2
Third probe temp is 65.4
Fourth probe temp is 66.5
Fifth probe temp is 65.5
 ```

A: After looking at your code some more, and looking at your post again, the code below is an attempt at helping you get to what you are trying to do, here.
Some of the main changes to note are in the HTML part where you have the "&deg F" parts. In order to let your program know where to put the temperature data in the HTML, I added some id tags with names that match the various temperatures.
Taking the first temperature for example, the changed HTML looks like this:

Bio Falls Temperature

Another major area of change is in the $(document).ready(function(){ ... }); part of your code. I've added comments throughout that section to help explain what is happening there. Basically, the code is looping through your incoming data file based on the assumption that the data looks like your data example (with an extra temperature at the end) like this:
68.9 68.8 68.9 69.3 70.1 80.1

If your data file is actually delimited with commas instead of spaces, just make sure to change this line in the example code below:
let pond_data_parts = pond_data[i].split(' ');

to this:
let pond_data_parts = pond_data[i].split(',');

The new/adjusted code loops through each line of the data file and then loops through each of the temperature data items in a row of data. If you have multiple lines of data in your data file, this code approach loops through each line and I think the last row of data in your data file is what would show up last (and then stay) in your HTML temperature "table".
Finally, another part of the new code to note is the part where the temperature data values are actually placed in the HTML temperature "table". This is especially done with the following lines of code inside of the related loops:
// Find element in HTML where temperature data will be placed
let item = document.querySelector('#' + pond_data_var_names[j]);
// Put temperature data in HTML along with "&deg F" part
item.innerHTML = pond_data_parts[j] + ' &deg F';

The actual id values that are selected with the document.querySelector() are listed earlier in the code:
let pond_data_var_names = [
  'bio_falls_temp',
  'stream_temp',
  'waterfall_temp',
  'deep_end_temp',
  'skimmer_temp',
  'outside_air_temp'
];

These are each looped through and the resulting temperature data is set in the HTML temperature "table" with this line:
item.innerHTML = pond_data_parts[j] + ' ° F';

If the temperatures are not showing up in the right spots in your HTML temperature "table", you might need to rearrange the order of the items in pond_data_var_names area. I just took a simple approach for this code example and assumed that your data values from the data file go left to right, starting at Bio Falls Temperature, then Stream Temperature, then Waterfall Temperature, then Deep End Temperature, then Skimmer Temperature, and then Outside Air Temperature.
In addition to the additions/changes I went over, I also rearranged some of your HTML so that there is a consolidated  section and combined some of the code from both of your example HTML files in your original post for this code. Also formatted the code in general, but you can change that if need be.
Here is what the result of my code attempt looks like based on your code:
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">

Pond Temperature & Camera

Bio Falls Temperature

Stream Temperature

Waterfall Temperature

Deep End Temperature

Skimmer Temperature

Outside Air Temperature

I used a test pond_temp.csv file with the following data that you gave as an example (adding 80.1 at the end to fill the remaining HTML temperature "table" cell):
68.9 68.8 68.9 69.3 70.1 80.1

Here is what the output looks like on my side:

I hope this helps with your project!

Update:
In order to refresh the incoming pond data temperatures, you could potentially use the setInterval() method which should run every "n" milliseconds.
If you would like to refresh the data every 5 seconds, for example, here is what the end part of the earlier code example could look like:
    function getPondDataAndDisplay() {
      $.ajax({
        url: "pond_temp.csv",
        dataType: "text",
        success: function(data) {
          // Split data file line by line
          let pond_data = data.split(/\r?\n|\r/);
          // Remove empty row if found
          if (pond_data[pond_data.length-1] == "") {
            pond_data.pop();
          }
          // Loop through lines from data file
          for (let i = 0; i < pond_data.length; ++i) {
            // Split up line of data using space as delimiter
            let pond_data_parts = pond_data[i].split(' ');

            // Loop through each item from line of data
            for (let j = 0; j < pond_data_parts.length; ++j) {
              // Find element in HTML where temperature data will be placed
              let item = document.querySelector('#' + pond_data_var_names[j]);
              // Put temperature data in HTML along with "° F" part
              item.innerHTML = pond_data_parts[j] + ' ° F';
            }
          }
        }
      });
    }

    // ref: https://developer.mozilla.org/en-US/docs/Web/API
    //   /WindowOrWorkerGlobalScope/setInterval
    let pondDataInterval = window.setInterval(getPondDataAndDisplay, 5000);

I took the ajax part of the earlier code and placed it in its own function called getPondDataAndDisplay(). Then, you can use window.setInterval(getPondDataAndDisplay, 5000); to call the new function and run it every 5 seconds.
Also, I removed the $(document).ready(function(){ ... }); part that had surrounded the ajax part of the code, as well, for this example.
Note: Something to keep in mind with your incoming data file, though, is that it might get to be a large file after a while (with all the pond temperature data collected over time). It might be a good idea to make a copy of the data file on your own (saving it to another location), and then to clear out the incoming data file at some point in order to keep the file data somewhat small.


text:
Q: MKMapView detecting left or right iOS 11.x Swift 4.0
Learning about mapview and created a pin with left and right accessoryviews with this code.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    if annotation is MKUserLocation  {
        return nil
    }

    let reuseId = "pin"
    var pav:MKPinAnnotationView?
    if (pav == nil)
    {
        pav = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pav?.isDraggable = true
        pav?.canShowCallout = true;
        pav?.rightCalloutAccessoryView = UIButton(type: .infoLight)
        pav?.leftCalloutAccessoryView = UIButton(type: .contactAdd)
    }
    else
    {
        pav?.annotation = annotation;
    }

    return pav;
}

Using this call to detect when you press on the infoLight and/or the contactAdd UIButtons. But I struggling to figure out how to tell which one was pressed? This call fires? But how to figure if it was the left or the right?
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    print("go figure annotationView \(view)")
    if (view.rightCalloutAccessoryView != nil) {
        print("right \(view.rightCalloutAccessoryView)")
    }
}

Obviously this is wrong, but how to know if the left or the right was tapped?

A: Try following code:
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if view.rightCalloutAccessoryView == control {
        //right accessory
    } else {
        // left Accessory
    }
}

A: You can cast the control as UIButton and check it's type
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    let btn  = control as! UIButton

    if(btn.buttonType == .infoLight)
    {
        // right Accessory
    }
    else
    {
        // left Accessory
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: pgfgantt high temporal resolution I would like to create a GANTT chart that covers 3 years and (this is the issue) where I can create work packages in daily resolution. Currently, I'm at this point:
\documentclass[%
       a4paper,%
       oneside,
       10pt,
       ]{article}

    \usepackage{lscape}
    \usepackage{xcolor,color,colortbl}

    % Tikz packages
    \usepackage{tikz}
    \usepackage{pgfplots}

    % GANTT plots
    \usepackage{pgfgantt}
    \usepackage{graphicx}
    \ganttset{group/.append style={blue},
    milestone/.append style={red},
    progress label node anchor/.append style={text=red},
    bar/.append style={fill=white!40!black!20,draw=blue}}

    \begin{document}

    \begin{landscape}
    %--------------------------------------------------------------------
    \subsection{GANTT chart}
    \label{cha:manage_planning_barchart}
    % -------------------------------------------------
     \begin{figure}[!htb]
     \centering
     \begin{tikzpicture}[scale=0.6, every node/.style={transform        shape}]
     \begin{ganttchart}[
            vgrid,
            hgrid,
            bar label anchor/.append style={align=left},
            bar/.style={fill=blue,draw=blue},
            bar incomplete/.append style={fill=blue!40!black!20},
            bar progress label font=\mdseries\footnotesize\color{black},
            group label anchor/.append style={align=left, text width=25em},
            y unit chart=0.65cm,
            %x unit=0.5cm,
            milestone label anchor/.append style={align=left, text width=10em},
            Mile1/.style={milestone/.append style={fill=red}},
            time slot format=isodate,
            today=\the\year-\the\month-\the\day,
            today offset = 0.5,
            today label=Today,
            today label node/.append style={anchor=north west},
            today label font=\itshape\color{red},
            today rule/.style={draw=red, thick, dashed}
          ]{2019-02-1}{2019-10-31}
      \gantttitle{My long project}{33}\\
      \gantttitle{2019}{11}
      \gantttitle{2020}{12}
      \gantttitle{2021}{10}\\
      \gantttitlelist{2,...,12}{1}
      \gantttitlelist{1,...,12}{1}
      \gantttitlelist{1,...,10}{1} \ganttnewline
      \ganttmilestone{START!}{2019-02-18} \ganttnewline
      \ganttgroup{First group}                         {2019-2-18}{2019-4-31} \ganttnewline
      \ganttbar[progress=10]{First task in first group}{2019-2-18}{2019-3-31} \ganttnewline
      \ganttbar[progress=0]{Second task in first group}{2019-3-31}{2019-4-31}

      \end{ganttchart}
     \end{tikzpicture}
     \caption{GANTT-Chart}
     \label{fig:GANTT}
     \end{figure}
     \end{landscape}
     \end{document}

This gives:

Can anyone explain to me (1) why it cuts off at the very right and (2) how I get daily resolution over the 3 years?
Thanks much!!


text:
Q: How to empty and print the buffer to browser as it's processing I have a csv file (@fn) with close to 100,000 records (about 50 megs) that I am inserting into a mysql table. For example:
FCSV.foreach(@fn, {:headers => true}) do |row|
    model = Model.new(Hash[row])
    model.save
end

Back in my ASP days, I could output and print the buffer as html to the users screen durring this loop so as to provide a visual feedback as to how far along the process was. In ruby on rails, is there an equivalent of this approach?
If it helps, I'm using Rails 2.3.9 and Ruby 1.8.7.
I realize there are a dozen ways to accomplish the feedback, such as background jobs, etc. But what I am really wondering about is how to dump and print the buffer to the screen (not the console) with each iteration of the loop.

A: This question might be of some help to you. It explains how to stream using the older rails client.
Ruby on Rails 3: Streaming data through Rails to client
Here is the example directly from the post:
render :text => proc { |response, output|
  10_000_000.times do |i|
    output.write("This is line #{i}\n")
  end
}


text:
Q: Plotly R : Format axis tick labels to log10 I am creating line charts in plotly using plotly::ggplotly() with x and y-axis representing log10 values.
Is there a way to display x and y-axis tick labels as log10?
I have tried using tickformat = ".1r" but that doesn't seem to be working.
Thanks.
p <- ggplot(data, aes(x=x, y=y)) +
     scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                   labels = trans_format("log10", math_format(10^.x))) +
     scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                   labels = trans_format("log10", math_format(10^.x)))

p <- plotly::ggplotly(p)

p <- p %>% layout(
           yaxis = list(
                 tickformat=".1r"
                 ),
           xaxis = list(
                 tickformat=".1r"
                )
         )
p

A: When you want to use something like superscripts in ggplot, you use commands like expression. When the data was sent through ggplotly, so was `expression.
If you wanted the axes labeled like the ggplot graph, you can remove the command expression and replace the ^ with  from the ggplotly object. However, for the y axes, the values aren't rounded, so I've shown you the literal result, the object valy. Then I rounded them in valy2. That way, whatever you were looking for might already be here.
I used p1, not p for the Plotly object.
Later in this answer, I'm going to show you what .1r will give you, which is unlikely what you were looking for.
library(tidyverse)
library(plotly)
library(scales)

set.seed(23)
df1 <- data.frame(x = rnorm(100, 1000000, 39999),
                  y = rnorm(100, 99999999999, 111111))
p <- ggplot(df1, aes(x = x, y = y)) +
    geom_point() +
    scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                  labels = trans_format("log10", math_format(10^.x))) +
    scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                  labels = trans_format("log10", math_format(10^.x)))
p1 <- plotly::ggplotly(p)

valx <- p1$x$layout$xaxis$ticktext %>%
  toString() %>% str_split(", ") %>%  # <---- that's a comma and whitespace
  unlist() %>% str_replace("\\^(.*)$", "\\1")
valy <- p1$x$layout$yaxis$ticktext %>%
  toString() %>% str_split(", ") %>%  # <---- that's a comma and whitespace
  unlist() %>% str_replace("\\^(.*)$", "\\1")
valy
# [1] "1010.999999"  "1010.9999995" "1011"
# [4] "1011.0000005" "1011.000001"
valy2 <- p1$x$layout$yaxis$ticktext %>%
  toString() %>% str_split(", ") %>%  # <---- that's a comma and whitespace
  unlist() %>% str_replace("\\^(.*)", "\\1") %>%
  str_replace("(\\...).*()", "\\1\\2") # wow, just didn't want to do it in one...
# [1] "1010.99" "1010.99" "1011"    "1011.00"
# [5] "1011.00"

p1$x$layout$xaxis$ticktext <- valx
p1$x$layout$yaxis$ticktext <- valy2
p1

Now to show you other ways that would work for formatting text if you started in Plotly.
e on the x-axis and r on the y-axis
plot_ly(df1, x = ~x, y = ~y, type = "scatter", mode = "markers") %>%
  layout(xaxis = list(type = "log", tickformat = ".1e"),
         yaxis = list(type = "log", tickformat = ".1r"))

~s on the x-axis and y on the y-axis
plot_ly(df1, x = ~x, y = ~y, type = "scatter", mode = "markers") %>%
  layout(xaxis = list(type = "log", tickformat = "~s"),
         yaxis = list(type = "log", tickformat = ".1y"))


text:
Q: Autolayout constraints for UIImageView with margins I'm attempting to create a custom TableView cell that contains a UIImageView with margins. No matter what I try, the top and bottom margins collapse. I've read through various threads here and around the web, and I'm at a loss for what I'm doing wrong. At this point, I have to assume there is a fundamental flaw in how I'm thinking about this problem. Can anyone here help me?
Here is my current setup:

And here is part of the output in the simulator:

A: Thank you for your help. This turned out to be simple user error, though it would have been nice to get a warning from the compiler ;)
In my ViewController, I wasn't setting my Custom Cell's profileImage.image property—I was instead setting the image on some default imageView property, which I wasn't even aware existed.
The default imageView of course did not make use of the constraints. Now I need to do some research on that default imageView... doh!


text:
Q: "Missing source managed object model" error when making changes to data model I'm trying to add a new attribute to my entities but when I do it, the app crashes at launch on my phone, and it throws the following error:
Persistent store migration failed, missing source managed object model
When I remove the new attribute from every entity, the app launches normally.
I have no idea what may be causing this.


text:
Q: Почему выводит не все флаги Есть готовые enum-ы
[Flags]
public enum UserFlags {
    guest = 0, // GUEST USER             //
        normal = 1, // NORMAL USER (DEFAULT)  //
        banned = 2, // USER IS BLOCKED        //
        online = 4 // USER IS ONLINE         //
}

Вот так устанавливаю флаги:
user.Flags = UserData.UserFlags.normal;
user.SetFlag(UserData.UserFlags.guest);
user.SetFlag(UserData.UserFlags.online);

public UserFlags Flags {
    get;
    internal set;
}

public void SetFlag(UserFlags flag, bool state = true) {
    Flags = state ? Flags |= flag : Flags &= ~flag;
}

Но если я пробую вывести Flags как тест в консоль от возвращает только Online и Normal а вот guest не учитывается.Почему?

A: Проблема в том, что флагом guest вы пытаетесь оперировать с несуществующим 0-вым битом.
Решение достаточно простое - начинать с 1-го бита:
[Flags]
public enum UserFlags {
    guest = 1, // GUEST USER             //
    normal = 2, // NORMAL USER (DEFAULT)  //
    banned = 4, // USER IS BLOCKED        //
    online = 8 // USER IS ONLINE         //
}

другой вариант - использовать битовый сдвиг, чтобы не путаться в значениях когда флагов достаточно много и они становятся достаточно крупными числами:
[Flags]
public enum UserFlags {
    guest = 1 << 0, // GUEST USER             //
    normal = 1 << 1, // NORMAL USER (DEFAULT)  //
    banned = 1 << 2, // USER IS BLOCKED        //
    online = 1 << 3 // USER IS ONLINE         //
}

A: ToString() не обрабатывает enum со значением 0 и не выводит в консоль


text:
Q: Как получить все записи из таблицы, если есть массив id У меня есть массив строк где хранятся id продуктов. Как я смогу сделать один запрос в таблицу products, чтобы получить все строки с данным id?

A: Для таких целей используется предикат IN.
Пример:
SELECT * FROM [dbo].[MyTable] mt WHERE mt.Id IN ('1','2','5')


text:
Q: Kubernetes: weave picked the public IP on one of the worker nodes I have a 2 master and 2 worker kubernetes cluster. Each node has private IP in the range 192.168.5.X and public IP.
After creating the weave daemonset, the weave pod picked the correct internal IP on one node but on the other node it picked the public IP. Is there any way we can instruct weave pod to pick the private IP on the node?
Im creating the cluster from scratch by doing everything manually on the VMs created on Virtual Box on local laptop. I refer the below link
https://github.com/mmumshad/kubernetes-the-hard-way
After deploying weave pods on worker node, weave pod on one of the worker nodes uses the NAT ip as below.
10.0.2.15 is the NAT IP and 192.168.5.12 is internal IP
kubectl get pods -n kube-system -o wide
NAME              READY   STATUS    RESTARTS   AGE   IP             NODE      NOMINATED NODE   READINESS GATES
weave-net-p4czj   2/2     Running   2          26h   192.168.5.12   worker1   <none>           <none>
weave-net-pbb86   2/2     Running   8          25h   10.0.2.15      worker2   <none>           <none>

[@master1 ~]$ kubectl describe node
Name:               worker1
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=worker1
Annotations:        node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Tue, 10 Dec 2019 02:07:09 -0500
Taints:             <none>
Unschedulable:      false
Conditions:
  Type                 Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----                 ------  -----------------                 ------------------                ------                       -------
  NetworkUnavailable   False   Wed, 11 Dec 2019 04:50:15 -0500   Wed, 11 Dec 2019 04:50:15 -0500   WeaveIsUp                    Weave pod has set this
  MemoryPressure       False   Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 02:09:09 -0500   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure         False   Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 02:09:09 -0500   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure          False   Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 02:09:09 -0500   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready                True    Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 04:16:26 -0500   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  192.168.5.12
  Hostname:    worker1
Capacity:
 cpu:                1
 ephemeral-storage:  14078Mi
 hugepages-2Mi:      0
 memory:             499552Ki
 pods:               110
Allocatable:
 cpu:                1
 ephemeral-storage:  13285667614
 hugepages-2Mi:      0
 memory:             397152Ki
 pods:               110
System Info:
 Machine ID:                 455146bc2c2f478a859bf39ac2641d79
 System UUID:                D4C6F432-3C7F-4D27-A21B-D78A0D732FB6
 Boot ID:                    25160713-e53e-4a9f-b1f5-eec018996161
 Kernel Version:             4.4.206-1.el7.elrepo.x86_64
 OS Image:                   CentOS Linux 7 (Core)
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://18.6.3
 Kubelet Version:            v1.13.0
 Kube-Proxy Version:         v1.13.0
Non-terminated Pods:         (2 in total)
  Namespace                  Name                   CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                  ----                   ------------  ----------  ---------------  -------------  ---
  default                    ng1-6677cd8f9-hws8n    0 (0%)        0 (0%)      0 (0%)           0 (0%)         26h
  kube-system                weave-net-p4czj        20m (2%)      0 (0%)      0 (0%)           0 (0%)         26h
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests  Limits
  --------           --------  ------
  cpu                20m (2%)  0 (0%)
  memory             0 (0%)    0 (0%)
  ephemeral-storage  0 (0%)    0 (0%)
Events:              <none>

Name:               worker2
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/hostname=worker2
Annotations:        node.alpha.kubernetes.io/ttl: 0
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Tue, 10 Dec 2019 03:14:01 -0500
Taints:             <none>
Unschedulable:      false
Conditions:
  Type                 Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----                 ------  -----------------                 ------------------                ------                       -------
  NetworkUnavailable   False   Wed, 11 Dec 2019 04:50:32 -0500   Wed, 11 Dec 2019 04:50:32 -0500   WeaveIsUp                    Weave pod has set this
  MemoryPressure       False   Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 03:14:03 -0500   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure         False   Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 03:14:03 -0500   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure          False   Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 03:14:03 -0500   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready                True    Wed, 11 Dec 2019 07:13:43 -0500   Tue, 10 Dec 2019 03:56:47 -0500   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  10.0.2.15
  Hostname:    worker2
Capacity:
 cpu:                1
 ephemeral-storage:  14078Mi
 hugepages-2Mi:      0
 memory:             499552Ki
 pods:               110
Allocatable:
 cpu:                1
 ephemeral-storage:  13285667614
 hugepages-2Mi:      0
 memory:             397152Ki
 pods:               110
System Info:
 Machine ID:                 455146bc2c2f478a859bf39ac2641d79
 System UUID:                68F543D7-EDBF-4AF6-8354-A99D96D994EF
 Boot ID:                    5775abf1-97dc-411f-a5a0-67f51cc8daf3
 Kernel Version:             4.4.206-1.el7.elrepo.x86_64
 OS Image:                   CentOS Linux 7 (Core)
 Operating System:           linux
 Architecture:               amd64
 Container Runtime Version:  docker://18.6.3
 Kubelet Version:            v1.13.0
 Kube-Proxy Version:         v1.13.0
Non-terminated Pods:         (2 in total)
  Namespace                  Name                    CPU Requests  CPU Limits  Memory Requests  Memory Limits  AGE
  ---------                  ----                    ------------  ----------  ---------------  -------------  ---
  default                    ng2-569d45c6b5-ppkwg    0 (0%)        0 (0%)      0 (0%)           0 (0%)         26h
  kube-system                weave-net-pbb86         20m (2%)      0 (0%)      0 (0%)           0 (0%)         26h
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests  Limits
  --------           --------  ------
  cpu                20m (2%)  0 (0%)
  memory             0 (0%)    0 (0%)
  ephemeral-storage  0 (0%)    0 (0%)
Events:              <none>

A: I can see that you have different IPs not only in your pods, but also in your nodes.
As you can see in the kubectl describe node output InternalIP for worker1 is 192.168.5.12 and for worker2 is 10.0.2.15.
This is not expected behavior, so it's important to make sure you have attached both of your VirtualBox VMs to the same adapter type.
Both should be in the same network and in the comments you confirmed that this was the case and that explains this behavior.
Here is an example of that configuration:

As you mentioned on comments, the first node was added manually and the second was added during the TLS bootstraping and it got added even with "wrong" IP Address.
To solve this issue the best thing you can do is to bootstrap you cluster from scratch again using the same Adapter Settings on Virtual Box for all nodes.


text:
Q: Does default directory structure for .net Blazor have to stay? I am very new to working with C# and the blazor. (I do have experience working with Svelte, react and other frameworks. But none with C#.
I was curious if/how I can create my own folder structure from the templated structure it gives when you run dotnet new blazorwasm.
.vscode/
bin/
obj/
Pages/
Properties/
Shared/
wwwroot/
_Imports.razor
Program.cs
Program.csproj
Project.sln

Following the tutorials microsoft has, they just put scripts into the root folder, which I do not like.
Any advice would be appreciated thanks!
EDIT:
@andrew wynn
Okay I understand. But outside of the wwwroot folder, can I take and move folders into other folders like Pages or Shared which contain razor component files? Something like this? Because from what I can tell I don't see anything linking them directly. It looks like everything is linked via namespaces if I am understanding it correctly.
.vscode/
bin/
obj/
Pages/
Properties/
Shared/
wwwroot/
_Imports.razor
Program.cs
Program.csproj
Project.sln

A: wwwroot is the root directory for the site, so it's where all of the source files go. They can go into subdirectories in there as long as they are referetially linked.
You can make some middleware to use a different folder if you wish though, see [this link][1]
Edit:
So each of the folders in a Blazor project is for a specific set of files. Pages is there for the .blazor and .cshtml files, these don't exist on the public facing site as they are dynamically translated into html when requested.
I'm not entirely sure what it is you would like to acheive. The folder structure is hard coded into the server host application. The static components (javascript, css, html, images etc) all go into wwwroot as they can be accessed directly by clients, the content to dynamically generate by ASP.NET or Blazor is in Pages, your classes and such go in Data... Do you just want to rename these folders?
.
[1]: JS File outside www root folder

A: I have figured it out. Yes you can structure it how ever you want. You just to make sure you update the _imports.razor file to reference the new location.
So if I move everything into a Source folder I would need to update.
@using MyProject.Shared

//TO
@using MyProject.Source.Shared

And then make sure to add any new files that need referenced.


text:
Q: Advanced criteria find blanks / non-blanks I have successfully used the following to filters for    ="=" (Blanks only) and ``="<>" (Non-blanks only)
However it isn't working with a large range for some reason. If I look for a value, ie ="*CC"then the filter is applied as expected.
Any ideas as to why my Blank and Non-Blank filters might be failing?
Cheers
** LATEST UPDATE **
Am pretty sure the underlying issue is that the value of the column I want to filter is the result of a formula! Anyone know how to handle that?
** UPDATE **
This is a partial view of the data I want to filter (it's a ListObject)

Here is the criteria range. It's located on a separate worksheet (which shouldn't matter, and again, is working fine searching for a given value (ie "LNG")

And finally, this is a picture of the desired result of filtering out blanks:

I can easily get this with AutoFilter of course, but this is a large table and I am using VBA to switch between different analytical views. The AdvancedFilter is more appropriate in this context.
** UPDATE **
I have the same issue whether I apply the filter manually or via code, which further leads me to believe there is something flaky about the filter itself. The code has been successfully tested, and so in fact has the filter on a simple table.
I tried changing the type of the 'Position' column cells (currently it's Text). Just a head scratcher at the moment

A: PROBLEM:
The value in the column I want to filter on is the result of a formula which either gives a value or an empty string "".
Using ="<>" is the right way to get Non-Blank but Excel is not considering the empty string to be Blank!
A SOLUTION:
For lack of knowing a criteria friendly way of saying something like ="vbNullString", I just added another column which evaluates the "Y" if the column I really want is not blank. After hiding the column, I can Filter on that and get the results I need.
Please post if you know a way to get Excel to recognize the empty string tho!


text:
Q: Argument 1 passed to ...LeadRep::create() must be an instance of ...Entities\Lead, array given, called in .....LeadController.php on line 108 I have tried to insert lead_name,lead_status,lead_description value in db in laravel 6.18.41 version.
Controller code(LeadController.php):
<?php
namespace App\Http\Controllers;

use App\Repository\LeadRep as LeadRepo;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController as BaseController;
use Illuminate\Support\Facades\Log;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;

class LeadController extends BaseController
{
    private $leadRepo;

    public function __construct(LeadRepo $leadRepo)
    {
        $this->leadRepo = $leadRepo;
    }
    /**
    * @param OptionsResolver $resolver
    */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'App\Entities\Lead'
        ));
    }
    /**
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        //$started = microtime(true);
        $count = $this->leadRepo->count();
        //$end = microtime(true);
        //$queryTime = $end - $started;
        $lead = $this->leadRepo->findAll();

        if (is_null($lead)) {

            return $this->sendError('Lead not found.');

        }
        $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
        JsonEncoder()));
        $json = $serializer->serialize($lead, 'json');

        return $this->sendResponse($json, 'Leads retrieved successfully.');
        //return $this->sendResponse($count . "<-count ... querytime -> " . $queryTime . " ms", 'Leads retrieved successfully.');

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */

    public function store(Request $request)

    {
        $input = $request->all();

        // $validatedData = $request -> validate([

        //     'lead_name' => 'required',

        //     'lead_status' => 'required',

        //     'lead_description' => 'required'

        // ]);

        /*$validator = Validator::make($input, [

            'lead_name' => 'required',

            'lead_status' => 'required',

            'lead_description' => 'required'

        ]);*/

        /*if ($validator->fails()) {

            return $this->sendError('Validation Error.', $validator->errors());

        }*/

        //$input = $request->all();
        Log::info($input);

        //$lead = Lead::create($input);
        $lead = $this->leadRepo->create($input);

        return $this->sendResponse($lead, 'Lead created successfully.');

    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */

    public function show($id)

    {

        $lead = $this->leadRepo->findById($id);

        Log::info(print_r($lead,true));

        if (is_null($lead)) {

            return $this->sendError('Lead not found.');

        }

        $serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new
        JsonEncoder()));
        $json = $serializer->serialize($lead, 'json');

        return $this->sendResponse($json,
            'Lead retrieved successfully.');

    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param Lead $lead
     * @return \Illuminate\Http\Response
     */

    public function update(Request $request, Lead $lead)

    {

        $input = $request->all();

        $validator = Validator::make($input, [
            'id' => 'required',

            'lead_name' => 'required',

            'lead_status' => 'required',

            'lead_description' => 'required'

        ]);

        if ($validator->fails()) {

            return $this->sendError('Validation Error.', $validator->errors());

        }

        $lead = $this->leadRepo->findById($input['id']);

        if (is_null($lead)) {

            return $this->sendError('Lead cannot be updated. Lead Id not found.');

        }

        $lead->lead_name = $input['lead_name'];

        $lead->lead_status = $input['lead_status'];

        $lead->lead_description = $input['lead_description'];

        $lead = $this->leadRepo->create($lead);

        return $this->sendResponse([], 'Lead updated successfully.');

    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return \Illuminate\Http\Response
     */

    public function destroy(Lead $lead)

    {

        //$lead->delete();
        return $this->sendResponse([], 'Lead deleted successfully.');

    }

}

Lead Entity(Lead.php):
<?php

namespace App\Entities;
use Doctrine\ORM\Mapping as ORM;
use JsonSerializable;

/**
 * @ORM\Entity @ORM\Table(name="lead")
 */
class Lead
{
    /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue */
    protected $id;
    /** @ORM\Column(type="string") */
    protected $lead_name;

    /** @ORM\Column(type="string") */
    protected $lead_status;

    /** @ORM\Column(type="string") */
    protected $lead_description;

    public function getId()
    {
        return $this->id;
    }

    public function getLeadName()
    {
        return $this->lead_name;
    }

    public function setLeadName($lead_name)
    {
        $this->lead_name = $lead_name;
    }
    public function getLeadStatus()
    {
        return $this->lead_status;
    }

    public function setLeadStatus($lead_status)
    {
        $this->lead_status = $lead_status;
    }
    public function getLeadDescription()
    {
        return $this->lead_description;
    }

    public function setLeadDescription($lead_description)
    {
        $this->lead_description = $lead_description;
    }
}

Lead Repository(LeadRep.php):
<?php
namespace App\Repository;

use App\Entities\Lead;
use App\Entities\Post;
use Doctrine\ORM\EntityManager;
use Illuminate\Support\Facades\Log;
use Doctrine\Persistence\ManagerRegistry;

/**
 * Class LeadRep
 * @package App\Repository
 */
class LeadRep {
    /**
     * @var string
     */
    private $class = 'App\Entities\Lead';

    /**
     * @var EntityManager
     */
    private $em;

    /**
     * LeadRep constructor.
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @param Lead $lead
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function create(Lead $lead)
    {
        $this->em->persist($lead);
        $this->em->flush();
    }

    /**
     * @param Lead $lead
     * @param $data
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function update(Lead $lead, $data)
    {
        $lead->setLeadDescription($data['lead_description']);
        $lead->setLeadName($data['lead_name']);
        $lead->getLeadStatus($data['lead_status']);
        $this->em->persist($lead);
        $this->em->flush();
    }

    /**
     * @param $id
     * @return object|null
     */
    public function findById($id)
    {
        Log::info("Id info".$id);
        return $this->em->getRepository($this->class)->findOneBy([
            'id' => $id
        ]);
    }

    public function findAll()
    {
        return $this->em->getRepository($this->class)->findAll();
    }

    public function count()
    {
        $criteria = [];
        return $this->em->getRepository($this->class)->count($criteria);
    }

    /**
     * @param Lead $lead
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(Lead $lead)
    {
        $this->em->remove($lead);
        $this->em->flush();
    }

    /**
     * @param $data
     * @return Lead
     */
    public function prepareData($data)
    {
        return new Lead($data);
    }
}

Web Route:
 use App\Http\Controllers\Lead;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('lead/{key}','LeadController@show');

Route::get('lead_all','LeadController@index');

/*Route::get('create_lead/{lead_name}/{lead_status?}/{lead_description?}',function () {
    return view('leadview');
});*/

Route::post('lead_create','LeadController@store');

Route::get('create_lead',function () {
    return view('leadview');
});

Route::get('student/{key}','StudentController@show');

Route::get('student_all','StudentController@index');

Blade View file(leadview.blade.php):
<form method="POST" action="http://127.0.0.1:8000/lead_create" accept-charset="UTF-8">
@csrf

            Your lead_name
                    <input class="form-control" placeholder="" name="lead_name" type="text" id="name">

            Your lead_status
                    <input class="form-control" placeholder="" name="lead_status" type="text" id="email">

            Your lead_description
                    <textarea class="form-control" placeholder="" name="lead_description" cols="50" rows="10" id="message"></textarea>

   <input class="btn btn-default" type="submit" value="Send">

                </form>

I have used doctine with laravel in this project.When submit the form to insert lead value from from,it returning below error,
Argument 1 passed to App\Repository\LeadRep::create() must be an instance of App\Entities\Lead, array given, called in D:\wamp64\www\projects\laraveldemo\crmapp-crud\app\Http\Controllers\LeadController.php on line 108
How can i solve this issue? Can anyone provide solution for this?

A: The problem is you pass the array of inputs instead of model.
You have function prepareData inside the repo, so you can use it to prepare the model.
$lead = $this->leadRepo->prepareData($input);
$this->leadRepo->create($lead);

UPD
  /**
   * Class LeadRep
   * @package App\Repository
   */
   class LeadRep
   {
      /**
       * @param $data
       * @return Lead
       */
       public function prepareData(array $data): Lead
       {
          $lead = new Lead();
          $lead->setLeadName($data['lead_name']);
          $lead->setLeadStatus($data['lead_status']);
          $lead->setLeadDescription($data['lead_description']);

          return new $lead;
       }
   }

A: $lead = $this->leadRepo->create(new LeadRep($lead));

You must pass an instance of a model you are creating.

A: I changed controller function like below, then added this line in top of controller file - use App\Entities\Lead; ,then it worked.
public function store(Request $storeRequest)
{
    $storeRequest->validate([
        'lead_name' => 'required',
        'lead_status' => 'required',
        'lead_description' => 'required'
    ]);

    $lead = new Lead();
    $lead->setLeadName($storeRequest->get('lead_name'));
    $lead->setLeadStatus($storeRequest->get('lead_status'));
    $lead->setLeadDescription($storeRequest->get('lead_description'));

    $this->leadRepo->create($lead);

    return $this->sendResponse($lead, 'Lead created successfully.');
}


text:
Q: Using sqlldr in python subprocess.call() fails, but no information I'm in need of some assistance. I'm attempting to perform SQLLDR from within python. The best method I found was to use subprocess.call.  Using the params for another function, I duplicated it within this code.
When I run it, I get the appropriate fields, as expected.
But, the process returns a 1, which is a failure.
I have no additional information and can't locate what could be the problem.
I have verified the data.csv loads into my table from BASH, however python doesn't.
def load_raw():
    DATA_FILE='data.csv'
    CONTROL_FILE='raw_table.ctl'
    LOG_FILE='logfile.log'
    BAD_FILE='badfile.log'
    DISCARD_FILE='discard.log'
    connect_string = os.environ['CONNECT_STRING']

    sqlldr_parms='rows=1000 readsize=50000 direct=true columnarrayrows=100 bindsize=500000 streamsize=500000 silent=(HEADER,FEEDBACK)'

    parms = {}
    parms['userid'] = connect_string
    parms['sqlldr'] = sqlldr_parms
    parms['data'] = DATA_FILE
    parms['control'] = CONTROL_FILE
    parms['log'] = LOG_FILE
    parms['bad'] = BAD_FILE
    parms['discard'] = DISCARD_FILE

    cmd = "userid=%(userid)s %(sqlldr)s data=%(data)s control=%(control)s log=%(log)s bad=%(bad)s discard=%(discard)s" % parms

    print "cmd is: %s" % cmd

    with open('/opt/app/workload/bfapi/bin/stdout.txt', 'wb') as out:
      process = call(cmd, shell=True, stdout=out, stderr=out)

    print process

cmd is: sqlldr userid=usr/pass rows=1000 readsize=50000 direct=true columnarrayrows=100 bindsize=500000
    streamsize=500000 silent=(HEADER,FEEDBACK) data=data.csv control=raw_table.ctl
    log=logfile.log bad=badfile.log discard=discard.log
process returns 1
The log files for log, bad and discard are not created
stdout.txt contains
    /bin/sh: -c: line 0: syntax error near unexpected token ('
    /bin/sh: -c: line 0:sqlldr userid=usr/pass rows=1000 readsize=50000 direct=true columnarrayrows=100
       bindsize=500000 streamsize=500000 silent=(HEADER,FEEDBACK) data=data.csv control=raw_table.ctl
       log=logfile.log bad=badfile.log discard=discard.log'
data.csv contains
id~name~createdby~createddate~modifiedby~modifieddate
6~mark~margaret~"19-OCT-16 01.03.23.966000 PM"~kyle~"21-OCT-16 03.11.22.256000 PM"
8~jill~margaret~"27-AUG-16 12.10.12.214000 PM"~kyle~"21-OCT-16 04.16.01.171000 PM"

raw_table.ctl
OPTIONS ( SKIP=1)
LOAD DATA
CHARACTERSET UTF8
INTO TABLE RAW_TABLE
FIELDS TERMINATED BY '~' OPTIONALLY ENCLOSED BY '"' TRAILING NULLCOLS
(ID,
NAME,
CREATED_BY,
CREATED_DATETIME TIMESTAMP,
MODIFIED_BY,
MODIFIED_DATETIME TIMESTAMP)

A: The error was caused by the silent param. Wrapping it in single quotes allowed the code to work, as here:  silent='(HEADER,FEEDBACK)'


text:
Q: Displaying Stats with arrays in Java I am trying to display statistics from a simple text file using arrays in Java. I know what I am supposed to do, but I don't really how how to code it. So can anybody show me a sample code on how to do it.
So let's say the text file is called gameranking.txt, that contains the following information (This is a simple txt file to use as an example):
Game Event, 1st place, second place, third place, fourth place
World of Warcraft, John, Michael, Bill, Chris
Call of Duty, Michael, Chris, John, Bill
League of Legends, John, Chris, Bill, Michael.

My goal is to display stats such as how many first places, second places.. each individual won in a table like the following
Placement     First place, second, third, fourth
John            2            0       1      0
Chris           0            2       0      1
etc...

My thought:
First, I would read the gameranking.txt and stores it to "input". Then I can use the while loop to read each line and store each line into a string called "line", afterward, I would use the array method "split" to pull out each string and store them into individual array. Afterward, I would count which placement each individual won and display them into a neat table using printf.
My first problem is I don't know how to create the arrays for this data. Do I first need to read through the file and see how many strings are in each row and column, then create the array table accordingly? Or can I store each string in an array as I read them?
The pseudocode that I have right now is the following.

*

*Count how many rows are there and store it in row

*Count how many column are there and store it in column

*Create an array

*String [] [] gameranking = new String [row] [column]

*Next read the text file and store the info into the arrays

using:
while (input.hasNextLine) {
    String line = input.nextLine();
    while (line.hasNext()) {
        Use line.split to pull out each string
        first string = event and store it into the array
        second string = first place
        third string =......

*

*Somewhere in the code, I need to count the placement....

Can somebody please show me how I should go about doing this?

A: I am not going to write the full program, but I will try to tackle each question and give you a simple suggestion:
Reading the initial file, you can get each line and store it in a string using a BufferedReader (or if you like, use a LineNumberReader)
BufferedReader br = new BufferedReader(new FileReader(file));
String strLine;
while ((strLine = br.readLine()) != null)   {
......Do stuff....
}

At that point, in the while loop you will go through the string (since it comma delimited, you can use that to seperate each section).  for each substring you can
a) compare it with first, second, third, fourth to get placement.
b) if its not any of those, then it could either be a game name or a user name
You can figure that out by position or nth substring (ie if this is the 5th substring, its likely to be the first game name.  since you have 4 players, the next game name will be the 10th substring, etc.).  Do note, I ignored "Game event" as that's not part of the pattern.  You can use split to do this or a number of other options, rather than try to explain that I will give you a link to a tutorial I found:
http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html
As for tabulating results, Basically you can get an int array for each player which keeps track of their 1st, 2nd, 3rd,  awards etc.
int[] Bob = new int[4]; //where 0 denotes # of 1st awards, etc.
int[] Jane = new int[4]; //where 0 denotes # of 1st awards, etc.

Showing the table is a matter of organizing the data and using a JTable in a GUI:
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
Alrighty...Here is what I wrote up, I am sure there is a cleaner and faster way, but this should give you an idea:
String[] Contestants = {"Bob","Bill","Chris","John","Michael"};

int[][] contPlace=new int[Contestants.length][4];
String file = "test.txt";

public FileParsing() throws Exception {
    Arrays.fill(contPlace[0], 0);
    Arrays.fill(contPlace[1], 0);
    Arrays.fill(contPlace[2], 0);
    Arrays.fill(contPlace[3], 0);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String strLine;
    while((strLine=br.readLine())!=null){
        String[] line = strLine.split(",");
        System.out.println(line[0]+"/"+line[1]+"/"+line[2]+"/"+line[3]+"/"+line[4]);
        if(line[0].equals("Game Event")){
            //line[1]==1st place;
            //line[2]==2nd place;
            //line[3]==3rd place;
        }else{//we know we are on a game line, so we can just pick the names
            for(int i=0;i<line.length;i++){
                for(int j=0;j<Contestants.length;j++){
                    if(line[i].trim().equals(Contestants[j])){
                        System.out.println("j="+j+"i="+i+Contestants[j]);
                        contPlace[j][i-1]++; //i-1 because 1st substring is the game name
                    }

                }
            }
        }
    }
    //Now how to get contestants out of the 2d array
    System.out.println("Placement  First Second Third Fourth");
    System.out.println(Contestants[0]+" "+contPlace[0][0]+" "+contPlace[0][1]+" "+contPlace[0][2]+" "+contPlace[0][3]);
    System.out.println(Contestants[1]+" "+contPlace[1][0]+" "+contPlace[1][1]+" "+contPlace[1][2]+" "+contPlace[1][3]);
    System.out.println(Contestants[2]+" "+contPlace[2][0]+" "+contPlace[2][1]+" "+contPlace[2][2]+" "+contPlace[2][3]);
    System.out.println(Contestants[3]+" "+contPlace[3][0]+" "+contPlace[3][1]+" "+contPlace[3][2]+" "+contPlace[3][3]);
    System.out.println(Contestants[4]+" "+contPlace[4][0]+" "+contPlace[4][1]+" "+contPlace[4][2]+" "+contPlace[4][3]);

}

If you need to populate the contestants array or keep track of the games, you will have to insert appropriate code.  Also note, using this 2-d array method is probably not best if you want to do anything other than display them.  You should be able to take my code, add a main, and see it run.

A: Since it's a text file, use Scanner class.
It can be customized so that you can read the contents line-by-line, word-by-word, or customized delimiter.
The readfromfile method reads a plain text file one line at a time.
 public static void readfromfile(String fileName) {
  try {
   Scanner scanner = new Scanner(new File(fileName));
   scanner.useDelimiter(",");
   System.out.println(scanner.next()); //instead of printing, take each word and store them in string array
   scanner.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

This will get you started.


text:
Q: Grid View lags when scrolling I have a grid view with 32 elements or images. The images are quite low quality and are not more than 300kb. Everytime I scroll, the grid view lags, and it lags quite noticeably. I would like to get ideas or actual code about what next to do.
I've tried making pictures even lower quality but it did not help. Only if I use one image for all 32 elements in grid view everything forks fine, but as soon as I have more difrent images it lags.
my class:
private GridView gridView;
    ArrayList<CreateProduct> products;

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

        products = new ArrayList<CreateProduct>();
        createAllProducts2();

        gridView = (GridView) findViewById(R.id.allProductGrid);
        GridAdapter customAdapter = new GridAdapter(this, products);
        gridView.setAdapter(customAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                CreateProduct x = products.get(i);
                goToProductDetails(x.productName, x.id, x.productDesc,x.productKulise, x.image);
            }
        });

    }

my adapter:
public class GridAdapter extends BaseAdapter {

    ArrayList<CreateProduct> arrayGrid;
    Context context;

    public GridAdapter(Context context, ArrayList<CreateProduct> arrayList){
        this.arrayGrid = arrayList;
        this.context = context;
    }
    @Override
    public int getCount() {
        return arrayGrid.size();
    }
    @Override
    public long getItemId(int i) {
        return 0;
    }
    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        final CreateProduct product = arrayGrid.get(i);
        if (view == null){
            final LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.grid_row, null);
        }
        final TextView title33 = view.findViewById(R.id.titleGrid);
        final ImageView image33 = view.findViewById(R.id.grid_image);

        title33.setText(product.productName);
        image33.setImageResource(product.image);

        return view;
    }
}

ma grid_row xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/grid_image"
        android:layout_gravity="center"
        android:layout_width="130sp"
        android:layout_height="130sp"
        android:contentDescription="@string/comment_button_product_details"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/titleGrid"
        android:layout_width="130sp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/product_name"
        android:textAlignment="center" />
</LinearLayout>

I dont get any error messages. I would like the grid view to not lag.

A: If you want to solve lagging, you should use ViewHolder pattern in your gridView adapter. I tried to google a bit and I found this sample, which can help you: https://github.com/first087/Android-ViewHolder-Example/blob/master/app/src/main/java/com/artitk/android_viewholder_example/GridViewActivity.java
Especially check how to make ViewHolder and setTag to view container, so adapter can recycle items properly without any performance appliances.
For next step I suggest that you get rid of GridView and use instead RecyclerView, because it's much more powerful and performant.
For loading images use Glide or any other similar libraries for loading images efficiently.


text:
Q: php session on refresh page or on button submit My site url like this: http://localhost/record/index.php
when I add,update,delete record from table then my url like this: http://localhost/record/index.php?delmsg=Users%20has%20been%20deleted
how Can I remove this php variable on refresh page or button submit using session

A: You are right trying to remove this message handling from the GET variables, using sessions is a lot better and let GET control the logic is not safe as some users pointed.
Use session_start(); in the beginning of every PHP file where you want to handle the session values.
To set a value that you want to read later:
if (isset($_GET['del'])) {
    $del_id = intval($_GET['del']); // intval will improve security
    if (mysqli_query($sql,"Delete from user where id = ".$del_id.";")) {
        $_SESSION["delmsg"] = "User ID = " . $del_id . " has been deleted";
        header('Location: index.php');
    }
}

To read the value in a further request and show contents accordingly:
if (isset($_SESSION["delmsg"])) {
    echo "
".$_SESSION["delmsg"]."
";
    // clean up the session variable value if you don't need it anymore
    unset($_SESSION["result"]);
}

This code will help you understand session variables, but there are still security flaws in this code, don't go live with it. First, learn about SQL Injection: http://php.net/manual/en/security.database.sql-injection.php and PDO: http://php.net/manual/en/book.pdo.php
Hope it helps.

Read more about the $_SESSION array: http://php.net/manual/en/reserved.variables.session.php

A: after successful add, update or delete record redirect your page back to the same page using a header like below.
header('location:yourpage.php');
exit;


text:
Q: Poor resolution of axes and ticks in `DensityPlot` When I am plotting some data with Spectrogram the ticks and axes are very clean and nice, but DensityPlot produces a horrible resolution of ticks and axes, why is that?
I am using MMA12.2 on Win64
Here are the results for Spectrogram
Spectrogram[Table[Cos[i^2] + Sin[i^2], {i, 300}],
 PlotLegends -> Automatic]

and this is form DensityPlot
DensityPlot[x y, {x, 0, 30}, {y, 0, 1}, AspectRatio -> 1/3,
 ColorFunction -> "SunsetColors", PlotLegends -> Automatic]

For both, I save the plots with a right click and save them as png


text:
Q: Count nulls in properties with one LINQ query Paste into LINQPad:
void Main()
{
    List<Data> list = new List<Data>();
    list.Add(new Data());
    list.Add(new Data{a="a", b="b"});
    list.Add(new Data{a=null, b="b"});

    var queryA = from data in list where data.a == null select data;
    var queryB = from data in list where data.b == null select data;

    var countNulls = new {a = queryA.Count(),b = queryB.Count()};
    countNulls.Dump();
}

class Data
{
    public string a {get;set;}
    public string b {get;set;}
}

Instead of using queryA and queryB is it possible to do this in one query?
Answer:
All queries below generate exactly same SQL, so it's just a preference of coder what to choose.
var countNulls = new
    {
        a = queryA.Count(),
        b = queryB.Count()
    };

    var countNulls2 = new
    {
        a = list.Count(d => d.a == null),
        b = list.Count(d => d.b == null)
    };

    var countNulls3 = list.Aggregate(
    new { a = 0, b = 0 },
    (acc, data) => new
    {
        a = acc.a + (data.a == null ? 1 : 0),
        b = acc.b + (data.b == null ? 1 : 0),
    });

Update: apparently (thanks to Evan Stoev) this task can be done 20x faster on EF's DbSet and it creates one SQL query.
var countNulls4 =
    (from data in db.Data
     group data by 1 into g
     select new
     {
         a = g.Sum(data => data.a == null ? 1 : 0),
         b = g.Sum(data => data.b == null ? 1 : 0)
     }).First();

A: You can simply use the Count() overload that takes a predicate:
var countNulls = new
{
    a = list.Count(d => d.a == null),
    b = list.Count(d => d.b == null)
};

Output is:

A: For completeness, you can use Aggregate to get the result in a single pass over the input sequence:
var countNulls = list.Aggregate(
    new { a = 0, b = 0 },
    (acc, data) => new
    {
        a = acc.a + (data.a == null ? 1 : 0),
        b = acc.b + (data.b == null ? 1 : 0),
    });

But I'm not sure it would be more efficient compared to 2 separate Count calls due to the need of anonymous object allocation on each step.
UPDATE: It turns out that you are asking for a single SQL query (so list is not actually a List<Data> but DbSet<Data> I guess). In LINQ to Entities, you can use group by constant technique, which combined with replacing Count(condition) with Sum(condition ? 1 : 0) will produce a nice single SQL query pretty similar to what you would write manually:
var countNulls =
    (from data in db.Data
     group data by 1 into g
     select new
     {
         a = g.Sum(data => data.a == null ? 1 : 0),
         b = g.Sum(data => data.b == null ? 1 : 0)
     }).First();

A: As far as I understand, you want to count nulls for two different object properties regardless if the other one is null. In other words:
a=null, b="b"
a="a", b=null
a=null, b=null

would return count for 2 and 2.
In that case you can do it this way in one query:
var queryAB = from data in list where data.a == null || data.b == null select data;


text:
Q: ARCGIS Runtime for .NET How to set background color for Text Symbol in SceneView My code looks like this:
            TextSymbol ts = new TextSymbol()
            {
                Font = new SymbolFont("Arial", 18),
                BackgroundColor = Color.FromArgb(160, 255, 255, 255),
                HorizontalTextAlignment = HorizontalTextAlignment.Center,
                VerticalTextAlignment = VerticalTextAlignment.Baseline,
                Text = icon.description,
                XOffset = 0,
                YOffset = -icon.height
            };

            var pointGraphic = new Graphic(GeometryEngine.Project(new MapPoint(icon.Longitude, icon.Latitude, 100, wgs84), MyViewBase.SpatialReference), ts);

The text symbol shows up as expected on the MapView, but the SceneView there is no background box and the text is not centered under the appropriate lat/long.
Is this capability not available for SceneView? If not, how can I do this?

A: Unfortunately text background is not supported in the first v100 release. We hope to have it in the next update, but it's not be in yet, so I can't with 100% certainty promise it yet.
We do however support outline color, so perhaps you can use that instead?


text:
Q: Programming in Objective-C Stephen Kochan. Chapter 21, exercise 21.2 Hello!
I have a trouble in 21.2 exercise. In that exercise I build Fraction calculator. I have 9 buttons and math actions. When I press any digit (either 1,2,3 or any else) on iOS Simulator it generates an error:
    2012-08-05 15:09:05.026 Fraction_Calculator[834:f803] -[ViewController digit5]: unrecognized selector sent to instance 0x6843e00
2012-08-05 15:09:05.029 Fraction_Calculator[834:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ViewController digit5]: unrecognized selector sent to instance 0x6843e00'
*** First throw call stack:
(0x14b5022 0xeb5cd6 0x14b6cbd 0x141bed0 0x141bcb2 0x14b6e99 0x1b14e 0x1b0e6 0xc1ade 0xc1fa7 0xc1266 0x403c0 0x405e6 0x26dc4 0x1a634 0x139fef5 0x1489195 0x13edff2 0x13ec8da 0x13ebd84 0x13ebc9b 0x139e7d8 0x139e88a 0x18626 0x28ad 0x2815)
terminate called throwing an exception

What that means: "unrecognized selector sent to instance 0x6843e00" and "'-[ViewController digit5]: unrecognized selector sent to instance 0x6843e00'".
Here is my code of that program:
ViewController.h
Code: Objective-C
#import <UIKit/UIKit.h>
#import "Calculator.h"

@interface ViewController : UIViewController

@property (strong, nonatomic) IBOutlet UILabel *display;

-(void) processDigit: (int) digit;
-(void) processOp: (char) theOp;
-(void) storeFracPart;

-(IBAction) clickDigit: (UIButton *) sender;

-(IBAction) clickPlus;
-(IBAction) clickMinus;
-(IBAction) clickMultiply;
-(IBAction) clickDivide;

-(IBAction) clickOver;
-(IBAction) clickEquals;
-(IBAction) clickClear;

@end

ViewController.m
Code: Objective-C
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    char                op;
    int                 currentNumber;
    BOOL                firstOperand, isNumerator;
    Calculator          *myCalculator;
    NSMutableString     *displayString;
}

@synthesize display;

-(void) processDigit:(int)digit
{
    currentNumber=currentNumber*10+digit;

    [displayString appendString:[NSString stringWithFormat:@"%i", digit]];
    display.text=displayString;
}

-(IBAction) clickDigit:(UIButton *)sender
{
    int digit=sender.tag;

    [self processDigit: digit];
}

-(void) processOp: (char) theOp
{
    NSString *opStr;

    op=theOp;

    switch(theOp)
    {
            case '+':
                opStr=@"+";
                break;
            case '-':
                opStr=@"-";
                break;
            case '*':
                opStr=@"*";
                break;
            case '/':
                opStr=@"/";
                break;
    }

    [self storeFracPart];
    firstOperand=NO;
    isNumerator=YES;

    [displayString appendString: opStr];
    display.text=displayString;
}

-(void) storeFracPart
{
    if(firstOperand)
    {
       if(isNumerator)
       {
           myCalculator.operand1.numerator=currentNumber;
           myCalculator.operand1.denominator=1;
       }
        else
            myCalculator.operand1.denominator=currentNumber;
    }
    else if (isNumerator)
    {
        myCalculator.operand2.numerator=currentNumber;
        myCalculator.operand2.denominator=1;
    }
    else
    {
        myCalculator.operand2.denominator=currentNumber;
        firstOperand=YES;
    }
currentNumber=0;
}

-(IBAction) clickOver
{
    [self storeFracPart];
    isNumerator=NO;
    [displayString appendString: @"/"];
    display.text=displayString;
}

-(IBAction) clickPlus
{
    [self processOp: '+'];
}

-(IBAction) clickMinus
{
    [self processOp: '-'];
}

-(IBAction) clickMultiply
{
    [self processOp: '*'];
}

-(IBAction) clickDivide
{
    [self processOp: '/'];
}

-(IBAction) clickEquals
{
    if (firstOperand==NO)
    {
        [self storeFracPart];
        [myCalculator performOperation: op];

        [displayString appendString: @"="];
        [displayString appendString: [myCalculator.accumulator convertToString]];
        display.text=displayString;

        currentNumber=0;
        isNumerator=YES;
        firstOperand=YES;
        [displayString setString: @""];
    }
}

-(IBAction) clickClear
{
    isNumerator=YES;
    firstOperand=YES;
    currentNumber=0;
    [myCalculator clear];

    [displayString setString:@""];
    display.text=displayString;
}

- (void)viewDidLoad
{
    //[super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    firstOperand=YES;
    isNumerator=YES;
    displayString=[NSMutableString stringWithCapacity:40];
    myCalculator=[[Calculator alloc]init];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

Thanks a lot!

A: This might be happening if you haven't set the tag value for each button. For example, for button 4 the tag should be 4 and so on:

A: Check digit buttons tag property (UIButton settings in the Interface Builder). It looks like all of them has value 0. Just set tags for buttons propiretly (ex. tag=3 for button with digit 3).


text:
Q: how can I insert into Stringp[ I have currently predefined data
String[] values = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu",
                "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu",
                "Windows7", "Max OS X", "Linux", "OS/2", "Android", "iPhone", "WindowsMobile" };

I want to insert into values from array of object
List<Scores> myScore = db.getAllScore();

        for (Scores cn : scor)
        {
            // how can I insert it into values

        }

A: try this.
List<Score> myScore = db.getAllScore();

        for (int i = 0,j=value.length; i < myScore.size(); i++,j++) {
            value[j]=myScore.get(i);
        }


text:
Q: How to put a rounded div in a bootstrap site I have the following code

...

        @foreach (var image in Model.Images)
        {

        }

What I want is to put make the div with id "gallery" as a rounded div and make it to be able to keep the aspect ratio when resizing the browser screen size.
Right now, if I put these lines of css code I get the div well rounded in a full screen mode. But when I resize it to a smaller screen size (mobile) I get the right side of the dive overlapped over the images in div:
border-radius: 25px;
border: 2px solid #8AC007;
padding: 20px;

How can I do to make a well responsive rounded div that contains images?
Thank you in advanced.

A: You will need your images to be responsive with 'img-responsive' class, (you will need to change the width and height elements to just a max-width (or height) and you might want to check out this S.O. post about managing responsive divs.
Then just keep the responsive image inside the responsive div, and you should be all set.

Your divs > Your images


text:
Q: what is wrong with this sql query to get all files? SELECT User1.NAME,User1.PORT,User1.IP,File1.SIZE,File1.FNAME

FROM [User_File],[User1],[File1] WHERE User1.ACTIVE = 'TRUE' AND [User_File].UID= User1.UID AND
[User_File].FID=File1.FID
i'm trying to get all the files of the users that are '"active".
this query return nothing.
pls help!

A: You should create a property to hold the collection of Downfile objects, for example
ObservableCollection<Downfile> downFileList = new ObservableCollection<Downfile>();

Then add concrete instances to that list
downFileList.Add(new DownFile (...));

And finally bind that collection to the items source of the ListView
<ListView x:Name="downList" ItemsSource="{Binding downFileList}" />


text:
Q: Deploy SQL Server and my dataBase with oneClick setup I'm asking if it's possible to deploy SQL Server and my database with oneClick setup.
I'm mean that I have to give to my client the setup file that contains my application and my database. The user should just have to click on the setup, and automatically install my application, SQL Server and deploy the database in one operation.
Is that possible?

Thanks but I
need alos to know how to deply te SQL SERVER 2008 runTime?
I mean after installing the application, I have to instal the SQL Server and then deploy the database

A: You can script all the objects in a database via the SSMS by right clicking on the db -> Tasks -> Generate Scripts -> Check Script All Objects in this database. Save the script to a .sql file and execute it against their SQL Server Instance.

A: Of course it is possible, your client just needs to provide SQL Server credentials during setup and your code can execute scripts during setup to create all the necessary database objects. If this doesn't fit your definition of "oneClick" than you would need to have this information ahead of time and include it in your installation but that would not be secure and it doesn't make much sense because you'd than have to create a unique setup for each client...


text:
Q: React-Redux - How to update a piece of state without causing unnecessary re-renders on unrelated components I'm struggling to pose this question in a concise manner.  I am having some major performance issues with my app.  I have installed the Perf add-on tools for react and can see where the issue is, however I am unsure of the best way to fix it.
I think it will probably have something to do with ReSelect... but need some guidance on where to begin.
I have a component that renders a number of other components.  This uses size-me (to calculate the size of the browsing window), and react-grid-layout (to layout each component and permit their positioning to be changed).  This is resource intensive, so I can't have this happening unnecessarily.
The user can click on a button to open a modal window (to add or edit the components that are being rendered in the grid).
The issue: When the modal window opens, the underlying component re-renders, causing size-me and react-grid-layout to re-render, which thus causes the modal to "jerkingly" open!
This is the entire state tree:

This is the only part of the state that changes when I open the modal:

The size-me and react-grid-layout stuff is rendering state from the formEngine.form part of the state tree, yet it is being re-rendered when state updates are made to the formEngine.addComponent part of the tree
Here are the performance logs:

As you can see, there are some wasted renders happening AND this will only grow incrementally based on the number of nested layout components the user decides to add to the form...
So to try and prevent this question from becoming too convoluted, let me ask first:

*

*How do I prevent the underlying page from re-rendering when I open the modal?

*Why are components that are watching formEngine.form triggered to re-render when fromEngine.addComponent gets modified?

Thank you.

EDIT 1:
I'm not sure if this is relevant, but to answer the comment, I added this code.  The AddFormComponent is the Modal that jerks open.
Form.js:
const Form = (props) => (

      {
        props.editMode &&

          <AddFormComponent parentId={"root"} />

      }
      {
        props.form.components.root.childComponentIds.length > 0 ?
          <LayoutComponent componentKey={"root"} />
        :
          <EmptyGridLayout />
      }

)

LayoutComponent.js:

import React from 'react'
import _ from 'lodash'
import SizeMe from 'react-sizeme'
import { Responsive as ResponsiveReactGridLayout } from 'react-grid-layout'
import 'react-grid-layout/css/styles.css'
import 'react-resizable/css/styles.css'

import FormComponent from '../containers/FormComponent'
import NestedLayoutComponent from '../containers/LayoutComponent'

import AddFormComponent from '../containers/AddFormComponent'
import LayoutComponentEditor from '../containers/LayoutComponentEditor'

//Setup SizeMe Configuration
let sizeMeConfig = {
  monitorWidth: true
}
let sizeMeHOC = SizeMe(sizeMeConfig)

//Wrap ResponsiveReactGridLayout in sizeMeHOC so that it is aware of it's width
var GridLayout = ResponsiveReactGridLayout
GridLayout = sizeMeHOC(GridLayout)

const LayoutComponent = (props) => (

    <GridLayout
      cols={props.cols}
      className={props.className}
      breakpoints={props.breakpoints}
      rowHeight={props.rowHeight}
      draggableCancel={props.draggableCancel}
      layouts={props.layouts}
      isDraggable={props.isDraggable}
      isResizable={props.isResizable}
      onLayoutChange={(currentLayout, allLayouts) => props.handleLayoutChange(props.componentKey, currentLayout, allLayouts)}
      width={props.size.width}
    >
      {
        //Map out any child layouts
        props.childComponents.map((component) => {
          if (component.type === "card") {
            return (

                  {component.header}

                  {
                    //Hide if editMode={false}
                    props.editMode &&

                        <LayoutComponentEditor path={component.key} />

                        <AddFormComponent parentId={component.key} />

                  }
                  <NestedLayoutComponent componentKey={component.key} />

            )
          }
          else if (component.type === "fieldGroup") {
            return (

                  {
                    //Hide if editMode={false}
                    props.editMode &&

                        <AddFormComponent parentId={component.key} />

                  }
                  <NestedLayoutComponent componentKey={component.key} />

            )
          }
          else if (component.type === "paragraph") {
            return (

                {
                  <FormComponent component={component} editMode={props.editMode} />
                }

            )
          }
          else {
            return (

                {
                  <FormComponent component={component} editMode={props.editMode} />
                }

            )
          }
        })
      }
    </GridLayout>

)

export default SizeMe()(LayoutComponent)

EDIT 2:
AddFormComponent.js -- Component

import React from 'react'
import AddFormComponentDetails from './AddFormComponentDetails'

import Perf from 'react-addons-perf'; // ES6

class AddFormComponent extends React.Component {

  constructor(props) {
    super(props);
    this.localOpenModal = this.localOpenModal.bind(this);
  }

  localOpenModal() {
    console.log("----STARTING PERFORMANCE MONITOR-----")
    Perf.start()
    this.props.handleOpenModal();
  }

  componentDidUpdate() {
    console.log("-----PERFORMANCE MONITOR STOPPING------")
    Perf.stop()
    console.log("-----PRINT INCLUSIVE------")
    Perf.printInclusive()
    console.log("-----PRINT WASTEED------")
    Perf.printWasted()
  }

  render() {
    return (

    <Modal isOpen={this.props.modalOpen} size={"lgr"} toggle={this.props.handleCloseModal}>
      <ModalHeader toggle={this.props.handleCloseModal}>Add Component</ModalHeader>
      <ModalBody>
        ...Removed For Breviety
      </ModalBody>
      <ModalFooter>
        ...Removed For Breviety
      </ModalFooter>
    </Modal>

)
  }
}

export default AddFormComponent

AddFormComponent.js -- Container

import { connect } from 'react-redux'
import {
  handleOpenModal,
  handleCloseModal,
  handleGoBack,
  handleComponentPropertyChange,
  handleComponentNameChange,
  handleComponentTypeChange,
  handleSubmit
} from '../actions/addFormComponentActions'
import AddFormComponent from '../components/AddFormComponent'

const mapStateToProps = (state) => ({
  steps: [
    { icon: 'superpowers', title: 'Select Component', description: 'Select the Component you wish to add', active: state.addComponent.currentStep == 1 },
    { icon: 'info circle', title: 'Enter Details', description: 'Enter details to customize component', active: state.addComponent.currentStep == 2 },
    { icon: 'check', title: 'Add Component', description: 'Add component to form' }
  ],
  currentStep: state.addComponent.currentStep,
  modalOpen: state.addComponent.modalOpen,
  component: state.addComponent.component,
  errors: state.addComponent.errors,
  componentType: state.addComponent.componentType
})

export default connect(
  mapStateToProps,
  {
    handleOpenModal,
    handleCloseModal,
    handleGoBack,
    handleComponentPropertyChange,
    handleComponentNameChange,
    handleComponentTypeChange,
    handleSubmit
  }
)(AddFormComponent)

addFormComponentReducer.js

import _ from 'lodash'
import {
  ADD_FORM_COMPONENT_TOGGLE_MODAL,
  ADD_FORM_COMPONENT_CLOSE_MODAL,
  ADD_FORM_COMPONENT_GO_BACK,
  ADD_FORM_COMPONENT_SUBMIT,
  ADD_FORM_COMPONENT_PROPERTY_CHANGE,
  ADD_FORM_COMPONENT_PROPERTY_ERROR,
  ADD_FORM_COMPONENT_KEY_ERROR,
  ADD_FORM_COMPONENT_NAME_CHANGE,
  ADD_FORM_COMPONENT_NAME_ERROR,
  ADD_FORM_COMPONENT_TYPE_CHANGE,
  ADD_FORM_COMPONENT_TYPE_ERROR
} from '../actions/addFormComponentActions'

let initialState = {
  currentStep: 1,
  modalOpen: false,
  component: {
    key: '',
    label: '',
    headingText: '',
    text: ''
  },
  errors: {
    key: {
      hasError: false,
      msg: ''
    },
    label: {
      hasError: false,
      msg: ''
    },
    text: {
      hasError: false,
      msg: ''
    }
  }
}

function addFormComponentReducer(state = initialState, action) {
  switch (action.type) {
    case ADD_FORM_COMPONENT_TOGGLE_MODAL:
      return {
        ...state,
        modalOpen: action.payload.isOpen,
        currentStep: 1
      }
    case ADD_FORM_COMPONENT_CLOSE_MODAL:
      return initialState;
    case ADD_FORM_COMPONENT_GO_BACK:
      return {
        ...state,
        currentStep: 1
      }
    case ADD_FORM_COMPONENT_SUBMIT:
      return initialState;
    case ADD_FORM_COMPONENT_PROPERTY_CHANGE:
      return {
        ...state,
        component: {
          ...state.component,
          [action.payload.key]: action.payload.value
        }
      }
    case ADD_FORM_COMPONENT_PROPERTY_ERROR:
      return {
        ...state,
        errors: {
          ...state.errors,
          [action.payload.key]: {
            hasError: action.payload.hasError,
            msg: action.payload.msg
          }
        }
      }
    case ADD_FORM_COMPONENT_TYPE_CHANGE:
      return {
        ...state,
        componentType: action.payload.componentType,
        currentStep: 2
      }
    default:
      return state
  }
}

export default addFormComponentReducer

index.js -- Combine Reducers

import { combineReducers } from 'redux'

//import FormEngine reducers
import formReducer from './formReducer'
//import addFormComponentReducer from './addFormComponentReducer'
import componentEditorReducer from './componentEditorReducer'

const rootFormEngineReducer = combineReducers({
  form: formReducer,
  //addComponent: addFormComponentReducer,
  componentEditor: componentEditorReducer
})

export default rootFormEngineReducer

rootReducer.js

import { combineReducers } from 'redux'

//import reducers
import rootCoreLayoutReducer from '../features/CoreLayout/reducers'
import rootFormEngineReducer from '../features/FormEngine/reducers'
import addComponentReducer from '../features/FormEngine/reducers/addFormComponentReducer'

const rootReducer = combineReducers({
  coreLayout: rootCoreLayoutReducer,
  formEngine: rootFormEngineReducer,
  addComponent: addComponentReducer
})

export default rootReducer

A: If you are using a pure component any performance optimizations have to be handled manually(using shouldComponentUpdate). Since you are using redux it can handle that for you. But you have to "connect" it to the redux store.
If you choose to use redux connect ensure that the modal visibility is not related to your other properties specifically in your case:
modalOpen is nested in formEngine. When it changes anything else that listens to formEngine will rerender


text:
Q: storing user input rating for each given phrase and print in the order of rating given I basically have these 5 random sentences that are stored in the array and I basically want the user to input a score for each sentence out of 10 and store that in the array and then include a way of sorting the sentences in order of the scores given to them and print them in that order
i.e. from highest to lowest.
I am new to java, would really appreciate if someone could help out on how do I go about solving this problem, apparently I have to use comparatives, but how do I use that? Is there any other way?
    public static void loopswithinloops()

    {

    String[] sentences = {"I am blessed to have you in my life. You are the one thing in my life that is true and real",
                    "I am honoured to have you by my side to love and to cherish each day of our lives.",
                    "More precious than any other thing in my life is to see your face each and every day",
                    "To wake up beside you is a treasure that I have found in you and that I am thankful for.",
                    "Your beautiful eyes dance bright and clear and I can see forever in your eyes." };
    Random random = new Random();
    int rand = random.nextInt(sentences.length);

    for (int i=0; i<=4; i++)
    {
    ratemessage(sentences[rand]);

    }

    public static void ratemessage (String sentences)

    {
        JOptionPane.showMessageDialog( sentences );

        JOptionPane.showInputDialog("what do you rate this sentence out of 10?");
        Scanner input = new Scanner(System.in);
        int result = input.nextInt();
    }
        Arrays.sort(result);// this is the Array.sort()method

        for (int i=0; i<=4; i++)
        {
        System.out.println("you given rating is " + result + "for " + sentences);
        }
}
// END loopswithinloops

A: You only need the Random if want to randomize your sentences (you say 5 random sentences).
You don't need Scanner when you're using JOptionPane.
So this is how you could do it - I've added some comments:
String[] sentences = {"I am blessed to have you in my life. You are the one thing in my life that is true and real",
                        "I am honoured to have you by my side to love and to cherish each day of our lives.",
                        "More precious than any other thing in my life is to see your face each and every day",
                        "To wake up beside you is a treasure that I have found in you and that I am thankful for.",
                        "Your beautiful eyes dance bright and clear and I can see forever in your eyes." };

int[] result = new int[sentences.length];//you have to give the array a size
String inputStr;
for (int i = 0; i < sentences.length; i++) {
    JOptionPane.showMessageDialog(null, sentences[i]);//the sentences one at at time
    inputStr = JOptionPane.showInputDialog("what do you rate this sentence out of 10?");
    result[i] = (int)Float.parseFloat(inputStr);//put the input into the array - it comes as a float so you'll have to cast it to int
}
Arrays.sort(result);
for (int i = 0; i < sentences.length; i++) {
    System.out.println("you given rating is " + result[i] + " for " + sentences[i]);
}


text:
Q: removing outliers in a vector The aim is to remove outliers in a vector.
x = datasets::islands ($area)
x =    12    13    13    13    14    14    15    15    16    16    16    19    21    23    25    26    29    29    30    30
       32    33    36    40    42    43    43    44    49    58    73    82    82    84    89   183   184   227   280   306
       840  2968  3745  5500  6795  9390 11506 16988

so far by using
x_rm_out <- x[!x%in% boxplot.stats
                    (x, coef = .05, do.conf = TRUE, do.out = TRUE)$out]

Result
 [1]  12  13  13  13  14  14  15  15  16  16  16  19  21  23  25  26  29  29  30  30  32  33  36  40  42  43  43  44  49  58  73
[32]  82  82  84  89 183 184

Is there a way to remove 183 & 184 from vector (x)?

A: Finding Outliers
A very easy way to find outliers is with the rstatix package, then filter them out with dplyr:
# Load library:
library(rstatix)
library(dplyr)

# Make x into dataframe:
x <- data.frame(x)

# Identify outliers:
x %>%
  identify_outliers()

You should get an output like this now:
      x is.outlier is.extreme
1   840       TRUE       TRUE
2  2968       TRUE       TRUE
3  3745       TRUE       TRUE
4  5500       TRUE       TRUE
5  6795       TRUE       TRUE
6  9390       TRUE       TRUE
7 11506       TRUE       TRUE
8 16988       TRUE       TRUE

Creating Dataframe Without Them
Now you have to filter out the data, which you can then turn into a new dataframe (< 840). You may also remove them with your previously established criterion (< 183) if you desire:
# Filter outliers and create new file:
x2 <- x %>%
  filter(x < 183)
x2

Which after you enter x2, gives you this output without outliers:
     x
1   12
2   13
3   13
4   13
5   14
6   14
7   15
8   15
9   16
10  16
11  16
12  19
13  21
14  23
15  25
16  26
17  29
18  29
19  30
20  30
21  32
22  33
23  36
24  40
25  42
26  43
27  43
28  44
29  49
30  58
31  73
32  82
33  82
34  84
35  89

A: To supplement the Shawn's answer, you can also use rstatix::is_outlier() function for numeric vectors.


text:
Q: Proving the Mean Value Theorem Theorem

The Mean Value Theorem: Let there be a function $f$ which is continuous on $[a,b]$ and differentiable on $(a,b)$. Then there exists $f'(c)=\dfrac{f(b)-f(a)}{b-a}$

I'd like to prove the Mean Value Theorem, assuming Rolle's Theorem has already been proved.
Proof
Let $f$ be the function whose graph is the chord between the endpoints $(a,f(a))$, and $(b,f(b))$.
Then let $g(x)=\dfrac{f(b)-f(a)}{b-a}(x-a)+f(a)$, and let $h(x)=f(x)-g(x)$, so $h$ is continuous on $[a,b]$ and differentiable on $(a,b)$. Note that $h(a)=h(b)=0$, and so the hypotheses of Rolle's Theorem are met, and thus there exists a $c\in(a,b)\ni h'(c)=0$.
$$0=h'(c)=f'(c)-g'(c)=f'(c)-\dfrac{f(b)-f(a)}{b-a}$$ $$\implies f'(c)=\dfrac{f(b)-f(a)}{b-a}\tag*{$\blacksquare$}$$
Is the above proof valid (and are there any suggestions for improvement?)

A: Another way to prove the MVT:
Let us define a function $\phi$:[a,b]$\rightarrow IR$ by
$$\begin{matrix}
f(x)&g(x)&h(x) \\
f(a)&g(a)&h(a)\\
f(b)&g(b)&h(b)
\end{matrix}$$
Observe that $\phi (a)$=$\phi (b)$=0. Hence by Rolle's theorem $\exists$ c $\in$ (a,b) such that $\phi^{'} (c)$=0.
$$\begin{matrix}
f^{'}(x)&g^{'}(x)&h^{'}(x) \\
f(a)&g(a)&h(a)\\
f(b)&g(b)&h(b)
\end{matrix}$$
is equal to 0.Take h(x) to be a constant function,g(x)=x and expand the determinant to get the desired result.


text:
Q: can not run Qi4j two minutes tutorial I am trying to run the project in 'Qi4j in 2 minutes' tutorial
while I can`t find the Qi4j lib files in the maven repository.
Can anyone tell me how to import the Qi4j lib files with maven?
thanks in advance :)

A: Qi4j SDK 2.0 is under development. If you want to use 2.0 you can download builds from Qi4j continuous integration or build the Qi4j SDK from source.
Weekly SNAPSHOTs are uploaded to https://repository-qi4j.forge.cloudbees.com/snapshot/ so you need to add this url as a maven repository :
<repositories>
    [...]
    <repository>
        <id>qi4j-snapshots</id>
        <url>https://repository-qi4j.forge.cloudbees.com/snapshot/</url>
        <releases>
            <enabled>false</enabled>
        </releases>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    [...]
</repositories>

And then you can add dependencies to Qi4j:
<dependencies>
    [...]
    <dependency>
        <groupId>org.qi4j.core</groupId>
        <artifactId>org.qi4j.core.bootstrap</artifactId>
        <version>2.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.qi4j.core</groupId>
        <artifactId>org.qi4j.core.runtime</artifactId>
        <version>2.0-SNAPSHOT</version>
    </dependency>
    [...]
</dependencies>

All this information can now be found on the Qi4j website, see http://qi4j.org/howto-depend-on-qi4j.html


text:
Q: Showing two different gradients as a background using CSS? I want to have 2 different gradients in the background of my site - I am using the following to call one gradient - how do I declare more than one (i.e. to show a different gradient on the left and a different one on the right)
body
{

    background: -webkit-gradient(linear, left top, left bottom, from(#E0E0E0), to(#fff));
    background: -moz-linear-gradient(top,  #E0E0E0,  #fff);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#E0E0E0', endColorstr='#ffffff');

}

So I want want the left side of the background to be a different colour gradient to the right.
Any ideas?
Cheers!

A: <void after update of your question>
You should use a [multi-background](http://www.w3.org/TR/css3-background/#layering)
declaration where the first and second values are separated by a comma like
`background: value1, value2;`.

Also the background on top (here a gradient) should whether not recover entirely the
first one or have some transparency, obviously.
</void>

Here's a fiddle using the :before pseudo to create something to stick a background on without creating an extra element in the HTML code. If linear-gradient is supported by a browser, then :before is also supported AFAIK so no problem here.
http://jsfiddle.net/URWD8/
The main trick is creating a box half-size and well positioned (and then having text content above this absolutely positioned box with z-index ... by trial and error I admit).
And use also declarations with the other vendor prefixes: -o- is lacking here and also the one without prefix linear-gradient for IE10 and future versions of other browsers. See http://caniuse.com/#feat=css-gradients
OT:
Fun and/or abusing of :before and :after :) with http://css-tricks.com/examples/ShapesOfCSS/ and http://ie7nomore.com/#CSS2 (search for those pseudos in both pages)


text:
Q: Fubini Theorem apply on measure Let $\mu$ be a finite measure on $\mathbb{R}$ and let $$f(x) = \mu((-\infty,x]).$$ Show that $$\int (f(x+c)-f(x)) dx = c\mu (\mathbb{R})$$ for any $c>0.$
This is what I attempt :
First, $$f(x+c) - f(x) = \mu ((x, x+c])$$
So $$\int (f(x+c)-f(x)) dx = \int \mu((x, x+c]) dx = \int\int 1_{(x, x+c]} d\mu dx$$
If I apply Fubini's Theorem, then $$\int\int 1_{(x, x+c]} d\mu dx =\int\int 1_{(x, x+c]} dx d\mu = \int c d\mu = c\mu(\mathbb{R}).$$
But I am not sure why $1_{(x, x+c]}$ is jointly-measurable or $(\mu \times m)$-integrable where $m$ is a Lebesgue measure. (Precisely, I am not sure why the assumption for using Fubini's theorem is satisfied)


text:
Q: mkisofs - Floppy Image to Disk Image I'm trying to compile MikeOS on windows. I've successfully (I think) created a floppy (.flp) image of the operating system. I want to convert it to a disk image (.iso) so I can run it in virtual box. I've tried
mkisofs -quiet -V 'MIKEOS' -input-charset iso8859-1 -o disk_images/mikeos.iso -b mikeos.flp disk_images/

Which is the command in the Linux build script. It does create an ISO image, but when I try to run in in VirtualBox, I get a black screen. What am I doing wrong? Here's my build script.

A: You don't want to create a bootable CD-rom from a bootable floppy, that'd involve some complexity around El Torito.
Just add a floppy controller!
Go into your VM's preferences, choose Storage, right-click on the storage tree and Add Floppy Controller. Then Add Floppy Device, pick the floppy image you generated (rename it to .raw if needed).


text: Q: How to generate Aggregate graph in jmeter dashboard I want to generate Aggregate graph in jmeter dashboard as a custom graph in jmeter dashboard like we have an option in UI mode of jmeter. Basically I want to generate a graph with the average time of all my transactions. I know there is a section in jmeter dashboard about custom graphs and how to add it but I am not able to understand it how to use it in my case


text:
Q: Is it necessary to create a new table if I have two tables with common column names? SQL Best practices I need help to do a good database analysis and learn
I have two tables:

*

*Patient

*Specialist

These two tables have column names in common:

*

*first_name

*last name

*level of education

*e-mail

*phone

Is it necessary to create a new table with these elements in common and that they are related to the other two tables?
or
It is not necessary in this case. I try to make a good analysis and apply good practices
PICTURE BELOW HERE
ER_Model

A: These are just suggestions and not an answer.
Kind of very small questions, but very difficult to answer because answers may contradict each while explaining.

explenation

That depends on your requirement actually. for example,

*

*How many records that you going to manage inside a table?

*

*if it is comparably small, you can keep both patients and specialists on the same table with a flag to categorize them.

*comparably big, you can keep Patient and specialist tables separately with common fields inside each table.

*What level of segregation do you expect from your system?
For example in microservices, keeping two different tables is better to isolate each service. But that also depends on the architecture you're going to use.
But separating common fields into a different table and managing those fields are not necessary like what we are doing with OOP concepts. because unwanted DB relations give you an extra burden to your queries.
This is my idea. You can have many from others :)


text:
Q: Should installation of Linux on Macbook Air (2015) be avoided for any reason? I bought a Macbook Air (2015), it's on it's way. What I want to do is to install a Linux distro on the computer. Before I do this I just want to make sure that this won't break my computer. Should installing Linux on a Macbook Air be avoided for any reason?
Merry Xmas

A: @The_IT_Guy_You_Don't_Like
Someone told me that it could cause CPU death since Linux cannot control the proprietary drivers of the power-save-system. I was told that this was specific to a Macbook Air, but on a Macbook Pro it should be possible for some reason. I can't find the source now, but I also read somewhere that Linus Torvalds had to replace his motherboard a few times because of this problem.


text:
Q: How to Trim a Leading and Trailing char in regular expressions? I have a requirement to trim a leading and trailing character of a fixed length column.
Ex: I have column IdNumber which is of fixed length say 11, with below values
X3343438594
7743438534X
I want to trim the leading and trailing X, and result should look like this.
3343438594
7743438534

A: Try this:
Search: ^X(?=\d{11}$)|(?<=^\d{11})X$
Replace: <blank>

Regex breakdown:

*

*^X means "start of input then X"

*(?=\d{11}$) means "followed by 11 digits then end"

*| means "logical OR"

*(?<=^\d{11}) means "preceded by start then 11 digits"

*X$ means "X then end of input"

You want to delete all matches, so replace them with nothing.

A:

var re = /(?=^X|X$)(([A-Z])(\d{10})(\s)(\d{10})([A-Z]))/;
var str = 'X3343438594 7743438534X';
var subst = '$3$4$5';
var result = str.replace(re, subst);
alert(result);

The regex first asserts that the string should have an X at the beginning or at the end, regardless of the length of your data (not necessarily 11 characters).  If that's the case, it tests for a pattern that starts with one letter, followed by 10 digits (totalling 11 characters), then a space, then ten digits followed by one letter (another 11 characters).