text:
Q: why I am getting an 403 error and my Delete API not working from front-end I am a Newbie please help me
I am working on MERN Project and can't figure out how to make my Delete API work from front-end.
Delete API is working when i am testing it from Postman but when trying from front-end its not working.
here is the code of my Delete API
//delete a post

router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
     if (post.userId === req.body.userId) {
      await post.deleteOne();
      res.status(200).json("the post has been deleted");
    } else {
      res.status(403).json("you can delete only your post");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

I have made a button and for Delete operation
<button className="postdeletebutton" onClick={deleteHandler} >Delete</button>

and I have also added deletehandler which is suppose to perdform delete operation
const deleteHandler = () => {
  try {
    axios.delete("/posts/" + post._id, {userId: "6245aebc58a3a42100e43e94"});
    } catch (err){}
};

like, dislike and Add post are working fine from the frontend but delete is not working
I get 403 Error in the terminal as I mentioned it on the back-end i also tried hardcoding the userid but it did not work
here is the full code of Post.JSX
import "./post.css";
import React from "react";
import { MoreVert } from "@material-ui/icons";
import IconButton from "@material-ui/core/IconButton";
import MenuItem from "@material-ui/core/MenuItem";
import Menu from "@material-ui/core/Menu";
import { useContext, useEffect, useState, useRef} from "react";
import axios from "axios";
import { format } from "timeago.js";
import { Link } from "react-router-dom";
import { AuthContext } from "../../context/AuthContext";
import { PermMedia, Cancel } from "@material-ui/icons";

export default function Post({ post }) {
  const [like, setLike] = useState(post.likes.length);
  const [isLiked, setIsLiked] = useState(false);
  const [user, setUser] = useState({});
  const PF = process.env.REACT_APP_PUBLIC_FOLDER;
  const { user: currentUser } = useContext(AuthContext);

  useEffect(() => {
    setIsLiked(post.likes.includes(currentUser._id));
  }, [currentUser._id, post.likes]);

  useEffect(() => {
    const fetchUser = async () => {
      const res = await axios.get(`/users?userId=${post.userId}`);
      setUser(res.data);
    };
    fetchUser();
  }, [post.userId]);

  const [anchorEl, setAnchorEl] = React.useState(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const open = Boolean(anchorEl);

  const handleClose = () => {
    setAnchorEl(null);
  };

  const likeHandler = () => {
    try {
      axios.put("/posts/" + post._id + "/like", { userId: currentUser._id });
    } catch (err) {}
    setLike(isLiked ? like - 1 : like + 1);
    setIsLiked(!isLiked);
  };

const deleteHandler = () => {
  try {
    axios.delete("/posts/" + post._id, {userId: "6245aebc58a3a42100e43e94"});
    } catch (err){}
};

//temp
// const [file, setFile] = useState(null);
// const desc = useRef();

// const submitHandler = async (e) => {
//   e.preventDefault();
//   const newPost = {
//     userId: user._id,
//     desc: desc.current.value,
//   };
//   if (file) {
//     const data = new FormData();
//     const fileName = Date.now() + file.name;
//     data.append("name", fileName);
//     data.append("file", file);
//     newPost.img = fileName;
//     console.log(newPost);
//     try {
//       await axios.post("/upload", data);
//     } catch (err) {}
//   }
//   try {
//     await axios.post("/posts", newPost);
//     window.location.reload();
//   } catch (err) {}
// };
//temp

  return (

            <Link to={`/profile/${user.username}`}>

            </Link>
            {user.username}
            {format(post.createdAt)}

          <IconButton
          aria-label="more"
          onClick={handleClick}
          aria-haspopup="true"
          aria-controls="long-menu"
          >
            <MoreVert />
          </IconButton>

          {currentUser._id === post.userId && (
          <Menu
          anchorEl={anchorEl}
          keepMounted onClose={handleClose}
          open={open}>
            <MenuItem
            onClick={handleClose}
            >
              <button className="posteditbutton" >Edit  </button>

              <button className="postdeletebutton" onClick={deleteHandler} >Delete</button>
            </MenuItem>
         </Menu>
         )}

         {/* temp */}

         {/*

        {file && (

            <Cancel className="shareCancelImg" onClick={() => setFile(null)} />

        )}
        <form className="shareBottom" onSubmit={submitHandler}>

              <PermMedia htmlColor="tomato" className="shareIcon" />
              Add Photo
              <input
                style={{ display: "none" }}
                type="file"
                id="file"
                accept=".png,.jpeg,.jpg"
                onChange={(e) => setFile(e.target.files[0])}
              />

          <button className="shareButton" type="submit">
            Share
          </button>
        </form> */}

         {/* temp */}

          {post?.desc}

            <img
              className="likeIcon"
              src={`${PF}like.png`}
              onClick={likeHandler}
              alt=""
            />
            <img
              className="likeIcon"
              src={`${PF}heart.png`}
              onClick={likeHandler}
              alt=""
            />
            {like} people Appreciate it

          {/*

            {post.comment} comments

 */}

  );
}

A: Error was with the data type
I was using === and we use it only when we have value + data type but in my case we have only value so instead on using === in API I used == and it worked
here is the code of it
Special Thanks to Mr. Saad who helped me in this
Before
//delete a post

router.delete("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
     if (post.userId === req.body.userId) {
      await post.deleteOne();
      res.status(200).json("the post has been deleted");
    } else {
      res.status(403).json("you can delete only your post");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

After
//delete a post
router.delete("/:id", async (req, res) => {
try {
    const post = await Post.findById(req.params.id);

    if (post._id == req.params.id) {
      await post.deleteOne();
      res.status(200).json("the post has been deleted");
    } else {
      res.status(403).json("you can delete only your post");
    }
  } catch (err) {
    res.status(500).json(err);
  }
});

I have also made slight changes on the frontend
const deleteHandler = () => {
    try {
      axios.delete("/posts/" + post._id);
    } catch (err) { }
  };

and this is how now delete button looks like
<button className="postdeletebutton" onClick={deleteHandler} >Delete</button>

Thank you


text:
Q: Difference between .h files and .inc files in c I have been looking at various open source projects, and they have a bunch of files written in C that have .inc as a file extension. As far as I can tell, they are used like header files.
I thought the standard convention was to use .h files for header files and .c for source files. So, is there a standard convention on when a header file should be an .inc file rather than being a .h file, or are these decided only at a per project basis? (Or am I just looking at weird projects that use .inc?)

A: The standard convention is to use .h for header files that contain only macro definitions and other declarations and .c for C source files that contain code and data definitions.
In some projects, code fragments are stored in separate files and included in C source files with some macro tricks to expand specifically in different files or circumstances. Sometimes, these files are even included multiple times in the same source file. To underscore the special semantics attached to such files, giving them a different extension may be a useful hint.  These files may also have been generated as part of the build process: naming them specifically may prevent confusion with actual source files.
Look at the files you came across in these projects and verify if this explanation holds.

A: .inc files are often associated with templated classes and functions.
Standard classes and functions are declared with a .h file and then defined with a .cpp file. However, a template is neither a class nor a function but a pattern that is used to generate a family of classes or functions. In order for the compiler to generate the code for the template, it needs to see both the declaration and definition and therefore they both must be included in the .h file.
To keep the declaration and definition separate, the definition is placed in its own file and included at the end of the .h file. This file will have one of many possible file extensions .inc, .imp, .impl, .tpp, etc.
Declaration example:
// Foo.h
#ifndef FOO_H
#define FOO_H

template<typename T>
class Foo {
public:
    Foo();
    void DoSomething(T x);
private:
    T x;
};

#include "Foo.inc"
#endif // FOO_H

Definition example:
// Foo.inc
#include "Foo.h"

template<typename T>
Foo<T>::Foo() {
    // ...
}

template<typename T>
void Foo<T>::DoSomething(T x) {
    // ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring MVC AngularJS handle image upload I have an application using Spring MVC for back-end and AngularJS for front-end.
Problem:
I have a multi-step form there on one of the steps user uploading an image.
For now, this i use this algorithm:
On form, there is a button to choose an image. once image is selected it is sent to /upload_image controller and uploaded into the temp folder. Then, once the user submit a final request, the image moved from img_temp to images/created_item_id
But it also creating much complications with image moving because i also have some additional manual approval for the form data in some cases.
Question:
Do i do it in the right way? Maybe there is some methods to do so without temporal image creation?


text:
Q: Leaflet map showing on only one card when it needs to show on all of them I have 5 card I want that a Leaflet map  will show on each one of them but it only shows on one card,
each map take lat and lot from an array, the index number  for the array is taken by "data-index" attributes on the HTML fill

this is the JS fill

const cards = document.querySelectorAll(".card");

const mapInfo = [
  { curessTitle: "Big City", mapLat: 51.505, mapLon: 10 },
  { curessTitle: "Food", mapLat: 51.505, mapLon: 0 },
  { curessTitle: "Nature", mapLat: 51.505, mapLon: 0 },
  { curessTitle: "Culture", mapLat: 51.505, mapLon: 0 },
  { curessTitle: "Pepole", mapLat: 51.505, mapLon: 0 },
];

cards.forEach((cards) => {
  let cardDataIndex = cards.dataset.index;
  console.log(cardDataIndex);
  const mymap = L.map("mapid").setView(
[mapInfo[cardDataIndex].mapLat, mapInfo[cardDataIndex].mapLon],
13
  );

  L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
attribution:
  '© OpenStreetMap contributors',
  }).addTo(mymap);
});

so how can i fixe it? or improve  it ?
any suggestions ?

A: I adapted one of my fiddles to show you a way to do this.
Here's how I initialized my maps in the fiddle:
const myMaps = [];

function initMap() {
  const myArray = ['first', 'second'];
  myArray.forEach((element, index) => {
    // set up the map
    const map = new L.Map('map' + index);

    // create the tile layer with correct attribution
    const osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    const osmAttrib = 'Map data © OpenStreetMap contributors';
    const osm = new L.TileLayer(osmUrl, {
      minZoom: 8,
      maxZoom: 15,
      attribution: osmAttrib
    });

    // start the map
    map.setView(new L.LatLng(51.503, -0.06), 13);
    map.addLayer(osm);
    myMaps.push(map);
    addMarker(element, map);
    createCircles(map);
  })
}

and the html:


text:
Q: How do you place a curve over a histogram with multiple factors? I think I am making this out to be much more complicated than it is, but I haven't been able to figure it out.
I essentially have created a bar plot from some count data (vector counts), by day (vector day).  Within the plot I am factoring color by treat (vector treat).  What I would like to do is overlay some sort of curve instead of having the bars.  I am most interested in showing where the peaks are in the vector "counts" for each treat.
Here are the vectors within my dataframe, which I have named "data"
treat<-c(1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4)
counts<-c(9,12,11,5,3,2,0,2,0,0,1,1,0,10,4,7,6,1,4,1,1,0,0,0,0,0,12,5,15,3,4,2,0,0,1,0,0,0,0,4,6,11,7,7,4,1,1,0,0,0,0,0)
day<-c(1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13,1,2,3,4,5,6,7,8,9,10,11,12,13)

q=ggplot(data, aes(x=factor(day), y=counts, fill=factor(treat), color=factor(treat)))
q+geom_bar(stat= "identity", position=position_dodge(), width=.75)

Thank you for taking a look!

A: Is this what you're looking for?
data = data.frame(treat, counts, day)

ggplot(data, aes(x=factor(day), y=counts, group=factor(treat), color=factor(treat))) +
  geom_line(lwd=1) +
  geom_point()

The result is a bit hard to read for the these data, but maybe it will look better with your real data. Or you can use faceting, as shown by @Jaap.

Also, you can simplify your data creation as follows:
treat = rep(1:4, each=13)
day = rep(1:13, 4)

A: If you want to show the peaks for count in each treat, then you might consider using facets with either facet_wrap or facet_grid. An example with facet_wrap:
ggplot(data, aes(x=factor(day), y=counts, color=factor(treat), group=factor(treat))) +
  geom_line() +
  facet_wrap(~treat)

which gives you the following plot:


text:
Q: malloc() always returns NULL in ChibiOS I have a ChibiOS application where I'm using dynamic memory allocation via malloc().
However, I observed that 100% of the time I call malloc(), it returns NULL. I have confirmed that:

*

*The microcontroller memory is not full

*The error also occurs for size-1 malloc calls, so the memory chunk size is not the cause of the issues.

*errno is always ENOMEM after the malloc() call

How can I resolve this issue?

A: When you look at the definition of _sbrk in os/various/syscalls.c, you can clearly see that it always returns a ENOMEM error if CH_CFG_USE_MEMCORE == FALSE.
Unless you set CH_CFG_USE_MEMCORE = TRUE in chconf.h, the ChibiOS core memory manager is disabled completely and _sbrk and other memory-related functions are only included in the object files so no linking errors occur.
In order to properly configure ChibiOS correctly, ensure that the following is set in chconf.h:
#define CH_CFG_USE_MEMCORE                  TRUE

In order to avoid running into reliability issues, you might want to use memory pools or alternative algorithms instead where possible. See this detailed explanation for a description why malloc() is often a bad idea on embedded systems (it's actually forbidden in most embedded coding standards entirely).


text:
Q: How can retrieve pixel value using CvMat img->data.ptr[i,j]=img1.data.ptr[(m_c*w_in)+n_c];

I tried this but it is showing me only one value.
Any help can be appreciated.

A: first of all why are  you using the old interface. If you have new opencv then convert the CvMat to cv::Mat and then do the operations. Once you are done then you can convert the Mat back to CvMat.

A: First of all, switch to cv::Mat
Then, you have several ways to access pixel x,y:
cv::Mat img;
int x,y;

//[...] Initialize here x and y

cv::Point p(x,y);
int stride = img.step1();

//All of these are valid ways to access pixel x,y
img.at<uint8_t>(y,x); //Or, for example, cv::Vec3b in place of uint8_t in case of color images
img.at<uint8_t>(p);
//The following are valid only for grayscale 8-bit images, otherwise they have to be modified a bit
img.ptr(y)[x];
img.ptr()[y * stride + x];

In fact, once you switch to cv::Mat you can find other extensive answers here OpenCV get pixel channel value from Mat image and here Accessing certain pixel RGB value in openCV

A: This is an old question, just for anybody who do not have the luxury to use the newer cv:mat format, and must use cvmat to access pixel. Tested using OpenCV 1.1.
static unsigned long get_color(IplImage *img, CvPoint* pt, double *luma) {
    uchar blue, green, red;
    unsigned long color = 0;
    CvMat hdr;
    CvMat *mat = cvGetMat(img, &hdr);
    int col = mat->step / mat->cols;
    uchar *pix = mat->data.ptr + (pt->y * mat->step + pt->x * col);

    if (col == 1) {
        // Grayscale
        color = *pix;
        blue = color * 11 / 100;
        green = color * 59 / 100;
        red = color * 30 / 100;
    } else if (col == 3) {
        // 3 channel RGB
        blue = *pix;
        green = *(pix + 1);
        red = *(pix + 2);
        color = red << 16 | green << 8 | blue;
    } else {
        printf("Unsupported number of channel %d\n", col);
        return 0;
    }

    if (luma)
        *luma = 0.2126 * red + 0.7152 * green + 0.0722 * blue;

    printf("\n\nb=%x g=%x, r=%x color=%x\n", blue, green, red, color);
    printf("cols=%d, step=%d, col=%d, x=%d, y=%d loc=%d\n",
           mat->cols, mat->step, col, pt->x, pt->y,
           (pt->y * mat->step + pt->x * col));
    return color;
}

Output:
1. Output from a grayscaled 600x600 Red.jpeg file
// Pixel (0,0)
b=8 g=2c, r=16 color=4c
cols=600, step=600, col=1, x=0, y=0 loc=0

// Pixel (1,0)
b=8 g=2c, r=16 color=4c
cols=600, step=600, col=1, x=1, y=0 loc=1

// Pixel (1,1)
b=8 g=2c, r=16 color=4c
cols=600, step=600, col=1, x=1, y=1 loc=601

2. Output from a 3 channel rgb 600x600 Red.jpeg file
// Pixel (0,0)
b=0 g=0, r=fe color=fe0000
cols=600, step=1800, col=3, x=0, y=0 loc=0

// Pixel (1,0)
b=0 g=0, r=fe color=fe0000
cols=600, step=1800, col=3, x=1, y=0 loc=3

// Pixel (1,1)
cols=600, step=1800, col=3, x=1, y=1 loc=1803
b=0 g=0, r=fe color=fe0000

A: for accessing data using CvMat you have to use "img->data.ptr[x*col+y]" it can used to store data of uchar. CvMat also support double,float,string and integer type. So you can store data according to your convince.


text:
Q: JPAQL concat operation I am trying to do following to get output like 'MASTHANVALI - Technical Writer'
Query query = em.createQuery("select concat(upper(ename) , \" - \", deg )from employee");

But having following error.
Exception in thread "main" java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: Exception Description: Syntax error parsing [select concat(upper(ename) , " - ", deg )from employee].
[20, 25] The encapsulated expression is not a valid expression.
[37, 40] The expression 'deg' is not valid expression.
[54, 54] An identification variable must be provided for a range variable declaration.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1605)
at com.tutorialspoint.eclipselink.service.ScalarandAggregateFunctions.main(ScalarandAggregateFunctions.java:14) Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.JPQLException

Any idea how to do this?

A: try replacing the double quotes with single qoutes and add a space after the closing bracket
 Query query =
   em.createQuery("select concat(upper(ename) , ' - ', deg ) from employee");


text:
Q: adding ui with jquery plugin not working my plugin
$.fn.myplugin=function(){

var element=$('
').addClass('select').appendTo(this);

return this;
}

and script
$('
').myplugin().appendTo('body');

problem is element not appending.

A: It seems you code is OK.
$.fn.myplugin = function() {
    // hello is for just view purpose
    $('
hello
').addClass('select').appendTo(this);
    return this;
}

$('
').myplugin().appendTo('#target'); // here instead of '#target' use 'body'

DEMO
For collection
$.fn.myplugin = function() {
    return $.each(this, function() {
       $('
hello
').addClass('select').appendTo(this);
    });
}

Note
Put all your code within $(document).ready({ .. }).

A: add a document ready could help here too
    $(document).ready(function() {
            $('
').myplugin().appendTo('body');
    });

A: It works as is: http://jsfiddle.net/7n2Bd/
But you will have a problem if you are passing a collection of elements. Try this:
$.fn.myplugin=function() {
    return this.each(function() {
        $('
').addClass('select').appendTo(this);
    });
};


text:
Q: How to calculate accuracy for K-means clustering model from "Within Set Sum of Squared Errors" value in Spark? I am working with Spark and wondering how to obtain the accuracy value for the K-means clustering model created. While, checking the Spark - KMeansModel APIs, I found "ComputeCost" and that returns the "Within Set Sum of Squared Errors" value.
Is there a way to calculate accuracy of the model created from the "Within Set Sum of Squared Errors" value?
Or, is there any other option available in Spark to obtain it? Please advise me on this.
Thanks in advance :)

A: Accuracy is a useful metric in supervised learning, such as classification. However, in case of unsupervised learning (like KMeans), there is no accuracy (as there is no labeled data / gold standard you can evaluate against.
Assuming you are using Spark 2.3.0, you can use the ClusteringEvaluator for assessing the quality of your KMeansModel. You can find more information in the docs: https://spark.apache.org/docs/2.3.0/api/java/org/apache/spark/ml/evaluation/ClusteringEvaluator.html

A: If you use pyspark to run K-Means clustering, getting "Within Set Sum of Squared Errors" is fairly straighforward:
#K-Means
from pyspark.ml.clustering import KMeans

ClusterData=data.select("ID","features")

#Fitting
kmeans = KMeans().setK(10).setSeed(1)
model = kmeans.fit(ClusterData)

#Evaluation

wssse = model.computeCost(ClusterData)
print("Within Set Sum of Squared Errors = " + str(wssse))

#Results
centers = model.clusterCenters()
print("Cluster Centers: ")
for center in centers:
 print(center)

The cluster center information is another good indicator that could later be fed into a visualization tool.


text:
Q: How can I check an instance's type in Swift? I want to use an unwind segue to navigate from the current UIViewController to the second presenting UIViewController:
let unwindDestinationViewController = self.presentingViewController!.presentingViewController!
                    switch unwindDestinationViewController{
                    case is UIViewControllerSubclass:
                        self.performSegue(withIdentifier: "unwindToUIViewControllerSubclass", sender: self)
                        break
                    default:
                        break
                    }

However this does not work. I also tried changing the case statement to UIViewControllerSubclass.Type but it gave me an error: cast from UIViewController to unrelated type UIViewControllerSubclass always fails.
I'd really appreciate if someone could tell me what I am doing wrong.

A: Your code is correct for checking the type:
case is UIViewControllerSubclass:

Another way to test the class:
case let vc as UIViewControllerSubclass:

which is helpful if you need to access a method or property specific to that class.
If you don't need to use vc then just do:
case _ as UIViewControllerSubclass:

You could just use an if statement here:
if unwindDestinationViewController is UIViewControllerSubclass {
    self.performSegue(withIdentifier: "unwindToUIViewControllerSubclass", sender: self)
}


text:
Q: Safari: Can I open all bookmarks in a bookmark folder in a new window? Is it possible to open all bookmarks in a bookmark folder in Safari in a new Safari window?
I know that I can do this with a single bookmark, but can I do the same with a bookmark folder?

A: Open the Bookmarks menu, top left, right click the folder of bookmarks, Open in Tabs...

Though irritatingly, it re-uses the current window, so maybe start with a new one first.

A: Option click folder in Favorites.

A: use Bookmarks->Show BookMarks from the Safari menu. This will open all the list of bookmarks on your left side. There you can rearrange or edit the bookmarks.


text:
Q: Memory issue and duplicate in my C# program can someone help me fix this specific block of code?
This is my issue. I wrote a program that acts in a similar fashion as Windows Explorer, which gives me an hierarchy of files and folder within the hard drive and all other drives in a computer.
This piece of code below seemed to have an issue with running the program smoothly. When I start the program, the program starts off very slow and it takes a long while until it finally load. This is due to the fact that my program is going through all my files and folders before finally loading it. This can be bothersome for computers with lots of data.
I'm able to fix the problem by commenting out the two lines at the try block. But when I run the program and I open up a drive, it duplicates (example: when I expand C:/ drive, and then I collapse the C:/ drive, a duplicate of the C:/ drive shows up in the program)
Here are the images below.
image1

image2

And this is the piece of code I'm talking about. If you guys want the full code please let me know.
 private void GetDirectories(DirectoryInfo[] subDirs, TreeNode nodeToAddTo)
    {
        TreeNode aNode;
        DirectoryInfo[] subSubDirs;
        foreach (DirectoryInfo subDir in subDirs)
        {
            aNode = new TreeNode(subDir.Name, 0, 0);
            aNode.Tag = subDir;
            aNode.ImageKey = "folder";
            try
            {
                //subSubDirs = subDir.GetDirectories();
                //GetDirectories(subSubDirs, aNode);
                nodeToAddTo.Nodes.Add(aNode);
            }
            catch(Exception e)
            {
                Console.WriteLine("none");
            }
        }
    }

A: This code should not be written recuresively. This is the problem. Let's say that you have 100 directories. Every directory has 100 subdirectories. Every subdirectory has 100 sub-subdirectories. That's quite a lot. But does the user want to see deepest directory? No. He wants to see directories in the directory he is now. So you should list only directories and files that are in selected node.
So don't build the whole tree on startup. Just list main directories. And when user clicks a directory, list only it's subdirectories.


text:
Q: Slider on mobile view images not showing this is my slider code I got from codepen, I did some minor changes on it, but before and after changes in code, this slider not showing/loading images on any mobile view, I don't know how to solved it..
please help!!
My codepen link
https://codepen.io/guenon/pen/GRZrqgq
Some CSS link
https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css
Some JS links
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js

jQuery(function($){

    $('.flickfeed').on('init', function(){
        var currentfirst = $(this).find('.slick-active').first();
        $(currentfirst).addClass('firster');
        // console.log('thishere');
        var currentlast = $(this).find('.slick-active').last();
        $(currentlast).addClass('laster');
        });

    function getSliderSettings(){
        return {
            dots: false,
          infinite: true,
          speed: 300,
                    autoplay: true,
          slidesToShow: 6.17,
          slidesToScroll: 2,
          responsive: [
            {
              breakpoint: 1024,
              settings: {
                slidesToShow: 2.25,
                slidesToScroll: 2

              }
            },
            {
              breakpoint: 600,
              settings: {
                slidesToShow: 2,
                slidesToScroll: 1
              }
            },
            {
              breakpoint: 480,
              settings: {
                slidesToShow: 1,
                slidesToScroll: 1
              }
            }
            // You can unslick at a given breakpoint now by adding:
            // settings: "unslick"
            // instead of a settings object
          ]
        }
    }

    $('.flickfeed').slick(getSliderSettings());

    $( ".slick-slide" ).mouseenter(function() {

       if ($(this).hasClass("firster")) {
         //  console.log('firster');
           var hoverslide = $(this);
            $(hoverslide).nextAll().addClass('furthernextslides');
          //  $(hoverslide).prevAll().addClass('prevslides');

       }else if ($(this).hasClass("laster")){
           var hoverslide = $(this);
            $(hoverslide).prevAll().addClass('furtherprevslides');
        }else{
             var hoverslide = $(this);
            $(hoverslide).nextAll().addClass('nextslides');
            $(hoverslide).prevAll().addClass('prevslides');
        }

    });

    $( ".slick-slide" ).mouseleave(function() {
      $(this).parent().find( ".slick-slide" ).removeClass('nextslides');
    $(this).parent().find( ".slick-slide" ).removeClass('prevslides');
      $(this).parent().find( ".slick-slide" ).removeClass('furthernextslides');
      $(this).parent().find( ".slick-slide" ).removeClass('furtherprevslides');
    });

    // on slide change, find the new first slide-active
    $('.flickfeed').on('afterChange', function(event, currentSlide, nextSlide){
     var currentfirst = $(this).find('.slick-active').first();
     $(this).find( ".slick-slide" ).removeClass('firster');
     $(currentfirst).addClass('firster');
    var currentlast = $(this).find('.slick-active').last();
     $(this).find( ".slick-slide" ).removeClass('laster');
     $(currentlast).addClass('laster');
    });

    // on slide init, find the new first slide-active

});
body {
    background: #141414;
    color: #eee;
}

.slick-track
{
    display: flex !important;
  padding: 40px 3px;
}

.slick-slide
{
    margin: 1px;
    height: inherit !important;

    > div {    height: 100% !important;}
}

button.slick-arrow {
    font-size: 0;
    line-height: 0;
    position: absolute;
    top: 0;
    display: block;
    height: 61.8%;
    top: 18%;
    background: rgba(0,0,0,.5);
    padding: 0;
    cursor: pointer;
    color: transparent;
    border: none;
    outline: none;
    text-rendering: auto;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    z-index: 10;
   width: 2.5vw;
    background-repeat: no-repeat;
    background-position: center center;
}

button.slick-arrow.slick-next {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='width:24px;height:24px' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z' /%3E%3C/svg%3E");
    right: 0px;

}

button.slick-arrow.slick-prev {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='width:24px;height:24px' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z' /%3E%3C/svg%3E");
    left: 0px;

}

button.slick-disabled {
    opacity: 0!important;
}

.flickfeed {
    opacity:0;
}

.slick-initialized{
    opacity:1;
    transition:opacity .3s ease-out;
}

.flix-parents {overflow: hidden;}

.flix-parents{
    position: relative;
    z-index: 5;
   // height: 500px;
}
.flixer {
    position: relative;
    z-index: 5;
    height: 500px;
}

.video-list-slider {
    background: 0 0;
    border: none;
    border-radius: 0;
    overflow: visible;
}

.slick-list {
 overflow: visible;
}

.flickfeed .slick-slide .card {
    border-radius: 0px;
@include anislow;
    //animation-delay: 0.5s;
    padding-top: 55%; background-size: cover; background-repeat: no-repeat; border:0;
}

.slick-slide {
  //  transition-delay: 0.5s;
    @include anislow;
    &:hover {
      //  animation-delay: 0.5s;
      transform: scale(1.5); z-index: 3;
}
}
.prevslides {
    transform: translateX(-3.95vw);

}

.nextslides {
    transform: translateX(3.95vw);
    }

.furthernextslides {
    transform: translateX(7.9vw);
    }
.furtherprevslides {
    transform: translateX(-7.9vw);
    }

.firster {transform-origin: center left!important;}
.laster {transform-origin: center right!important;}

.flickfeed .card {position: relative; overflow: hidden;
    .back {position: absolute; height: 100%; width: 100%;
   // background-image: linear-gradient(rgba(0,0,0,0),#000);
   // background-color: #222;
        background-image: linear-gradient(to top, rgba(0, 0, 0, 0.7) 10%, rgba(0, 0, 0, 0));
    background-color: transparent;
    top: 100%; @include anislow;
        h1, p {margin: 0; color: #fff;}
    }
    &:hover .back{top: 1px;}
}

.back .h4 {font-size: 14px; font-weight: 700; margin-bottom: 5px;}
.back p {font-size: 12px; oapcity: 0.9;}

button.more { position: absolute;
bottom: 10px; width: 100%; height: 10%;
    left: 0;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='width:24px;height:24px' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z' /%3E%3C/svg%3E");
    left: 0px;
    background-repeat: no-repeat;
    background-position: center center;
    color: transparent; font-size: 0px;

background-color: transparent; border: 0; outline: 0;
}

A: Please try this instead,
Codepen demo : https://codepen.io/Rayeesac/pen/rNejyvM

$(".flickfeed").on("init", function () {
  var currentfirst = $(this).find(".slick-active").first();
  $(currentfirst).addClass("firster");
  var currentlast = $(this).find(".slick-active").last();
  $(currentlast).addClass("laster");
});

$(".flickfeed").slick({
  dots: false,
  infinite: true,
  speed: 300,
  autoplay: true,
  slidesToShow: 6.17,
  slidesToScroll: 2,
  responsive: [
   {
    breakpoint: 1024,
    settings: {
     slidesToShow: 2.25,
     slidesToScroll: 2,
    },
   },
   {
    breakpoint: 600,
    settings: {
     slidesToShow: 2,
     slidesToScroll: 1,
    },
   },
   {
    breakpoint: 480,
    settings: {
     slidesToShow: 1,
     slidesToScroll: 1,
    },
   },
  ],
});

$(".slick-slide").mouseenter(function () {
  if ($(this).hasClass("firster")) {
   var hoverslide = $(this);
   $(hoverslide).nextAll().addClass("furthernextslides");
  } else if ($(this).hasClass("laster")) {
   var hoverslide = $(this);
   $(hoverslide).prevAll().addClass("furtherprevslides");
  } else {
   var hoverslide = $(this);
   $(hoverslide).nextAll().addClass("nextslides");
   $(hoverslide).prevAll().addClass("prevslides");
  }
});

$(".slick-slide").mouseleave(function () {
  $(this).parent().find(".slick-slide").removeClass("nextslides");
  $(this).parent().find(".slick-slide").removeClass("prevslides");
  $(this).parent().find(".slick-slide").removeClass("furthernextslides");
  $(this).parent().find(".slick-slide").removeClass("furtherprevslides");
});

//on slide change, find the new first slide-active
$(".flickfeed").on("afterChange", function (event, slick, currentSlide, nextSlide) {
  var currentfirst = $(this).find(".slick-active").first();
  $(this).find(".slick-slide").removeClass("firster");
  $(currentfirst).addClass("firster");
  var currentlast = $(this).find(".slick-active").last();
  $(this).find(".slick-slide").removeClass("laster");
  $(currentlast).addClass("laster");
});
body {
 background: #141414 !important;
 color: #eee;
}
.slick-slide img {
 height: 150px;
}
.slick-track {
 display: flex !important;
 padding: 40px 3px;
 position: absolute;
 top: 0;
 left: 0;
}
.slick-slide {
 margin: 1px;
 height: inherit !important;
}
.slick-slide > div {
 height: 100% !important;
}
button.slick-arrow.slick-prev {
 background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='width:24px;height:24px' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M15.41,16.58L10.83,12L15.41,7.41L14,6L8,12L14,18L15.41,16.58Z' /%3E%3C/svg%3E");
 left: 0px !important;
}
button.slick-arrow.slick-next {
 background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' style='width:24px;height:24px' viewBox='0 0 24 24'%3E%3Cpath fill='white' d='M8.59,16.58L13.17,12L8.59,7.41L10,6L16,12L10,18L8.59,16.58Z' /%3E%3C/svg%3E");
 right: 0px !important;
}
button.slick-disabled {
 opacity: 0 !important;
}
button.slick-arrow {
 font-size: 0;
 line-height: 0;
 position: absolute;
 display: block;
 height: 61.8%;
 top: 15%;
 background: rgba(0, 0, 0, 0.5);
 padding: 0;
 cursor: pointer;
 color: transparent;
 border: none;
 outline: none;
 text-rendering: auto;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 z-index: 10;
 width: 2.5vw;
 background-repeat: no-repeat;
 background-position: center center;
}
.flickfeed {
 opacity: 0;
}
.slick-initialized {
 opacity: 1;
 transition: opacity 0.3s ease-out;
}
.flix-parents {
 overflow: hidden;
}
.flix-parents {
 position: relative;
 z-index: 5;
}
.flixer {
 position: relative;
 z-index: 5;
 height: 500px;
}
.slick-list {
 overflow: visible;
}
.slick-slide:hover {
 transform: scale(1.5) !important;
 z-index: 3;
}
.prevslides {
 transform: translateX(-3.95vw);
}
.nextslides {
 transform: translateX(3.95vw);
}
.furthernextslides {
 transform: translateX(7.9vw);
}
.furtherprevslides {
 transform: translateX(-7.9vw);
}

.firster {
 transform-origin: center left !important;
}
.laster {
 transform-origin: center right !important;
}
.slick-list {
 display: flex;
 justify-content: center;
 align-items: center;
}
.flickfeed .slick-slide .card {
 background-size: cover;
 background-repeat: no-repeat;
 border: 0;
}
.flickfeed .slick-slide {
 transform: scale(1);
 position: relative;
}
.flickfeed .slick-active:first-child .card {
 transform-origin: center left;
}
.flickfeed .slick-track {
 height: auto;
}
.flickfeed .slick-list {
 overflow-y: visible;
 height: 255px;
 overflow-x: hidden;
}
@media only screen and (max-width: 640px) {
 button.slick-arrow {
  width: 5vw;
 }
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css" integrity="sha512-yHknP1/AwR+yx26cB1y0cjvQUMvEa2PFzt1c9LlS4pRQ5NOTZFWbhBig+X9G9eYW/8m0/4OXNx8pxJ6z57x0dw==" crossorigin="anonymous" />


text:
Q: Why do I have difference in output to console Why do I have difference in output?
$f = Get-WindowsFeature
$f[1].GetType()
$f[1]

output
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Name                      : ADCS-Cert-Authority
DisplayName               : Certification Authority
Description               : Certification Authority (CA) is used to issue and manage certificates. Multiple CAs can be linked to form a public key infrastructure.
...
and
$f = Get-WindowsFeature
$f[1]

output
Display Name                                    Name                       Install State
------------                                    ----                       -------------
[ ] Certification Authority                     ADCS-Cert-Authority            Available
Also get more verbose output from $lines.GetType() if don't remove $f[1].
$f = Get-WindowsFeature
$f[1]

$lines = Get-Content featuresinarray.txt | Where {$_ -notmatch '^\s+$'}
$lines.GetType()

output
Display Name                                    Name                       Install State
------------                                    ----                       -------------
[ ] Certification Authority                     ADCS-Cert-Authority            Available

Module                     : CommonLanguageRuntimeLibrary
Assembly                   : mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
TypeHandle                 : System.RuntimeTypeHandle
DeclaringMethod            :
BaseType                   : System.Array
But now if I add $f.GetType() after $f = Get-WindowsFeature I get short output from both $lines.GetType() and $f.GetType():
True     True     Object[]                                 System.Array
If I add $f.GetType() after $lines.GetType() then I have 2 times verbose output of Array class in ouput. So why this is happening?


text:
Q: Sqlite database location via javascript in the context of Chrome browser [PRE-NOTE: I am targeting only chrome/android default browser]
Hi,
I am currently using js statement var db = openDatabase ('db_name', '', 'db_desc', 2*1024*1024); to open sqlite database and run my transactions.
I find the sqlite file located at C:\Documents and Settings\Administrator\Local Settings\Application Data\Google\Chrome\User Data\Default\databases\file__0\5.
Can I somehow indicate the location to my sqlite database file explicitly (absolute path or something as mentioned here)?
I see this can be done for XUL applications e.g. var con = new SQLite("test.sqlite",{location:'Desk'});.

A: No, you can't specify a SQLite database manually.
The web sql database support in Chrome sandboxes the database to a specific origin (schema, host, port combination), and handles the database's creation and permissions transparently. It's quite different than the SQLite API in XUL, but has the advantage of being useful inside everyday web applications that don't require permissions to access arbitrary bits of the local computer's filesystem.


text:
Q: Finding $a$ and $b$ so that the function is continuous $$f(x) = \begin{cases}
\displaystyle\frac{x^2-4}{x-2}&\quad x<2\\[0.4em]
ax^2-bx+3&\quad 2 \leq x <3\\[0.3em]
2x-a+b&\quad x \geq 3
\end{cases}$$
I can't make the right limit of second piece equal to left limit of the first piece. And then how to solve for a and b? I get $4a-2b = 1$ but what do I do with that?
When I try to graph it I'm confused about how to get the $y$-values.

A: First note that $f$ is continuous over $\mathbb R \backslash \{2, 3\}$. Then take the limits as $x$ approaches those two points:
$$\begin{align}
\lim_{x \to 2^-}f(x) &= \lim_{x \to 2^-}\frac{x^2-4}{x-2} = 4\\
\lim_{x \to 2^+}f(x) &= \lim_{x \to 2^+}\left[ax^2 - bx + 3\right] = 4a - 2b + 3 = f(2)\\
\lim_{x \to 3^-}f(x) &= \lim_{x \to 3^-}\left[ax^2 - bx + 3\right] = 9a - 3b + 3\\
\lim_{x \to 3^+}f(x) &= \lim_{x \to 3^+}\left[2x - a + b\right] = 6 - a + b = f(3)\\
\end{align}$$
The first two have to be equal, and that holds for the last two as well. That's because if $x_0$ is an accumulation point for $f$, then $f$ is continuous in $x_0$ if $\lim_\limits{x \to x_0} f(x) = f(x_2)$: for this to happen the limits from the sides have to be equal. We then have a system of two equations in two unknowns, which is solvable:
$$\begin{cases}
4a - 2b + 3 &= 4\\
9a - 3b + 3 &= 6 - a + b
\end{cases}$$
The solution to the system is
$$\begin{cases}
a = \frac12\\
b = \frac12
\end{cases}$$
And those two values are the only values for which $f$ is continuous over $\mathbb R$.


text:
Q: Display a user's picture or avatar in the header using twitter bootstrap I am trying to insert the user's avatar next to the username in the bootstrap 3 header. I'm having a very hard time achieving this, and I don't want to hack into the provider's css. Any one has already done this ? Thanks for your help

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>
                    Foo's Bar

Awesome link

More Awesome link

                            Something 0

Chuck Norris

Log off

Edit : the Bootply's link, because that's what friends do ! http://www.bootply.com/X4FhzJiP3T

A: The avatar appears next to the username. If it's a styling or placement issue you're experiencing, just add a custom class to the avatar image and style accordingly
.avatar {
    /* put custom avatar css here */
}

I also added the .img-responsive class to the avatar...

        Chuck Norris


text:
Q: mouseout() not firing on disappearing objects The following is happening (see gif)

*

*I show a fontawesome icon that changes on mouseenter() and mouseout()

*Clicking a button hides the icons and makes new elements appear.

*Going back and making the old elements appear, the mouse technically never "left" the icons, so the fontawesome icon for the hovering state is still displayed.

Isn't there a way to have mouseout() firing whenever an element disappears? Because logically, the mouse isn't hovering that element anymore then

Here is the code, changing the icons is done by replacing the fontawesome prefix.
<div (mouseover)="ratingEmojis.right='fas'" (mouseout)="ratingEmojis.right='far'" (click)="this.state.jumpToConfigStep(100)" class="iconButton">
  <fa-icon style='pointer-events: none' [icon]="[ratingEmojis.right, 'frown-open']" size="6x" ></fa-icon>
</div>

A: Just change it to default icon when onclick is fired

A: I'm not sure what this.state.jumpToConfigStep(100) does but you could do this:
<div (mouseover)="ratingEmojis.right='fas'" (mouseout)="ratingEmojis.right='far'" (click)="rightClicked()" class="iconButton">
  <fa-icon style='pointer-events: none' [icon]="[ratingEmojis.right, 'frown-open']" size="6x" ></fa-icon>
</div>

rightClicked() {
   this.ratingEmojis.right = 'frown-open';
   this.state.jumpToConfigStep(100)
}

Though most of this looks like it could be achieved with css and :hover


text:
Q: Does AWS allow us to pre-process email for clients using SES? I'd like to pre-process my clients email via AWS SES, but I'm not sure Amazon allows for this per their policy and/or has a domain limitation. I see a rule-set for my SES engine and I'm able to manage multiple domain names, but these are my own. If I wanted to managed 100 or 200 domain names, would AWS SES allow me to do this?

A: If your clients grant you permission to manage their email on their behalf, it's not up to Amazon to tell you if you can or cannot. Remember, they are providing Infrastructure as a Service (IaaS).
As far as if it's possible technically, you'll have to either create your own e-mail client that integrates with SES or use Amazon WorkMail.

A: You can send any number of emails(based on your SES limits) and manage any number of domains as long as you comply with amazon policies. All they care about it quality of email response, if someone report spam and if your spam ration is high then your account might be at risk.


text:
Q: I cant make my discord bot fetch messages and add it to an embed const channel = client.channels.cache.get("844038570167238710");
const fetchedMessage = channel.messages.cache.fetch({ limit: 1 }).then(messages => {
  const embedtest = new Discord.MessageEmbed().setTitle("Test for embed send").setColor('#34d2eb').setFooter("Bot by").setThumbnail().setAuthor().setDescription(`${fetchedMessage}`);
  if (!fetchedMessage.author.bot) {
    message.channel.send(embedtest);
  }
}).catch(console.error);

I want the discord js bot to fetch messages from the channel add them in an embed and send them again to the same channel. I don't know why but this code isn't working.
Please help I'm stuck here for 1+ week.
Console log-
const fetchedMessage = channel.messages.cache.fetch({ limit: 1 }).then(messages => {
                               ^

TypeError: Cannot read property 'messages' of undefined
    at Object.<anonymous> (/home/container/index.js:34:33)

A: there is 3 errors in your example code .
1 . channel1 is not defined it's channel.
2 . you assigned fetchedMessage is a promise not a result. And if it's right it can be Message object so we can access fetchedMessage.content
3 . messages.cache.fetch() is not exactly it is messages.fetch().
So the working code will be :
Note: your execute function must be async

const channel = client.channels.cache.get("844038570167238710");
const fetchedMessage = await channel.messages.fetch({ limit: 1 });
// You can also do like this too
const fetchedMessage = await message.channel.messages.fetch({ limit: 1 });
const embedtest = new Discord.MessageEmbed()
  .setTitle("Test for embed send")
  .setColor("#34d2eb")
  .setFooter("Bot by")
  .setThumbnail()
  .setAuthor()
  .setDescription(`${fetchedMessage.content}`);
if (!fetchedMessage.author.bot) {
  message.channel.send(embedtest);
}


text:
Q: Not able to compute value of negative base in JAVA In my Android app I am trying to evaluate the expression: (-2^(x)) but can't seem
to get the Math.pow() method from the JAVA library to work. I am able to evaluate (2^(x)) but not the other with negative base.
Here is a look at the Logs. The y values are all returned as NaN.

to evaluate I am using the following statements:
double result = Math.pow(x,exponent);
result = coefficient * result;

I don't know what might seem to be the problem. Perhaps is the way the negative base is set up.
thanks for any advice
    return multiplier * Math.pow(base,result);

A: Assuming that you are trying to compute (-2) to the power x, where x is one of the x values shown in the image: this does not work unless x is an integer.  The reason is that the answer is not a real number.  (For example, what is (-1)^0.5?  That's the square root of -1, which is i, an imaginary number, not a real number.)  The x values shown in the image are all non-integers (there appear to be some that are very close to integers but still aren't--there's a non-zero in the last decimal place).  Thus, the results all come out as NaN.
This is explicit in the javadoc for Math.pow:

If the first argument is finite and less than zero:
if the second
argument is a finite even integer, the result is equal to the result
of raising the absolute value of the first argument to the power of
the second argument
if the second argument is a finite odd integer,
the result is equal to the negative of the result of raising the
absolute value of the first argument to the power of the second
argument
if the second argument is finite and not an integer, then the
result is NaN.

If what you're doing is something other than (-2)^x, then your question is confusing and needs clarification.

A: A negative base with a fractional exponent is a complex number with a real and imaginary part.  The Math.pow function is not equipped to return a complex number; a double return value can't represent or refer to a complex value.
The problem happens because of the way all languages represent floating point numbers.  You can no more represent 0.1 exactly as a binary number than you can 1/3 using base 10.


text:
Q: Assign std::vector to std::vector WITHOUT copying memory I have a function that returns a std::vector<std::byte>
I am aware that std::byte is not a character type nor an integral type, and that converting it to char is only possible through a typecast. So far so good.
So I would like (in cases where I know that the vector only contains character data) to transfer ownership of the underlying buffer from the std::vector<std::byte> to a std::vector<char> using std::move, so as to avoid copying the entire underlying buffer.
When I try doing this, I get this error:

no suitable user-defined conversion from "std::vector<std::byte, std::allocatorstd::byte>" to "std::vector<char,std::allocator>" exists

Is this at all possible using C++?
I think there are real use cases where one would want to do this

A: I would probably leave the data in the original vector<byte> and make a small class that keeps a reference to the original vector<byte> and does the necessary casting when you need it.
Example:
#include <cstddef>
#include <iostream>
#include <vector>

template<typename T>
struct char_view {
    explicit char_view(std::vector<T>& bytes) : bv(bytes) {}

    char_view(const char_view&) = default;
    char_view(char_view&&) = delete;
    char_view& operator=(const char_view&) = delete;
    char_view& operator=(char_view&&) = delete;

    // capacity
    size_t element_count() const { return bv.size(); }
    size_t size() const { return element_count() * sizeof(T); }

    // direct access
    auto data() const { return reinterpret_cast<const char*>(bv.data()); }
    auto data() { return reinterpret_cast<char*>(bv.data()); }

    // element access
    char operator[](size_t idx) const { return data()[idx]; }
    char& operator[](size_t idx) { return data()[idx]; }

    // iterators - with possibility to iterate over individual T elements
    using iterator = char*;
    using const_iterator = const char*;

    const_iterator cbegin(size_t elem = 0) const { return data() + elem * sizeof(T); }
    const_iterator cend(size_t elem) const { return data() + (elem + 1) * sizeof(T); }
    const_iterator cend() const { return data() + size(); }

    const_iterator begin(size_t elem = 0) const { return cbegin(elem); }
    const_iterator end(size_t elem) const { return cend(elem); }
    const_iterator end() const { return cend(); }

    iterator begin(size_t elem = 0) { return data() + elem * sizeof(T); }
    iterator end(size_t elem) { return data() + (elem + 1) * sizeof(T); }
    iterator end() { return data() + size(); }

private:
    std::vector<T>& bv;
};

int main() {
    using std::byte;

    std::vector<byte> byte_vector{byte{'a'}, byte{'b'}, byte{'c'}};

    char_view cv(byte_vector);

    for(char& ch : cv) {
        std::cout << ch << '\n';
    }
}

Output:
a
b
c

A simpler option if you only need const access could be to create a string_view:
template<typename T>
std::string_view to_string_view(const std::vector<T>& v) {
    return {reinterpret_cast<const char*>(v.data()), v.size() * sizeof(T)};
}
//...
auto strv = to_string_view(byte_vector);

A: std::vector does not allow attaching or detaching to memory allocations , other than moves from a vector of exactly the same type.  This has been proposed but people raised (valid) objections about the allocator for attaching and so on.
The function returning vector<byte> constrains you to work with a vector<byte> as your data container unless you want to copy the data out.
Of course, you can alias the bytes as char in-place for doing character operations.

A: You can achieve this with a cast, as shown below.  This is legal because the cast is to a char reference (if casting to any other type it would be UB) but, with gcc at least, you still have to compile it with -fno-strict-aliasing to silence the compiler warning.  Anyway, here's the cast:
std::vector <char> char_vector = reinterpret_cast <std::vector <char> &&> (byte_vector);

And here's a live demo


text:
Q: Why does Java compiler complain when I use Comparator.comparingand thenCompare I  have a Person class that has 2 fields, one is name, and the other is age, I would like to sort by age first and then by name.
Simple code is as follows:
import java.util.ArrayList;
import java.util.List;

public class Person {
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }

    String name;
    int age;

    public static List<Person> getPersons() {
        List<Person> persons = new ArrayList<>();
        Person p1 = new Person();
        p1.name = "Jack";
        p1.age = 29;
        persons.add(p1);

        p1 = new Person();
        p1.name = "Tom";
        p1.age = 27;
        persons.add(p1);

        p1 = new Person();
        p1.name = "Don";
        p1.age = 27;
        persons.add(p1);

        return persons;
    }

}

Test code is:
    @Test
    public void testComparator() {
        List<Person> persons = Person.getPersons();
        persons.sort(Comparator.comparing(p->p.getAge()).thenComparing(p->p.getName()));
        System.out.println(persons);
    }

It complains that getAge and getName are not methods of Object, I would ask where the problem is.


text:
Q: cannot import mongoengine from a python file which require SUDO to execute I want to import mongoengine in a python file which requires sudo to execute but I am getting the following error ModuleNotFoundError: No module named 'mongoengine'. I have tried the following:
1/ In terminal I have opened python shell and written pip show mongoengine and it can detect the version and location which means that library is installed correctly.
2/ I have tried to run the code by removing the sudo required part then also code has executed.
Which strength the point that using sudo python3 pyfile_name.py is causing the problem.
I am using it in a Flaks environment. Below I am giving the example code.
mongo_data.py

from mongoengine import *
from random import random, randint

connect(
    db='db_name',
    host='localhost',
    port=27017
)

class Mongo_User(Document):
    user_id = SequenceField(primary_key=True)
    json_data = DictField()
    meta = {'collection': "col_name"}

app.py
from flask import Flask, render_template, request, Response
from flask import jsonify
from mongo_data import *

app = Flask(__name__)
app.static_folder = os.path.abspath("templates/static/")

@app.route('/get_json_for_form')
def parse_get_json_for_form(name=None):
    user = Mongo_User()
    json_data = {"name":"xyz"} # sample data
    user.json_data = json_data
    user.save()
    return jsonify(json_data)

In my case, app.py must be run with sudo python3 app.py and which is causing the problem I guess. Any idea to overcome the problem is highly appreciable.

A: Got the answer by following this comment. Just used
sudo -E python3 app.py

Another way has also found but don't think as a recommended one
sudo python3 -m pip install mongoengine


text:
Q: FileNotFoundException Error creating Database WP8 Sqlite I am following this tutorial to create an application with an SQLite database.
When I executed it, I got System.IO.FileNotFoundException pointing to the file SQLite.cs, the line where the error originated is shown in the screen shot below(in the SQLite.cs file)

Below is the code snippet for creating a database
string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
if (!FileExists(dbPath).Result)
{
   using (var db = new SQLiteConnection(dbPath))
   {
        db.CreateTable<Person>();
   }
}

and the method FileExists
        private async Task<bool> FileExists(string fileName)
        {
            var result = false;
            try
            {
                var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
                result =true;
            }
            catch
            {
            }

            return result;

        }

I am wondering what went wrong. Any help?

A: With the line if (!FileExists(dbPath).Result) you're saying that if the file doesn't exist, connect to the database and create a table. So your condition is wrong, because the line
Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName)

wants an existing file to execute correctly.
Correct then your if condition with:
if (FileExists(dbPath).Result)


text:
Q: Alpinejs nesting x-data scope issue? How do I achieve x-data nested x-data component? The "showSingleOrDouble" works but the inner input with click "mainOptions" does not work.

            <input type="radio" name="test" @click="mainOptions= 'bienvenida'"> Welcome
            <input type="radio" name="test" @click="mainOptions= categorias"> Categories

            Showing this div

    // This is the div I want to show

            ....items to show

A: You are missing single quotes around categorias in the @click of the <input>.
Change:
<input type="radio" name="test" @click="mainOptions= categorias"> Categories

to:
<input type="radio" name="test" @click="mainOptions= 'categorias'"> Categories


text:
Q: How to access global variables from a thread in Python Consider the following code:
from threading import Thread

def main():
    number = 5

    class my_thread(Thread):
        def __init__(self, range):
            Thread.__init__(self)
            self.range = range

        def run(self):
            global number
            for i in self.range:
                number += 1

    t1 = my_thread(range(4))
    t1.start()
    t1.join()
    print number

main()

The output from this program is
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Tools\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Dev\Workspace\Hello World\Hello.py", line 14, in run
    number += 1
NameError: global name 'number' is not defined

5

Evidently, my_thread does not have access to number. Why is this, and how can I access it correctly?

A: You need to make number a global at its first definition, like this:
def main():
    global number
    number = 5

...etc...


text:
Q: A way to pin the screen refresh rate? So I've got a HP Probook 440 G6 with a full HD display. By default, Ubuntu 18.04 uses 1920x1080 resolution and 120.02Hz refresh rate. I believe (or found info about it somewhere) that high (and rather non standard) refresh rate is causing screen flickering sometimes. So I set it to 59.96Hz manually on every boot and it seems to solve the issue.
I would want it to be automated how can I do that.
Also are there recommended values for full HD screens?


text:
Q: Spring "webflux oauth2 resource server" with anonymous endpoint i'm using spring-boot-starter-oauth2-resource-server 2.3.6.RELEASE.
As described here the security config has to be done by providing:
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
        .authorizeExchange(exchanges -> exchanges
            .pathMatchers("/message/**").hasAuthority("SCOPE_message:read")
            .anyExchange().authenticated()
        )
        .oauth2ResourceServer(oauth2 -> oauth2
            .jwt(withDefaults())
        );
    return http.build();
}

Does anybody has an idea, how to add a "public" endpoint in the resource server, that is accessible ba an anonymous user?
Thanks Fredy
--- update 17.2.2021 8:43 ---
I changed the code as suggested, but still get a Access Denied.
In org.springframework.security.access.expression.SecurityExpressionRoot
Line 111 -> isAuthenticated() is returning false. That's correct, but for me just not so great.
@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
            .authorizeExchange(exchanges -> exchanges
                    .pathMatchers("/init").permitAll()
                    .pathMatchers("/message/**").hasAuthority("SCOPE_message:read")
                    .anyExchange().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
    return http.build();
}

Log:
2021-02-17 08:33:11 DEBUG [http-nio-8082-exec-2] org.springframework.security.web.FilterChainProxy [FilterChainProxy.java:328] /error at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2021-02-17 08:33:11 DEBUG [http-nio-8082-exec-2] org.springframework.security.web.FilterChainProxy [FilterChainProxy.java:328] /error at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2021-02-17 08:33:11 DEBUG [http-nio-8082-exec-2] org.springframework.security.web.access.intercept.FilterSecurityInterceptor [AbstractSecurityInterceptor.java:219] Secure object: FilterInvocation: URL: /error; Attributes: [authenticated]
2021-02-17 08:33:11 DEBUG [http-nio-8082-exec-2] org.springframework.security.web.access.intercept.FilterSecurityInterceptor [AbstractSecurityInterceptor.java:348] Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@615c75f9: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1CF0ACC15C790FEA93EF30F39DDC6492; Granted Authorities: ROLE_ANONYMOUS
2021-02-17 08:33:11 DEBUG [http-nio-8082-exec-2] org.springframework.security.access.vote.AffirmativeBased [AffirmativeBased.java:66] Voter: org.springframework.security.web.access.expression.WebExpressionVoter@4e3ebe19, returned: -1
2021-02-17 08:33:11 DEBUG [http-nio-8082-exec-2] org.springframework.security.web.access.ExceptionTranslationFilter [ExceptionTranslationFilter.java:180] Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)

A: A public endpoint is added in the same way that the /message endpoint was added:
http
    .authorizeExchange(exchanges -> exchanges
        .pathMatchers("/my/public/endpoint").permitAll()
        .pathMatchers("/message/**").hasAuthority("SCOPE_message:read")
        .anyExchange().authenticated()
    )
    // ...

The path matchers are interpreted one at a time for each request. The rules from the first path match are applied.

A: The reason was that the WebSecurityConfig was not in the "scanBasePackages" of  @SpringBootApplication.


text:
Q: Background Color of grid.arrange in gridExtra So I am trying to draw a few ggplots and their legend using gridExtra. The legend appears in the last cell on a white background - I would like to change the background color there, so that white background disappears. How can I do that?
Here's my code:
library(reshape)
library(ggplot2)
library(plyr)
library(wq)
library(gridExtra)
library(lattice)
library(grid)

testVisualization <- function()
{
  set.seed(123)

  xx <- sample(seq(from = 20, to = 50, by = 5), size = 50, replace = TRUE)
  yy <- sample(seq(from = 1, to = 50), size = 50, replace = TRUE)
  zz <- sample(seq(from = 1, to = 10, by = 1), size = 50, replace = TRUE)

  dd <- data.frame(xx,yy,zz)

  colRainbow <- rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha = 1)
  gg <- ggplot() + geom_point(data=dd, aes(x=xx, y=yy, colour=zz))+
    theme_custom()

  lay2 <- rbind(c(1,1,1,1,1),
                c(2,2,3,3,4))
  legg1 <- g_legend(gg)

  grid.arrange(
    gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
    gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
    gg+guides(fill=FALSE, colour=FALSE, size=FALSE),
    legg1,
    layout_matrix=lay2)
}

theme_custom <- function()
{
  theme(
    plot.background = element_rect(fill = "#002B36", colour = "#002B36"),
    panel.background = element_rect(fill = "#002B36"),
    panel.background = element_rect(fill = "#002B36"),
    legend.background = element_rect(fill="#002B36", colour = "#002B36"),
    legend.margin = unit(c(-4, -4), "cm"),
    legend.key = element_rect(fill="#002B36", colour ="#002B36"),
    legend.text =element_text(colour = "#DCD427"),
    legend.title=element_text(colour = "#DCD427")

  )
}

g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  #+ legend.margin = unit(-0.5, "cm")
  legend
}

A: Try this,
g_legend<-function(gg){
  tmp <- ggplot_gtable(ggplot_build(gg))
  id <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  leg <- tmp$grobs[[id]]
  bkg <- leg[["grobs"]][[1]][["grobs"]][leg[["grobs"]][[1]][["layout"]][,"name"]=="background"][[1]][["gp"]][["fill"]]
  leg <- gtable_add_grob(leg, grobs = rectGrob(gp=gpar(fill=bkg, col="red", lty=2)),
                         t=1, l=1, b=nrow(leg), r=ncol(leg), z=-1)

  # no idea why, but the legend seems to have weird negative sizes
  # that make the background overlap with neighbouring elements
  # workaround: set those unidentified sizes to 1null
  leg$widths[c(1,2,4,5)] <- unit(rep(1,4),"null")
  leg$heights[c(1,2,4,5)] <- unit(rep(1,4),"null")
  leg
}


text:
Q: Snapshot of KyotoCabinet database concurrent to writes Is it possible in Kyoto Cabinet database to make safely a database snapshot and concurrently write to database in the same time ?
The KyotoCabinet database class kyotocabinet.DB (for JAVA among other languages)
provides the following methods:
 boolean    dump_snapshot(String dest) // Dump records into a snapshot file.
 boolean    copy(String dest) // Create a copy of the database file.

Both operations could be quite long. I did not test this methods directly but by using the kcpolymgr utility from different process. I found that the operations blocks other writer process-es (kcpolymgr set) until the operations finish.
Is the behaviour the same when writes come from other threads in the same process ?

A: The snapshot or copy of the database blocks concurrent database operations from other threads and processes.
To test within the same process I exposed the Kyoto Cabinet methods by JMX and tried to set or get any value from the database while concurrently a snapshot or a copy were being in progress.
Methods set and get were waiting for the concurrent snapshot or copy to finish.

I found a part of the documentation that covers the issue. It mansions the cache hash database but it looks like the other database implementations behaves similarly:

Chiefly for the cache hash database and the cache tree database, the
  "pseudo-snapshot" mechanism is provided. The BasicDB::dump_snapshot'
  dumps all records into a stream or a file. The
  BasicDB::load_snapshot' method loads records from a stream or a file.
  Although the operations are performed atomically, they don't finish
  momentarily but take time in proportion of the database size with
  blocking the other threads. Because the format of pseudo-snapshot data
  is common among the all database classes, it is useful to migrate
  records for each other.
db.dump_snapshot("backup.kcss");
db.load_snapshot("backup.kcss");


text:
Q: Remote Backup MySQL database with routines unsuccess mysqldump -u root --password=123456 -h 110.4.43.111 --databases db_shuttlebus --routines --lock-tables=true --result-file=D:\Server-Backup.sql

everything has backuped, but the Routines are not backuped, why? what wrong with my command?
in Routines i have a function, but can't backuped.

UPDATE
DELIMITER ;;
/*!50003 CREATE*/ /*!50020 DEFINER=`root`@`localhost`*/ /*!50003 PROCEDURE `GenerateRouteFare`(
pRoute_ID int
)
BEGIN
-- SET SQL_SAFE_UPDATES=0;
-- DELETE FROM tbl_rate WHERE Route_ID = pRoute_ID;

INSERT INTO tbl_rate (Route_ID,From_LocationID,To_LocationID,Normal_Rate,Discounted_Rate)
select
   a.Route_ID,
   a.Route_LocationID from_loc_id,
   b.Route_LocationID to_loc_id,
   0,0

from tbl_route a
inner join tbl_route b on a.Route_ID = b.Route_ID and a.Route_Seq < b.Route_Seq and a.Route_ID = pRoute_ID
inner join tbl_location la on la.Location_ID = a.Route_LocationID
inner join tbl_location lb on lb.Location_ID = b.Route_LocationID
WHERE NOT EXISTS(SELECT Rate_ID
                    FROM tbl_rate
                   WHERE tbl_rate.From_LocationID = a.Route_LocationID AND tbl_rate.To_LocationID = b.Route_LocationID AND Route_ID = pRoute_ID)
order by a.Route_Seq, b.Route_Seq;

-- DELETE
DELETE
  FROM tbl_rate
 WHERE Rate_ID IN
(
  SELECT Rate_ID
    FROM
  (

select * from tbl_rate  WHERE Route_ID= pRoute_ID AND CONCAT(From_LocationID, ',', To_LocationID)
NOT IN
(select CONCAT(a.Route_LocationID,',', b.Route_LocationID) as Locname from tbl_route a
inner join tbl_route b on a.Route_ID = b.Route_ID and a.Route_Seq < b.Route_Seq and a.Route_ID = pRoute_ID)

  ) q
);
END */;;
DELIMITER ;


text:
Q: Store result of ExcecuteNonQuery() result into GridView in ASP.NET I am looking suggestions for store my ExecuteNonQuery() into  .csv file.
I am trying to execute .sql file in ASP.NET and try to store it's result into csv file.
Can anyone know how to do this?
My code snippet:
   protected void Btn_result_Click(object sender, EventArgs e)
   {
       string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

       string auctionFacilityProfitAdjustment = File.ReadAllText(@"E:\Profit Adjustment Data\Auction Facility Profit Adjustment.sql");

       SqlConnection connection = new SqlConnection(connectionString);
       connection.Open();

       Server server = new Server(new ServerConnection(connection));
       int count = server.ConnectionContext.ExecuteNonQuery(auctionFacilityProfitAdjustment);

   }

And result stores into GridView. And then csv file.
For eg. My result is 2 affected rows.
So, I want to store it into GridView like:
101 ABC 123467890
102 HHG 9876543210
103 JJL 3794826892
Like wise.


text:
Q: How to modify the display information after user log in? I want to modify the display information after user login. I know I can modify the /etc/motd file to change the information, but it still displays the last login time even I delete all text in /etc/motd file.

I would prefer no information after user log in.

A: This information comes from the lastlog PAM module.  In /etc/pam.d/login, you'll see

# Prints the last login info upon succesful login
# (Replaces the `LASTLOG_ENAB' option from login.defs)
session    optional   pam_lastlog.so

# Prints the message of the day upon succesful login.
# (Replaces the `MOTD_FILE' option in login.defs)
# This includes a dynamically generated part from /run/motd.dynamic
# and a static (admin-editable) part from /etc/motd.
session    optional   pam_motd.so  motd=/run/motd.dynamic noupdate
session    optional   pam_motd.so

Adding silent to the end of the pam_lastlog.so line should stop that message being printed.
A more brutal approach would be to comment out the line completely, but that will fail to update your wtmp file and is probably best avoided.
pam_lastlog has a man page; consult it for full detail.

A: The last login information is not shown by/from motd, it's printed by the login command. If you wish to suppress it, create a file called .hushlogin in your home directory:
touch ~/.hushlogin


text:
Q: Log retrieval solution using AWS CloudWatch insights logs I'm planning to implement a log retrieval solution from AWS CloudWatch logs using Insights logs query which let the users get the logs for 15 days. The queried data can range any where between KBs to GBs for that time frame.
Is there any way to retrieve that log data in paginated way using AWS services? Since the response limit is capped for API Gateway and Lambda, it is hard to retrieve the data in paginated fashion.
Are there any other AWS services that can be used to retrieve the cloudwatch logs data?

A: One option is that first you can export Cloudwatch data to S3. You may export data periodically from Cloudwatch or use Lambda subscription to export data to s3.
Once data are in s3, you can use Athena to query data using SQL like language.


text:
Q: Clear bar graph when the option changes When i select Quarter and Year based on the selection bar graph is created. When I am selected another option the previous created bar graph should be cleared. But it still shows the previous selection's bar graph.
var chart1 = new google.visualization.ColumnChart(
   document.getElementById('chart0')
   );
var chartTotal1 = new google.visualization.ColumnChart(
  document.getElementById('chart1')
   );
  $.ajax({
         url: url,
         type: "Get",
         dataType: "json",
         data: {
             Year: selectedYear,
             Filtertxt: selectedQuarter
         },
         crossDomain: true,
         success: function(data) {
                 if (data.length > 0) {

                if (selectedQuarter == 'Q1') {

                    drawchartQ1(data);

                }

                else {
                    clearChart1();
                }

                if (selectedQuarter == 'Q2') {

                    drawchartQ2(data);

                }
                else {
                    clearChart1();
                }

                if (selectedQuarter == 'Q3') {

                    drawchartQ3(data);

                }

                else {
                    clearChart1();
                }

                if (selectedQuarter == 'Q1,Q2,Q3,Q4') {

                    drawchartAll(data);
                }

                else {
                    clearChart1();
                }

            }

}
    });

    function clearChart1() {
        chart1.clearChart();
        chartTotal1.clearChart();
    }

    function drawchartQ1(data) {
        // another  graph to display the total of sprint
        var total = 0;
        for (var i = 0; i < data.length; i++) {
            total = total + data[i].TotalAmt;
        }
        var data2 = google.visualization.arrayToDataTable([
       ['Months', 'Total'],
       [null, total],
       [null, null]

        ]);

        var options = {
            width: 600,
            height: 400,
            vAxis: {
                title: ""
            },

            isStacked: true,
            hAxis: {
                title: "All Months"
            }
        };

        options.title = 'Quarter 1 Total';
        chartTotal1.draw(data2, options);

        var data1 = google.visualization.arrayToDataTable([
        ['Month', 'ID1', 'ID2', 'ID3', 'ID4', 'ID5'],
        ['Jan,2017', data[0].TotalAmt, null, null, null, null],

        ['Feb,2017', null, data[1].TotalAmt, data[2].TotalAmt, null, null],

        ['Mar,2017', null, null, null, data[3].TotalAmt, data[4].TotalAmt],

        ]);

        var options = {
            width: 600,
            height: 400,
            vAxis: {
                title: ""
            },

            isStacked: true,
            hAxis: {
                title: "Month"
            }
        };

        options.title = 'Quarter 1';
        chart1.draw(data1, options);

    }

A: save a reference to the chart, so you can clear it later
use chart method --> clearChart()
setup similar to following snippet...
function drawCharts() {
  var chart1 = new google.visualization.ColumnChart(
    document.getElementById('chart0')
  );
  var chartTotal1 = new google.visualization.ColumnChart(
    document.getElementById('chart1')
  );

  $.ajax({
    url: url,
    type: "Get",
    dataType: "json",
    data: {
      Year: selectedYear,
      Filtertxt: selectedQuarter
    },
    crossDomain: true,
  }).done(function (data) {
    if (data.length > 0) {
      switch (selectedQuarter) {
        case 'Q1':
          drawchartQ1(data);
          break;

        case 'Q2':
          drawchartQ2(data);
          break;

        case 'Q3':
          drawchartQ3(data);
          break;

        case 'Q4':
          drawchartQ4(data);
          break;

        default:
          clearChart1();
      }
    } else {
      clearChart1();
    }
  });

  function clearChart1() {
    chart1.clearChart();
    chartTotal1.clearChart();
  }

  function drawChart1(data) {
    var data1 = google.visualization.arrayToDataTable([
      ['Month', 'ID1', 'ID2', 'ID3', 'ID4', 'ID5'],
      ['Jan,2017', data[0].TotalAmt, null, null, null, null],
      //['Jan,2017', null, null, null, null, null],
      ['Feb,2017', null, data[1].TotalAmt, data[2].TotalAmt, null, null],
      //['Feb,2017', null, null, null, null, null],
      ['Mar,2017', null, null, null, data[3].TotalAmt, data[4].TotalAmt],
      //['Mar,2017', null, null, null, null, null]
    ]);
    var options = {
      width: 600,
      height: 400,
      vAxis: {
        title: ""
      },
      isStacked: true,
      hAxis: {
        title: "Month"
      }
    };
    options.title = 'Quarter 1';

    chart1.draw(data1, options);

    // another  graph to display the total of sprint
    var total = 0;
    for (var i = 0; i < data.length; i++) {
      total = total + data[i].TotalAmt;
    }

    var data2 = google.visualization.arrayToDataTable([
      ['Months', 'IDs'],
      [null, total],
      [null, null]
    ]);
    var options = {
      width: 600,
      height: 400,
      vAxis: {
         title: ""
      },
      isStacked: true,
      hAxis: {
         title: "All Months"
      }
    };
    options.title = 'Quarter 1 Total';
    chartTotal1.draw(data2, options);
  }
}


text:
Q: zuul + okta +springboot - OKTA redirect uri issue 404 I have Zuul server running on port 8080, a service running on 8082 and I've configured the following in OKTA
Login redirect URIs
http://localhost:8080/api/service-A/port
Logout redirect URIs
Login initiated by App Only
Initiate login URI http://localhost:8080/login

that redirect uri works if I access it without enabling @EnableOAuth2Sso
I've also tried to just do localhost:8080 (but thats not mapped)
I do not have a UI so I'm counting on OKTA's default form.
I've also added all of these properties in my zuul app.prop
security.oauth2.client.client-id={yourClientId}
security.oauth2.client.client-secret={yourClientSecret}
security.oauth2.client.access-token-uri=https://dev-187722.oktapreview.com/oauth2/default/v1/token
security.oauth2.client.user-authorization-uri=https://dev-187722.oktapreview.com/oauth2/default/v1/authorize
security.oauth2.client.scope=openid profile email
security.oauth2.resource.user-info-uri=https://dev-187722.oktapreview.com/oauth2/default/v1/userinfo
security.oauth2.resource.token-info-uri=https://dev-187722.oktapreview.com/oauth2/default/v1/introspect
security.oauth2.resource.prefer-token-info=false

but I still keep getting this error message: The 'redirect_uri' parameter must be an absolute URI that is whitelisted in the client app settings.
I dont even get the login form, just a 404
localhost:8080 is set as a trusted origin (as seen below)
SpringOauth 144 http://localhost:8080/

sources: I pretty much followed this guide https://developer.okta.com/blog/2018/02/13/secure-spring-microservices-with-oauth

A: *

*Can you please double check that your edge-service (zuul) is running on http://localhost:8080/ ?

*On okta console , you should have :
Login redirect URIs : http://localhost:8080/login
Hope this helps


text:
Q: WPF button, content to reach the sides So I have a button on a window in a grid column. The button is shown below:
<Button>
    <Border BorderThickness="3" BorderBrush="Red">
        <Grid Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button, AncestorLevel=1}, Path=Width}">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
                <TextBlock Grid.Row="0" Background="LightBlue">bunnies</TextBlock>
            <TextBlock Grid.Row="1" Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Button, AncestorLevel=1}, Path=Width}" Background="LightBlue">bunnies</TextBlock>
        </Grid>
    </Border>
</Button>

What I see is the example in the left most button below, I'd like it to look like 2 below.
EDIT:
If you add a Width="1000" to the first TextBlock, you will see the effect I want, except that then the text is not central to the column any more, it's central to a block 1000 wide. So what I am after is the binding syntax of the actual column width or the actual button width.
I've left in some of the things that I've tried, changing the Width of a single column definition, binding stuff, all sorts.

Ignore the dodgy editing on the text, I just want the border to reach the edge of the button.
Thanks

A: Try this:
<Button HorizontalContentAlignment="Stretch">
            <Border BorderThickness="3" BorderBrush="Red">
                <Grid HorizontalAlignment="Stretch">
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" TextAlignment="Center" Background="LightBlue">bunnies</TextBlock>
                    <TextBlock Grid.Row="1" TextAlignment="Center" Background="LightBlue">bunnies</TextBlock>
                </Grid>
            </Border>
        </Button>


text:
Q: can anyone please let me know why the bootstrap drop down menu is not working I am using bootstrap framework and tried to replicate http://twitter.github.com/bootstrap/examples/hero.html
can any one please tell me why the dropdown-menu is not working.
the drop down menu which works in the example is not working with my code and i have included proper styles and js ! and one other styles are working so thinking its not a prob with the style any help ll be greatly appreciated
<!DOCTYPE html>

    <meta charset="utf-8">
        <title> The first step</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">

          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

          </button>
          Project name

Home

About

Contact

                Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

            <form class="navbar-form pull-right">
              <input class="span2" type="text" placeholder="Email">
              <input class="span2" type="password" placeholder="Password">
              <button type="submit" class="btn">Sign in</button>
            </form>

© Company 2013

      </footer

A: @bana close the footer close tag
Edit your Script Reference like this

The html should like below :
<!DOCTYPE html>

      <meta charset="utf-8">
      <title> The first step</title>
      <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">

      <link href="//netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet">

And in footer :


text:
Q: How to get request referer path? I need the path of the referrer. I don't want the domain name. For example, if the referrer is
http://www.google.com/adsense I want /adsense.

A: You can access referer with
request.referer

A: request.referer returns a string, but you can use Ruby's URI Module to wrap it and then simply ask it for its path:
if URI(request.referer).path == '/adsense'


text:
Q: Need help on django urls How to validate the url if some change the name in url and  update  the form,
Suppose :
If i want to update a profile ,after click on the update button.ulr link will be like below
url : http://localhost:8000/profile_edit/sushanth/
i found there is an security loop here,a person can change the name on the url and he can edit other person profile,how to close this loop hole while updating the form in django.
Thanks in advance...:)

A: You just need to check in your view that the user is the correct one.
@login_required
def profile_edit(request, username):
    if username != request.user.username:
        return HttpResponseNotAllowed()


text:
Q: Middle-Ware Technologies As a Assignment our team have to develop a distributed system and we have to provide List of middle-ware technologies. What are the middle-ware technologies and examples?

A: Here is definition of middleware: https://en.wikipedia.org/wiki/Middleware

Middleware is computer software that provides services to software applications beyond those available from the operating system. It can be described as "software glue"

In distributed applications:

The term is most commonly used for software that enables communication and management of data in distributed applications. An IETF workshop in 2000 defined middleware as "those services found above the transport (i.e. over TCP/IP) layer set of services but below the application environment" (i.e. below application-level APIs). In this more specific sense middleware can be described as the dash ("-") in client-server, or the -to- in peer-to-peer. Middleware includes web servers, application servers, content management systems, and similar tools that support application development and delivery.

Simpler answers are for example:

*

*Database middleware: sqlnet(oracle), INet(IBM), ODBC Driver.

*RPC (Remote Procedure Call) middleware: DCE RPC etc..

*MOM (Message Oriented Middleware): MS series(IBM), BEA Message Q, JMS (based on J2EE) etc..

*TP-Monitor Middleware: BEA TUXEDO, BEA TOPEND, IBM TxSeries, CS TALK(Taiwan) etc..

*ORB (Object Request Broker) Middleware: IONA Orbix, Borland VisiBroker, BEA TUEXDO 8.0, COBRA engine etc...

*WAS (Web Application Server) Middleware: WebLogic, WebSphere, Tomcat...


text:
Q: Drawing in an NSView and Subclassing I am rewriting a pretty large drawing program, now that Xcode uses Storyboards for Cocoa apps, and was just confused about a few things regarding optimization.
Let's say I have a drawing program  where the user can draw different shapes (rectangles, triangles, circles, stars; etc) onto the NSView (Subclass: MyDrawing). Cleary these shapes' points will have to be saved in an array for drawRect to recall for later so that they don't get cleared, However I noticed that the more shapes there were DrawRect/Core Graphics really bogged down and when resizing shapes, it was very laggy.
What would the best practice in this sort of thing be? Should I create a separate class for each shape? Should I create a new NSView for each shape? (Although the second one doesn't make much sense to me)
All I did before was invoke the drawinRect method to update certain parts of the NSView, but found that it was still a little slow.
What is the best most optimal way be to go about drawing multiple shapes (while letting the user edit them later on) ?

A: I suggest CALayer's inside NSView.


text:
Q: How to stop MainLoop in Perl/Tk + AnyEvent I'm writing Perl/Tk program which uses AnyEvent's timer. And I have a problem with closing window if timer is active. I made this window close handler:
$self -> {window} -> protocol( 'WM_DELETE_WINDOW' => sub {
                                                   undef $self -> {timer};
                                                   $self -> {window} -> destroy;
});

If timer is active when I close the window, timer stops, window closes, but MainLoop doesn't stop. What's wrong?

A: According to the AnyEvent::Impl::Tk documentation, a hidden Tk MainWindow is created to get things working. But it seems that this hidden window is never destroyed automatically. As a workaround, you can do it yourself:
$AnyEvent::Impl::Tk::mw->destroy;


text:
Q: For which indexes there are no entry in the Index Usage Stats Table? I am trying to find which indexes are not used in order to clear them and reduce SQL Server index maintenance.
So, I have managed to extract two queries based on the official documentation and other articles(like this one):
The first one is returning not used indexes based on the sys.dm_db_index_usage_stats:
DECLARE @MinimumPageCount INT = 0

SELECT object_name(IDX.[object_id]) AS [Table]
      ,IDX.[name] AS [Index]
      ,PHS.[page_count] AS [Page_Count]
      ,CONVERT(DECIMAL(18,2), PHS.page_count * 8 / 1024.0) AS [Total Size (MB)]
      ,CONVERT(DECIMAL(18,2), PHS.avg_fragmentation_in_percent) AS [Frag %]
      ,PRS.row_count AS [Row Count]
      ,CONVERT(DECIMAL(18,2), (PHS.page_count * 8.0 * 1024) / PRS.row_count) AS [Index Size/Row (Bytes)]
      ,US.[user_updates]
      ,US.[last_user_update]
FROM [sys].[dm_db_index_usage_stats] US
INNER JOIN [sys].[indexes] IDX
    ON IDX.[index_id] = US.[index_id]
    AND IDX.[object_id] = US.[object_id]
INNER JOIN [sys].[dm_db_index_physical_stats] (DB_ID(),NULL,NULL,NULL,NULL) AS PHS
    ON PHS.[index_id] = US.[index_id]
    AND PHS.[object_id] = US.[object_id]
INNER JOIN [sys].[dm_db_partition_stats] PRS
    ON PRS.[index_id] = US.[index_id]
    AND PRS.[object_id] = US.[object_id]
WHERE
    -- showing only not used indexes
        US.[user_scans] = 0
    AND US.[user_seeks] = 0
    AND US.[user_lookups] = 0
    AND US.[system_scans] = 0
    AND US.[system_seeks] = 0
    AND US.[system_lookups] = 0
    -- ignore indexes with less than a certain number of pages of memory
    AND PHS.page_count > @MinimumPageCount
    -- exclude clustered and heaps tables
    AND US.[index_id] > 1
    --current db only
    AND US.[database_id]= DB_ID()
ORDER BY [Page_Count] DESC

The second one is extracting similar information for indexes for which there are no extries in the sys.dm_db_index_usage_stats like this:
DECLARE @dbid INT =  DB_ID()

SELECT DB.Name AS [Database]
      ,OBJ.NAME AS [Table]
      ,IDX.NAME AS [Index]
      ,IDX.INDEX_ID
      ,PHS.page_count AS [Page Count]
      ,CONVERT(DECIMAL(18,2), PHS.page_count * 8 / 1024.0) AS [Total Index Size (MB)]
      ,CONVERT(DECIMAL(18,2), PHS.avg_fragmentation_in_percent) AS [Fragmentation (%)]
FROM [sys].[indexes] IDX
INNER JOIN SYS.OBJECTS OBJ
    ON IDX.[object_id] = OBJ.[object_id]
LEFT JOIN [sys].[dm_db_index_physical_stats] (@dbid, NULL, NULL, NULL, NULL) PHS
    ON PHS.[object_id] = IDX.[object_id]
    AND PHS.[index_id] = IDX.[index_id]
INNER JOIN [sys].[databases] DB
    ON DB.[database_id] = PHS.[database_id]
WHERE OBJ.[type] = 'U' -- Is User Table
    AND IDX.[is_primary_key] = 0
    AND IDX.[index_id] NOT IN
    (
        SELECT US.INDEX_ID
        FROM [sys].[dm_db_index_usage_stats] US
        WHERE US.[object_id] = IDX.[object_id]
            AND IDX.[index_id] = US.[index_id]
            AND [database_id] = @dbid
    )
    AND IDX.[index_id] > 1
ORDER BY PHS.[page_count] DESC
        ,OBJ.[name]
        ,IDX.[index_id]
        ,IDX.[name] ASC

Looking the query above, the only filtering that is made is based on if there is a entry in the sys.dm_db_index_usage_stats for the particular index.
So, is there a rule that if there is no entry the index is not used?

A: The first query you gave searches for unused indexes. The sys.dm_db_index_usage_stats function has fields [user_scans],[user_seeks], [user_lookups], [system_scans], [system_seeks], [system_lookups]. If they are all 0 then according to your own link this means the index was never used.
The second query gives the indexes where there are no usage statistics available. According to your link the records for the sys.dm_db_index_usage_stats function are set to zero on every restart and deleted when the database is detached or is shut down. So if the index was never used since a database detach or shut-down there will be no usage statistic row for it.
This link you have allready given but I give it again for completeness of my answer:  http://technet.microsoft.com/en-us/library/ms188755.aspx