text:
Q: layout that forces vertical bar to always touch footer This fiddle...
http://jsfiddle.net/jeljeljel/5BSva/17/
Shows a layout I am trying to achieve.  I want the vertical bar from the base of the tab to extend to the footer.
Here is what I need to accomplish...

*

*In the initial state, no content is displayed, and the vertical bar correctly extends down to the footer.  The vertical bar should always extend to the footer.

*When you toggle the content to show, notice the vertical bar does not extend to the footer.  The vertical bar needs to extend to the footer.

*I want to accomplish this without the use of any image hacks.
Is there a way to change this fiddle so that the vertical bar always extends to the footer whether there is content that stretches the parent or not?
HTML

HEADER

Home

navigation

navigation

navigation

                    <button id="toggle">Toggle Content</button>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In congue odio quis libero dapibus ut tincidunt lectus vestibulum. Donec quis ligula tortor. Sed adipiscing tempor elit, at porttitor lacus luctus ut. Suspendisse suscipit, orci bibendum tincidunt venenatis, lorem ligula aliquet felis, in fringilla diam velit eu sapien. Aliquam vitae varius lacus. Nullam cursus nibh at leo varius vestibulum. Maecenas cursus dui quis metus hendrerit a lacinia est eleifend. Donec pharetra pharetra libero, non tincidunt magna fringilla in. Nulla convallis ornare dui, sed vestibulum turpis rutrum vestibulum. Duis convallis, eros nec vulputate congue, velit elit scelerisque purus, ut ultricies eros felis ac justo.

FOOTER

CSS
.body {
    border: 1px solid rgb(174, 174, 201);
    border-top: 5px solid rgb(174, 174, 201);
    border-bottom: 5px solid rgb(174, 174, 201);
    border-left: 2px solid rgb(174, 174, 201);
    border-right: 2px solid rgb(174, 174, 201);
    padding-bottom: 1000px;
    margin-bottom: -1000px;
}
/* Sticky Footer by Ryan Fait (http://ryanfait.com/) */
* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -50px auto;
    /* the bottom margin is the negative value of the footer's height */
    overflow: hidden;
}
.footer {
    height: 50px;
    background-color: red;
}
.footer, .push {
    height: 50px;
    /* .push must be the same height as .footer */
    clear: both;
}
form {
    height: 100%;
}
/* Sticky Footer by Ryan Fait (http://ryanfait.com/) */
.navigation {
    float: left;
    width: 150px;
    border-right: 3px solid rgb(174, 174, 201);
    padding-top: 10px;
    white-space: nowrap;
    position:absolute;
    bottom:50px;
    top:65px;
}
.content {
    padding-top: 10px;
    margin-left:160px;
}
.nav {
    margin-bottom: 0px;
}

JAVASCRIPT'

A: Is JS an option? I do this all the time:
Add an ID to your navigation and your content divs
$('#toggle').click(function () {
    $('#theContent').toggle(0,function(){
        $('#navigation').height($('#content').height());
    });
});

It would need a little finessing to work for you such as finding the minimum height when the text is hidden and picking up window resize events and adjusting accordingly, but it should work for you.


text:
Q: Logging Celery on Client/Producer This is not a question about how to capture logging on celery workers. Is there any way to capture celery logging on a Producer. What I want is to capture every log that get generated by celery on the Producer when I call task.delay(...) or task.apply_async(...).
EDIT:
I don't want to capture worker logs on producer. I want to capture everything that happen in celery from the time of my call to apply_async until the task is sent to the broker.

A: No, there is no way to capture worker logs on the producer. All you get is the exception, if thrown. Any logging is happening on the worker side, so you have to examine logs of that particular worker, or if you use some centralised log system then you have to look for logs from that worker...
Update: seems like you want to capture eventual logging from Celery on the producer (client) side. As far as I know Celery and the underlying transport handling library (Kombu) do not log anything. I could be wrong of course, but I can't remember seeing any logging there and I have read Celery (Kombu not that much to be fair) code many times...
A possible solution is to make Celery workers send logs to some centralised system that your Celery client can access...

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to repaint graphics after using a Keylistener? So my project is to create a shoot'em up type of game and i'd like that when i press arrows my square (that will after be the spaceship) change x;y position.
We managed to have a test that the keylistener works so we're sure that the problem comes from the repaint function.
Pls help, here's our code :
Class n°1
import java.awt.Color;

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.Dimension;

import javax.swing.JFrame;

public class Fenetre extends JFrame implements KeyListener {
Panneau pan = new Panneau();
  public Fenetre(){
    //nom de la fenetre
    this.setTitle("Projet");
    //taille
    this.setSize(450, 600);
    //centrer la fenetre
    this.setLocationRelativeTo(null);
    //Fenetre toujours en premier plan
    this.setAlwaysOnTop(true);
    //arrêt du processus à la fermeture de la fenêtre
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Fenetre non redimensionnable
    this.setResizable(false);
    //Couleur du fond
    this.setBackground(Color.DARK_GRAY);

    //Instanciation d'un objet JPanel
    JPanel pan = new JPanel();
    JPanel tir = new JPanel();
    //On prévient notre JFrame que notre JPanel sera son content pane
    this.setContentPane(new Panneau());

    this.setVisible(true);
    this.addKeyListener(this);
  }
@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    int c = e.getKeyCode();
        if(c==KeyEvent.VK_RIGHT){
            int x = pan.getPosX();
            x=x+10;
            pan.setPosX(x);
            pan.repaint();
            System.out.print("Droite ");}
        if(c==KeyEvent.VK_LEFT){
            int x = pan.getPosX();
            x=x-10;
            pan.setPosX(x);
            pan.repaint();
            System.out.print("Gauche ");}
        if(c==KeyEvent.VK_UP){
            int y = pan.getPosY();
            y=y+10;
            pan.setPosY(y);
            pan.repaint();
            System.out.print("Haut ");}
        if(c==KeyEvent.VK_DOWN){
            int y = pan.getPosY();
            y=y-10;
            pan.setPosY(y);
            pan.repaint();
            System.out.print("Bas ");}
        if(c==KeyEvent.VK_SPACE){
             this.setBackground(Color.CYAN);

        }

}
@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub
    int c = e.getKeyCode();
    if(c==KeyEvent.VK_SPACE){
         this.setBackground(Color.DARK_GRAY);}
}

 }

Class n°2
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;

import java.awt.Graphics;

import javax.swing.JPanel;

import java.awt.Graphics;
import java.awt.event.KeyListener;

import javax.swing.JPanel;

public class Panneau extends JPanel {

  public int posX = 450/2-15;
  public int posY = 500;

public void paintComponent(Graphics g){
    g.setColor(Color.red);
    g.fillRect(posX, posY, 30, 30);
    System.out.print("Carré ");
 }
  public int getPosX() {
    return posX;
  }
  public void setPosX(int posX) {
    this.posX = posX;
  }
  public int getPosY() {
    return posY;
  }
  public void setPosY(int posY) {
    this.posY = posY;
  }

}

And our main :
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Main extends JFrame {
public static void main (String [] Args){
    Fenetre fen = new Fenetre();

}}

PS: We're beginners so we might well have done a awful lots of things wrong

A: With
Panneau pan = new Panneau();

you are creating the instance of Panneau which is modified in the keyPressed method. But with
this.setContentPane(new Panneau());

you are adding a new instance of Panneau to the frame - this instance is not modified in the keyPressed method.
There are some other issues with the code, but the minimal change that is necessary to achieve the desired effect is to change this line to
this.setContentPane(this.pan);

In order to clear the background of the panel (that is, remove the previously painted rectangle) you also have to call super.paintComponent(g) in the first line of your paintComponent method:
public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setColor(Color.red);
    g.fillRect(posX, posY, 30, 30);
    System.out.print("Carré ");
}


text:
Q: Adding newline in google form created using Apps script I am fetching contents from Spreadsheet and adding it as items in form through Google Apps script. When I have a text in multiple lines (texts with new line breaks) in a cell, upon generating the form, it appears in a single line. I need to have it as exactly as I am giving in the sheet. Is there any way to achieve this using Apps script?
Here is the code I used to copy data from Sheet to crate item in form:
     var ss = SpreadsheetApp.openByUrl(mySheetURL);
     var sheet = ss.getSheets()[0];
     var cellRange = 'C2:C6'
     var ques = sheet.getRange(cellRange).getValues();
     var newForm = FormApp.openByUrl(myformURL);
     var QOD = newForm.addMultipleChoiceItem();
     QOD.setTitle(ques);

Content in my Spreadsheet Cell:

Content in form:

A: Apps Script retrieves and passes the line break as intended from Sheets to Form
The only problem is how you retrieve the values:

*

*cellRange[1][1] is not a valid request, because a range is a class, not a 2-D array.

*Opposed to it values indeed returns you a grid and you can retrieve the grid elements by their indices.
Mind that the indices start with [0], not with [1].

*Consequently getRange(cellRange).getValues()[1][1] would return you null because cellRange = 'C2:C6' contains only one column and it has the index [0].
Correct request:
     var ss = SpreadsheetApp.openByUrl(mySheetURL);
     var sheet = ss.getSheets()[0];
     var cellRange = 'C2:C6'
     var ques = sheet.getRange(cellRange).getValues()[0][0];
//also possible: var ques = sheet.getRange('C2').getValue();
     var newForm = FormApp.openByUrl(myformURL);
     var QOD = newForm.addMultipleChoiceItem();
     QOD.setTitle(ques);


text:
Q: Behavior of read function when child receive a sigstop signal Explanation of the program
The programs spawns n child process that are paused right after being created. After that, those child processes take turn to talk to the parent process via pipes.
They talk for a fixed amount of time (ex: should talk for a total of 20 times but stop when they've talked 7 times consecutively and pass to the next process)
Flow of the program

*

*Forking all the childs

*Pausing them right after their creation

*Waking them up by sending a signal

*Child write (for a fixed amount of time) to parent via pipe and then stop itself right after sending a signal to parent / Parent read content of pipe and write to STDOUT

*When parent receive signal change pipe to read other child and signal wake up the following child

The problem
The problem i'm facing is that when it is time to transition to the next process in order to listen to it, I don't get anything from the pipe of the following child even though I do write on the write-end of the pipe in the child process. Is there something I'm missing about SIGSTOP and SIGCONT when reading.
NB: I did read the docs
Program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <signal.h>

#define LOOP_SIZE 20;

/* SIG HANDLERS DEFINITION */
void parentsighandler(int);

/* GLOBAL VARIABLE DEFINITION */
pid_t n, ppid, wpid;
int nb_args,  read_return;

// array of pid_t to send signals to child
pid_t  *child_pids;

volatile sig_atomic_t status = 0;
volatile sig_atomic_t compteur = 0;

int main(int argc, char *argv[]){
    write(STDERR_FILENO, "** Begining the program\n", 24); // debug
    nb_args = argc - 1;
    if (nb_args >= 1 ){
        // Variable initialisation
        child_pids= malloc(nb_args * sizeof(pid_t));

        // String for sprintf
        char sstr[40];
        char rstr[40];
        char pidstr[23];
        char strichild[16];
        char strloopchild[10];

        // Initializing all the pipes for the processes
        int p[2 * nb_args];

        // getting the pid of the parent process
        ppid = getpid();
        sprintf(pidstr, "Pid of parent is : %d\n", ppid);
        write(STDERR_FILENO, pidstr, 23); // debug

        int i, j, stop_val;

        //Initializing all pipes
        write(STDERR_FILENO, "**Init pipes\n", 13); // debug
        for (i = 0; i < nb_args; i++){
            if (pipe(&p[2*i]) == -1){
                perror("Error : pipe failed");
                _exit(EXIT_FAILURE);
            }
        }
        write(STDERR_FILENO, "**end init pipes\n", 17); // debug
        write(STDERR_FILENO, "**Begin fork\n", 15); // debug
        for (i = 0; i <  nb_args; i ++){
            switch( n = fork()){
            case -1:
                perror("Error : fork failed");
                _exit(EXIT_FAILURE);
            case 0:
                /* CHILD */
                sprintf(strichild, "**In child n%d\n", i); // debug
                write(STDERR_FILENO, strichild, strlen(strichild)); // debug
                if (0 == (stop_val = atoi(argv[i+1]))){
                    perror("atoi failed");
                    _exit(EXIT_FAILURE);
                }
                sprintf(strichild, "stop_val is : %d\n", stop_val); // debug
                write(STDERR_FILENO, strichild, strlen(strichild)); // debug
                close(p[i*2]);
                for (j = 1; j <= 20 ; j++){
                    sprintf(strloopchild, "loop : %d\n", j); // debug
                    write(STDERR_FILENO, strloopchild , strlen(strloopchild)); // debug
                    if (j % stop_val == 0){
                        write(STDERR_FILENO, "I am  paused\n", 15); // debug
                        if ( kill(ppid, SIGUSR1) == -1){
                            write(STDERR_FILENO, "Could not kill\n",15); // debug
                        }
                        write(STDERR_FILENO, "Sent a sigusr1\n",15); // debug
                        kill(getpid(), SIGSTOP);

                    }
                    write(STDERR_FILENO, "In child : ",11);
                    sprintf(sstr, "J ecris sur l'entree %d du pipe\n", i*2+1);
                    write(STDERR_FILENO, sstr, strlen(sstr));
                    sprintf(sstr, "Je suis le proc %d : message %d\n", getpid(), j);
                    write(STDERR_FILENO, sstr, 40); // debug
                    write(p[i * 2 + 1], sstr, 40);
                    sleep(1);

                }
                close(p[i*2+1]);
                write(STDERR_FILENO, "**Exiting the child\n", 20); // debug
                _exit(EXIT_SUCCESS);

            default:
                /* PARENT - process scheduling */
                write(STDERR_FILENO, "**Parent - puting to sleep childs\n", 34); // debug
                child_pids[i] = n;
                kill(n, SIGSTOP);
                // Setting up the signal
                signal(SIGUSR1, parentsighandler);
            }
        }
        write(STDOUT_FILENO, "Debut de l'ordonnancement\n",26);
        char strpids[20];
        for (i = 0; i < nb_args; i++){
            sprintf(strpids, "id processus : %d\n", child_pids[i]);
            write(STDOUT_FILENO, strpids, 20);
        }
        char mystr[17];
        sprintf(mystr, "compteur : %d\n", compteur); // debug
        write(STDOUT_FILENO, mystr, 17); // debug
        kill(child_pids[compteur], SIGCONT);
        while(1){
            if (read(p[2 * compteur], rstr, 40) > 0) {
                write(STDOUT_FILENO,"P : ",5);
                write(STDOUT_FILENO, rstr, 40);
                sprintf(mystr, "compt value: %d\n", compteur); // debug
                write(STDOUT_FILENO, mystr, 17); // debug
            } else {
                write(STDERR_FILENO, "Erreur lecture\n", 15);
            }
            sleep(1);
        }

    } else {
        perror("Error : Not enough args\n");
        _exit(EXIT_FAILURE);
    }
    return 0;
}

void parentsighandler(int sig){
    if (sig == SIGUSR1){
        write(STDOUT_FILENO, "*************\n", 14);//debug
        write(STDOUT_FILENO, "P : going into sig handler\n", 28); // debug
        if (compteur == (nb_args - 1)){
            compteur = 0;
        } else {
            compteur ++;
        }
        kill(child_pids[compteur], SIGCONT);

        char strst[19];
        sprintf(strst, "P : compteur : %d\n", compteur); // debug
        write(STDOUT_FILENO, strst, 19); // debug
        write(STDOUT_FILENO, "*************\n", 14);//debug
    }
}


text:
Q: Smart folder: How to exclude all files and directories inside a folder with specific name I create a Smart folder to show all the files created today, but I want to exclude all the files inside any folders with a specific name.
Example:
- foobar
- - subfolder
- - - file1.doc
- - - file2.mp3
- - file3.doc
- - file4.mp3

I want to exclude all the files and directories inside any folders named  foobar.
Notice: also the files in the subfolders (foobar/subfolder/*)
I'm on macOS Sierra 10.12.2
How can do it?


text:
Q: Calculated column between two date fields but if one is blank use another date field I would like a calculation that gives the number of days between 2 dates (start date & end date) but if end date is blank I would like it to use todays date.  How can I set this formula up?

A: This should do the trick:
=IF(ISBLANK([EndDate]),DATEDIF([StartDate], Today(),"d"),DATEDIF([StartDate], [EndDate],"d"))


text:
Q: in Windows 10, How to configure Visual Studio Code to find the Python 3 interpreter? In Windows 10, How Visual Studio Code should be configured to find the Python 3 interpreter?
Visual Studio Code is not able to find the Python 3 interpreter.
I have added the Python extension, the Python extension at  https://marketplace.visualstudio.com/items?itemName=donjayamanne.python.
How settings.js should be changed to use Python?
Even if python.pythonPath in settings.js is changed to be led to python.exe, which is at "C:\Users<User>\AppData\Local\Programs\Python\Python36-32\python.exe",  if I select Python: Select Workspace Interpreter in the command palette, I get the message Please open a workspace to select the Python Interpreter. Why is this happening?

A: In the current directory where you open you VS Code, go to .vscode/settings.json and modify this line in the json file:
 {
    "python.pythonPath": "path_to_your_python_bin",
    # e.g., /home/myname/venv/bin/python3.7 or to a .exe file if you are on Windows
 }

A: I'm also using this  Python extension in Visual Studio Code on Windows 10.
Python is installed in C:\Python27\ and C:\Python36\ and both folders are added to the Windows PATH variable
With this setting VS Code should be able to find the Python interpreter. At least in my environment it worked well.
But VS takes the first interpreter it can find, which was in my case the Version 3.6. When I need 2.7 for a project I have to tell VS Code explicitely to use that one in the configration file settings.json
In VS Code press Ctrl, and then, in the right window add:
{
"python.pythonPath": "c:/python27/python.exe"
}

or whatever is the path to the Python interpreter on your PC.
This is also described in the Wiki under Manual Configuration.
Now, with this setting Python 2.7 was used.
Something that did not work was that the automatic detection of the Python versions and therefore I could also not choose the version I need with the Select an Interpreter command.

A: macOS

VSCode -> Preferences -> Settings -> scroll down to Python Configuration.

Click the pencil on the left of the configuration you'd like to use and click Copy Settings.
"python.pythonPath": "python3.6"

A: The Please open a workspace to select the Python Interpreter. error is simple.
I believe you've opened a VS Code window without selecting any folder.
As such, no workspace was opened, and workspace-specific settings cannot be set.
If you wish to set a default python interpreter for all workspaces, open settings with Ctrl+Shift+P, Preferences: Open User Settings and search for  Python: Default Interpreter Path. Otherwise, if you want to set it for only the current workspace, use Preferences: Open Workspace Settings.

In your case, you wish to set it to C:\Users<User>\AppData\Local\Programs\Python\Python36-32\python.exe. Though I would suggest using a virtual environment. If you edit settings.json directly instead of using the GUI:
{
  "python.defaultInterpreterPath": "C:\Users<User>\AppData\Local\Programs\Python\Python36-32\python.exe"
}

Detailed instructions can be found in the documentation "Manually specify an interpreter", including using environment variables as the interpreter's path.
Also, "python.pythonPath" has been deprecated. Therefore most other answers are outdated:

2021.6.0 (16 June 2021)
5. Added python.defaultInterpreterPath setting at workspace level when in pythonDeprecatePythonPath experiment. (#16485)
8. Show python.pythonPath deprecation prompt when in pythonDeprecatePythonPath experiment. (#16485)

2020.7.0 (16 July 2020)
9. Prompt users that we have deleted pythonPath from their workspace settings when in Deprecate PythonPath experiment. (#12533)

2020.5.0 (12 May 2020)
6. Do a one-off transfer of existing values for python.pythonPath setting to new Interpreter storage if in DeprecatePythonPath experiment. (#11052)
8. Added prompt asking users to delete python.pythonPath key from their workspace settings when in Deprecate PythonPath experiment. (#11108)
12. Rename string ${config:python.pythonPath} which is used in launch.json to refer to interpreter path set in settings, to ${config:python.interpreterPath}. (#11446)

2020.4.0 (20 April 2020)
13. Added a user setting python.defaultInterpreterPath to set up the default interpreter path when in Deprecate PythonPath experiment. (#11021)

A: Go to File/Preferences/Settings and find Python Configuration. This is where you manually change the configurations.
You can also select your interpreter from command palette. The following instructions are from DonJayamanne's Github.

Select the command Python: Select Workspace Interpreter from the command palette
Upon selecting the above command a list of discovered interpreters will be displayed in a quick pick list
Selecting an interpreter from this list will update the settings.json file automatically.

A: I also had this problem. I did what @jps said and it still didn't work, but then I changed my Environment Settings order so that Python36 precedes Python27, and it worked.

A: In my case I have seen the actual workspace you are working in override the File/Preferences/Settings (Windows) or Code/Preferences/Settings (Mac).
The solution was to manually edit the workspace file (usually in your home directory) or to create a new workspace and re-add your directory for your code.

A: Uninstall x64 version. and Install the x86 32bit version.  Exclude python from AV.  this should do the trick.  The Python extension. Be Sure to restart the VSCode each time.


text:
Q: MongoDB aggregation over a range I have documents of the following format:
[
  {
    date:"2014-07-07",
    value: 20
  },
  {
    date:"2014-07-08",
    value: 29
  },
  {
    date:"2014-07-09",
    value: 24
  },
  {
    date:"2014-07-10",
    value: 21
  }
]

I want to run an aggregation query that gives me results in date ranges. for example
[
  { sum: 49 },
  { sum:45 },
]

So these are daily values, I need to know the sum of value field for last 7 days. and 7 days before these. for example sum from May 1 to May 6 and then sum from May 7 to May 14.
Can I use aggregation with multiple groups and range to get this result in a single mongodb query?

A: You can use aggregation to group by anything that can be computed from the source documents, as long as you know exactly what you want to do.
Based on your document content and sample output, I'm guessing that you are summing by two day intervals.  Here is how you would write aggregation to output this on your sample data:
var range1={$and:[{"$gte":["$date","2014-07-07"]},{$lte:["$date","2014-07-08"]}]}
var range2={$and:[{"$gte":["$date","2014-07-09"]},{$lte:["$date","2014-07-10"]}]}
db.range.aggregate(
    {$project:{
         dateRange:{$cond:{if:range1, then:"dateRange1",else:{$cond:{if:range2, then:"dateRange2", else:"NotInRange"}}}},
         value:1}
    },
    {$group:{_id:"$dateRange", sum:{$sum:"$value"}}}
)
{ "_id" : "dateRange2", "sum" : 45 }
{ "_id" : "dateRange1", "sum" : 49 }

Substitute your dates for strings in range1 and range2 and optionally you can filter before you start to only operate on documents which are already in the full ranges you are aggregating over.


text:
Q: Conjugate of basic expression not simplified Why does Mathematica not simplify the following expression?
assumptions = {a \[Element] Reals, b \[Element] Reals, c \[Element] Reals}
FullSimplify[Conjugate[I a b + c (I b + c)], Assumptions -> assumptions]


text:
Q: Image overlay in react I need a help.
I am making a component using react Avatar (Material MUI - v5).
Initially, user profile avatar will be shown and when hovered over it then Edition will appear above user profile avatar and at the same time profile will be grayed out (sort of its opacity goes to 0.5).
I have solved it using react state hook. Is there a way to solve it using css (not external css file !!!).
This is my code.
import Avatar from "@mui/material/Avatar";
import IconButton from "@mui/material/IconButton";
import EditIcon from "@mui/icons-material/Edit";
import { useState } from "react";
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
const UserProfileCard = ({ imgUrl, uploadIconColor }) => {
  const [opacity, setOpacity] = useState(1);
  const onMouseEnterHandle = () => {
    setOpacity(0.3);
  };
  const onMouseLeaveHandle = () => {
    setOpacity(1);
  };
  return (
    <>
      <IconButton
        sx={{
          position: "absolute",
          "&:hover": {
            opacity: opacity,
            transition: "opacity 0.5s",
          },
          opacity: opacity,
          transition: "opacity 0.5s",
        }}
      >
        <Avatar src={imgUrl ? imgUrl : "/static/images/boy.jpg"} alt="User profile">
          {" "}
        </Avatar>
      </IconButton>
      <IconButton
        onMouseEnter={onMouseEnterHandle}
        onMouseLeave={onMouseLeaveHandle}
        sx={{
          opacity: 0,
          "&:hover": {
            opacity: 1,
            transition: "opacity 0.5s",
          },
        }}
      >
        <Avatar
          sx={{
            backgroundColor: "transparent",
          }}
        >
          <EditIcon
            sx={{
              color: uploadIconColor ? uploadIconColor : "#5B5B5B",
              position: "relative",
            }}
          />
        </Avatar>
      </IconButton>
    </>
  );
};
export default UserProfileCard;


text:
Q: How do I separate case ids from case values on a Discriminated Union? I want to build a dictionary from a list of items.
An item has the following definition:
type Item =
    | A of TotalPrice * Special
    | B of TotalPrice * Special
    | C of TotalPrice
    | D of TotalPrice

I want the keys of the dictionary to map to the case ids:
| A
| B
| C
| D

I would then have the values for the case id be a list.
How do I separate the case ids from the case values?
Example:
let dictionary = items |> List.map (fun item -> item) // uh...

Appendix:
module Checkout

(*Types*)
type UnitPrice = int
type Qty = int

type Special =
    | ThreeForOneThirty
    | TwoForFourtyFive

type TotalPrice = { UnitPrice:int ; Qty:int }

type Item =
    | A of TotalPrice * Special
    | B of TotalPrice * Special
    | C of TotalPrice
    | D of TotalPrice

(*Functions*)
let totalPrice (items:Item list) =
    let dictionary = items |> List.map (fun item -> item) // uh...
    0

(*Tests*)
open FsUnit
open NUnit.Framework

[<Test>]
let ``buying 2 A units, B unit, A unit = $160`` () =

    // Setup
    let items = [A ({UnitPrice=50; Qty=2} , ThreeForOneThirty)
                 B ({UnitPrice=30; Qty=1} , TwoForFourtyFive)
                 A ({UnitPrice=50; Qty=1} , ThreeForOneThirty)]

    items |> totalPrice |> should equal 160

A: Your data is badly defined for your use case. If you want to refer to the kinds of items by themselves, you need to define them by themselves:
type ItemKind = A | B | C | D

type Item = { Kind: ItemKind; Price: TotalPrice; Special: Special option }

Then you can easily build a dictionary of items:
let dictionary = items |> List.map (fun i -> i.Kind, i) |> dict

Although I must note that such dictionary may not be possible: if the items list contains several items of the same kind, some of them will not be included in the dictionary, because it can't contain multiple identical keys. Perhaps I didn't understand what kind of dictionary you're after.

A: If you want to create the dictionary with keys like A, B, C and D you will fail because A and B are constructors with type TotalPrice * Special -> Item and C and D are constructors of type TotalPrice -> Item. Dictionary would have to make a decision about type of keys.
Getting DU constructor name should be doable by reflection but is it really necessary for your case?
Maybe different type structure will be more efficient for your case, ie. Fyodor Soikin proposal.

A: Maybe the following will clarify somewhat why datastructure and code is no good, and as such also clarify that this mainly is not related to FP as indicated in some of the comments et al.
My guess is that the question is related to "how can this be grouped", and lo and behold, there is in fact a groupBy function!
(*Types*)
type UnitPrice = int
type Qty = int

type Special =
    | ThreeForOneThirty
    | TwoForFourtyFive

type TotalPrice = { UnitPrice:int ; Qty:int }

type Item =
    | A of TotalPrice * Special
    | B of TotalPrice * Special
    | C of TotalPrice
    | D of TotalPrice

let items = [A ({UnitPrice=50; Qty=2} , ThreeForOneThirty)
             B ({UnitPrice=30; Qty=1} , TwoForFourtyFive)
             A ({UnitPrice=50; Qty=1} , ThreeForOneThirty)]

let speciallyStupidTransformation =
    function
    | ThreeForOneThirty -> 34130
    | TwoForFourtyFive -> 2445

let stupidTransformation =
    function
    | A (t,s) -> "A" + (s |> speciallyStupidTransformation |> string)
    | B (t,s) -> "B" + (s |> speciallyStupidTransformation |> string)
    | C (t) -> "C"
    | D(t) -> "D"

let someGrouping = items |> List.groupBy(stupidTransformation)

val it : (string * Item list) list =

[("A34130",
    [A ({UnitPrice = 50;
         Qty = 2;},ThreeForOneThirty); A ({UnitPrice = 50;
                                           Qty = 1;},ThreeForOneThirty)]);
   ("B2445", [B ({UnitPrice = 30;
                  Qty = 1;},TwoForFourtyFive)])]

Yeah its still a bad idea. But its somewhat grouped uniquely, and may be misused further to aggregate some sums or whatever.
Adding some more code for that, like the following:
let anotherStupidTransformation =
    function
    | A(t,_) -> (t.UnitPrice, t.Qty)
    | B(t,_) -> (t.UnitPrice, t.Qty)
    | C(t) -> (t.UnitPrice, t.Qty)
    | D(t) -> (t.UnitPrice, t.Qty)

let x4y x y tp q =
   if q%x = 0 then y*q/x else tp/q*(q%x)+(q-q%x)/x*y

let ``34130`` = x4y 3 130
let ``2445`` = x4y 2 45

let getRealStupidTotal =
    function
    | (s, (tp,q)) ->
        (s|> List.ofSeq, (tp,q))
        |>  function
            | (h::t, (tp,q)) ->
                match t |> List.toArray |> System.String with
                | "34130" -> ``34130`` tp q
                | "2445" -> ``2445`` tp q
                | _ -> tp

let totalPrice =
    items
    |> List.groupBy(stupidTransformation)
    |> List.map(fun (i, l) -> i,
                    l
                    |> List.map(anotherStupidTransformation)
                    |> List.unzip
                    ||> List.fold2(fun acc e1 e2 ->
                         ((fst acc + e1) * e2, snd acc + e2)  ) (0,0))
    |> List.map(getRealStupidTotal)
    |> List.sum

val totalPrice : int = 160

might or might not yield some test cases correct.
For the above testdata as far as I can read the initial code at least is ok. The sum does get to be 160...
Would I use this code anywhere? Nope.
Is it readable? Nope.
Is it fixable? Not without changing the way the data are structured to avoid several of the stupid transformations...


text:
Q: Couchdb: Browser Access to list records I have just realised, all the curl commands being mentioned are able to be executed in the browser.
I can not seem to work out what is the correct command to get the output from a view.
My database is on iriscouch.
http://mysite.iriscouch.com/mydb/_design/myview

lists the view, but how do I run the view so that the records are displayed ?
Thanks - mcl

A: You need to insert _view into the url:
http://mysite.iriscouch.com/mydb/_design/mydesign/_view/myview


text:
Q: How can I deploy my Rank and Retrieve app in Bluemix team,
how can I deploy my "Rank and Retrieve" in bluemix. I already checked all possible links but those are either old or very confusing.
Please help.

A: Deploying an instance Retrieve and Rank in Bluemix is simply a matter of navigating to the Bluemix Catalog and selecting Retrieve and Rank. From here, you can choose a plan and create the service instance for Retrieve and Rank.
Once the service instance is created, you are provided a set of service credentials e.g. api url, username, and password. You can use these credentials the Retrieve and Rank API directly. If you application is also running in Bluemix, you can access the service credentials via the VCAP_SERVICES environment variable.


text:
Q: How to fill an array with 10 even integers following some user provided integer? Basically I just want to take the provided integer and fill the array with the 10 even integers that come after the input integer. For example, if the user inputs 10 then the resulting array would be {12, 14, 16, 18, 20, 22, 24, 26, 28, 30}. The current code I am using is below, and it produces an array of the correct magnitude but filled entirely with zeros ({0, 0, 0, 0, 0, 0, 0, 0, 0, 0}).
import java.util.*;

public class arrays {
    public static void main(String args[]) {

        int[] array = new int[10];

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter starting number: ");
        int number = sc.nextInt();

        for(int i = 0; i > number; i++) {
            if(i % 2 == 0) {
                array[i] = i;
            }
        }

        for(int element: array) {
            System.out.print(element + " ");
        }
    }
}

How do I generate the desired output array containing 10 even integers?

A: Since you want to add 10 numbers, you'll want to do something like
for (int i=0; i < 10; i++)
Which loops 10 times with i having the value of 0, 1, 2, ... 9. In the loop you can do something like array[i] = next_even_number+i*2; where next_even_number is the next even number after the user input to add the numbers.

A: Here is an answer which includes graceful failure for invalid input types and overflows of the int type maximum boundary. It also zero fills the result array upon detection of a failure to prevent an intermediate state from leaking.
import java.util.*;

public class arrays {
    public static void main(String args[]) {

        int[] array = new int[10];
        int number = Integer.MAX_VALUE;

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter starting number: ");

        try{
            number = sc.nextInt();
        }catch(InputMismatchException e){
            System.out.println("Invalid input detected - Not an integer");
            System.exit(0);
        }

        for(int i = 0; i < array.length; ++i) {

            if(number % 2 == 0){
                array[i] = (number + 2) + (2 * i);
            }else{
                array[i] = (number + 1) + (2 * i);
            }

            if(number > array[i]){
                System.out.println("Invalid input detected - overflow of type int!");
                Arrays.fill(array, 0);
                System.exit(0);
            }
        }

        System.out.println(Arrays.toString(array));
    }
}

A: The problem in your case is that for(int i = 0; i > number; i++) means
"do something as long as the 'i' is greater than number, so it will not even enter the loop as the i starts from 0 and the input number you put is greater than 0. Instead of this, try to do the following
int counter = 0;
int num = number;
while(counter < 10){
  num++;
  if(num%2 == 0){
     array[counter] = num;
     counter++;
  }
}

Use a while loop which will consider the amount of numbers greater than your input that are even (num%2==0) and assign to your array in the position of the current counter


text:
Q: Google map displayed but empty I want to display a Google map - however, the latter isn't filled (no Google's logo is shown, neither the cities, streets, etc.). There's no error in the console. Here is an illustration of the problem:

Sources
The following code is an extract. Tags like , etc. are not shown.

Question
It is a fake API key.
Why is the map empty and how can I fix the problem?

A: I would recommend loading the js file as:

This should ensure the deferred loading which I guess you were trying to achieve through the getScript call.
And define the initMap function at a script element in the head tag. Did the trick for me.

A: Please take the below code,

Let me know if you have any questions.

A: You need to generate an api key.
and replace the XYZ, in javascript call, by your key.

A: This is actually You Want. 1st You Must Add HTML, BODY Tags, then Must Import JQuery Plugin ($(document) is JQuery)
$(document).ready(function () {
        var map;
        $.getScript('https://maps.googleapis.com/maps/api/js?key=XYZ', initMap);
        function initMap() {
            var myOptions = {
            zoom: 12,
            center: new google.maps.LatLng(9.981496491854426, 76.30557754516597),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById('page-gaz-de-ville-map'), myOptions);
        }
    });


text:
Q: MySQL `BEFORE INSERT TRIGGER` how can I skip data insertion under condition?
Possible Duplicate:
MySQL Trigger to prevent INSERT under certain conditions

In MySQL BEFORE INSERT TRIGGER how can I skip data insertion under condition?
delimiter //
drop trigger if exists test_trigger //
create trigger test_trigger before insert on t
for each row
begin
  set @found := false;

  #Some code

  if @found then
    #How to skip the data insertion under condition?
  end if;
end   //

delimiter ;

A: Two solutions, both raise an error:

*

*Call non-existent stored procedure - CALL non_existent_proc()

*Use SIGNAL statement to raise the error (MySQL 5.5).

Example 1:
...
IF @found THEN
  CALL non_existent_proc();
END IF;
...

Example 2:
...
IF @found THEN
  SIGNAL SQLSTATE '02000' SET MESSAGE_TEXT = 'Wrong data';`
END IF;
...


text:
Q: Find and replace strings in file with $ selectors? I have a file and I'm looking to use () to select a piece of text, and the $1 and $2 respectivley to replace a string.
http://127.0.0.1:5080/tarballs/(.+)/(.+).tgz

https://registry.npmjs.org/$1/-/$1-$2.tgz

How can I do this in unix? I want to run a command like this:
$ regex-replace ./file.txt "http://127.0.0.1:5080/tarballs/(.+)/(.+).tgz" "https://registry.npmjs.org/$1/-/$1-$2.tgz"

A: You can use sed:
s='http://127.0.0.1:5080/tarballs/user/file.tgz'

sed -E 's~http://127\.0\.0\.1:5080/tarballs/(.+)/(.+.tgz)$~https://registry.npmjs.org/\1/-/\1-\2~' <<< "$s"

https://registry.npmjs.org/user/-/user-file.tgz

*

*DOT is special metacharacter in regex so it needs to be escaped, otherwise it will match any character.

*~ is used a regex delimiter in s (substitute) command of sed.

*-E is used for extended regex support.

*\1 and \2 are back-references of 2 captured groups.


text:
Q: Is it possible tpo use the excel weeksum function in SharePoint to return the week number from a date column? I am new to SharePoint and I know that in Excel you can use the WEEKSUM function to return the week number from a date column. Is it possible to do the same in SharePoint 2013? If so how can this be done please?

A: You'll need to create a new calculated column (GO TO: List settings>Create Column>Calculated Column).  Then use something like the formula in this article.  Watch out for fiddly brackets, sometimes you'll find you need one more than you think.

A: SharePoint only has a very basic set of Functions that work in Formulas.
WEEKNUM is not one of them.
For a complete list see: http://www.viewmaster365.com/365coach/#/Calculated_Column_Functions_List
The WEEKDAY function shows an example for an American Week Number is:


text:
Q: The second Insert does not work in my trigger I am trying to learn more about triggers and I wrote a simple SQL code in MySQL.
This code will work with one insert but it will cause an error when I add the second insert.
I think the code that I wrote does not compile the second insert.
I would be appreciate for Any Help
Code:
create trigger MasterInputTRG
after insert on MasterInput
for each row
   insert into NewEMCtestPLAN(ProjectNumber,Manufacture,ModelName,`PO Number`,AccountExecutive,AENotes) values(NEW.ProjectNumber,NEW.Applicant,NEW.ModelName,NEW.PONumber,NEW.AccountExecutive,NEW.AENotes);
   insert into NewRF(ProjectNumber,Applicant,ModelName,PONumber,AccountExecutive,AENotes) values(NEW.ProjectNumber,NEW.Applicant,NEW.ModelName,NEW.PONumber,NEW.AccountExecutive,NEW.AENotes);

Error:

Syntax error near 'insert into
  NewEMCtestPLAN(ProjectNumber,Applicant,ModelName,PONumber,AccountExe'
  at line 5

Update:
I got an answer and I add the other code with errors here.:
Second Code that does not work:
create trigger MasterInputTRG
after insert on MasterInput
for each row
BEGIN
   insert into NewEMCtestPLAN(ProjectNumber,Manufacture,ModelName,`PO Number`,AccountExecutive,AENotes) values(NEW.ProjectNumber,NEW.Applicant,NEW.ModelName,NEW.PONumber,NEW.AccountExecutive,NEW.AENotes);
   insert into NewRF(ProjectNumber,Applicant,ModelName,PONumber,AccountExecutive,AENotes) values(NEW.ProjectNumber,NEW.Applicant,NEW.ModelName,NEW.PONumber,NEW.AccountExecutive,NEW.AENotes);
END

Errors:

Error in query (1054): Unknown column 'NEW.ProjectNumber' in 'field
  list'

But this error did not appear when i used the new.projectnumber in first insert.
second error:

Error in query (1064): Syntax error near 'END' at line 1

A: You should add Begin End in the trigger.
create trigger MasterInputTRG
after insert on MasterInput
for each row
   BEGIN
   insert into NewEMCtestPLAN(ProjectNumber,Manufacture,ModelName,`PO Number`,AccountExecutive,AENotes) values(NEW.ProjectNumber,NEW.Applicant,NEW.ModelName,NEW.PONumber,NEW.AccountExecutive,NEW.AENotes);
   insert into NewRF(ProjectNumber,Applicant,ModelName,PONumber,AccountExecutive,AENotes) values(NEW.ProjectNumber,NEW.Applicant,NEW.ModelName,NEW.PONumber,NEW.AccountExecutive,NEW.AENotes);
   END

A: A trigger body with multiple statements need to be surrounded bei BEGIN and END. But then (depending on your client) you might need to change the delimiter:
delimiter //

create trigger MasterInputTRG
after insert on MasterInput
for each row
begin
   insert into NewEMCtestPLAN (...) values (...);
   insert into NewRF (...) values (...);
end //

delimiter ;

The same applies to stored procedures and functions.
Note that the CREATE TRIGGER statement is a single.. well.. statement. Statements are delimited by.. well.. a delimiter. So in your original query the trigger definition ends with the first delimiter (;):
create trigger MasterInputTRG
after insert on MasterInput
for each row
   insert into NewEMCtestPLAN (...) values (...); -- trigger ends here
-- anything else is outside the trigger
   insert into NewRF (...) values (...);

The second insert could be a valid statement but outside the trigger definition. However I would expect a different error message like: unknown table (alias) 'NEW', because NEW is not known outside the trigger.
Now if we change the delimiter to //, the create statement ends after the first occurance of //, so we can use ; in the trigger body without terminating the CREATE statement.
Usually // or $$ are used for a delimiter. You can try something else, but it should not have any meaning in (My)SQL. For example | is a bit operator.


text:
Q: Distance between a set of points and a polygon with sf in R I have a dataframe of points on map and an area of interest described as a polygon of points. I want to calculate the distance between each of the points to the polygon, ideally using the sf package.
library("tidyverse")
library("sf")

# area of interest
area <-
  "POLYGON ((121863.900623145 486546.136633659, 121830.369032584 486624.24942906, 121742.202408334 486680.476675484, 121626.493982203 486692.384434804, 121415.359596921 486693.816446951, 121116.219703244 486773.748535465, 120965.69439283 486674.642759986, 121168.798757601 486495.217550029, 121542.879304342 486414.780364836, 121870.487595417 486512.71203006, 121863.900623145 486546.136633659))"

# convert to sf and project on a projected coord system
area <- st_as_sfc(area, crs = 7415L)

# points with long/lat coords
pnts <-
  data.frame(
    id = 1:3,
    long = c(4.85558, 4.89904, 4.91073),
    lat = c(52.39707, 52.36612, 52.36255)
    )

# convert to sf with the same crs
pnts_sf <- st_as_sf(pnts, crs = 7415L, coords = c("long", "lat"))

# check if crs are equal
all.equal(st_crs(pnts_sf),st_crs(area))

I am wondering why the following approaches do not give me the correct answer.
1.Simply using the st_distance fun-doesn't work, wrong answer
st_distance(pnts_sf, area)

2.In a mutate call - all wrong answers
pnts_sf %>%
  mutate(
    distance = st_distance(area, by_element = TRUE),
    distance2 = st_distance(area, by_element = FALSE),
    distance3 = st_distance(geometry, area, by_element = TRUE)
  )

However this approach seems to work and gives correct distances.
3.map over the long/lat - works correctly
pnts_geoms <-
  map2(
    pnts$long,
    pnts$lat,
    ~ st_sfc(st_point(c(.x, .y)) , crs = 4326L)
  ) %>%
  map(st_transform, crs = 7415L)

map_dbl(pnts_geoms, st_distance, y = area)

I'm new to spatial data and I'm trying to learn the sf package so I'm wondering what is going wrong here. As far as i can tell, the first 2 approaches somehow end up considering the points "as a whole" (one of the points is inside the area polygon so i guess that's why one of the wrong answers is 0). The third approach is considering a point at a time which is my intention.
Any ideas how can i get the mutate call to work as well?
I'm on R 3.4.1 with
> packageVersion("dplyr")
[1] '0.7.3'
> packageVersion("sf")
[1] '0.5.5'

A: So it turns out that the whole confusion was caused by a small silly oversight on my part. Here's the breakdown:

*

*The points dataframe comes from a different source (!) than the area polygon.

*Overseeing this I kept trying to set them to crs 7415 which is a legal but incorrect move and led eventually to the wrong answers.

*The right approach is to convert them to sf objects in the crs they originate from, transform them to the one the area object is in and then proceed to compute the distances.

Putting it all together:
# this part was wrong, crs was supposed to be the one they were
# originally coded in
pnts_sf <- st_as_sf(pnts, crs = 4326L, coords = c("long", "lat"))

# then apply the transformation to another crs
pnts_sf <- st_transform(pnts_sf, crs = 7415L)

st_distance(pnts_sf, area)

--------------------------
Units: m
          [,1]
[1,] 3998.5701
[2,]    0.0000
[3,]  751.8097


text:
Q: How to make request in Android equivalent to these curl commands I've developed an API in Flask for a project in Android but I don't know how to call the service and get data back from it.
The examples that I have seen don't tell me anything about including username and passwords and data like I would do with curl.
I have tried following these but I keep getting lost:

*

*https://stackoverflow.com/a/6977616/4517985

*http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
I'm looking for the Android way of executing these curl commands:
curl -u miguel:python -i -X GET localhost/api/resource
curl -i -X POST -H "Content-Type: application/json" -d '{"username":"miguel","password":"python"}' localhost/api/users


text:
Q: Way to simulate hardware key press event I have custom InputMethod that have a BroadcastListener in it. When the listener catches an intent in onReceive() method I call the onKey method of my InputMethod and in that way I simulate a key press from the softkey board. If I call onKeyDown or onKeyUp then I simulate the hardware keyboard. So this is a solution that I dont like.
Yesterday I found this:
http://mylifewithandroid.blogspot.com/2009/01/generating-keypresses-programmatically.html
Is it a good idea to use Instrumentation.sendKeyDownUpSync to simulate key press and it is working perfectly, I don't even need to implement my own InputMethod. I mean this Instrumentation is provided for testing purpose as I understand.
Is it a good idea to be used in way I do?

A: I think it's too much to use your own IME to test your application.
You already have a way to do it with Android's Instrumentation.
You can also check Robotium which might be useful for what you are trying to test.


text:
Q: How to set layout dynamically in android Well, Suppose there is an Activity called MainActivity and there are two layouts called layout1 and layout2 both have few buttons. By default MainActivity layout is layout1 like following:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout1);

Now what I did actually is by clicking a button in layout1 the second layout is set like following:
    someBtn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.layout2);
        }
    });

There are another button in layout2 to return back to layout1 like following:
    someBtn2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.layout1);
        }
    });

Problem is when I returned back to layout1 then  OnClickListener of someBtn1 is not working. It seems I need to set OnClickListener again for someBtn1 of layout1.
How I can write code to make them work perfectly with best practices ?

A: If you just want to play around with your current code, a solution for your problem is that the listeners must be redeclared when the layout changes, as follows:
someBtn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        setContentView(R.layout.layout2);

        someBtn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setContentView(R.layout.layout1);
            }
        });
    }
});

someBtn2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        setContentView(R.layout.layout1);

        someBtn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setContentView(R.layout.layout2);
            }
        });
    }
});

An alternative to avoid declaring the listeners twice is to declare two methods to handle the layout changes and use the onClick property of the button in each of the layouts, for example:
public void setLayout1(View view) {
    setContentView(R.layout.layout1);
}

public void setLayout2(View view) {
    setContentView(R.layout.layout2);
}

In layout1.xml:
<Button
    android:id="@+id/someBtn1"
    android:onClick="setLayout2"/>

In layout2.xml:
<Button
    android:id="@+id/someBtn2"
    android:onClick="setLayout1"/>

However, if you want to follow best practices, the best practice is not to mix layouts in the same activity, but instead declare two different activities (each one with its own layout) and call one activity or the other depending on the button that was clicked. Suppose that you are in Activity1 and want to call Activity2, then go back to Activity1:
In Activity1.java:
someBtn1.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         startActivity(new Intent(this, Activity2.class));
     }
 });

In Activity2.java:
someBtn2.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         finish();
     }
 });

A: The best practice is to use fragments instead of change the content view.
In your code, setContentView with layouts recreate (inflate) all your views every time, so the call setContentView(R.layout.layout1) in someBtn2 click listener will create a new button without the associated listener.
If you don't want to use fragments you can do this:
private View view1, view2;

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  view1 = getLayoutInflater().inflate(R.layout.layout1, null);
  view2 = getLayoutInflater().inflate(R.layout.layout2, null);
  setContentView(view1);

The listeners will be:
someBtn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        setContentView(view2);
    }
});

someBtn2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        setContentView(view1);
    }
});

A: One way of doing this is loading both views in onCreate(...), and then switching between them by making the one you don't want invisible.  Something like the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    LayoutParams default_layout_params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    View view1 = inflater.inflate(R.layout.layout1, null);
    addContentView(view1, default_layout_params);
    View view2 = inflater.inflate(R.layout.layout2, null);
    addContentView(view2, default_layout_params);
    view2.setVisibility(View.INVISIBLE);
    view1.setVisibility(View.VISIBLE);
    view1.bringToFront();

A: At the time you callback layout1, data must be set again.
You could merge both layouts in one and then use ViewFlipper to switch between them.

A: When you are seting layout2, you should also set up OnClickListener to someBtn1 and vice versa, I'd suggest something like this. But as in prevoius answer, in general you should avoid mixing layouts in such manner.
public class MainActivity extends Activity {

    private final View.OnClickListener setLayout1Listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           setContentView(R.layout.layout2);
           ((Button)findViewById(R.id.Btn2Id)).setOnClickListener(setLayout2Listener);
           //do other stuff
        }
    };

    private final View.OnClickListener setLayout2Listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           setContentView(R.layout.layout1);
           ((Button)findViewById(R.id.Btn1Id)).setOnClickListener(setLayout1Listener);
           //do other stuff
        }
    };

    @Override
    public void onCreate(final Bundle savedInstance) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout1);
        ((Button)findViewById(R.id.Btn1Id)).setOnClickListener(setLayout1Listener);
        //do other stuff
    }
}


text:
Q: What does "your end" mean? In my English homework, a student gets asked if she would put "Any news your end" in a formal or informal letter.
My class should translate it, but in my native language it means something like "Some news you want to tell before/while dying?" and thats makes no sense to me.


text:
Q: Maven and LifecycleExecutionException I want to modelize the following 3 projects with Maven :

*

*parent project A

*2 modules B and C

*B->C and C->B
I tested 3 things :

*

*create dependencies B and C in A

*create dependency B in C and C in B

*idem 2 and adding exclusion of B inside B project coming from C dependency and exclusion of C inside C project coming from B dependency.

All give me LifecycleExecutionException.
So is there a way to modelize this please ?
I hope that the only way isn't to merge B and C inside one unique project...


text:
Q: Angular : add and Change class by clicking on button
I'm starting to study Angular. But I got some troubles and i need your knowledge. How can I do to up or down the number of my variable "loveIts" contains into my array "arrayPost" when I click on my buttons ?

Then, when I up or down my number, what I need to do to change my [ngClass] ? I have been already prepared my function "btnLove" et "btnNotLove".
app.component.html :

{{mainTitle}}

  <app-post *ngFor="let i of arrayPost"
  [postLoveIts]="i.loveIts"></app-post>

app.component.ts :
arrayPost = [
    {
      loveIts: -1,
    },
    {
      loveIts: 1,
    },
    {
      loveIts: 0,
    }
  ];

post.component.html :
<li [ngClass]="{'list-group-item': true,
                'list-group-item-danger': postLoveIts < 0,
                'list-group-item-success': postLoveIts > 0}">

  <button type="button" class="btn btn-success" (click)="btnLove">Love it !</button>

  <button type="button" class="btn btn-danger" (click)="btnNotLove">Don't love it !</button>

post.component.ts :
  @Input() postLoveIts: number;

  btnLove() {

  }

  btnNotLove() {

  }

A: I'm not really sure I understand your problem, but my intuition says that you want this piece of code
<li class="list-group-item"
    [class.list-group-item-danger]="postLoveIts < 0"
    [class.list-group-item-success]="postLoveIts > 0"


text:
Q: Service registry and api gateway knowledge of services I m actually studying microservices architecture and there are some points that I dont understand.
In fact, I know that when a user sends a request, the request (admitting in that case /users) is handled by an API gateway.
This API gateway knows that when an url like /users/* is called, it should discover the user service informations from a service registry (in this case ZooKeeper).
-> This means that the API gateway should known that on each different pattern, it has to get the concerned service. Is that right every time ?
The API gateway then knows how to redirect the request /users to to correct service (through the service registry) and then make the good request to the good endpoint (imagining that the microservice doesn't have an endpoint like /users, but /utilisateurs. The gateway has to know that
-> Does it imply that the API gateway has the knowledge of every microservice API endpoint ? Or does it exist a better (automated) manner to make it work ?

A: The gateway doesn't necessarily have to know about each endpoint specifically. I imagine you're probably trying to get at the problem that with knowing the endpoints, encapsulation is broken and there exists an implicit coupling.
Personally, I like the combination of an abstraction usually provided by the downstream service. Since all services provide a contract to how someone may make RPC calls to the services, it should also in that scenario  provide a client for a layer of abstraction. The client internally will know the endpoints but the methods could be abstract eg. a user-service to list users may call userServiceClient.getUsers or something like that. The other notion of service registry can also exist in this client as it should know what the service it is representing is registering to.
Now in the API gateway, this could be imported as a package and used without knowing the endpoints but knowing that there exists some user-service that can list users. The other benefit of having the abstraction is that it may use a protocol without requiring the upstream service to have any idea as to its implementation. Hope this helps!


text:
Q: Regex using Negative lookbehind and Negative lookahead assertion
Possible Duplicate:
Regex matching left single quotation outside the double quotations

First Note:
&ldquo - left double quote (")
&rdquo - right double quote (")
&lsquo - left single quote (')
&rsquo - right single quote (')

I need to match all "Left single quote" that are not inside of left and right double quote.
For clarricifcation:

*

*This is a "sample &lsquo string &rsquo &rdquo   -> this should not be match because the &lsquo (single quotes) is inside the double quote

*This is a &lsquo sample &rsquo   -> the &lsquo should be match because that is not inside the double quotation
Here's my current regex:
(?<!.*&ldquo)&lsquo(?!.*&rdquo)

The problem with this is, it is looking both the &ldquo and &rdquo, if any of ldquo and rdquo occure, it will not match
for example:

*

*This is a &lsquo sample &rdquo   -> I need to match &lsquo here but because of the appearance of &rdquo, the regex didn't match

*This is &ldquo a string &lsquo sample -> same problem with no.1 example
Hope somebody can help me! thanks!

A: Untested but try this
(?<!&ldquo.*)&lsquo(?!.*&rdquo)


text:
Q: Many failures trying to re-install ubuntu My situation has just gone from bad to worse.  First I had an issue that suddenly started with a black screen with just a cursor.  I spent a couple of days trying to fix it.  Now I've decided to reinstall (I do have my files backed up).
So, I begin the reinstall, and it failed with a 'executing grub-install failed this is a fatal error".
OK.  So then I tried again, and now I'm getting a ubi-partman failed with exit code 10.  Basically I can quit - which leaves me with a brick.  Or I can continue... which will likely leave me with a brick.
I have 2 500GB SSD's.  One has 1 partition, and I use it for media files.  It is not my boot drive.  However, for this discussion, it is important to note that device is '/dev/nvme0n1', an ext4 v1 linux file system.
The other drive is where I had Ubuntu 20.04.03 previously installed.  It is '/dev/nvme1n1' with 3 partitions.  The first partition, '/dev/nvme1n1p1' is 768MB, is and EFI system FAT (32).  It is where the old boot was.
The 2nd partition is and empty 539MB of free space (why I don't know).  It is called '/dev/nvme1n1'.
The 3rd partition is where all the linux files were, is is 511GB, and is '/dev/nvme1n1p4'.  It is saying it is a linux ext4 v1.
When the first grub failure occurred, it said it could not install on '/dev/nvme01n1'.  So it gives me a choice to go to others, all of which show the same failure.
What do I do now?


text:
Q: Configuring Route to allow dot as extension? Imagine the following:
client app, which no one has control over, calls Web API methods but each of these methods ends in extensions such as :
/api/{controller}/{method}.ab

How is it possible to configure the ASP.NET web API, for a specific controller, to allow extensions for the method being called but also allow the existing default controllers to continue working?
For instance if we have a method call GetCustomer, the client app will call GetCustomer.ab but want that call to be routed to GetCustomer which is the method in the controller "Customer", so something like this:
http://fake.com/api/SmallService/GetCustomer.ab

SmallService is the specific controller.
There are other controllers but only want to apply this type of routing to a specific controller.
Enabling the RAMMFAR is not an option either (RunAllManagedModulesForRequests) due to performance and security reasons too.
This is for ASP.NET Web API 2 running on .NET 4.6


text:
Q: Erase children of an InkCanvas I have an InkCanvas on a window in which I allow the user to draw with a stylus, touch, or mouse. I also allow the user to add text. The user taps an "add text" button, then taps where on the canvas they would like their text. A textbox appears there, allowing them to type. On enter or lost focus I create a ContentControl and add it to myInkCanvas.Children.
I would like the user to be able to erase the text they have created when the InkCanvas is in erase mode (I am using EraseByPoint). I've attempted to capture the MouseEnter and PreviewMouseMove events of the content controls, but neither seem to fire.
Is there an event that I can capture? Is there a better way to handle this scenario? Is it even possible?

A: You can use hit testing for this purpose
look at here
get InkPresenter first
public T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
        if (child != null)
            break;
    }
    return child;
}

InkPresenter inkPresenter = GetVisualChild<InkPresenter>(myInkCanvas);

then get HitTestResult of your Point
HitTestResult hitTestResult = VisualTreeHelper.HitTest(inkPresenter, new Point(x, y));

then you can use hitTestResult.VisualHit to remove this object


text:
Q: Simple sample query working update but skips the first condition I have a php code that updates the value in 2 tables and I used left join. It works but it keeps on skipping the first condition and always enters the second condition. I have no idea on mysql injection so please advice if my code is prone to mysql injection.
elseif ($_POST['check'])
{
    if ($row[typeofdog] = 'Labrador')
    {
            $id = $_POST['data'];
            $count = count($id);

        for($i=0;$i<$count;$i++)
            {

            $sql = "UPDATE animals LEFT JOIN treats ON animals.style = treats.style SET animals.bone = bone - treats.total, treats.status = 'Approved' WHERE treats.id='$id[$i]'";
            $result = mysql_query($sql);

            }

        if($result){header("location:login_success.php");}

    }
    else
    {
        $id = $_POST['data'];
        $count = count($id);

        for($i=0;$i<$count;$i++)
            {

            $sql = "UPDATE animals LEFT JOIN treats ON animals.style = treats.style SET animals.chunks = chunks - treats.total, treats.status = 'Approved' WHERE treats.id='$id[$i]'";
            $result = mysql_query($sql);

            }

        if($result){header("location:login_success.php");}

    }
}

A: First, = is for assignment. == is for comparison.
Second, using the index typeofdog without quotes is incorrect. PHP explains why here.
Try this:
if ($row['typeofdog'] == 'Labrador')

If this doesn't work, then $row['typeofdog'] does not equal 'Labrador'. In that case, try echoing $row['typeofdog'] just before the conditional so you can see what is being compared.
Also, yes, you are at risk for sql injection. First step to fixing this: don't use mysql. Instead use mysqli or pdo and utilize prepared statements.


text:
Q: Secure JSON requests and responses This may be a stupid question, but how can one write a secure RESTful API? If I want to ensure that the client is a valid user, would it be unwise to send a post request with the following object?
{
  "user": "some_user",
  "password": "some_password"
  "field1": "some_data",
  "field2": "some_more_data"
}

I currently hesitate to do something like that. Doesn't that reveal the username and password in plain text to everyone on the network and everything between the client and the server? Should I use SSL or something similar? Are there any RESTful security readings you have found valuable?
Thanks for the help.

A: For a RESTful API is not recommended to pass the credentials in the JSON body in every request, instead you use the headers to authenticate each call. For further options on how to secure your API you can check this blog, full disclosure I work for that company, but since it's what we do, I think is a good resource.


text:
Q: Interpretaion of Logistic Coefficients All,
I ran a logistic Regression on a set of variables both categorical and continuous with a binary event as dependent variable.
Now post modelling, I observe a set of categorical variables showing negative sign which I presume is to understand that if that categorical variable occurs high number of times then the probability of the dependent variable occurring is low.
But when I see the % of occurrence of that independent variable I see the reverse trend happening. hence the result seems to be counter intuitive. Any reason why this could happen. I have tried explaining below with a pseudo example.
Dependent Variable - E
Predictors:
   1. Categorical Var - Cat1 with 2 levels (0,1)
   2. Continuous Var  - Con1
   3. Categorical Var - Cat2 with 2 levels (0,1)
Post Modelling:
Say all are significant and the coefficients are like below,
Cat1 - (-0.6)
Con1-  (0.3)
Cat2 - (-0.4)
But when I calculate the % of occurrence of Event E on Cat 1, I observe that the % of occurence is high when Cat1 is 1, which I think is counter intuitive.
Pls help in understanding this.

A: There are at least two possibilities:

*

*The parameterization of the categorical variable may not be what you think it is. SAS PROC LOGISTIC, in particular, has defaults that are (to me and many other) counter intuitive in many cases.  R can also do some counterintuitive things with factors.

*If that isn't it, then bear in mind that your logistic regression has other variables included. So, it is controlling for those variables.  This has been discussed here multiple times.


text:
Q: Does marking e-mails as spam help other Mac users? Sometimes there's a spam e-mail in my inbox. I just have to click the spam button and the e-mail will get moved to the Junk folder. Some emails even land in the Junk folder automatically.
I assume over time Apple Mail learns and gets better in recognizing spam and will be better in automatically filtering it. That is right, isn't it?
Will marking an e-mail as spam also help other users spam filter? Does Apple has something like a spam filter that learns more the more users mark their e-mails as spam? Or does marking an e-mail as spam only influence the spam filter on my Mac?

A: Apple Mail will not share spam filtering directly with other Mac users.
If you use iCloud for email, and mark something as spam (regardless of in Mail or another email client), then iCloud will learn this and apply it appropriately. Apple does not specify whether this learning is shared across users.
https://support.apple.com/en-us/HT202315


text:
Q: Creating a new Word document from each row of Excel data I have a document template which needs to be filled in with data from my workbook - I've managed to get it to put the correct data at the correct part of the Word doc with bookmarks, but would like it to do a new doc for each line.
The code below will put the data in, and in column Y will put a yes when it has copied the data, however it currently tries doing every row in the same document rather than the new document with the pasted table in.
Public Sub openExistingWordFile()

   Dim objWord
   Dim objDoc
   Dim objRange

   Set objWord = CreateObject("Word.Application")
   Set objDoc = objWord.Documents.Open(".... Draft Invoice Template.doc")

   objWord.Visible = True

   objWord.Selection.WholeStory
   objWord.Selection.Copy

 R = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 6 To R
        With Cells(i, 2)
            If .Value <> "" And Cells(i, 25) = "" Then
                Cells(i, 25) = "Yes"

    Set objRange = objDoc.Bookmarks("OurRef").Range
    objRange.InsertAfter Cells(i, 4)

    Set objRange = objDoc.Bookmarks("WorkRef").Range
    objRange.InsertAfter Cells(i, 5)

    Set objRange = objDoc.Bookmarks("Location").Range
    objRange.InsertAfter Cells(i, 7)

    Set objRange = objDoc.Bookmarks("WorksType").Range
    objRange.InsertAfter Cells(i, 11)

    Set objRange = objDoc.Bookmarks("ReinCat").Range
    objRange.InsertAfter Cells(i, 12)

    Set objRange = objDoc.Bookmarks("TS").Range
    objRange.InsertAfter Cells(i, 13)

    Set objRange = objDoc.Bookmarks("Charge").Range
    objRange.InsertAfter Cells(i, 18)

    Set objRange = objDoc.Bookmarks("From").Range
    objRange.InsertAfter Cells(i, 15)

    Set objRange = objDoc.Bookmarks("To").Range
    objRange.InsertAfter Cells(i, 16)

    Set objRange = objDoc.Bookmarks("Days").Range
    objRange.InsertAfter Cells(i, 17)

    Set objRange = objDoc.Bookmarks("Total").Range
    objRange.InsertAfter Cells(i, 24)

    Set objRange = objDoc.Bookmarks("Date").Range
    objRange.InsertDateTime DateTimeFormat:="d/M/yyyy"

    objWord.Documents.Add DocumentType:=wdNewBlankDocument
    objWord.Activate
    objWord.Selection.PasteAndFormat (wdUseDestinationStylesRecovery)

        End If
        End With

    Next i

    End Sub

A: I did eventually manage to sort this, code below if anyone is interested.
Public Sub openExistingWordFile()

   Dim objWord
   Dim objDoc
   Dim objRange

   Set objWord = CreateObject("Word.Application")
   Set objDoc = objWord.Documents.Add(Template:="...S74 Draft Invoice Template.doc", NewTemplate:=False, DocumentType:=0)

   objWord.Visible = True

r = Cells(Rows.Count, 1).End(xlUp).Row
    For i = 6 To r
        With Cells(i, 2)
            If .Value <> "" And Cells(i, 25) = "" Then
                Cells(i, 25) = "Yes"

    Set objRange = objDoc.Bookmarks("OurRef").Range
    objRange.InsertAfter Cells(i, 4)

    Set objRange = objDoc.Bookmarks("WorkRef").Range
    objRange.InsertAfter Cells(i, 5)

    Set objRange = objDoc.Bookmarks("Location").Range
    objRange.InsertAfter Cells(i, 7)

    Set objRange = objDoc.Bookmarks("WorksType").Range
    objRange.InsertAfter Cells(i, 11)

    Set objRange = objDoc.Bookmarks("ReinCat").Range
    objRange.InsertAfter Cells(i, 12)

    Set objRange = objDoc.Bookmarks("TS").Range
    objRange.InsertAfter Cells(i, 13)

    Set objRange = objDoc.Bookmarks("Charge").Range
    objRange.InsertAfter Cells(i, 18)

    Set objRange = objDoc.Bookmarks("From").Range
    objRange.InsertAfter Cells(i, 15)

    Set objRange = objDoc.Bookmarks("To").Range
    objRange.InsertAfter Cells(i, 16)

    Set objRange = objDoc.Bookmarks("Days").Range
    objRange.InsertAfter Cells(i, 17)

    Set objRange = objDoc.Bookmarks("Total").Range
    objRange.InsertAfter Cells(i, 24)

    Set objRange = objDoc.Bookmarks("Date").Range
    objRange.InsertDateTime DateTimeFormat:="d/M/yyyy"

    Set objDoc = objWord.Documents.Add(Template:="...S74 Draft Invoice Template.doc", NewTemplate:=False, DocumentType:=0)

    objWord.Activate

        End If
        End With

    Next i

    objWord.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges

    End Sub


text:
Q: Передача актуального state в redux-toolkit Всем привет! Столкнулся с такой проблемой. Есть приложение на React + redux-toolkit. В бэкенде прописана логика авторизации и проверки jwt-токена. На фронте я делаю запрос на проверку пользователя. Если пришел корректный ответ, я этого пользователя диспатчу в стейт. Дальше я хочу пробросить этот стейт в дочерний компонент, что бы проверить, авторизован ли пользователь, и вывести нужную страницу, либо редирект на страницу логина. Суть проблемы в том, что в дочерний компонент пробрасывается initial state, в котором нет пользователя. Помогите решить проблему!
App.jsx
import { Routes, Route } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { setUser } from "store/slices/userSlice";
import SignIn from "./components/SignIn/SignIn";
import SignUp from "./components/SignUp/SignUp";
import Main from "./components/Main/Main";
import { useEffect } from "react";
import { checkAuth } from "api";

function App() {
  const dispatch = useDispatch();
  const state = useSelector((state) => state);

  useEffect(() => {
    if (localStorage.getItem("email")) {
      checkAuth().then((data) => {
        dispatch(
          setUser({
            email: data.email,
            id: data.id,
            firstName: data.firstName,
            lastName: data.lastName,
            phone: data.phone,
            nickname: data.nickname,
            description: data.description,
            position: data.position,
            isAuth: true,
          })
        );
      });
    }
  }, []);

  return (

      <Routes>
        <Route path="/" element={} />
        <Route path="/signin" element={<SignIn />} />
        <Route path="/signup" element={<SignUp />} />
      </Routes>

  );
}

export default App;

Дочерний компомнент
import { Navigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { removeUser } from "store/slices/userSlice";
import Header from "components/Header/Header";
import { logout } from "api/index";

const Main = ({ isAuth }) => { //тут приходит false
  const dispatch = useDispatch();

  const handleLogout = () => {
    logout();
    dispatch(removeUser());
  };

  return isAuth ? (

Welcome

      <button>Log out from</button>

  ) : (
    <Navigate to="/signin" />
  );
};

export default Main;

Redux Slice
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  email: null,
  id: null,
  firstName: null,
  lastName: null,
  phone: null,
  nickname: null,
  description: null,
  position: null,
  isAuth: false,
};

const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    setUser(state, action) {
      state.email = action.payload.email;
      state.id = action.payload.id;
      state.firstName = action.payload.firstName;
      state.lastName = action.payload.lastName;
      state.phone = action.payload.phone;
      state.nickname = action.payload.nickname;
      state.description = action.payload.description;
      state.position = action.payload.position;
      state.isAuth = action.payload.isAuth;
    },
    removeUser(state) {
      state.email = null;
      state.token = null;
      state.id = null;
      state.firstName = null;
      state.lastName = null;
      state.phone = null;
      state.nickname = null;
      state.description = null;
      state.position = null;
      state.isAuth = false;
    },
  },
});

export const { setUser, removeUser } = userSlice.actions;

export default userSlice.reducer;

A: Вам не следует так прокидывать значения стейта в дочерние компоненты, которые находятся в рендер функциях роутов. Вы можете сделать все гораздо проще. Используйте useSelector в необходимом компоненте, в вашем случае это видимо Main и получите необходимое значение как только оно изменится в слайсе.

A: Хотел в комментарии написать, но в комментарии репутации не хватает, поэтому придется в ответе. :)
Вы как-то слишком усложнили и вам в принципе верно посоветовали упростить, используя useSelector в компоненте.
Еще правильнее будет сделать защищенные роуты. Оборачивая компоненты в компонент-обертку, который будет проверять логин и перенаправлять если пользователь незалогинен.
Вот так будет выглядеть защищенный роут (пример).
  <Route path='profile/orders/:id'
    element={
      <ProtectedRoute>
        <Order />
      </ProtectedRoute>
    } />

А вот так компонент ProtectedRoute.
import { useSelector } from "../../redux/store";
import { Navigate, useLocation } from "react-router-dom";

export function ProtectedRoute(props) {
  const { children } = props;
  const location = useLocation();
  const { isLoggedIn } = useSelector((store) => store.auth);

  if (!isLoggedIn) {
    return <Navigate to="/login" state={{ from: location }} />
  }

  return children;
}

Удачи.


text:
Q: Kotlin: OpenJDK 64-Bit Server VM warning My Kotlin code is running well, though I'm getting this warning:

OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.

How can I fix this?
I'm using Ubuntu 22.10; VS Code with the following installed:
Kotlin Command line Kotlin compiler
openjdk 18.0.2-ea 2022-07-19
OpenJDK Runtime Environment (build 18.0.2-ea+9-Ubuntu-2)
OpenJDK 64-Bit Server VM (build 18.0.2-ea+9-Ubuntu-2, mixed mode, sharing)
I tried renaming the .kt files with underscores but nothing changed.


text:
Q: How to HealthCheck on ECS without an ELB We have a Docker container(Spring Boot) that runs in an ECS cluster. We run it without Elastic Load Balancing.
We want to update the service without downtime, so when the new task is up and healthy, the old task stops. We have been trying to add a health check on the task definition, however it refuses to work. I have tried basic healthcheck commands.
But not work.


text:
Q: Link to a telegram bot with pre-written command I'm writing a telegram bot now and I have a question. As I know any user can link to a bot using "@" symbol, like this @my_bot. Is there any possibility to make such a link, that when a user click on it, not only he is redirected to this bot, but also a specific command is sent to this bot by a user automatically.
Something like this @my_bot/my_command. I've tried this link, but it doesn't work. I don't know, if it is possible, maybe you do.
Thanks in advance!

A: You can use a deep link adding an additional parameter
https://t.me/mybot?start=task_name

The deep link opens the bot with the start command, the additional parameter is passed to your handler to customise what the start command_handler should do.


text:
Q: Make mate 1.6 look like lucid lynx default theme I happened to like the way Lucid Lynx looks. This is not a lucid lynx question, I just want the panels on mate 1.6 to look like the ones of Lucid lynx. I went to the properties of the panel, but it says the colour is a system theme. -Thus I cannot manage to get the exact same look. I have copied the themes out of /usr/share/themes but I still do not get the same look.
This is strictly an question of aesthetics. I loved the theme of lucid, and just want to continue using something that looks the same. How Can i achieve this look in Mate 1.6?I am using Ubuntu 13.04

A: So then I made this: http://nanocluster.umeche.maine.edu/panel.png which can now be my background to the mate panel. it looks ok, though I should change the system fonts to be more white. But I guess I'm good for now.


text:
Q: Function for drawing group of dots gives me a warning or doesn't draw at all The following simple code generates dots on a given image (which is dynamically generated too), but for unknown reason I don't see them ...
for ($i = 0; $i < $max; $i++)
{
  $xcoords = mt_rand(50, 450);
  $ycoords = mt_rand(50, 450);
  if ($ycoords > 300)
  {
    drawMe($red);
  }
  elseif ($ycoords > 150 && $ycoords < 300)
  {
    drawMe($green);
  }
  else
  {
    drawMe($blue);
  }

This is the code for used colors:
$red = imagecolorallocate($im, 255, 0, 0);
$green = imagecolorallocate($im, 0, 128, 0);
$blue = imagecolorallocate($im, 0, 0, 255);

And this is the drawMe() func:
function drawMe($color)
{
  ob_start();
  imagesetpixel($im, $xcoords, $ycoords - 1, $color);
  imagesetpixel($im, $xcoords + 1, $ycoords - 1, $color);
  imagesetpixel($im, $xcoords + 1, $ycoords, $color);
  imagesetpixel($im, $xcoords + 1, $ycoords + 1, $color);
  imagesetpixel($im, $xcoords, $ycoords, $color); // main dot !!!
  imagesetpixel($im, $xcoords, $ycoords + 1, $color);
  imagesetpixel($im, $xcoords - 1, $ycoords + 1, $color);
  imagesetpixel($im, $xcoords - 1, $ycoords, $color);
  imagesetpixel($im, $xcoords - 1, $ycoords - 1, $color);
  return ob_get_clean();
}

If I remove ob_start and ob_get_clean, I've got warning:
Warning: imagesetpixel() expects parameter 1 to be resource, null given in /var/www/test.php on line 75 to 83

That's $im and the background:
$im = imagecreate(640, 480);
$bg = imagecolorallocate($im, 255, 255, 255);

A: you need to define the new $im as new image before you start
you can use imagick class
$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');


text:
Q: Route not restored for alias interface I've this network configuration on a Debian 10 Buster:
auto lo
iface lo inet loopback

allow-hotplug enp3s0
iface enp3s0 inet static
        address 192.168.0.175
        netmask 255.255.255.0
        gateway 192.168.0.254
        dns-nameservers 8.8.8.8 8.8.4.4

allow-hotplug enp3s0:1
iface enp3s0:1 inet static
        address 192.168.3.175
        netmask 255.255.255.0

It works perfectly, but when making some tests like repeatedly unplugging the network cable and putting back  I'm running into a weird issue: route for the alias interface :1 is not restored, but IP address is!
To make it short, when I put back the network cable the two IP addresses are configured correctly, but only the 192.168.0.0/24 route is restored.
After reboot everything works fine. This just happens when unplugging network cable. I tried with auto enp3s0 instead of allow-hotplug but behaves the same.

A: I figured out the problem, which wasn't due to the interfaces file but a conflict with wcid, LXDE network manager. The LAN interface was managed by both systems and did get unconfigured on cable disconnect but wasn't on reconnection.
Removing it from wcid restored full functionality.


text:
Q: Unable to set default selected option in selection tag I have encountered issue with angular.js 1.4.0. I can't set the default in select tag if I will use a 'number' but it will work if I use a 'string'. The select statement is hard code in the view. I already initialize my model in the controller.
// This will NOT WORK, value passed is a 'number'
$scope.colors = 2;
// This will WORK, value passed is a 'string'
$scope.colors='2';
VIEW/MODEL:

    <select ng-model="colors">
      <option value="1">Red</option>
      <option value="2">Blue</option>
      <option value="3">Green</option>
    </select>

Selected Color: {{colors}}

CONTROLLER:
angular.module('app', []).controller('MyController', function($scope) {
   /* angular.js version 1.4.0 issue:
      $scope.colors = 2; --> will not work
      $scope.colors = '2'; --> will work

      This is working on angular.js version 1.3.15
   */
   $scope.colors = 1;
});

If I use angular.js version 1.3.15, both 'number' and 'string' will work.
Note: angular version set in codepen is 1.4.0 so you can see the error.
http://codepen.io/joemalski/pen/YXQMKO?editors=001

A: JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];

HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>

This would leave the "b" item to be selected.

A: Ok, instead of having a static select/option use a dynamic one :
$scope.colors = ["red","blue","green"];

in your HTML
<select ng-model="selectedColor" ng-option="color in colors"></select>

use string like so you'll be safe.


text:
Q: Using map to sum the elements of list I was wondering if map can be used at all to sum the elements of a list.
assume a = [1, 2, 3, 4]
list(map(sum, a)) will give an error that int object is not iterable because list wants iterables.
map(sum, a) is a valid statement but given the object, I do not see an easy way to dereference it.
[map(sum, a)] will return an object inside the list
this answer states that it should be easy. What am I missing here?

A: x = list(map(sum,a))

Is equivalent to
x = []
for i in a:
    x.append(sum(i))

Sum needs a iterable to apply sum across. If you see the docs syntax goes this way sum(iterable[, start]). Since int is not an iterable you get that error.

A: Of course if one just want to sum the elements of a list, he should simply call sum(list_).
Now, comming to your question: map, both the Python built-in and the pattern refer to applying a function to a data sequence, and yield another sequence, with a separate result for each element in the initial sequence.
sum does not do that - it yields a single result for the whole sequence. That pattern is called reduce, and so is the Python ex-built-in to do that. In Python 3, it was "demoted" to the functools module, as it is rarely used when compared to the map pattern.
The sum built-in itself employs the "reduce" pattern alone - but if you were to explicitly recreate sum using the reduce pattern it goes like:
from functools import reduce
a = [1, 2, 3, 4]
reduce(lambda result, value: result + value, a, 0)

The first parameter is a callable that takes the "accumulated result so far", the second value is the sequence of items you want to run reduce at, and the third parameter is the initial value to be passed as the accumulated result. (so,it starts at zero). For a multiplicatory, we could use:
reduce(lambda result, value: result * value, a, 1)

update: Python 3.8 implemented the "multiplicatory" in the standard library as math.prod.

A: map applies a function to every element in the list. Instead, you can use reduce:
a = [1, 2, 3, 4]
sum_a = reduce(lambda x, y:x+y, a)

In this case, purely sum can be used, however, to be more functional, reduce is a better option.
Or, in Python3:
from functools import reduce
a = [1, 2, 3, 4]
sum_a = reduce(lambda x, y:x+y, a)

A: The error int object is not iterable is not because list expects an iterable, but sum expected an iterable.
The following code:
map(sum , [1,2,3,4])

Is somewhat equivalent to:
[sum(x) for x in [1,2,3,4]]

Executing the last expression yields the same error.

A: reduce(lambda x,y:x+y, L) #summing all elements of a list L

Using map reduce and printing the elapsed time in seconds
import time
from six.moves import reduce
import numpy as np
start=time.time()
L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = reduce(lambda x,y:x+y, L)
end=time.time()
print("sum of list L ", L, " is equal to", result)
print("elapsed time is ", end-start, ' seconds')

output:
sum of list L  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  is equal to 55
elapsed time is  0.00014519691467285156  seconds

using python's build-in sum function and elapsed time
start=time.time()
s = sum([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
end=time.time()
print("elapsed time is ", end-start, ' seconds')

output:
elapsed time is  9.226799011230469e-05  seconds

sum is a slightly faster method since 9e-05 is less than 1e-04

A: Here's one way to do it purely functionally.
from operator import add
from functools import reduce
result = reduce(add, a)

A: Indirectly you can add all the elements of a list using a map function using a global variable like below:
# reading the file
with open('numbers.txt') as f:
    lines = [line.strip() for line in f]

numbers = [int(line) for line in lines]
all_sum = 0
def add(n):
    global all_sum
    all_sum += n
    return(all_sum)

result = map(add, numbers)
print(list(result)[-1])

There is only one number in one line in the text file.


text:
Q: Rectangular Movement using ActionScript 3 Good evening. I am working on a simple project which involves a symbol moving in a rectangular fashion (Right, Up, Left, Down, Repeat) using an EVENT_FRAME handler. this is my code
import flash.events.Event;

var moveRate:Number = 20;
var maxX:Number = 500;
var minX:Number = 80;
var maxY:Number = 60;
var minY:Number = 320;
var endOfLineX:int = 0;
var endOfLineY:int = 0;

roboSym.addEventListener(Event.ENTER_FRAME, move1);
roboSym.addEventListener(Event.ENTER_FRAME, move2);

    function move1(e:Event):void
    {
    if (endOfLineX == 0)
    {
        roboSym.x +=  moveRate;
        if (roboSym.x >= maxX)
        {
                endOfLineX = 1;
        }
    }
    else if (endOfLineX == 1)
    {
        roboSym.x -=  moveRate;
        if (roboSym.x <= minX)
        {
            endOfLineX = 0;
        }
    }

    }
    function move2(e:Event):void
    {

    if (endOfLineY == 0)
    {
        roboSym.y -=  moveRate;
        if (roboSym.y <= maxY)
        {
            endOfLineY = 1;
        }
    }
    else if (endOfLineY == 1)
    {
        roboSym.y +=  moveRate;
        if (roboSym.y >= minY)
        {
            endOfLineY = 0;
        }
    }
    }

Thing is, the motion keeps going diagonal, and not in a straight motion. I know there is an error somewhere in my logic, but I can't pinpoint what it is.

A: Well you've got 2 EnterFrame events, and they both have the variable endOfLine that makes them both go vertical and horizontal at the same time, which results in a diagonal motion. Also a small tip, you don't have to have 2 Event functions for EnterFame, you can just paste the code from move2 into move1 and it still works!
You basically got this:
function moveCombined(e:Event):void{
    if(endOfLineX == 1){
        roboSym.x += rate;
        //So the robot moves horizontal
    }else if(endOfLineX == 0){
        roboSym.x -= rate;
        //It still moves horizontal but the other way
    }
    //And you do the same for the vertical motion
    if(endOfLineY == 1){
        roboSym.y += rate;
        //So the robot moves vertical
    }else if(endOfLineY == 0){
        roboSym.y -= rate;
        //It still moves vertical but the other way
    }
}

So every frame, robotSym.x gets added (or subtracted) up with the rate, and also robotSym.y gets added (or subtracted) up with the rate. And that creates a diagonal motion.


text:
Q: Firebase deploy displays Welcome Screen with no App Content I cloned a quickstart angular application.
I run firebase init and firebase deploy,
and output shows deploy successful. I naviagate to the url, but it just shows the Welcome screen. Why don't I see my content?

A: The repo I cloned didn't place an index.html file in the /dist directory.
The welcome screen is the default index.html that firebase creates.

A: After running: firebase init
Few questions will be asked and Reply(In Bold) as follows:

*

*Are you ready to proceed? : Yes

*Which Firebase CLI features do you want to set up for this folder? Press Space to select features, then Enter to confirm your choices. : Hosting: Configure and deploy Firebase Hosting sites
=== Project Setup

*Select a default Firebase project for this directory: Your firebase Project name
=== Hosting Setup

*What do you want to use as your public directory? dist

*Configure as a single-page app (rewrite all urls to /index.html)? No

*File dist/404.html already exists. Overwrite? No

*File dist/index.html already exists. Overwrite? No
-----Firebase initialization complete!-----
Now Re-run your app using: ng build (Imp step)
----Deploy----
firebase deploy

A: I jsut had this issue, its because I ran a build and then firebase init which caused the /build/index.html file to be overriten.
After you init the firebase project just rerun the build and then deploy.

A: there is no problem if you ran build and then do firebase init.
After deployment, if you see the welcome screen. Before doing anything just wait for some time and Refresh the page. it worked for me

A: Angular projects aren't built directly inside /dist. They are usually built like /dist/your-project-name
So when you firebase init and you are asked What do you want to use as your public directory? provide it /dist/your-project-name instead of just /dist
And if /dist/your-project-name folder really has your project then it'll surely ask you File dist/your-project-name/index.html already exists. Overwrite?, you say no
In case it didn't ask you about overwriting then it means the public address you gave above is either incorrect or maybe you haven't yet built your project using ng build command.

A: Don't forget to rebuild you application again before firebase deploy. Your dist folder should be same folder name you setup as the public folder during your firebase init.

A: I had same problem with my deployed react app using Firebase to solve that as suggested above in first answers rebuild your app after running firebase init successfully & before running firebase deploy command. Then deploy your app.
If it's first time then you see welcome screen with hosting documentation. Then wait for few minutes around 15 to 20 minutes, then open app URL. It's running

A: Update the firebase.json file
 "hosting": {
    "public": "dist/your-app-name"

for ex: my app name is "DataView" and looks like this the firebase config file:
 "hosting": {
    "public": "dist/DataView",

A: Important:

If you are already tried to deploy the flutter web app project, then 1st remove (1).firebase,(2)build,(3)firebase.json from your project directory root page.

then just follow the below 7 steps-->
1 step: First run firebase init
     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  {project path}\{projectname}

Before we get started, keep in mind:

  * You are currently outside your home directory

2nd step:
? Are you ready to proceed? Yes
3rd step:
? Which Firebase features do you want to set up for this directory? Press Space to select features, then Enter to confirm your choices. Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Actio
n deploys
=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

i  Using project ****21ed1 (projectname)

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

4th step:
? What do you want to use as your public directory? build/web
5th step:
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? Set up automatic builds and deploys with GitHub? **No**
+  Wrote build/web/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

+  Firebase initialization complete!

6th step:
Then run: flutter build web
 Building with sound null safety

Compiling lib\main.dart for the Web...                           2,656ms

7th step:
Then run: firebase deploy
=== Deploying to '****21ed1'...

i  deploying hosting
i  hosting[****21ed1]: beginning deploy...
i  hosting[****21ed1]: found 15 files in build/web
+  hosting[****21ed1]: file upload complete
i  hosting[****21ed1]: finalizing version...
+  hosting[****21ed1]: version finalized
i  hosting[****21ed1]: releasing new version...
+  hosting[****21ed1]: release complete

+  Deploy complete!

A: Just refresh the page . If you had deployed your project currectly. Its just a matter of refresh , that will show your content.