text:
Q: Isset function notice in php The code below throws a notice.

( ! ) Notice: Undefined index: product_id in C:\xampp\htdocs\WilliesFishing\admin\product\index.php on line 55

I checked and I am on line 55 but it doesn't like the isset().
I have also tried if(isset($_GET['product_id']; and it throws the same error.  Shouldn't this work?
case 'show_add_edit_form':
    if (isset($product_id)) {
        $product_id = $_GET['product_id'];
    } else {
        $product_id = $_POST['product_id']; // --> Line #55
    }

A: Either $_GET or $_POST doesn't have an index named product_id. Your isset line only checks whether the global variable $product_id is set, which may not imply anything about the state of $_GET and/or $_POST. You probably want to do something like this instead:
if (isset($_GET['product_id')) {
    $product_id = $_GET['product_id'];
} else if (isset($_POST['product_id')) {
    $product_id = $_POST['product_id'];
} else {
    // provide a reasonable default, or otherwise handle the edge-case, in here
}

A: You should use isset on your get parameters. Something like this:
 if (isset($_GET['product_id'])) {
     $product_id = $_GET['product_id'];
 }
 else if (isset($_POST['product_id'])) {
     $product_id = $_POST['product_id'];
 }

The error tells you this because $_GET['product_id'] has no value. So instead of using $product_id. use the request parameter in the condition instead


text:
Q: The column name specified in the PIVOT operator conflicts with the existing column name in the PIVOT argument I my SQL Server stored procedure I have following pivot:
SELECT *
FROM
    (SELECT
         CustomerProvince,
         SalesCount,
         InstallationCount,
         Brand,
         Brand AS Brandt
     FROM
         #salehi1) StudentResults
PIVOT
    (SUM(SalesCount)
        FOR Brand IN ([XVISION], [TCL])
    ) AS PivotTable
PIVOT
    (SUM(InstallationCount)
        FOR Brandt IN ([XVISION], [TCL])
    ) AS PivotTable1

When I execute this query, I get an error but I must only use [XVISION] and [TCL] in this query:

The column name "XVISION" specified in the PIVOT operator conflicts with the existing column name in the PIVOT argument
The column name "TCL" specified in the PIVOT operator conflicts with the existing column name in the PIVOT argument

How can I solve the problem. Any help will be appreciated!

A: With your current code, you would end up with two sets of identical columns.
It looks like you are just trying to pivot two columns into four. It's easier to do this with conditional aggregation.
SELECT
  CustomerProvince,
  XVISION_SalesCount = SUM(CASE WHEN Brand = 'XVISION' THEN SalesCount END),
  TCL_SalesCount     = SUM(CASE WHEN Brand = 'TCL'     THEN SalesCount END),
  XVISION_InstallationCount = SUM(CASE WHEN Brand = 'XVISION' THEN InstallationCount END),
  TCL_InstallationCount     = SUM(CASE WHEN Brand = 'TCL'     THEN InstallationCount END)
FROM
    #salehi1 StudentResults
GROUP BY
  CustomerProvince;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable all searching from the location bar in firefox? (I found similar older questions, but their answers are now obsolete.)
How can I completely disable searching from Firefox's location bar?  In other words, if I type some search terms in the location bar, as opposed to a valid, reachable server address, I want Firefox to respond with a "Server Not Found" error.
I tried doing this through Settings, but, no matter what I do, Firefox keeps accepting search terms in the location bar, and passing them off to my chosen (and only) search engine.  (Of course, I tried to delete this last search engine, but Firefox won't let me.)
Alternatively, is there a simple way I can implement a "do-nothing" search engine that I can then choose as my default search engine?

A: Step 1
type the "about:config" on Firefox location bar and Press Enter

Step 2
Find the keyword.enabled and make it as "false"

Step 3
Go to Firefox Setting then click on Privacy and Security
Find Address Bar
When using the address bar, Disable suggest
Browsing history
Bookmarks
Open tabs
Shortcuts
Search engines
Source -How to Fix Firefox Address Bar Search Not Working


text:
Q: Not able to understand how values in loop work I tried writing code for cs50 pset1's problem: credit.c(more comfortable) after week2. My code is given below. The problem is that 'sumx' and 'sumy' are just 0 and hence 'sum' is always equal to 0. So whenever I give a correct credit card number, it is just going to new line and program ends. How can I solve this problem and why are 'sumx' and 'sumy' not adding up to their respective sums as they should according to the algorithm?
My code is:
#include <cs50.h>
#include <stdio.h>

int main(void){

  long long i;
  do{
    printf("Your credit card number:\n");
    i = get_long_long();
  }
  while(i < 4e12 || i > 5.5e15);
  int count = 0;
  int n;
  long long c = i;

  while(i != 0){
    n = i%10;
    i = i/10;
    count++;
  }
  int x[count];

  for(int j = 0; j < count; j++){
    x[j] = c%10;
    i = c/10;
  }

  int sumx = 0;

  for(int j = 0; j < count - 1; j += 2){
    x[j] = x[j] * 2;
    sumx = sumx + x[j];
    printf("%i", sumx);
  }

  int sumy = 0;

  for(int j = 0; j < count; j += 2){
    sumy = sumy + x[j];
  }

  int sum;
  sum = sumx + sumy;

  if(sum%10 == 0){
    if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
        printf("AmEx\n");
    }
    else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
        printf("MASTERCARD\n");
    }
    else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
        printf("VISA\n");
    }
  }
  else{
    printf("Invalid Number\n");
  }

  return 0;
  }

A: //#include <cs50.h>
#include <stdio.h>

int main(void){

  long long i=4111111111111111;
  //Master: 5105105105105100;//16
  //visa: 4111111111111111
  printf("%lld\n",i);

  //~ do{
    //~ printf("Your credit card number:\n");
    //~ i = get_long_long();
  //~ }
  //~ while(i < 4e12 || i > 5.5e15);

  int count = 0;
  long long c = i;
  int k=0;
  int x[100];//

  while(c != 0){
    x[k] = c%10;
    c = c/10;
    printf("%lld\n",c);
    count++;
    k++;
  }

  //k==count
  printf("count:%d\n",count);
  printf("k:%d\n",k);

    // x[i] contains all the digits of credit card
    printf("print x[i]\n");
    for (int i=0;i<count;i++){
        printf("%d ",x[i]);
    }

    printf("\n");

    int addsum=0,x2prod=0;

     for (int j=0; j<k; j+=2 ){
        addsum += x[j];
    }

 printf("addsum:%d\n",addsum);

    for (int j=1; j<k; j+=2 ){
        if ( (2 * x[j]) > 9 ){ //have 2 digit
            x2prod += (2 * x[j]) / 10;
            x2prod += (2 * x[j]) % 10;
        }
        else // have one digit
            x2prod += 2 * x[j];
    }

    printf("x2prod:%d\n",x2prod);

    int sum;

    sum = addsum + x2prod;

  printf("\nsum: %d\n",sum);

  if(sum%10 == 0){
    if((count == 15 && x[14] == 3) && (x[13] == 4 || x[13] == 7)){
        printf("AmEx\n");
    }
    else if((count == 16 && x[15] == 5) && (x[14] > 1 || x[14] < 5)){
        printf("MASTERCARD\n");
    }
    else if((count == 13 && x[12] == 4) || (count == 16 && x[15] == 4)){
        printf("VISA\n");
    }
  }
  else{
    printf("Invalid Number\n");
  }

  return 0;
  }

I apply some correction on your code, store all credit card digits on x[]array in  first while().
I checked code output with only three samples and by the way this is not a reliable version, try to catch any error.
As you read on my comment i don't any idea about that, but by perform simple search this link
show me what to do and decode it to your way.


text:
Q: SQL Inner Join consulta multiple y mostrar el registro con el valor maximo Tengo un inconveniente con una de mis consultas , le e estado moviendo de diferentes maneras pero no he dado con el correcto , tal vez sea sencillo , explico un poco , la consulta trae información de 4 tablas diferentes por ejemplo:
-Tabla ENT_PERFIL_EMP : trae campo Nombre y valida campo puesto con tabla ENT_PERFILES.
-Tabla ENT_PERFILES : trae doc_nombre.
-Tabla ENT_DOCS: trae revision_actual, descripcion, ultima_mod, categoria.
-Tabla ENT_ENTRENAMIENTO: trae fecha_ent , revision.

la consulta es esta, si me muestra lo que necesito mas sin embargo en la tabla ENT_ENTRENAMIENTO se alojan todos los registros de ENT por lo cual necesito traerme solamente el máximo de la columna Revision, utilize MAX(Revision) me funciono una vez pero le agregue otro dato y ya no me funciono.
select ENT_PERFIL_EMP.Nombre,ENT_PERFILES.Doc_nombre as 'Nombre Documento',ENT_DOCS.Descripcion,ENT_PERFILES.Categoria,ENT_DOCS.Revision_actual as 'Revision actual documento',max(Revision) as 'Revision Entrenamiento',ENT_DOCS.Ultima_mod as 'Fecha Ultima Revision',ENT_ENTRENAMIENTO.Fecha_ent as 'Fecha Entrenamiento',DATEDIFF(DAY,ENT_DOCS.Ultima_mod,GETDATE()) as 'Dias Transcurridos',ENT_DOCS.[Status] from ENT_PERFIL_EMP left join ENT_PERFILES on ENT_PERFIL_EMP.Puesto=ENT_PERFILES.Puesto left join ENT_DOCS on ENT_PERFILES.Doc_nombre=ENT_DOCS.Doc_nombre left join ENT_ENTRENAMIENTO on ENT_PERFILES.Doc_nombre=ENT_ENTRENAMIENTO.Doc_nombre where ENT_PERFIL_EMP.Num_emp='15483' and ENT_DOCS.[Status]='Actual' group by ENT_PERFIL_EMP.Nombre,ENT_PERFILES.Doc_nombre,ENT_DOCS.Descripcion,ENT_PERFILES.Categoria,ENT_DOCS.Revision_actual,ENT_DOCS.Ultima_mod,ENT_ENTRENAMIENTO.Fecha_ent,ENT_DOCS.[Status] order by Categoria,ENT_PERFILES.Doc_nombre asc

En la imagen se puede ver como me trae ambos registros de l campo revision entrenamiento , yo solo necesitaría traerme el máximo en este caso seria el registro con el numero 13.

A: Lo resolví modificando un poco el query.......
select ENT_PERFIL_EMP.Nombre,ENT_PERFILES.Doc_nombre,ENT_DOCS.Descripcion,ENT_PERFILES.Categoria,ENT_DOCS.Status,ENT_DOCS.Ultima_mod,DATEDIFF(DAY,ENT_DOCS.Ultima_mod,GETDATE()) as 'Dias Transcurridos',ENT_DOCS.Revision_actual,MAX(Revision) as 'Revision Entrenamiento' from ENT_PERFIL_EMP inner join ENT_PERFILES on ENT_PERFIL_EMP.Puesto=ENT_PERFILES.Puesto inner join ENT_DOCS on ENT_PERFILES.Doc_nombre=ENT_DOCS.Doc_nombre left join ENT_ENTRENAMIENTO on ENT_PERFILES.Doc_nombre=ENT_ENTRENAMIENTO.Doc_nombre where ENT_PERFIL_EMP.Num_emp='15483' and ENT_DOCS.Status='Actual' group by ENT_PERFIL_EMP.Nombre,ENT_PERFILES.Doc_nombre,ENT_DOCS.Descripcion,ENT_PERFILES.Categoria,ENT_DOCS.Status,ENT_DOCS.Ultima_mod,ENT_DOCS.Revision_actual order by ENT_PERFILES.Categoria,ENT_PERFILES.Doc_nombre asc


text:
Q: Why i am not able to read data countinoulsy from in_voltage0_raw channel in linux ADC read Here i pasted my code, the problem i am facing is i can able to read the data but i can't able to read change in data in in_voltage1_raw ,
can you please anyone help me out to how to solve this problem,
Here i pasted my code, the problem i am facing is i can able to read the data but i can't able to read change in data in in_voltage1_raw ,
can you please anyone help me out to how to solve this problem,
Here i pasted my code, the problem i am facing is i can able to read the data but i can't able to read change in data in in_voltage1_raw ,
can you please anyone help me out to how to solve this problem,
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/ioctl.h>
#include<signal.h>

int fd_adc[8];
int fd_adc_p[8];
char buffer[256];

float voltage,current;

void adc_int(void);
void adc_read(void);

int count;

int main(void)
{
   adc_int();

   while(1)
   {
    adc_read();
    usleep(100000);
   }

}

void adc_int(void)
{

   fd_adc[0]=open("/sys/bus/iio/devices/iio:device0/in_voltage1_raw",O_RDWR|O_NDELAY|O_NOCTTY);
   perror("open");

   fcntl(fd_adc[0],F_SETFL,O_ASYNC);

   fd_adc_p[0]=open("/sys/bus/iio/devices/iio:device0/power/runtime_enabled",O_RDWR);
   perror("open");
   write(fd_adc_p[0],"1",2);

}

void adc_read(void)
{
  int data;
  ioctl(fd_adc[0],FIONREAD,&count);
  if(count>0)
  {
    read(fd_adc[0],&buffer[0],count);
  }

  data=atof(buffer);
  printf("data %d\n",data);

  if(data<=387)
  {
   voltage=((data/100)-0.1);
  }
  else if((data>=388)&&(data<=775))
  {
   voltage=((data/100)-1.1);
  }

  else if((data>=776)&&(data<=1100))
  {
      voltage=((data/100)-1.0678);
  }

  else if((data>=1101)&&(data<=1397))
  {
      voltage=((data/100)-2.0123);
  }

  else if((data>=1398)&&(data<=1652))
  {
      voltage=((data/100)-3.123);
  }

  else if((data>=1653)&&(data<=1904))
  {
      voltage=((data/100)-3.023);
  }
  else if((data>=1905)&&(data<=2165))
  {
        voltage=((data/100)-4.0197);
  }

  else if((data>=2166)&&(data<=2414))
  {
      voltage=((data/100)-4.5023);
  }

  else if((data>=2415)&&(data<=2655))
  {
      voltage =((data/100)-5.04);
  }

 printf("%f\n",voltage);
 //close(fd_adc[0]);

}

Here i pasted my code, the problem i am facing is i can able to read the data but i can't able to read change in data in in_voltage1_raw ,
can you please anyone help me out to how to solve this problem,


text:
Q: How phasset get video url? Show all videos in camera roll and displaying them in UICollectionView.
How phasset get video url?
    var videos: PHFetchResult<PHAsset>!

    fileprivate func fetchVideos() {
        print("fetch Videos")
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ]
        fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.video.rawValue)
        videos = PHAsset.fetchAssets(with: fetchOptions)
        print(videos)
        collectionView?.reloadData()
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.row)

        let asset = videos!.object(at: indexPath.row)
                   ???

    }

CollectionViewCellHeader ;
let fileUrl = ""

override init(frame: CGRect) {
    super.init(frame: frame)

    let videoURL = "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"

    let fileUrl = NSURL(string: videoURL) as! URL

    var aPlayer = AVPlayer(url: fileUrl)
    let moviePlayerController = AVPlayerViewController()

    moviePlayerController.player = aPlayer
    moviePlayerController.view.frame = CGRect(x:0, y:0, width:frame.size.width, height:frame.height)
    moviePlayerController.videoGravity = AVLayerVideoGravity.resizeAspectFill.rawValue
    moviePlayerController.view.sizeToFit()
    moviePlayerController.showsPlaybackControls = false
    moviePlayerController.player?.play()
    addSubview(moviePlayerController.view)

}

How do I get the selected video URL?
How can I use the requestPlayerItem() method?

A:
How do I get the selected video URL

You don't. And you don't need it. The PHImageManager gives you the video directly from the PHAsset, in various forms, depending what you want to do with it.
For example, if your goal is to play the video, call this method:
https://developer.apple.com/documentation/photos/phimagemanager/1616958-requestplayeritem


text:
Q: finding the integrating factor of $y \ dx+(x+3x^{3}y^{4}) \ dy = 0$ Let
$$M=y \; \mbox{and} \; N=x+3x^3y^4$$
We know that our integrating factor will be determined by
$$\mu = e^{\int g(x) \ dx}$$
$g(x)$ will be obtained by assuming that there is a general solution for the differential equation we are trying to solve. $g(x)$ is given by
$$\frac{\frac{\partial M}{\partial y}- \frac{\partial N}{\partial N}}{N}$$
$\Rightarrow \frac{1-(1+9x^2y^4)}{x+3x^2y^4}$
$\Rightarrow - \frac{9xy^4}{1+3x^2y^4}=g(x)$
so far so good, this means our integrating factor will be given by
$\mu = e^{\int \frac{-9xy^4}{1+3x^2y^4}dx}$
$\Rightarrow e^{-\frac{3}{2}ln(1+3x^2y^4)}$
$\Rightarrow \mu = \frac{1}{\sqrt{(1+3x^2y^4)^3}}$
the problem is that my textbook indicates that the integrating factor is $\frac{1}{(xy)^3}$ I can't seem to understand the mistake I'm making any help would be much appreciated

A: $$y \ dx+(x+3x^{3}y^{4}) \ dy = 0$$
$$ydx+xdy+3x^{3}y^{4}\ dy = 0$$
$$d(xy)+3x^{3}y^{4}\ dy = 0$$
The integrating factor is now obvious:
$$\mu (x,y)= \dfrac  1 {(xy)^3}$$
$$\dfrac {d(xy)}{x^3y^3}+3ydy=0$$
Integrate. The integrating factor given is correct. It depends on both $x$ and $y$ not only on $x$.
You can find the correct formula for this kind of integrating factor here at section 3 : Formula integrating factor


text:
Q: Using Amixer to control volume I'm running 14.04, and I was told I could use amixer to control volume via the command line. For example, to mute sound you would use
amixer set Master mute

The output for me is
amixer: Unable to find simple control 'Master',0

So I did some man reading and found out I needed to replace Master with the name of my laptop's mixer control. Typing amixer returns:
Simple mixer control 'IEC958',0
  Capabilities: pswitch pswitch-joined
  Playback channels: Mono
  Mono: Playback [off]

So naturally, I enter amixer set IEC958 mute but all I get is
Simple mixer control 'IEC958',0
  Capabilities: pswitch pswitch-joined
  Playback channels: Mono
  Mono: Playback [off]

Once again. I've tried sset and some other commands but every single one returns the same text. Also, why is there no "Master" or "Speaker" controls? Is there something I'm doing wrong?

A: If you want to use amixer to control the volume, this should work in a terminal:
amixer -D pulse sset Master 0%

(0% to mute or use any percentage you like)
To reduce/increase the volume, you can add - or + after % (but that doesn't work to increase the sound beyond 100%).

A: might be possible you use the wrong card.
make sure you use the right card. If you have attached a webcam with mic for example, then it might eat the first slot ;-)
list all cards first:
cat /proc/asound/card

for me itlooks like:
 0 [Webcam         ]: USB-Audio - Philips SPC 1030NC Webcam
                      Philips CE Philips SPC 1030NC Webcam at usb-orion-ehci.0-1.2, high speed
 1 [Audio          ]: USB-Audio - USB Audio
                      USB Audio at usb-orion-ehci.0-1.5.7, full speed

then chose your card. 1st card would be default -c 0, so if you want to chose the 2. card then do:
amixer -c 1 Master +10

A: I have found 3 useful commands:
amixer -D pulse sset Master 5%-
amixer -D pulse sset Master 5%+
amixer -D pulse sset Master toogle
Other 2 commands:
amixer -D pulse sset Master mute
amixer -D pulse sset Master unmute

A: amixer set IEC958,0 mute

You have to specify your card as shown in the amixer output. Use "unmute" instead of "mute" to turn the sound back on again.


text:
Q: Vue JS load dynamic component in element I have the code below:
let templateName = '#' + className + 'Properties';
const vue2 = {
               template: templateName,
               el: "#app2"
             };
var vm = new Vue(vue2).$mount();

Everytime, the variable className will have different value, so that template will be different everytime. Now once I mount the component for the first time, it works, but the same template mounts always even if the className is different.
Please guide

A: I solved it as below :
                    if (null !== vm) {
                        vm.$destroy();
                        vm.$el.remove()
                        vm = null
                    }

                    const vueContainer = document.createElement('div');
                    vueContainer.setAttribute("id", "app9");
                    $("#app2").append(vueContainer);

                    let templateName = '#' + className + 'Properties';
                    const vue2 = {
                        template: templateName,
                        el: "#app9"
                    };

                    vm = (new (Vue.extend(vue2))).$mount(vueContainer)


text:
Q: How to `conda install ipython`? System: Ubuntu 14.04, python 2.7.6, pip 1.5.4 from /usr/lib/python2.7/dist-packages (python 2.7). I am trying to setup my packages by conda because of this table here in my system.
I did successfully
sudo -H pip install auxlib
sudo -H pip install conda

I do successfully conda create -n my_root --clone=/usr. I run source activate my_root but I get
bash: activate: No such file or directory

I still run conda install ipython but I get eventually
Error: Missing write permissions in: /usr
#
# You don't appear to have the necessary permissions to install packages
# into the install area '/usr'.
# However you can clone this environment into your home directory and
# then make changes to it.
# This may be done using the command:
#
# $ conda create -n my_root --clone=/usr

How can you run conda install ipython?

A: You'll need to run at least conda install ipython as root (sudo).
The same likely applies to the other commands.


text:
Q: Do section names have to be globally unique in Doxygen? I am writing some overview documentation of modules in my application.  I mainly use the \page, \subpage, \section and \subsection tags.
The \page and \subpage tags allow me to give a nice hierarchical structure to the documentation, which is clearly visualized in the header of the web pages, or is used to build the table of contents when converted to Qt Help using QHelpGenerator.  Therefore, I understand that the pages should have unique names.
When I give my sections in my pages names like 'overview', 'introduction', 'section1', 'section2' and so on, it seems to work correctly when I build a subset of my documentation.  It seems that the section names don't have to be unique.
But, when I build a larger set of documentation files, some pages are not correctly created anymore.  Could this be caused by the section names that are not globally unique?
I tried to find information regarding the global-uniqueness of section names but I can't find any statement regarding uniqueness of section names.  Do they have to be globally unique?
EDIT:
I now notice that if one file has a section with id X and title A, and another file has section with id X and title B, that both get the same title in the generated documentation (A or B).  So this seems to indicate that the id's should be globally unique.  Is there a way to circumvent this?

A: Section names in doxygen are intended to be globally unique. This allows a section to be referenced (\ref) from any part of the documentation.
If you're only looking for a section heading (where the id isn't used/important), you could rely on one of the other mechanisms for specifying a header that Doxygen provides, for example:

*

*Use HTML tags for headers:

Header 1

Header 2

Header 3

*Use the Markdown representation of headers (assuming Markdown support is enabled):
Header 1
========

Header 2
--------

or
# Header 1
## Header 2
### Header 3


text:
Q: How to put labels/frequencies over geom_bar r in R with ggplot2 there. So, this is my code:
library(ggplot2); library(scales); library(reshape2);
da1 <- read.table(text = "NÃO SIM
5 1
24 44
",sep = "",header = TRUE)
da1m <- melt(cbind(da1, ind = rownames(da1)), id.vars = c('ind'))
da1m$Resposta <- c( "NÃO", "SIM", "NÃO", "SIM" )
names(da1m) <- c("Resposta", "variable", "value")

ggplot(da1m,aes(x = variable, y = value,fill = Resposta)) +
geom_bar(position = "fill",stat = "identity", colour = "black") +
scale_y_continuous(labels = percent_format())+
labs(title = "Gráfico 1", x="Gosta de utilizar o R",
    y="Há interessse em aprimorar os conhecimentos em R")+
scale_fill_manual(values=c("#E69F00", "#56B4E9"))+
geom_text(aes(label=value), position=position_dodge(width=0.9),
        vjust=-0.5)

And this is what I get:
geom_bar with label error
What am I doing wrong? The chart is strangely starting to be also in function of the geom_text when I try to add the frequencies.

A: For illustration, here are two different options for positioning text labels, but you can alter these as needed:
library(dplyr)

# Add two position locations for text labels (centered and top)
da1m = da1m %>% group_by(variable) %>%
  mutate(y.pos.ctr = cumsum(value) - 0.5*value,
         y.pos.top = cumsum(value))

ggplot(da1m, aes(x=variable, y=value, fill=Resposta)) +
  geom_bar(stat = "identity", colour = "black") +  # get rid of position="fill"
  #scale_y_continuous(labels = percent_format()) +  # y values don't seem to be percentages
  labs(title = "Gráfico 1", x="Gosta de utilizar o R",
       y="Há interessse em aprimorar os conhecimentos em R")+
  scale_fill_manual(values=c("#E69F00", "#56B4E9")) +
  geom_text(aes(label=value, y=y.pos.ctr), colour="white") +  # Centered value labels
  geom_text(aes(label=value, y=y.pos.top), colour="red")    # Value labels at top of each bar section


text:
Q: How can i use JQuery fadeTo() in IE 7? I am using jquery fadeTo() its working in chrome and firefox but not in IE 7. Below code is not working in IE 7..
I have fixed       table.nav td:have{ opacity:0.2;}
Run time i use jquery to change opacity 0.2 to 1.0
 $(document).ready(function() {

          $("table.nav td").hover(function() {

              $("table.nav td:hover").fadeTo("slow", 1.0);

          });

      });

A: I guess this is how you want it to work?
$(function() {
    $("table.nav td")
        .css("opacity", "0.2") //Doing this in jQuery is better cross browser than just opacity in CSS
        .hover(function() {
            $(this).fadeTo("slow", 1.0);
        },function() {
            $(this).fadeTo("slow", 0.2);
        });
});

Example: http://jsfiddle.net/wk74b/1/
That code works in IE7 for me.

A: I created a sample and it does work in IE 7. Check out demo here.
Agree with jAndy about opacity issue.
$(document).ready(function() {

        $("#hello").fadeTo("slow", 0.2);

        $("#hello").hover(function() {

                              $("#hello").fadeTo("slow", 1);

                            },
                            function ()
                            {
                              $("#hello").fadeTo("slow", 0.2);

                            }
          );
      });


text:
Q: UINavigationController acting funny after pushViewController UPDATE 2 I'm having a weird problem, I have a slide menu in my app, for some unknown reason every time that I go from one view to another using the .pushViewController instruction the navigation controller acts funny and it resets my UIBarButtonItems. (They change to their original tintcolor, and the badgeValue disappears).
This is the methods I'm using in the slide menu to do the transition:
func openViewControllerBasedOnIdentifier(_ strIdentifier:String){
    let destViewController : UIViewController = self.storyboard!.instantiateViewController(withIdentifier: strIdentifier)

    let topViewController : UIViewController = self.navigationController!.topViewController!

    if (topViewController.restorationIdentifier! == destViewController.restorationIdentifier!){
        print("Same VC")
    } else {
        var numeroProductos = String(Carrito.numProd)

        self.navigationController!.pushViewController(destViewController, animated: true)

    }
}

and
func slideMenuItemSelectedAtIndex(_ index: Int32) {
    let topViewController: UIViewController = self.navigationController!.topViewController!
    print("View Controller is : \(topViewController) \n", terminator: "")
    switch(index) {
    case 0:
        print("Home\n", terminator: "")

        self.openViewControllerBasedOnIdentifier("Home")

        break

    case 1:
        print("Play\n", terminator: "")

        self.openViewControllerBasedOnIdentifier("MiCuenta")

        break

    case 2:
        print("Play\n", terminator: "")

        self.openViewControllerBasedOnIdentifier("QuienesSomos")

        break

    case 3:
        print("Play\n", terminator: "")

        self.openViewControllerBasedOnIdentifier("NuestraCausa")

        break

    case 4:
        print("Play\n", terminator: "")

        self.openViewControllerBasedOnIdentifier("Contacto")

        break

    case 5:
        print("Play\n", terminator: "")

        self.openViewControllerBasedOnIdentifier("FAQ")

        break

    default:
        print("default\n", terminator: "")
    }
}

According to Apple's own documentation:

A UINavigationItem object manages the buttons and views to be
  displayed in a UINavigationBar object. When building a navigation
  interface, each view controller pushed onto the navigation stack must
  have a UINavigationItem object that contains the buttons and views it
  wants displayed in the navigation bar. The managing
  UINavigationController object uses the navigation items of the topmost
  two view controllers to populate the navigation bar with content.

But this is clearly not happening, the button is there in the interfase builder and it works when I land on that view without using the slide menu, but it disappears when I click any option of my slide menu.

This is the code I have on my viewDidLoad method on that view
override func viewDidLoad() {
    super.viewDidLoad()
    addSlideMenuButton()
    Carrito.numProd = productosCarrito.count
    print(productosCarrito.count)
    var numeroProductos = String(Carrito.numProd)
    navigationItem.rightBarButtonItem?.badgeValue = numeroProductos

}

If I reach the page without using the slidemenu (Like when you segue there after succesfully clearing the login view) the badgeValue is shown properly

But if I use the slide menu this happens

Any ideas on what could be causing this issue?
UPDATE
I discovered something.
If I insert this instruction either in the openVIewControllerBasedOnIdentifier method or in the slideMenuSelectedAtIndex
navigationItem.rightBarButtonItem?.badgeValue = "25"

The badgevalue gets changed to that number just before disappearing, I'm also using this instruction
print("Badge Value:\(navigationItem.rightBarButtonItem?.badgeValue as Any)")

so the value is there because I get this in the debug console:
Badge Value: Optional("40")

But for some unknown reason it disappears
UDATE 2
 self.navigationController!.pushViewController(destViewController, animated: false)

I Discovered that if I turn off animation the badgevalue doesn't disappear, but I need the animation to work too.

A: I found the solution and it's very simple actually, the avoid this behavior the badgeValue should be set in viewDidLayoutSubViews() instead of viewDidLoad()
override func viewDidLayoutSubviews() {
    var numeroProductos = String(Carrito.numProd)
    carritoButton.badgeValue = numeroProductos
}

EDIT MikeMTOL's library is buggy and causes a lot of problems not just this one so for Swift Users I recommend these extensions instead. -> link


text:
Q: IEnumerables behaving different when deleting Items from them in a For Each loop It is commonly known that removing items from an IEnumerable inside a For Each loop iterating over it is a really bad idea. I always thought that IEnumerable would throw an exception when you still try to do it.
However I noticed that List and TreeNodeCollection don't behave the same way, even though they both implement IList, ICollection and IEnumerable.
List behaves as I expected. The following code throws an InvalidOperationException:
Dim list As New List(Of String)

list.Add("Entry 1")
list.Add("Entry 2")
list.Add("Entry 3")
list.Add("Entry 4")
list.Add("Entry 5")

For Each entry As String In list
    list.Remove(entry)
Next

but TreeNodeCollection doesn't throw an exception in .NET 2 and deletes some of the Items, in .NET 4.5.2 the snippet throws a NullReferenceException:
Dim tree As New TreeView
Dim root As TreeNode = tree.Nodes.Add("Root")
root.Nodes.Add("Node 1")
root.Nodes.Add("Node 2")
root.Nodes.Add("Node 3")
root.Nodes.Add("Node 4")
root.Nodes.Add("Node 5")

For Each node As TreeNode In root.Nodes
    root.Nodes.Remove(node)
Next

Why is there such a different behaviour between two IEnumerables?

A: The IEnumerable interface doesn't have anything, either technically or via documentation, to say about modifications. There is nothing contractual that requires a collection that implements the interface to throw an exception if they are modified during enumeration.
It may be that some collections are perfectly capable of continuing enumeration even after modification. I.e. what they enumerate may be "the contents of the collection as it was when enumeration started", or they may offer some other guarantees about items which are added or removed after enumeration starts.

A: As a general rule, if you want to remove items you should make a copy first:
For Each entry As String In list.ToList()
    list.Remove(entry)
Next

Other options include:

*

*Using a backwards For loop. For i = list.Count-1 To 0 Step - 1

*Use LINQ to make a new list. list = list.Where(...).ToList


text:
Q: How to find a matrix declaration pattern in C I'm building a two-pass assembler in C.
A part of its job is to be able to work on matrices.
Let's say that there is the following line:
mov m[r2][r5], XYZ
mov is the operation.
and m[r2][r5] and XYZ are the operands.
I need to find out if an operand is a matrix. and get the:
1. matrix name.
2. row.
3. column.
How is it possible?
Tried to use sscanf without any success.
Thanks in advance!

A: Unfortunately writing an assembler is not as easy as using the scanf. Simplifying: You need to divide the input stream into the tokens, then you need to parse it and build the semantic tree, then you need to do the semantic analysis, reduce the tree (by evaluating constant expressions, finding addresses etc etc), and eventually generate the machine code.


text:
Q: How to add new key with value as Null in to the dynamic response body based on the condition I am validating output of the GET request with the data stored in the ms sql table using jdbc connection.
I would like to achieve below.
Output of my get request is like below
[
{
    "Id1": "9f3da555-136b-461d-a6d6-575c61599896",
    "Id2": "96135439-17f5-424c-9285-fc672b0626ac",
    "Id3": "da2e6593-381b-452b-9879-e61f5b97f97b",
    "Name": "abc",
    "name2": "xyz"
},

{
    "Id4": "9f3da555-136b-461d-a6d6-575c61599896",
    "Id5": "96135439-17f5-424c-9285-fc672b0626ac",
    "Id6": "da2e6593-381b-452b-9879-e61f5b97f97b",
    "Name": "abc1",
    "name2": "xyz1",
    "productName":"Amazon",
    "ProductFamily":"Mobile"
},
{
    "Id7": "9f3da555-136b-461d-a6d6-575c61599896",
    "Id8": "96135439-17f5-424c-9285-fc672b0626ac",
    "Id9": "da2e6593-381b-452b-9879-e61f5b97f97b",
    "Name": "abc3",
    "name2": "xyz3",
    "productName":"Amazon",
    "location":"India"
    }
    .............}

But my query output is
[
{
"Id1": "9f3da555-136b-461d-a6d6-575c61599896",
"Id2": "96135439-17f5-424c-9285-fc672b0626ac",
"Id3": "da2e6593-381b-452b-9879-e61f5b97f97b",
"Name": "abc",
"name2": "xyz"
"productName":null,
"ProductFamily":null,
"location":null
},
{
    "Id4": "9f3da555-136b-461d-a6d6-575c61599896",
    "Id5": "96135439-17f5-424c-9285-fc672b0626ac",
    "Id6": "da2e6593-381b-452b-9879-e61f5b97f97b",
    "Name": "abc1",
    "name2": "xyz1",
    "productName":"Amazon",
    "ProductFamily":"Mobile",
    "location": null
},
{
    "Id7": "9f3da555-136b-461d-a6d6-575c61599896",
    "Id8": "96135439-17f5-424c-9285-fc672b0626ac",
    "Id9": "da2e6593-381b-452b-9879-e61f5b97f97b",
    "Name": "abc3",
    "name2": "xyz3",
    "productName":"Amazon",
    "productFamily":null,
    "location":"India"
    }
    .............}

So I am looking for a solution where I can add ProductName, ProductFamily and location in the output of GET API call with value as null if the kay is not present in the object but if it is present like shown above in one of the json object then it should not change that value.
Can someone please guide me.


text:
Q: Hide divs based on number of check boxes checked with CSS or JS I want to hid divs based on number of check boxes checked. Div A is visible on page load while div B is hidden. If total number of checkboxes checked is equal 2 or great than 2 than i want to hide div A and show div B.
 <input class="iput" type="checkbox" name="E33" value="33" stock="20"/> A
    <input class="iput" type="checkbox" name="E34" value="33" stock="6"/>
    <input class="iput" type="checkbox" name="E646" value="33" stock="7"/>
    <input class="iput" type="checkbox" name="E46" value="33" stock="7"/>
    <input class="iput" type="checkbox" name="E626" value="33" stock="7"/>
    <input class="iput" type="checkbox" name="E656" value="33" stock="7"/>

 Hello

 BYE

  Total checked boxes=

Have constantly failed to achieve this. Currently i am able to count the total checked boxes but unable to find a way to use the total count to show and hide divs.
      function showChecked(){
        var length = document.querySelectorAll("input:checked").length,
        text = "Total Number of Items Selected = "

    document.getElementById("result").textContent = length;
        document.getElementById("final").value = length;
}
 document.querySelectorAll("input[type=checkbox]").forEach(i=>{
  i.onclick = function(){
  showChecked();
 }
});

A: Add a click event listener to each of the checkboxes to increment a counter variable and if the counter is more than or equal to 2, set the display property of the .a div to none and the .b div to block.
You can use a querySelector to get all of your checkboxes if you give them all the same name (like "E33"):
document.querySelectorAll("input[name=E33]");

To get all checked checkboxes with the name "E33", use the :checked selector:
document.querySelectorAll("input[name=E33]:checked").length;

<input class="iput" type="checkbox" name="E33" value="33" stock="20"/> A
<input class="iput" type="checkbox" name="E33" value="33" stock="6"/>
<input class="iput" type="checkbox" name="E33" value="33" stock="7"/>
<input class="iput" type="checkbox" name="E33" value="33" stock="7"/>
<input class="iput" type="checkbox" name="E33" value="33" stock="7"/>
<input class="iput" type="checkbox" name="E33" value="33" stock="7"/>

 Hello

 BYE

If you want to select your checkboxes by class:

<input class="input" type="checkbox" name="E33" value="33" stock="20"/> A
<input class="input" type="checkbox" name="E34" value="33" stock="6"/>
<input class="input" type="checkbox" name="E646" value="33" stock="7"/>
<input class="input" type="checkbox" name="E46" value="33" stock="7"/>
<input class="input" type="checkbox" name="E626" value="33" stock="7"/>
<input class="input" type="checkbox" name="E656" value="33" stock="7"/>

 Hello

 BYE

A: A function to scan all of your elements would be the easiest way.
In this example, I have created a function named getAmountChecked which scans all checkboxes with the class 'iput'. This then calculates how many there were, how many are checked and how many aren't checked; I like to have access to any important info when I check things like this. This comes in the form of an object with the values totalItems, totalChecked and totalUnchecked.
My function verifyInputs calls getAmountChecked and uses the value of totalChecked to determine which elements to show/hide.
<!DOCTYPE html>

       <input class="iput" onclick="verifyInputs('iput')" type="checkbox" name="E33" value="33" stock="20"/>
        <input class="iput" onclick="verifyInputs('iput')" type="checkbox" name="E34" value="33" stock="6"/>
        <input class="iput" onclick="verifyInputs('iput')" type="checkbox" name="E646" value="33" stock="7"/>
        <input class="iput" onclick="verifyInputs('iput')" type="checkbox" name="E46" value="33" stock="7"/>
        <input class="iput" onclick="verifyInputs('iput')" type="checkbox" name="E626" value="33" stock="7"/>
        <input class="iput" onclick="verifyInputs('iput')" type="checkbox" name="E656" value="33" stock="7"/>

 Hello

 BYE

A: This is, with caveats, possible entirely in CSS:
/* styling the
 element with a class of "a",
   the 'default' state and the state in which
   one of the <input> elements are checked: */
div.a,
input:checked~div.a {
  display: block;
}

/* styling the
 element with the class of 'b',
   and also the
 element with the class of 'a'
   when it's preceded by two <input> elements that
   are checked: */
div.b,
input:checked~input:checked~div.a {
  display: none;
}

/* finally we show the
 with a class of 'b'
   when it's preceded by two <input> elements
   both of which are checked: */
input:checked~input:checked~div.b {
  display: block;
}

div.a,
input:checked~div.a {
  display: block;
}

div.b,
input:checked~input:checked~div.a {
  display: none;
}

input:checked~input:checked~div.b {
  display: block;
}
<input class="iput" type="checkbox" name="E33" value="33" stock="20" />
<input class="iput" type="checkbox" name="E34" value="33" stock="6" />
<input class="iput" type="checkbox" name="E646" value="33" stock="7" />
<input class="iput" type="checkbox" name="E46" value="33" stock="7" />
<input class="iput" type="checkbox" name="E626" value="33" stock="7" />
<input class="iput" type="checkbox" name="E656" value="33" stock="7" />

 Hello

 BYE

JS Fiddle demo.
With the CSS above I've used the tilde (~) operator, the general-sibling combinator; this selects a following sibling element. The selector:
`input:checked ~ input:checked ~ div.b`

will match div.b if two, or more, <input> elements are checked.
This approach works. But, on to the caveats: if there are multiple groups of radio-buttons each group followed by the
 elements, checking <input> elements in the first group – by virtue of the ~ combinator – will also select, and style, the
 elements in the second group:

div.a,
input:checked~div.a {
  display: block;
}

div.b,
input:checked~input:checked~div.a {
  display: none;
}

input:checked~input:checked~div.b {
  display: block;
}
<input class="iput" type="checkbox" name="E33" value="33" stock="20" />
<input class="iput" type="checkbox" name="E34" value="33" stock="6" />
<input class="iput" type="checkbox" name="E646" value="33" stock="7" />
<input class="iput" type="checkbox" name="E46" value="33" stock="7" />
<input class="iput" type="checkbox" name="E626" value="33" stock="7" />
<input class="iput" type="checkbox" name="E656" value="33" stock="7" />

 Hello

 BYE

<input class="iput" type="checkbox" name="E33" value="33" stock="20" />
<input class="iput" type="checkbox" name="E34" value="33" stock="6" />
<input class="iput" type="checkbox" name="E646" value="33" stock="7" />
<input class="iput" type="checkbox" name="E46" value="33" stock="7" />
<input class="iput" type="checkbox" name="E626" value="33" stock="7" />
<input class="iput" type="checkbox" name="E656" value="33" stock="7" />

 Hello

 BYE

JS Fiddle demo.
To prevent this each of the 'groups' must be wrapped in an element to prevent the general-sibling combinator from matching elements in subsequent groups:

div.a,
input:checked~div.a {
  display: block;
}

div.b,
input:checked~input:checked~div.a {
  display: none;
}

input:checked~input:checked~div.b {
  display: block;
}

  <input class="iput" type="checkbox" name="E33" value="33" stock="20" />
  <input class="iput" type="checkbox" name="E34" value="33" stock="6" />
  <input class="iput" type="checkbox" name="E646" value="33" stock="7" />
  <input class="iput" type="checkbox" name="E46" value="33" stock="7" />
  <input class="iput" type="checkbox" name="E626" value="33" stock="7" />
  <input class="iput" type="checkbox" name="E656" value="33" stock="7" />

 Hello

 BYE

  <input class="iput" type="checkbox" name="E33" value="33" stock="20" />
  <input class="iput" type="checkbox" name="E34" value="33" stock="6" />
  <input class="iput" type="checkbox" name="E646" value="33" stock="7" />
  <input class="iput" type="checkbox" name="E46" value="33" stock="7" />
  <input class="iput" type="checkbox" name="E626" value="33" stock="7" />
  <input class="iput" type="checkbox" name="E656" value="33" stock="7" />

 Hello

 BYE

JS Fiddle demo.
Further, a common UI approach for <input> elements is to wrap them in a  element in order for a click on the text/content of the  to check/uncheck the check-box.
If these check-boxes are wrapped in a  then, predictably, the general-sibling combinator will be unable to select the
 elements based on the state of the <input> elements (see: "Is there a CSS parent selector?").  elements can, of course, appear as siblings (or any other relationship) to the <input> elements; although this requires that each <input> with a  in the document must have an id property in order for an association to be formed:

label {
  display: inline-block;
  width: 1.4em;
  height: 1.4em;
  text-align: center;
  line-height: 1.4em;
  box-shadow: 0 0 0 1px #000;
  border-radius: 0.2em;
  cursor: pointer;
  margin: 0 0.2em;
}

div.a,
input:checked~div.a {
  display: block;
}

div.b,
input:checked~input:checked~div.a {
  display: none;
}

input:checked~input:checked~div.b {
  display: block;
}
<form>
  <fieldset>
    <legend>All the labels</legend>
    <fieldset>
      <legend>One</legend>
      a
      b
      c
      d
      e
      f
    </fieldset>
    <fieldset>
      <legend>Two</legend>
      g
      h
      i
      j
      k
      l
    </fieldset>
  </fieldset>
  <fieldset>
    <legend>Group 1</legend>
    <input class="iput" type="checkbox" name="E33" value="33" stock="20" id="a">
    <input class="iput" type="checkbox" name="E34" value="33" stock="6" id="b">
    <input class="iput" type="checkbox" name="E646" value="33" stock="7" id="c">
    <input class="iput" type="checkbox" name="E46" value="33" stock="7" id="d">
    <input class="iput" type="checkbox" name="E626" value="33" stock="7" id="e">
    <input class="iput" type="checkbox" name="E656" value="33" stock="7" id="f">

 Hello

 BYE

  </fieldset>
  <fieldset>
    <legend>Group 2</legend>
    <input class="iput" type="checkbox" name="E33" value="33" stock="20" id="g">
    <input class="iput" type="checkbox" name="E34" value="33" stock="6" id="h">
    <input class="iput" type="checkbox" name="E646" value="33" stock="7" id="i">
    <input class="iput" type="checkbox" name="E46" value="33" stock="7" id="j">
    <input class="iput" type="checkbox" name="E626" value="33" stock="7" id="k">
    <input class="iput" type="checkbox" name="E656" value="33" stock="7" id="l">

 Hello

 BYE

  </fieldset>
</form>

JS Fiddle demo.
More sensibly, and to allow styling of those  elements to reflect the styling of the checked/unchecked nature of the <input> elements they would follow the elements (although it's perfectly valid to associate one <input> with multiple  elements, and in this demo I'm leaving the badly-placed original group in place to demonstrate that multiple  elements associated with a single <input> works):

label {
  display: inline-block;
  width: 1.4em;
  height: 1.4em;
  text-align: center;
  line-height: 1.4em;
  box-shadow: 0 0 0 1px #000;
  border-radius: 0.2em;
  cursor: pointer;
  margin: 0 0.2em;
}

/* styling the  adjacent to an <input>: */
input+label {
  color: #000;
  background-color: #fff;
}

/* styling the  adjacent to a checked <input>: */
input:checked+label {
  color: #fff;
  background-color: limegreen;
}

div.a,
input:checked~div.a {
  display: block;
}

div.b,
input:checked~input:checked~div.a {
  display: none;
}

input:checked~input:checked~div.b {
  display: block;
}
<form>
  <fieldset>
    <legend>All the labels</legend>
    <fieldset>
      <legend>One</legend>
      a
      b
      c
      d
      e
      f
    </fieldset>
    <fieldset>
      <legend>Two</legend>
      g
      h
      i
      j
      k
      l
    </fieldset>
  </fieldset>
  <fieldset>
    <legend>Group 1</legend>
    <input class="iput" type="checkbox" name="E33" value="33" stock="20" id="a">a
    <input class="iput" type="checkbox" name="E34" value="33" stock="6" id="b">b
    <input class="iput" type="checkbox" name="E646" value="33" stock="7" id="c">c
    <input class="iput" type="checkbox" name="E46" value="33" stock="7" id="d">d
    <input class="iput" type="checkbox" name="E626" value="33" stock="7" id="e">e
    <input class="iput" type="checkbox" name="E656" value="33" stock="7" id="f">f

 Hello

 BYE

  </fieldset>
  <fieldset>
    <legend>Group 2</legend>
    <input class="iput" type="checkbox" name="E33" value="33" stock="20" id="g">g
    <input class="iput" type="checkbox" name="E34" value="33" stock="6" id="h">h
    <input class="iput" type="checkbox" name="E646" value="33" stock="7" id="i">i
    <input class="iput" type="checkbox" name="E46" value="33" stock="7" id="j">j
    <input class="iput" type="checkbox" name="E626" value="33" stock="7" id="k">k
    <input class="iput" type="checkbox" name="E656" value="33" stock="7" id="l">l

 Hello

 BYE

  </fieldset>
</form>

JS Fiddle demo.
References:

*

*Combinators:

*

*Adjacent-sibling (+).

*General-sibling (~).

*:checked pseudo-class.


text:
Q: How to define URI for types of a certain resource Currently, I have an API for showing a list of spots using this route: GET /spots
I also have an API which gets the details for a certain spot: GET /spots/{spot-id}
Now, I will be making another API, which shows all the categories of the spots. Do you guys know of a proper way to go about with this?
So far I have decided on using GET /spots/categories but my manager said it was kind of weird for the spots resource to have categories.
His current suggestions are GET /spot-categories and GET /spotcategories.
Also, for reference, I have database tables spot and spot_category.
Thank you!

A: I tend to agree with your manager, your spotcategories look like a different entity altogether, so as a resource it deserves a separate url. That being said, if the goal is to find the categories for a particular spot (as opposed to simply browsing through the different available spotcategories), you should only be able to navigate to them through the spots (presuming your API is on level 3 of the Richardson Maturity Model). As in a link from the spots to the categories (or simply embed them, depending on the usage requirements).
So you might end up with something like
GET /spots/{spot-id}/categories


text:
Q: behave - Code coverage tool - System test We use behave for system test, where the test spawns containers and then run tests which invokes the REST API call and it actually fetches data from other microservices.
Now, how I can achieve the code coverage for this? For example:
the test sends a message on kafka, then kafka consumer handles the message and process the message and after doing some process on the message, it stores to DB.
I was using coverage tool to code coverage, but seems, it does not cover the part of code kafka consumer handling part and storing the db and all.
How I can achieve this? Is there any other tool I can use for system test based on behave?


text:
Q: how to store answer into a database I have created a multiple choice question and able to store them into a database, I need when a user select the correct answer it stores the id of the question and the answer. Please anyone who can help me how to do it
Here is my form for creating the questions
@foreach($qns as $qn)
   {{$qn->question_name}}

         <input type="radio" class="form-check-input" id="opt1"
           name="opt{{ $qn->id }}" value="a">{{$qn->opt1}}

          <input type="radio" class="form-check-input" id="opt2"
            name="opt{{ $qn->id }}" value="b">{{$qn->opt2}}

            <input type="radio" class="form-check-input" id="opt3"
             name="opt{{ $qn->id }}" value="c">{{$qn->opt3}}

             <input type="radio" class="form-check-input" id="opt4"
             name="opt{{ $qn->id }}" value="d">{{$qn->opt4}}

 @endforeach

Here is my controller
public function store(Request $request){
   // dd($request->all());
   $this->validate($request,[
      'question_id' =>'required|string',
      'opt'.$qn->id  =>'required|string',
   ]);

    $qn= Answer::create([
       'question_id'=>$request['question_id'],
       'opt'=>$request['opt'.$qn->id],

    ]);
}

A: Do it like
public function saveAnswers(Request $request)
{
    $questions = Questions::all();
    foreach($questions as $qns){
        $name = "opt".$qns->id;
        Answer::create([
            'question_id'=>$qns->id,
            'answer'=>$request->$name,

        ]);
    }
}


text:
Q: Helm not upgrading app to new version from my repo, even on recreating deployment I've created deployment with Helm
takayoshi@minikube:~$ sudo helm list
NAME                    NAMESPACE       REVISION        UPDATED                                 STATUS          CHART           APP VERSION
todo-app-1593610885     default         13              2020-07-01 13:56:28.395561055 +0000 UTC deployed        todo-app-1.0.0  1.0

As you can see my app has version 1.0 and chart is todo-app-1.0.0
I upgraded my chart in repository and helm search give me result
takayoshi@minikube:~$ sudo helm search repo todo-app
NAME            CHART VERSION   APP VERSION     DESCRIPTION
my/todo-app     1.1.0           1.1

After upgrade it gives me same version
takayoshi@minikube:~$ sudo helm upgrade todo-app-1593610885 todo-app
Release "todo-app-1593610885" has been upgraded. Happy Helming!
NAME: todo-app-1593610885
LAST DEPLOYED: Wed Jul  1 14:06:14 2020
NAMESPACE: default
STATUS: deployed
REVISION: 14
TEST SUITE: None
takayoshi@minikube:~$ sudo helm list
NAME                    NAMESPACE       REVISION        UPDATED                                 STATUS          CHART           APP VERSION
todo-app-1593610885     default         14              2020-07-01 14:06:14.103577369 +0000 UTC deployed        todo-app-1.0.0  1.0

Moreover if I delete and recreate mydeployment helm create with 1.0 version
takayoshi@minikube:~$ sudo helm uninstall todo-app-1593610885
release "todo-app-1593610885" uninstalled
takayoshi@minikube:~$ sudo helm install todo-app --generate-name
NAME: todo-app-1593612528
LAST DEPLOYED: Wed Jul  1 14:08:49 2020
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
takayoshi@minikube:~$ sudo helm list
NAME                    NAMESPACE       REVISION        UPDATED                                 STATUS          CHART           APP VERSION
todo-app-1593612528     default         1               2020-07-01 14:08:49.721404647 +0000 UTC deployed        todo-app-1.0.0  1.0

How can I upgrade my app?
My repo is https://krllevchenko.github.io/helm/index.yaml
apiVersion: v1
entries:
  todo-app:
  - apiVersion: v2
    appVersion: "1.1"
    created: "2020-07-01T16:27:45.9002382+03:00"
    digest: fc66ebe7b404abd2b0f6054afce68aa0ee6c6789188778eeb6e71a665e9ecf64
    name: todo-app
    type: application
    urls:
    - https://krllevchenko.github.io/helm/todo-app-1.1.0.tgz
    version: 1.1.0
  - apiVersion: v2
    appVersion: "1.0"
    created: "2020-07-01T16:27:45.899239+03:00"
    digest: 59e61c0009df31d4c37ab95dc027d910f176d0ce723d4ff3bab9ba854f4fa7af
    name: todo-app
    type: application
    urls:
    - https://krllevchenko.github.io/helm/todo-app-1.0.1.tgz
    version: 1.0.1
  - apiVersion: v2
    appVersion: "1.0"
    created: "2020-07-01T16:27:45.8982364+03:00"
    digest: 6daa536f5957584b7f40f7150f80e4b57ddc739e3016e21d2f14f9ca406ce4c9
    name: todo-app
    type: application
    urls:
    - https://krllevchenko.github.io/helm/todo-app-1.0.0.tgz
    version: 1.0.0
generated: "2020-07-01T16:27:45.8962467+03:00"

A: Since you are saving the chart of todo-app in a remote repository, I would suggest you have a local chart file, something like:
apiVersion: v2
name: my-local-chart
description: A Helm chart for Kubernetes
type: application
version: 0.1.0
appVersion: 1

dependencies:
- name: todo-app
  version: "1.1.0"
  repository: "https://krllevchenko.github.io/helm"

Then do a helm dependency update:
helm dependency update .

And then do a helm upgrade:
helm upgrade --install my-release .


text:
Q: heroku deploy error with static root path django. static_root not set to file system path my static files settings are improperly configured according to heroku when I attempt to deploy. I am without doubt this is false as I still lack understanding of the proper way to set up static files.
I have ran collect static on my machine and it did work. I will provide the information my ask is to help me clear this up. I am going to continue to research and hope to come with a solution.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#angular distro root
ANGULAR_APP_DIR = os.path.join(BASE_DIR, 'frontend/dist')

STATICFILES_DIRS = [
    os.path.join(ANGULAR_APP_DIR),

]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

these are my current root urls:
urlpatterns = [
    url(r'^$', serve, kwargs={'path': 'index.html'}),
    url(r'^(?!/?static/)(?!/?media/)(?P<path>.*\..*)$',RedirectView.as_view(url='/static/%(path)s', permanent=False)),
    url(r'api/',include(rootapi)),
]

A: Add STATIC_URL to your urlpatterns.
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # your url patterns
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


text:
Q: introduce a line break in a long equation \documentclass[12pt,twoside,a4paper,openright]{report}
\usepackage[portuguese]{babel}
\usepackage[utf8]{inputenc}
\usepackage[inner=3cm,outer=2cm,tmargin=2.0cm,bmargin=2.0cm, includefoot, includehead, headheight=15.8pt]{geometry}
\usepackage{mathtools}
\usepackage{amsmath}

\begin{document}
\begin{equation}
\label{equacao_silica}
\binom{\text{Quantidade}}{\text{Sílica (\% (w/w))}}
  = 100 - \left[\binom{\text{Perda de Massa}}{\text{(580\degree C-900\degree C)}
     \times \frac{100,1}{44}} - \binom{\text{Perda de Massa}}{\text{(30\degree C-200\degree C)}}
     -  \binom{\text{\% Resíduos}}{\text{GCC}} \right]\\
\end{equation}

\end{document}

How I can introduce a line break in this equation ?

A: For example (the presence of - at the end of line depends on typographic rules in your country):
\documentclass[12pt,twoside,a4paper,openright]{report}
\usepackage[portuguese]{babel}
\usepackage[utf8]{inputenc}
\usepackage{siunits} % added - PS
\usepackage[inner=3cm,outer=2cm,tmargin=2.0cm,bmargin=2.0cm, includefoot, includehead, headheight=15.8pt]{geometry}
\usepackage{mathtools}
\usepackage{amsmath}

\begin{document}
\begin{equation}
\label{equacao_silica}
\begin{aligned}
&\binom{\text{Quantidade}}{\text{Sílica (\% (w/w))}}
  = 100 - {}\\
&\qquad{} - \left[\binom{\text{Perda de Massa}}{\text{(580\degree C-900\degree C)}
     \times \frac{100,1}{44}} - \binom{\text{Perda de Massa}}{\text{(30\degree C-200\degree C)}}
     -  \binom{\text{\% Resíduos}}{\text{GCC}} \right]\\
\end{aligned}
\end{equation}

\end{document}

Probably some other environment, e.g. gathered, may be more suitable; aligned is only an example.

A: There are many possibilities for introducing a line break. A key step is not to use \left and \right to size the square brackets, since you can't have a line break across a \left-\right pair.
Here are two possible solutions, one using the multline environment, the other the split environment nested inside an equation environment.

\documentclass[12pt,twoside,a4paper,openright]{report}
\usepackage[portuguese]{babel}
\usepackage[utf8]{inputenc}
\usepackage[inner=3cm,outer=2cm,tmargin=2.0cm,bmargin=2.0cm, includefoot, includehead, headheight=15.8pt]{geometry}
\usepackage{mathtools}
%\usepackage{amsmath}  % is loaded automatically by 'mathtools'
\newcommand\degree{\ensuremath{^{\circ}}} %% correct this if necessary

\begin{document}
\begin{multline}
\label{equacao_silica}
\binom{\text{Quantidade}}{\text{Sílica (\% (w/w))}}
  = 100 - \biggl\{\binom{\text{Perda de Massa}}{\text{(580\degree C--900\degree C)}
     \times \frac{100,1}{44}} \\
- \binom{\text{Perda de Massa}}{\text{(30\degree C--200\degree C)}}
     -  \binom{\text{\% Resíduos}}{\text{GCC}} \biggr\}
\end{multline}

\begin{equation}\begin{split}
\label{equacao_silica}
\binom{\text{Quantidade}}{\text{Sílica (\% (w/w))}}
  &= 100 - \biggl\{\binom{\text{Perda de Massa}}{\text{(580\degree C--900\degree C)}
     \times \frac{100,1}{44}} \\
&\quad{}- \binom{\text{Perda de Massa}}{\text{(30\degree C--200\degree C)}}
     -  \binom{\text{\% Resíduos}}{\text{GCC}} \biggr\}
\end{split}\end{equation}

\end{document}

By the way, I think en-dashes (--) instead of single dashes should be used to indicate the temperature ranges.


text:
Q: Xcode not recognizing Unit Test I have the following test file. The strange thing is that when I hit CMD+U the test runs perfectly however there are no indications of the file being a test file (i.e. no diamonds on the left side of the code).

import XCTest
@testable import Saba_Center

class SabaCenterTests: XCTestCase {

    var residentAlimVC: ResidentAlimViewController!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.

        let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
        vc = storyboard.instantiateInitialViewController() as! ResidentAlimViewController
        _ = vc.view

    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

}

A: You don't have any tests to test. You need to make a test like the one it scaffolds for you.
e.g.:
func testExample() {
    // Put your test code here
}


text:
Q: HorizontalScrollView in View Pager I have view pager with list of child views. Every child is horizontal view. When horizontal view is not active view pager not scroll to the next page. If horizontal view is active then It scrolls horizontally but in horizontal scroll view. I need to scroll to next page of view pager if the horizontal view is not active. So I don't know where to handle this action and how to do it.

A:
The following is a complete example of how to implement a ViewPager with different fragment Types and different layout files.

Try This


text:
Q: Loading relation of new model in Laravel I just want to get hasOne relation of New model.
Can I load it before I will save it.
I have $user = new User(['order_id' => $order_id]);
How can I get $user->order; without build new request?

A: As others have already pointed out the model must be saved before retrieving any relations.
My usual approach for this is using lazy eager loading:
// Create new model with data
$newModel = Model::create([
    'column' => $value
]);

// Use load to retrieve any relations
return $newModel->load('myRelationship');


text:
Q: Can I get the url referral of the original referral website? is it possible to get the original referrer in php ie.
google.com -> yourwebsite.com -> mywebsite.com
is it possible to get google.com as url referer on mywebsite.com if a visitor click on google.com then yourwebsite.com then mywebsite.com
and can i know that the visitor originally came from google.com at the point of mywebsite.com
i am trying
session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

A: no, its not possible, http is by definition a stateless protocol

A: This is one really good question I have come across in recent times. Something, to be honest, which even I wondered this possibility sometime. Technically, 'No'. This simply cannot be done at the moment. Primarily because of the way HTTP is designed to work.
As @priyabrata pointed out earlier, HTTP is a stateless protocol.
To begin with, lets consider your example
You visit google.com and then from there you are directed to yourwebsite.com. Here, this request from google to the yourwebsite.com page and then page load response from yourwebsite.com completes one HTTP cycle. At this, point HTTP has is sitting stale. It has no strings attached with previous cycle. HTTP is simple waiting for another request to be made.
Now, when you go to mywebsite.com from yourwebsite.com, HTTP calls and exits one new HTTP cycle.


text:
Q: Применение события mousemove На https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event к переменной myPics применяется событие mousemove, а мне необходимо, чтобы вместо myPics фигурировал скроллбар (т.е. курсор мыши остановился бы на скроллбаре) , если я правильно понял событие mousemove (подробности см. на Получение координат курсора мыши после её передвижения. Обращение к скроллбару). Каким образом отследить момент, при котором курсор мыши переводится с левого бокового меню на скроллбар?
P.S. Создал новый вопрос, т.к. предыдущий стал довольно объемным. Прошу не минусовать, поскольку я новичок.

A: Есть вариант с определением координат мыши за пределом документа:

document.addEventListener("mousemove", function(e){
    if( document.querySelector('body').offsetWidth <= e.offsetX ){
      console.log('GOTCHA!')//если мышь вышла за пределы body, то срабатывает код на этом месте
    }
});
body {
    overflow-y: scroll;
    height: 200vh;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
</body>
</html>

Также вы можете попробовать сделать html-элемент, который с помощью js будет осуществлять прокрутку страницы (или другого элемента), а в CSS его поместить на место скроллбара задав абсолютное позиционирование, указав для этого элемента position: absolute, и свойства top, right, left, bottom, задать по длине всей страницы.


text:
Q: Python - how to refer main app's variable in app's modules I have following files' structure for Flask app (/env is virtual env):
/env
/env/bin/...
/env/include/...
/env/lib/...
/env/lib64/...
/env/myapp.py
/mymodules/__init__.py
/mymodules/users/__init__.py
/mymodules/users/controller.py

myapp.py has below content:
# -*- coding: utf-8 -*-

from flask import Flask
from flask import request, current_app
from flask.ext.sqlalchemy import SQLAlchemy
import mymodules.users.controller as MyMods

app = Flask(__name__)

db = SQLAlchemy(app)

# [...]

@app.route(u"/test", methods=['GET'])
def test():

    return MyMods.mytest()

if __name__ == u"__main__":
    app.run()

Content of controller.py
# -*- coding: utf-8 -*-

def mytest():
    return "ok"

Question: how can I use app and db inside controller.py?
I can pass it as param:
MyMods.mytest(app, db)

def mytest(app_ref, db_ref):

but is it the proper way of doing it?

A: You can pass it param as you did or could set module level variables:
# controller.py
some_var = None
def mytest():
    print(some_var)

# myapp.py
MyMods.some_var = db
...rest of your code...

As long as some_var gets set before mytest() gets called.


text:
Q: Polymorphism in action I have encountered some code in Java that I am not able to comprehend. It uses polymorphism in java.
public class MyAnimalList {
    private Animal[] animals = new Animal[5];
    private int nextIndex = 0;

    public void add(Animal a) {
        if (nextIndex < animals.length) {
            animals[nextIndex] = a;
            System.out.println("Animal added at " + nextIndex);
            nextIndex++;
        }
    }
}

public class AnimalTestDrive{
    public static void main (String[] args) {
        MyAnimalList list = new MyAnimalList();
        Dog a = new Dog();
        Cat c = new Cat();
        list.add(a);
        list.add(c);
    }
}

Here the reference variable a, which is referring to a dog object on the heap, is being passed to the add function. Now when the reference goes as an argument and received as a parameter as Animal a. My question starts from here, animals[0]=a, that is the animals[0] refers to object referred by a.
animals[1]=a that means it also points to the object referred by a, that is the same object.
Then how is the new dog-list created if all animal array references are pointing to the same object?

A: Dog a = new Dog();

Here, a is the reference to the Dog object.
This reference is passed to the add(Object a) method.
Here, a, which is a Dog reference variable, is cast into an Animal reference variable. But still does point to the same Dog object. though it is an Animal reference variable now. And that is passed and added to the list.
Dont get confused with the Dog a, and the add(Animal a).. These two a references are completely different. The Dog a, is cast into the Animal a when passed into the method. These two are not the same thing. You can name them what ever you want.
This is all possible because class Dog extends Animal.
Now, suppose there are 3 Dog objects
Dog a = new Dog();
Dog b = new Dog();
Dog c = new Dog();

And suppose in the Dog class, there is an instance variable String name;
So, for each Dog object, you can set different names.
a.setName("Tom");
b.setName("Dick");
c.setName("Harry");

Now you can add these to the list by,
list.add(a);
list.add(b);
list.add(c);

All the object references are cast into Animal references and added to the same list. But all of them refer to different objects. with different names in the Array.
Now, similarly, Cat class also extends Animal. Hence you can make Cat objects and cast them to Animal objects and then add them to the list too.
Thus, instead of just having a array of Dog objects, Dog[] or an array of Cat objects, Cat[], in which we can only put Dog objects, or Cat objects, we can take advantage of polymorphism, and make an array of the supercalss Animal and cast the subclass objects all into Animal superclass objects and then put them all in the array together. Both Cat and Dog objects stay in the list together.

A: There are two unrelated things named a. There's a local variable in the main method of one class and a parameter of the add method on another class. A local variable declared in a method is not visible outside that method, so the add method cannot see the a declared in the main method.
The code in main that calls the add method supplies a different object for each call, so the references are not pointing to the same object; the parameter of the add method is pointing to whatever was passed in. In the first call to add, the parameter a references the Dog referenced by the local variable a in the main method. In the second call to add, the parameter a references the Cat referenced by the local variable c.

A: you might be confused by the fat that in your main code you have the Dog variable 'a' and in your 'add' method also have a variable with the same name.
But i hope i can answer your question  the best way possible.
when you say

list.add(a);

what is actually happening is that when you call the method  you get a new Object that references the old one (this means that all changes you do to the object in the method will remain in the original object) and you can think of it just like a change --momentarily-- of name of your original variable.
That's means that when you say

list.add(c);
  what you have in your add method is  a Animal type Cat in the variable a.


text:
Q: find out url from given paragraph using regex c# can anyone help me find out url  from given paragraph  using regex c#
Note: Paragraph may contain string and url also
Input like this
"My website   http://www.google.com/myMail/1212  this is my favorite website"

out put looks:
My website http://www.google.com/myMail/1212 this is my favorite website

A: Stolen from here:
public string[] ExtractURLs(string str)
{
    // match.Groups["name"].Value - URL Name
    // match.Groups["url"].Value - URI
    string RegexPattern = @"<a.*?href=[""'](?<url>.*?)[""'].*?>(?<name>.*?)"

    // Find matches.
    System.Text.RegularExpressions.MatchCollection matches
        = System.Text.RegularExpressions.Regex.Matches(str, RegexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

    string[] MatchList = new string[matches.Count];

    // Report on each match.
    int c = 0;
    foreach (System.Text.RegularExpressions.Match match in matches)
    {
        MatchList[c] = match.Groups["url"].Value;
        c++;
    }

    return MatchList;
}

Googling can really pay off you know

A: Taken straight from RegexBuddy:
resultString = Regex.Replace(subjectString, @"\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]", "$0", RegexOptions.IgnoreCase);

Note that the protocol is mandatory.

A: Thank you Mr. M.edmondson
Googling helped me  , got the answer below
string FindUrl(string url)
{
    Regex r1= new Regex("((http://|www\\.)([A-Z0-9.-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})",    RegexOptions.Compiled | RegexOptions.IgnoreCase);

    MatchCollection mc = r1.Matches(url);
    foreach (Match m in mc)
    {
        url = url.Replace(m.Value, "" + m.Value + "");
    }
    return url;
}


text:
Q: Locating the terminal currently in use I need to write a script to test if I'm using the correct terminal and then print a message.
This is what I have so far:
if(???? == dev/pts/1)
  echo Access Granted. Welcome.
endif

I don't know how to use tty to find the terminal though.
Using csh.

A: In bash you can test as follows:
[[ `tty` = "/dev/pts/1" ]] && echo Access Granted. Welcome.

tty will generally output something like /dev/pts/1 or not a tty
As you mentioned, apparently in csh you can do as follows:
if ($tty == "pts/1") then
    echo Access Granted. Welcome.
endif


text:
Q: Problems building a world map showing population size in QGIS 2.10 using Cartogram plugin I am using the Cartogram plugin to build a world map showing population size. I have all required data in the attribute table.
My source layer  looks like this:

The plugin starts processing, but the output layer looks like nothing happened:

What could the problem be?
I  used this dataset for polygon layer and this  downloaded as a CSV file, with CRS 4326.

A: The QGIS cartogram plugin seem to work a bit fragile. I get cartograms for Europe, America and Africa, but the whole world seems to be too big for the plugin.
Alternatively, you can add the standalone program ScapeToad. It can read and write shapefiles, and has more tools to control the output. You can still load the result into QGIS:

I used the Natural Earth ne_110m_admin_0_countries shapefile, with the pop_est field for calculating. Make sure that all countries have positive values for that.
There are other ways to get cartograms with R:
https://www.r-bloggers.com/cartograms-with-r/
https://github.com/pvictor/topogRam
https://github.com/chxy/cartogram
but I have not yet tested those.

A: I agree with AndreJ - I've used scapetoad for a few years and it works really well (but slowly, for good results)
However, with the cartogram plugin, check out the "add demo layer" menu option. It adds a layer showing Danish regions. Running on this gives a valid result

I noticed that the demo uses a local UTM projection in meters. I think this is key. You're using a projection in degrees.
I was able to get a worldwide example to work, using the same example as AndreJ, but by reprojecting the shapefile to EASE Grid (epsg:3410) to get coordinates worldwide in meters, and using MapColour1 as the value (which has a fairly small range, 1-10 or so)

That's a hacky way to do it and i don't recommend it as the distortions will mess with the areas of the cartogram, but it does suggest the cause...
I think that the ratio of the area to the value is key to getting this plugin to work.
I think you might need to experiment with reprojecting/scaling the polygons and/or scaling your values up or down to get a decent result.


text:
Q: MERN Up/Down Vote Not Updating Without Browser Refresh I am studying the MERN stack and trying to build a forum app whereby comments can be up/downvoted. Via React, a parent component connected to a MongoDB through Express passes state(props) to a child component which then maps the props and also contains the logic for the up/down voting. The problem is after clicking to vote and the server responds to the fetch the state of the counter( {x.score} in the map method) is not updated without refreshing the browser.
Typically, updating state is pretty straightforward. However, my code has grown a bit unwieldy for my basic skills. My questions are: 1. how to alter this code so that the state of the counter updates without a manual browser refresh. 2. whether the overall architecture of this code is correct, i.e. should passing props to a child component be avoided in this case? should hooks and useEffect be used instead? Or, even should I alter the click logic in the return?
I had a hard time finding any comprehensive internet sources on MERN voting. Also, I would prefer to set up a example via stackblits or other, however, this code is dependent upon a mongoDB source and express server.
child component:
  constructor(props){
    super(props);
    this.state={
      comments: this.props.comments,
    }
  }
  upvote = (x) => {
    const user = accountService.userValue;
    if (user) {
      fetch(`http://localhost:4000/posts/comment/${x}/upvote`, {
        method: 'PUT',
        headers: {
           'Accept': 'application/json, text/plain, */*',
           'Content-Type': 'application/json'
        },
        body: JSON.stringify({user :user.id})
      })
        .then((res) => {
          if (res.success) {
            this.updateComment(res.comment);
          } else {
            console.log('oops: ' + res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      alert('Please sign up to vote!');
    }
  };
  updateComment = (updatedComment) => {
    let comments = [...this.props.comments];
    comments.forEach((comment, index) => {
      if (comment._id === updatedComment._id) {
        comments[index] = updatedComment;
      }
    });
    this.setState({ comments });
  };
    ...
  render(){
   return(
    ...
        {this.props.comments.map((x,y)=>(

{x.score}

              <i className={`fas fa-thumbs-up ${user && x.upvotedby.includes(user.id) ? 'upvoted' : ''}`} onClick={this.upvote.bind(this, x._id)}>
              <i className={`fas fa-thumbs-down ${user && x.downvotedby.includes(user.id) ? 'downvoted' : ''}`} onClick={this.downvote.bind(this, x._id)}>

 {x.comment_body}

              posted by {x.userName}
               on {moment(x.createdAt).format('MM/DD/YYYY')}

        ))}

A: You're updating the state comments, but when you go to render you're using this.props.comments.  Try using the comments in state to render.
You'll want to update two spots

*

*In your Render

...
{this.state.comments.map((x,y)=>(

...

*In your update

...
  updateComment = (updatedComment) => {
    let comments = [...this.state.comments];
...

If you don't change your update, the next update will clear the previous.


text:
Q: Why am I getting  expected error? class return{
        public static void main(String args[]){
            boolean t = true;
            System.out.println(" this is before");
            if (t) return;
            System.out.println(" this is not going to be printed on the screen");
    }
}

Here is my code and my command line brings

identifier expected error

Who can explain where the problem lies?

A: return is a java keyword and you cannot use it as class name, change it to Return or some other meaningful name


text:
Q: How to calculate storage required per node in a cluster setup with redundancy We have a cluster with 5 nodes where we store objects of different sizes with 3 copies for redundancy. I want to calculate the maximum storage I need to allocate for each node for a given number of objects and their sizes. How can I do it?

A: Try give memory and then limit the data that you wanna store in cache and see how much its all adding up to then you can determine how much you need for your store. Use max entries setting in the cache.


text:
Q: Identity for convolution of central binomial coefficients: $\sum\limits_{k=0}^n \binom{2k}{k}\binom{2(n-k)}{n-k}=2^{2n}$ It's not difficult to show that
$$(1-z^2)^{-1/2}=\sum_{n=0}^\infty \binom{2n}{n}2^{-2n}z^{2n}$$
On the other hand, we have $(1-z^2)^{-1}=\sum z^{2n}$.  Squaring the first power series and comparing terms gives us
$$\sum_{k=0}^n \binom{2k}{k}\binom{2(n-k)}{n-k}2^{-2n}=1$$
that is,
$$\sum_{k=0}^n \binom{2k}{k}\binom{2(n-k)}{n-k}=2^{2n}$$
My question: is there a more direct, combinatorial proof of this identity?  I've been racking my brains trying to come up with one but I'm not having much success.

A: It is possible to give a direct combinatorial proof, but it is quite difficult to find it.
One possibility is to use paths between points with integer coordinates and steps $(1,1)$ and $(1,-1)$.
1) $\binom{2n}{n}$ counts all paths from $(0,0)$ to $(2n,0)$.
2) $2^{2n}$ counts all paths starting from $(0,0)$ with $2n$ steps.
3) $\binom{2n}{n}$ counts all paths with $2n$ steps that never touch the  $x$-axis again after the start. (This one is not obvious, but can be proved
with a bijection.)
Now you can conclude that all paths are a concatenation of a path that returns a certain number of times to the $x$-axis and a path that never does.
Note that the main difficulty here was that the two binomial coefficients are interpreted differently.
Edited to add reference:
In Richard P. Stanley: Enumerative Combinatorics Volume 1, Chapter 1, Solution to exercice 2c the following reference is given:

The problem of giving a combinatorial proof was raised by P. Veress and solved by G. Hajos in the 1930s. A recent proof appears in D.J. Kleitman, Studies in Applied Math. 54 (1975), 289 - 292. See also M. Sved, Math. Intelligencer, vol.6, no. 4 (1984), 44-45.

But I have not looked to check which article gives the proof I have outlined above.

A: Here is another proof by Egecioglu. It was published as a technical report, not a journal paper, so it's not easy to find.

A: Here is another proof, one that I slightly prefer. I'll start with the hardest part.
Lemma. The number of all words of length $n$ in the alphabet $\{A,B\}$ such that no prefix (left factor) of it contains more letters $B$ than $A$, is $\binom n{\lceil n/2\rceil}$.
Instead of these words one may also take, interpreting $A$ as an up-step and $B$ as a down-step, paths as in the answer by Phira that never go below the horizontal axis; or one can formulate as ballot sequences as in Bertand's ballot problem, with the difference that we allow $B$ to catch up with $A$ without overtaking, and that the (non-negative) size of the eventual lead of $A$ is not fixed.
Proof. The following step can be applied to any word for which some prefix does contain more letters $B$ than$~A$: find the smallest prefix for which the majority of its letters $B$ over its letters $A$ is maximal among all prefixes, and change its last letter (which is a $B$) into $A$. There is an inverse step that can be applied to any word with more letters $A$ than letters $B$ (or more generally to a word for which some suffix (right factor) has this property): find the  smallest suffix for which the majority of its letters $A$ over its letters $B$ is maximal among all suffixes, and change its first letter (which is an $A$) into $B$. The easiest way to see that these are inverse operations is that the presence of subwords in the Dyck language for $\{A,B\}$ has no effect on these operations (in particular they will never change inside such words), and that what remains when ignoring such subwords is of the form $BB\ldots BAA\ldots A$, where the last $B$ respectively first $A$ will be changed. Now given a word of length $n$ with $\lceil n/2\rceil$ letters $A$ and  $\lfloor n/2\rfloor$ letters $B$, one can iterate the first operation until no prefix contains more letters $B$ than $A$, and conversely given a word of length $n$ satisfying that condition, if there are $d\geq0$ more letters $A$ than $B$ in all, one can iterate the reverse operation $\lfloor d/2\rfloor$ times to obtain a word of length $n$ with $\lceil n/2\rceil$ letters $A$ and  $\lfloor n/2\rfloor$ letters $B$. This bijection proves the lemma. QED
Now to prove the identity of the question, consider the words of length $2n+1$ in which the letters $A$ are in the majority; their number is $2^{2n+1}/2=2^{2n}$. Consider the longest prefix (possibly empty) in which there are as many letters $A$ as $B$; it has an even length $2k$, and given that length there are $\binom{2k}k$ possibilities for this prefix. The next letter is necessarily an $A$, and after that there is a suffix of length $2n-2k$ in which no prefix (of that suffix) contains more letters $B$ than $A$. By the lemma there are $\binom{2n-2k}{n-k}$ of them, whence the result.

A: There is also a probabilistic proof of this identity.
Start with an urn containing one red marble and one blue marble. Make a series of $n$ draws from the urn; for each draw, remove a random ball in the urn, then put it back, along with two extra balls of the same color. We then ask, what is the probability that exactly $k$ of the draws were red?
The probability that the first $k$ draws are red and the last $n-k$ are blue is
$$
\frac12\cdot\frac{3}4\cdot\frac5{6}\cdots\cdot\frac{2k-1}{2k}\cdot\frac1{2k+2}\cdot\frac{3}{2k+4}\cdots\frac{2(n-k)-1}{2n}=\frac{(2k-1)!!(2(n-k)-1)!!}{(2n)!!}
$$
where $n!!=\prod_{k=0}^{\lfloor n/2\rfloor-1}(n-2k)=n(n-2)(n-4)\cdots$.
It is not hard to see that every sequence of $k$ red and $n-k$ blue draws has this same probability; rearranging the order of draws just changes the order of the factors in the numerator. Therefore, the probability of $k$ red draws is, using the identities $(2n)!!=2^nn!$ and $(2k-1)!!=\frac{(2k)!}{(2k)!!}=\frac{(2k)!}{2^kk!}$,
$$
\binom{n}k\frac{(2k-1)!!(2(n-k)-1)!!}{(2n)!!}=\frac{\binom{2k}k\binom{2(n-k)}{n-k}}{2^{2n}}
$$
Since these probabilities must sum to $1$, the desired identity follows!


text:
Q: how can I search for file within a directory (and sub's) using bash shell, how can I search for a particular file in a folder (and its sub-folders)

A: find dirname -name "filename"

For example:
find /usr/bin -name "*sh"

would find all the files that end in "sh" in that directory.
Or:
find /usr/share/doc -iname "*readme*"

would find all files with "readme" in their names regardless of capitalization in that directory and its subdirectories.

A: There are two ways to do this.
If slocate is installed and the database is up to date you can use "locate pattern | grep /path/you/wish/tosearch"
This is faster than the find command if you're searching a large directory or directories.
The other more traditional method is using the find command as Dennis has already pointed out so I won't go into that one.


text:
Q: REST API - appropriate response statuses I'm designing a REST API. I would like to know what are the most appropriate http statuses in the 2 following scenarios:
A user tries to register and:

*

*Username already exists.

OR:

*Password and password repeat fields do not match.

Thanks.

A:
Username already exists

409 Conflict sounds correct for this situation.

Password or password repeat fields do not match

This is a general error on the client side. Use 400 Bad Request for this.
See https://en.wikipedia.org/wiki/List_of_HTTP_status_codes for more.

A: 409 status code is a good choice for a username that already exists:

6.5.8 409 Conflict
The 409 (Conflict) status code indicates that the request could not
be completed due to a conflict with the current state of the target
resource.  This code is used in situations where the user might be
able to resolve the conflict and resubmit the request.  The server
SHOULD generate a payload that includes enough information for a user
to recognize the source of the conflict.

400 status code is just fine for passwords that do not match:

6.5.1.  400 Bad Request
The 400 (Bad Request) status code indicates that the server cannot
or will not process the request due to something that is perceived
to be a client error (e.g., malformed request syntax, invalid
request message framing, or deceptive request routing).


text:
Q: In the DC Universe does Batman know that Clark Kent is Superman? In the DC universe, i.e the main DC continuity,has it ever been mentioned whether Batman knows that Clark Kent is actually Superman?

A: Yes, many times in different, always entertaining ways, they discover each other's identities.
My favorite is in All-Star Superman where superman gives clues to Batman to see if he can determine the identity and they each call out the other's secret... it's very similar to Adventures of Superman #440 that Richard posts above.
If you want, however, one of the arguably best Justice League stories of all time that deals heavily with secrets identities and all of the members knowing each other's identities, then you must read Frank Miller's Identity Crisis.

A: Yep. Depending on the continuity, they've known for a very long time. Let's not forget that Batman is the world's greatest detective and Superman has x-ray vision.
Superman #76

JLA: Trinity War

Adventures of Superman #440

Justice League: War

Justice League: Animated Series


text:
Q: Jumpy behavior on Android Using full width and full height on background images for sections of my site but I'm experiencing some jumpy behavior on Android. I'm using modernizr to detect touchevents and changing the background-attachment from fixed to local. Here is the site and below is the css that I'm using:
.intro, .behind-the-scenes, .the-scene, .the-stage, .contact {
    height: 100vh;
    min-width: 100%;
    color: $white;
    display: table;
    background-attachment: fixed;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}

// if a touchevent is detected

.touchevents {

    .intro, .behind-the-scenes, .the-scene, .the-stage, .contact {
        background-attachment: local;
    }
}

A: The problem was caused by these two properties combined with the Chrome for Android browser's behavior:
CSS:
.intro,
.behind-the-scenes,
.the-scene,
.the-stage,
.contact {
    height: 100vh;
    background-size: cover;
}

As the user scrolls down the browser's top toolbar will disappear, thus the five elements will gain height. Because the background-size is set to cover the image will have to quickly stretch as well.
SOLUTION
I couldn't test it on a mobile device, but adding transition to the height property might solve the issue.
.intro,
.behind-the-scenes,
.the-scene,
.the-stage,
.contact {
    -webkit-transition: height 0.2s linear;
    transition: height 0.2s linear;
}

If it doesn't help, there's a jQuery solution which would set the height of these elements on page-load and on window resize so the background wouldn't jump every time the top toolbar disappears.
jQuery:
(function($) {
    var elements = $('.full-height');

    function elementHeightFix() {
        var windowHeight = $(window).height();

        elements.each(function() {
            $(this).css('height', windowHeight);
        });

    }

    $(window).resize(function() {
        elementHeightFix();
    });

    elementHeightFix();
}(jQuery));

For the sake of simplicity I used a single selector, you can store the selectors in an object and iterate through them. Please note that I mainly use CoffeeScript and TypeScript, so my pure jQuery code might be messy.


text:
Q: Java generics - casting one generic to another Here's my code:
public class AnimationManager<STATE> {

private Map<STATE, Animation> animationMap = new HashMap<STATE, Animation>();

public void addAnimation(STATE state, BufferedImage[] frames, int frameDuration){
        animationMap.put(state, new Animation(frames, frameDuration));
}

public <E extends Enum<E>> void initAnimations(Player player, Constants.Heros chosen_hero, Class<E> heroStates){
        LinkedList<BufferedImage[]> frames = AssetsManager.getHeroGraphics(chosen_hero);

        assert frames != null;

        player.width = frames.get(0)[0].getWidth();
        player.height = frames.get(0)[0].getHeight();

        for(int i=0;i<frames.size();i++)
            addAnimation(heroStates.getEnumConstants()[i],frames.get(0),15);

}

}

At this line:
addAnimation(heroStates.getEnumConstants()[i],frames.get(0),15);

compiler shouts: Wrong 1st argument type, found 'E', required 'STATE'.
When initAnimations() method is in a different class (without STATE) it compiles and works like a charm. How is that possible that he doesn't want to get the first parameter and convert it to a STATE type?

A: The type parameter STATE are unbounded and can be invoked with any class. The type parameter E is bounded to be a subclass of Enum. The variable heroStates are a Class which means the getEnumConstants() method returns an array of E (which means an array of some subclass of Enum). That can not safely be cast to the type of STATE.
There are several ways to proceed from here, depending on your specific requirements. If casting can be avoided, that would be preferable.
If you know that STATE type parameter always is going to be an enum, you could put a bound on STATE and skip the type parameter E altogether:
class AnimationManager<STATE extends Enum<STATE>>
...
void initAnimations(Player player, Heros chosen_hero, Class<STATE> heroStates)

Otherwise, if you do not know that STATE is an enum, then you can avoid the class reflection exercise of getting the enum types by letting the caller of your initAnimations() method provide them:
void initAnimations(Player player, Heros chosen_hero, List<STATE> heroStates)
...
addAnimation(heroStates.get(i), frames.get(0), 15);

and the invocation would be something like
AnimationManager<Foo> animationManager = ...;
animationManager.initAnimations(null, null, Arrays.asList(Foo.values()));

The third option, which I really don't like, would be to cast. In that case you just need to change the problematic line to
addAnimation((STATE)heroStates.getEnumConstants()[i], frames.get(0), 15);

That will generate a warnings for an unchecked cast, which means the generics type system cannot guarantee that you're not ending up with ClassCastExceptions when you run your code.
Good luck with your game!