text:
Q: How to unregister a dll and then register a dll on the same batch file? I unregistered and registered a dll manually by using the following commands in the command prompt.
Unregister:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe "C:\Program Files\ABC\foo.dll" /codebase /u

Register:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe "C:\Program Files\ABC\foo.dll" /codebase

So help me using batch commands so that clients can run this batch without knowing how to do it manually

A: A batch file, simply put, is just a long list of command line commands that are executed sequentially. So to make a .bat file with your commands.  Create a text file and name it File.bat and then copy an paste your commands into the file.  Save and you are done.  Note that there are a few differences when working with symbols on the command and then in bat files, but for what you need it is not an issue.
Example:
:: Hide commands statements
@echo off

:: Unregister
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe" "C:\Program Files\ABC\foo.dll" /codebase /u

:: Register
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe" "C:\Program Files\ABC\foo.dll" /codebase

Great Batch References:
Technet, Rob, SS64, DosTips


text:
Q: how to connect to cachedb (intersystems) from php (on windows) natively? I am hoping it is possible to connect to a CacheDB from PHP, without using ODBC.   I have found the ODBC connectivity to Cache is not reliable a number of times, so I am hoping there is some other native method / driver I can use to connect to a Cache DB?
If it's not possible through PHP, I might consider .net (VB or C#) if it's possible there.
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why does this range blow up Why does the following code segment work
int sizearray[3] = {3,4,2};
Mat OneM = Mat::ones(3,4,CV_8UC1);
Mat TwoM = Mat::ones(3,4,CV_8UC1)+1;
Mat OneTwo3D = Mat::zeros(3,sizearray,CV_8UC1);
Mat OneTwo3DPlaneM;
Range OneTwo3DRanges[] = {Range(1,3),Range(1,4),Range(1,2)};
OneTwo3DPlaneM = OneTwo3D(OneTwo3DRanges);

but if I change the ranges to
Range OneTwo3DRanges[] = {Range(1,4),Range(1,4),Range(1,2)};

it blows up.
In the working one, OneTwo3DPlaneM is apparently a 2x3x1 matrix as expected given that the "end" of a Range is exclusive (confirmed by looking at the working code/range result OneTwo3DPlaneM.size.p which is [2,3,1]).  However, just increasing the first range from Range(1,3) to Range(1,4) causes an error on
OneTwo3DPlaneM = OneTwo3D(OneTwo3DRanges);

Note, what I'm trying to do, eventually, is assign an image into a slice of a 3d arrray (via OneM.copyTo(OneTwo3DPlaneM) I think).  The code above is just a test for that.  So, I just want to create a matrix that references a plane OneTwo3D so that, for this test, I can assign the matrices OneM to the first plane and, eventually, TwoM to the second plane (after I change the third range to point to OneTwo3D's second plane)
Given that I don't have much experience with opencv I assume I'm doing something retarded. Apologies up front.

A: The code below seems to work  Apparently, copyTo doesn't like assigning from a 2d into a slice of a 3d array.  So, as shown below, I changed the OneM and TwoM from 3x4 matrices to 3x4x1 and then it worked.  I guess then the question is given an image (2d) can I just reshape it to a 3d entity with a singleton 3rd dimension to copyTo happy.  I'm not sure how to do that considering that reshape only works on 2d arrays.
int sizearray1[3] = {3,4,1};
int sizearray[3] = {3,4,2};
//      Mat OneM = Mat::ones(3,4,CV_8UC1);
Mat OneM = Mat::ones(3,sizearray1,CV_8UC1);
//      Mat TwoM = Mat::ones(3,4,CV_8UC1)+1;
Mat TwoM = Mat::ones(3,sizearray1,CV_8UC1)+1;
Mat OneTwo3D = Mat::zeros(3,sizearray,CV_8UC1);
Mat OneTwo3DPlaneM;
Range OneTwo3DRanges[] = {Range::all(),Range::all(),Range(0,1)};
OneTwo3DPlaneM = OneTwo3D(OneTwo3DRanges);
OneM.copyTo(OneTwo3DPlaneM);
OneTwo3DRanges[2] = Range(1,2);
OneTwo3DPlaneM = OneTwo3D(OneTwo3DRanges);
TwoM.copyTo(OneTwo3DPlaneM);


text:
Q: React-Bootstrap dropdown on hover I am working on my first react-bootstrap website and I am noticing that the dropdown in navbar won't allow dropdown on hover.
I am wondering if there is a workaround. I tried adding some code to my CSS.
demo - https://codesandbox.io/s/react-bootstrap-nav-active-link-5v5jq?fontsize=14&hidenavigation=1&theme=dark
/*MENU*/
.dropdown:hover {
  display: block;
}
/*END MENU*/

However, this did not work
This is the code.
import React from 'react';
import {Nav, Navbar, NavDropdown } from 'react-bootstrap';
import '../App.css';

function Header() {
    return (
            <Navbar bg="transparent" variant="dark" expand="lg">
            <Navbar.Brand href="#home" className="App-logo">AdStichr</Navbar.Brand>
            <Navbar.Toggle aria-controls="basic-navbar-nav" />
            <Navbar.Collapse id="basic-navbar-nav">
                <Nav className="ml-auto">
                <Nav.Link href="#home">Home</Nav.Link>
                <Nav.Link href="#link">Link</Nav.Link>
                <NavDropdown title="Dropdown" id="basic-nav-dropdown" alignRight>
                    <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
                    <NavDropdown.Item href="#action/3.2">Another action</NavDropdown.Item>
                    <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
                    <NavDropdown.Divider />
                    <NavDropdown.Item href="#action/3.4">Separated link</NavDropdown.Item>
                </NavDropdown>
                </Nav>

            </Navbar.Collapse>
            </Navbar>
    )
}
export default Header;

even tried this
const Header = props => {
    const { location } = props;
    const [isOpen, updateIsOpen] = useState(false);
    return (
        <Navbar bg="transparent" variant="dark" expand="lg">
        <Navbar.Brand href="#home" className="App-logo">AdStichr</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
            <Nav className="ml-auto" activeKey={location.pathname}>
            <Nav.Link href="/">Home</Nav.Link>
            <Nav.Link href="/advertisers">Advertisers</Nav.Link>
            <NavDropdown title="Publishers" id="basic-nav-dropdown" alignRight
             onMouseOver={() => updateIsOpen(true)}
             onFocus={() => updateIsOpen(true)}
             onMouseLeave={() => updateIsOpen(false)}
             onBlur={() => updateIsOpen(false)}
             toggle={() => updateIsOpen(!isOpen)}
             isOpen={isOpen}>
                <NavDropdown.Item href="/publishers/radio">Radio Stations</NavDropdown.Item>
                <NavDropdown.Divider />
                <NavDropdown.Item href="/publishers/podcasters">Audio Podcasters</NavDropdown.Item>
                <NavDropdown.Divider />
                <NavDropdown.Item href="/publishers/videopodcasters">Video Podcasters</NavDropdown.Item>
            </NavDropdown>
            <Nav.Link href="/case-studies">Case Studies</Nav.Link>
            <Nav.Link href="/contact">Contact</Nav.Link>
            </Nav>

        </Navbar.Collapse>
        </Navbar>
    );
  };
  const HeaderWithRouter = withRouter(Header);
  export default HeaderWithRouter;

But no success.

A: const [show, setShow] = useState(false);
const showDropdown = (e)=>{
    setShow(!show);
}
const hideDropdown = e => {
    setShow(false);
}

  <NavDropdown title="Dropdown"
   id="collasible-nav-dropdown"
   show={show}
   onMouseEnter={showDropdown}
   onMouseLeave={hideDropdown}
   >

I Have Used This For Open Dropdown Menu On Hover in React Bootstrap.

A: It doesn't render the dropdown menu when the NavDropdown component mounts for the first time.
CSS Solution: You just need to add renderMenuOnMount={true} on your NavDropdown element like this:
<NavDropdown title={name} id={name} renderMenuOnMount={true}>
...menu items...
</NavDropdown>

And in CSS:
.nav-item.dropdown:hover .dropdown-menu {
    display: block;
}

A: Use this code.
  const [showDropdown, setShowDropdown] = useState(false);
  return (
    <Dropdown
      onMouseLeave={() => setShowDropdown(false)}
      onMouseOver={() => setShowDropdown(true)}
      style={{ width: '166px' }}
    >
      <Dropdown.Toggle
        className="main-style"
        id="dropdown-basic"
      >
        Dropdown Button
      </Dropdown.Toggle>

      <Dropdown.Menu show={showDropdown}>
        <Dropdown.Item href="#/action-1">
          Action
        </Dropdown.Item>
        <Dropdown.Item href="#/action-2">
          Another action
        </Dropdown.Item>
        <Dropdown.Item href="#/action-3">
          Something else
        </Dropdown.Item>
      </Dropdown.Menu>
    </Dropdown>
  );

Codesandbox

A: Add the below code to the css, Checked in sandbox and worked fine. Let me know if you still have issue.
Check the sandbox snippet Here
.nav-item:hover .dropdown-menu{
  display:block!important
}

A: This should work:
.nav-item.dropdown:hover .dropdown-menu {
    display: block;
}

A: For multiple dropdowns I took a modified approach to Rubel's solution.
I created a NavHoverDropdown wrapper component that managed it's own isOpen state and renders children.
const NavHoverDropDown = (props) => {
const [dropdownOpen, setDropdownOpen] = useState(false);

const handleMouseOver = () => {
    setDropdownOpen(true);
}

const handleMouseOut = () => {
    setDropdownOpen(false);
}

return (
    <UncontrolledDropdown isOpen={dropdownOpen} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut} nav inNavbar>
        {props.children}
    </UncontrolledDropdown>
) }

export default NavHoverDropDown

Then I went back to my NavMenu component and replaced all my UncontrolledDropdown's with my NavHoverDropdown. Contents of the dropdown remain the same.
<NavHoverDropdown >
    <DropdownToggle nav caret>
    Options
    </DropdownToggle>
    <DropdownMenu end>
        <DropdownItem>
            <NavItem>
                <NavLink tag={Link} className="text-dark" to="/options/opton1">Option 1</NavLink>
            </NavItem>
        </DropdownItem>
        <DropdownItem>
                <NavLink tag={Link} className="text-dark" to="/options/option2">Option 2</NavLink>
        </DropdownItem>
    </DropdownMenu>
</NavHoverDropdown>


text:
Q: Vue-router push to Named View I can't find solution to go to named view. My routes ,
routes: [
{
  path: '/',
  component: App,
  children : [
    {
      path: '/',
      redirect: 'home'
    },
    {
      path: 'home',
      components: {
        home : Home,
        contact : Contact,
        geo : Geo,
        shake : Shake,
        camera : Camera
      }
    },
  ]
}

]
This is my app.vue
...
<ion-fab vertical="bottom" horizontal="center" slot="fixed">
    <ion-fab-button @click="page()">
        <ion-icon name="camera"></ion-icon>
    </ion-fab-button>
</ion-fab>
...

export default {
    name : 'App',
    methods: {
        page() {
            this.$router.push('home');
        }
    }
}

I want to go to the Camera component when I click camera icon/button. How can I achieve this?

A: You have to define multiple router views for each name in named views. There should be one default, and multiple others for each name. Like this.
<router-view></router-view>
<router-view name="home"></router-view>
<router-view name="contact"></router-view>

All respective components will all be loaded in router-view when a url is hit.
You can read more about it in this doc. An see a working example here

A: if you want to redirect using the script you can try this to change the route.
this.$router.push({ name: 'your_route_name' })

in addition, you can also send params to that route by enabling props: true while defining routes,
this.$router.push({name: 'your_route_name', params: { var_name: data } })


text:
Q: How to re apply js and css files for appended tags by javascript I am trying to create infinite pagination. I am sending an id of a last element using ajax to a controller. Then, the controller is returning response consisted of html tags.
When I am trying to append it into a div, javascript and css files doesn't apply for new-added html tags. I have scanned some questions on the website, but I couldn't find any solution for my problem.
Could you help?
Script:
<script type="text/javascript">
  $(document).ready(function() {
    var counting = 1;
    $(document).on('click', '.pagination-button', function() {
      var id = $('.projects:last').data('id');
      $.ajax({
        url: '/projects/projectloader/',
        type: "post",
        beforeSend: function() {
          if (counting > 0)
            $('.ajax-load').show();
          $('.mobile-product-loader').hide();
        },
        data: {
          id: id,
        },
        success: function(data) {
          if (data) {
            $('.ajax-load').hide();
            $(".cbp-wrapper").append(data);
            $('.mobile-product-loader').show();
            counting++;
            console.log(data);
          } else if (!data) {
            $('.ajax-load').hide();
            $('.mobile-product-loader').hide();
            console.log('no data');
          }
        }
      });
    });
  });
</script>

A: You can maybe try something like this :
    function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

A: If you need to apply events to dynamic generated content, consider to refactor your event syntax (in main js files) with event delegation, for example:
$(document).on("click", '.mylink', function(event) {
    alert("new link clicked!");
});

Imho its best option to support events in dynamic generated content.


text:
Q: Show custom post type endpoint in REST API just if user has capability I created a custom post type for WP, that should just be visitable for user that have a custom capability read_cpt. Within templates and pre_get_posts I can run checks to include or exclude the CPT by using current_user_can().
I don't want the CPT, not even the endpoint, to show up within the REST API, to keep it top secret, as long as a user doesn't have the custom capability.
The only way I could figure out to hide the endpoints in the API to run this code.
Register post type for "classic" WP:
function add_post_type() {
    $args = array(
        [...]
        'public'                => false,
        'has_archive'           => false,
        'exclude_from_search'   => true,
        'publicly_queryable'    => false,
        'show_in_rest'          => false,
    );
    register_post_type( 'cpt', $args );
}
add_action( 'init', 'add_post_type', 0 );

and separately add it to the REST API:
add_action( 'init', 'cpt_rest_support', 25 );
function cpt_rest_support() {
    global $wp_post_types;

    if ( current_user_can( 'read_addresses' ) ) {
        //be sure to set this to the name of your post type!
        $post_type_name = 'address';
        if( isset( $wp_post_types[ 'cpt' ] ) ) {
            $wp_post_types[ 'cpt' ]->show_in_rest = true;
        }
    }
}

By creating a custom WP_REST_Posts_Controller class I couldn't find a way to hide the endpoint by modifying any of the *_permissions_check
Is there something like a "show_in_rest_permition_check" argument for  register_post_type() or is the described way the only method?

A: The REST API has no parameters, options to solve this - in my opinion. But you should register only if the users have the capability in his role, like the follow example.
add_action( 'rest_api_init', function() {

    // Exit, if the logged in user have not enough rights.
    if ( ! current_user_can( 'edit_posts' ) ) {
        return;
    }

    // Register Meta Data.
    register_meta( 'post', 'foo', array(
        'show_in_rest' => true,
    ));
});

That's fire the custom data in the REST API only, if the user have enough rights, capabilities in his role. My register_meta() is only an example, that should also work with your additional parameter for register_post_type, like $wp_post_types[ 'cpt' ]->show_in_rest = true;.

A: Don't rely solely on hiding it.
Instead, return an error in the handler:
if (!current_user_can('read_addresses')) {
    return new WP_REST_Response('restricted', 403);
}

To hide it as well, filter the content of the hooks rest_index and rest_namespace_index.

A: Use the register_rest_route() function.
if( current_user_can( 'read_addresses' ) ) {
    register_rest_route( 'namespace/v1', 'cpt', array(
        'methods' => array( 'GET' ),
        'callback' => 'callback_function',
        'permission_callback' => 'permission_callback_function'
    ) );
}

Your callback_function would handle the request and return the response. The permissions_callback_function would check the user permissions and return an error if the user does not have the specified capabilities. In this case the permissions callback is probably not necessary, but it wouldn't hurt to have it in place just in case.

A: Old question but this worked for me following @Drivingralle requirements. You could use current_user_can() as a boolean switch to modify show_in_rest parameter behaviour:
function add_post_type() {

    $show_in_rest = current_user_can( 'read_cpt' ); //this will return true or false

    $args = array(
        [...]
        'public'                => false,
        'has_archive'           => false,
        'exclude_from_search'   => true,
        'publicly_queryable'    => false,
        'show_in_rest'          => $show_in_rest, //bool switch from current_user_can()
    );
    register_post_type( 'cpt', $args );
}
add_action( 'init', 'add_post_type' );

This way the custom post type is only shown in rest for users with the required capability.


text:
Q: How to retreive original folder contents from Appium pull_folder output? Based on the appium doc at http://appium.io/docs/en/commands/device/files/pull-folder/ a folder can be pulled following way
folder_base64 = self.driver.pull_folder('/path/to/device/foo.bar')

As per the doc the response folder_base64 is : "A string of Base64 encoded data, representing a zip archive of the contents of the requested folder."
So, based on my understanding of the above, i tried followings(A to D) which did not work.
A)

*

*base64 decoding of the folder_base64

*Unzipping the decoded output

decoded_base64 = base64.b64decode(folder_base64)
folder_base64 = ZipFile.extractall(decoded_base64)
this fails with following error:
zipfile.py", line 1493, in extractall
AttributeError: 'bytes' object has no attribute 'namelist'

B)

*

*base64 decoding of the folder_base64

*zipping the decoded output

*unzipping

decoded_base64 = base64.b64decode(folder_base64)
zipfile.ZipFile('out.zip', mode='w').write(decoded_base64)
fails with following error at step 2:
zipfile.py", line 484, in from_file
    st = os.stat(filename)
ValueError: stat: embedded null character in path

C)

*

*unzipping the folder_base64

*base64 decoding of the output

unzipped_base64 = ZipFile.extractall(folder_base64)
decoded_base64 = base64.b64decode(unzipped_base64)
fails at step 1 with following error
zipfile.py", line 1493, in extractall
AttributeError: 'str' object has no attribute 'namelist'

D)

*

*base64 decoding of the folder_base64

*read the file as zip file

*extract the files

decoded_base64 = base64.b64decode(folder_base64)
zip_folder = zipfile.ZipFile(decoded_base64, 'r')
ZipFile.extractall(zip_folder, "./mp3_files")
fails with following error:
zipfile.py", line 241, in _EndRecData
    fpin.seek(0, 2)
AttributeError: 'bytes' object has no attribute 'seek'

E)
Finally following worked, but i am wondering why it had to be routed via a temp file to make it work? Also, is there a better way/more direct way to handle appium pull_folder output?
decoded_base64 = base64.b64decode(folder_base64)
with SpooledTemporaryFile() as tmp:
    tmp.write(decoded_base64)
    archive = ZipFile(tmp, 'r')
    ZipFile.extractall(archive, "./mp3_files")

Note: following python packages are used in above code snippets
import zipfile
from tempfile import SpooledTemporaryFile


text:
Q: tidyverse do a pivot_wider with two different reshaping strategies (creating categorical and binary columns) Using the following data:
df <- data.frame(id = c("A", "B", "C", "A", "B", "A"),
                 value = c(1, 2, 3, 4, 5, 6))

I want to pivot_wider this data so that the reshaping creates two different sets of columns:

*

*One set where I create a bunch of binary columns that take the column names from the value columns (e.g. bin_1, bin_2 and so on) and that are coded as 0/1.

*An additional set where I create as many necessary columns to store the values in a "categorical" way. Here, id "A" has three values, so I want to create three columns cat_1, cat_2, cat_3 and for IDs B and C I want to fill them up with NAs if there's no value.

Now, I know how to create these two things separately from each other and merge them afterwards via a left_join.
However, my question is: can it be done in one pipeline, where I do two subsequent pivot_widers? I tried, but it doesn't work (obviously because my way of copying the value column and then try to use one for the binary reshape and one for the categorial reshape is wrong).
Any ideas?

Code so far that works:
df1 <- df %>%
  group_by(id) %>%
  mutate(group_id = 1:n()) %>%
  ungroup() %>%
  pivot_wider(names_from = group_id,
              names_prefix = "cat_",
              values_from = value)

df2 <- df %>%
  mutate(dummy = 1) %>%
  arrange(value) %>%
  pivot_wider(names_from = value,
              names_prefix = "bin_",
              values_from = dummy,
              values_fill = list(dummy = 0),
              values_fn = list(dummy = length))

df <- df1 %>%
  left_join(., df2, by = "id)

Expected output:
# A tibble: 3 x 10
  id    cat_1 cat_2 cat_3 bin_1 bin_2 bin_3 bin_4 bin_5 bin_6
  <chr> <dbl> <dbl> <dbl> <int> <int> <int> <int> <int> <int>
1 A         1     4     6     1     0     0     1     0     1
2 B         2     5    NA     0     1     0     0     1     0
3 C         3    NA    NA     0     0     1     0     0     0

A: In base you can try:
tt <- unstack(df[2:1])
x <- cbind(t(sapply(tt, "[", seq_len(max(lengths(tt))))),
           t(+sapply(names(tt), "%in%", x=df$id)))
colnames(x) <- c(paste0("cat_", seq_len(max(lengths(tt)))),
              paste0("bin_", seq_len(nrow(df))))
x
#  cat_1 cat_2 cat_3 bin_1 bin_2 bin_3 bin_4 bin_5 bin_6
#A     1     4     6     1     0     0     1     0     1
#B     2     5    NA     0     1     0     0     1     0
#C     3    NA    NA     0     0     1     0     0     0

A: With the addition of purrr, you could do:
map(.x = reduce(range(df$value), `:`),
    ~ df %>%
     group_by(id) %>%
     mutate(!!paste0("bin_", .x) := as.numeric(.x %in% value))) %>%
 reduce(full_join) %>%
 mutate(cats = paste0("cat_", row_number())) %>%
 pivot_wider(names_from = "cats",
             values_from = "value")

  id    bin_1 bin_2 bin_3 bin_4 bin_5 bin_6 cat_1 cat_2 cat_3
  <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A         1     0     0     1     0     1     1     4     6
2 B         0     1     0     0     1     0     2     5    NA
3 C         0     0     1     0     0     0     3    NA    NA

A: Slightly modifying your approach by reducing df2 code and including it all in one pipe by taking advantage of the list and . trick which allows you to work on two versions of df in the same call.
Its not much of an improvement on what you have done but it is now all in one call. I can't think of way you can do it without a merge/join.
library(tidyverse)
df %>%
  list(
    pivot_wider(., id_cols = id,
                names_from = value,
                names_prefix = "bin_") %>%
      mutate_if(is.numeric, ~ +(!is.na(.))), #convert to binary

    group_by(., id) %>%
      mutate(group_id = 1:n()) %>%
      ungroup() %>%
      pivot_wider(names_from = group_id,
                  names_prefix = "cat_",
                  values_from = value)
  ) %>%
  .[c(2:3)] %>%
  reduce(left_join)

#   id    bin_1 bin_2 bin_3 bin_4 bin_5 bin_6 cat_1 cat_2 cat_3
#   <chr> <int> <int> <int> <int> <int> <int> <dbl> <dbl> <dbl>
# 1 A         1     0     0     1     0     1     1     4     6
# 2 B         0     1     0     0     1     0     2     5    NA
# 3 C         0     0     1     0     0     0     3    NA    NA

A: Even you can join both your syntax into one without creating any intermediate object
df %>%
  group_by(id) %>%
  mutate(group_id = row_number()) %>%
  pivot_wider(names_from = group_id,
              names_prefix = "cat_",
              values_from = value) %>% left_join(df %>% mutate(dummy = 1) %>% arrange(value) %>% pivot_wider(names_from = value,
                                                                                names_prefix = "bin_",
                                                                                values_from = dummy,
                                                                                values_fill = list(dummy = 0),
                                                                                values_fn = list(dummy = length)), by = "id")

# A tibble: 3 x 10
# Groups:   id [3]
  id    cat_1 cat_2 cat_3 bin_1 bin_2 bin_3 bin_4 bin_5 bin_6
  <chr> <dbl> <dbl> <dbl> <int> <int> <int> <int> <int> <int>
1 A         1     4     6     1     0     0     1     0     1
2 B         2     5    NA     0     1     0     0     1     0
3 C         3    NA    NA     0     0     1     0     0     0


text:
Q: Fontd CPU usage making Mac Mail useless Macbook Pro running El Capitan. Fontd utility just started using 100% of cpu when doing anything in Mac Mail. I have researched and performed recommendations (validate fontbook  fonts, clear/restart font server) with no benefit. Fontd still taking up nearly 100% of cpu when navigating mail.
Other suggestions would be appreciated.


text:
Q: Does using recursive template functions introduce a function call overhead or does the compiler inline it most of the times (example below)? I have been trying to understand the practical usages of TMP. I see a lot of code along the following lines:
#ifndef LOOP2_HPP
#define LOOP2_HPP

// primary template
template <int DIM, typename T>
class DotProduct {
  public:
    static T result (T* a, T* b) {
        return *a * *b  +  DotProduct<DIM-1,T>::result(a+1,b+1);
    }
};

// partial specialization as end criteria
template <typename T>
class DotProduct<1,T> {
  public:
    static T result (T* a, T* b) {
        return *a * *b;
    }
};

// convenience function
template <int DIM, typename T>
inline T dot_product (T* a, T* b)
{
    return DotProduct<DIM,T>::result(a,b);
}

Is it a good practice to always explicitly inline such heavily recursive functions?
EDIT:
For a more concrete example take the following code:
template <int N>
inline void f() {
    f<N-1>();
    std::cout << N << "\n";
}

template <>
void f<0>() {
    std::cout << 0 << "\n";
};

int main() {
      f<1>();
    return 0;
}

I just want to use the function f as a way to unroll a bunch of cout statements which I don't want to write at compile time. Following is the assembly generated by gcc-8.3, all optimizations enabled:
        void f<0>():
            push    rbp
            mov     rbp, rsp
            mov     esi, 0
            mov     edi, OFFSET FLAT:_ZSt4cout
            call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
            mov     esi, OFFSET FLAT:.LC0
            mov     rdi, rax
            call    std::basic_ostream<char, std::char_traits<char> >& s

td::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
        nop
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        call    void f<1>()
        mov     eax, 0
        pop     rbp
        ret
void f<1>():
        push    rbp
        mov     rbp, rsp
        call    void f<0>()
        mov     esi, 1
        mov     edi, OFFSET FLAT:_ZSt4cout
        call    std::basic_ostream<char, std::char_traits<char> >::operator<<(int)
        mov     esi, OFFSET FLAT:.LC0
        mov     rdi, rax
        call    std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)
        nop
        pop     rbp
        ret

It seems that each of the unrolling leads to a runtime call instruction. It is this cost I want to avoid. I just want the final generated code to be a concatenation of multiple couts.

A:
Is it a good practice to always explicitly inline such heavily recursive functions?

Is there still a need for templating such functions with MTP anymore as we have constexpr for many years now? And even if constexpris not enough, we will have consteval in c++20 ( hopefully ).
Inlining only gives the compiler the chance to optimize the code away, but it is not a guarantee. Make it a recursive template function gives the compiler the chance to waste your memory with non inlined recursive template instances which is the opposite of what you want to achieve! If you compile with -O0 you see a lot of code generated from your example.
You can force the compiler to generate the result in compile time, as long you can use the resulting value as template parameter for example.
But as always regarding optimizations:
1) Try to get the best algorithm
2) Try to implement to make the code maintainable
3) Measure
4) Measure
5) Measure
And only if your code did not fulfill your speed requirements, start optimizing by hand.
In fact, your code has the chance to waste a lot of memory and also has the chance to optimize well. But you should move to constexpr functions instead of using more or less unreadable MTP code. So "inline" is only a very small part of the problem.
Your compiler is better as you believe! Normally! If you don't trust: Measure! And only if you see a real problem: handcraft optimization.
If using constexpr, especially with recursive functions, most compilers provide command line flags to give a level for deeper compile time evaluation if you do NOT force the compiler to get the result in compile time with using the result as template parameter or any other "must be a compile time constant" like size for an array. It depends on the compiler you use, so please read the manual!
If you use std::cout inside a recursion/loop, you will never see a "single output optimization". But at all: if you have enough time for using std::cout you don't have to think of the few lines of assembly around it. std::cout is typically slow related to the code generating the data which should be written to console at all!
Don't optimize the wrong things!
Add on:
If you really want to generate a compile time string from a list of integers, you can take that as a base for your example: C++ convert integer to string at compile time


text:
Q: Bootstrap dropdown closing when clicked I put a form inside a bootstrap dropdown, but when I click any of the fields in the form, the dropdown goes away. I have this piece of code but I don't know where to put it to prevent the dropdown disappearing.
$(function test() {
  // Setup drop down menu
  $('.dropdown-toggle').dropdown();

  // Fix input element click problem
  $('.dropdown input, .dropdown label').click(function(e) {
    e.stopPropagation();
  });
});

Could someone please tell me where I should put this? I tried in the bootstrap-dropdown, I tried within the HTML but it still doesn't work.

A: Time passed since answer had been accepted, but if you want to keep the dropdown opened, if it acts like a kind of dialog, the best way i think is:
$('.dropdown').dropdown().on("hide.bs.dropdown", function(e) {
            if ($.contains(dropdown, e.target)) {
                e.preventDefault();
            //or return false;
            }
        });

A: You need to stop event from bubbling up the DOM tree:
$('.dropdown-menu').click(function(e) {
    e.stopPropagation();
});

event.stopPropagation prevents event from reaching the node where it's eventually handled by Bootstrap hiding menu.

A: This works for my (lateral sidebar opening a simple link with bootstrap toggle)
$('.dropdown').find("a").not('.dropdown-toggle').on("click",function(e){
    e.stopImmediatePropagation();
});

A: Thank you for the above answer, I was having the same issue w/ submenus under the dropdown menus. Using the above solution I was able to solve the problem for this as well.
$('.dropdown-menu .dropdown-submenu a[data-toggle="dropdown-submenu"]').click(function (e)
{
    e.stopPropagation();
});

A: Put

on the original answer, remove all the classes, and just put the ".dropdown-menu" class, it worked for me.
i have an input field inside the dropdown menu.

A: If you look to the bottom of sources of dropdown widget, you will see this:
$(document)
  .on('click.bs.dropdown.data-api', '.dropdown form', function(e) {
    e.stopPropagation()
  })

So you have the following choices:

*

*Simply wrap yor dropdown with form

*Or you can add event listener for click event of .dropdown YOUR_SELECTOR

$(document)
  .on('click.my', '.dropdown some_selector', function(e) {
    e.stopPropagation()
  })

A: Simply use this example.This solution works for me.

Hope it'll help. Thanks.

A: You can omit the dropdown call all together, the bootstrap dropdown works without it. Make sure you're wrapping your script properly, you can include it on the header or body of your page, although personally i prefer placing it on the body of your page.
JS

A: If you want to stop closing only some of dropdown menu, not all of them, then just add an additional class to your ul block:

And use this code:
$(document).on('click', '.dropdown-menu', function(e) {
    if ($(this).hasClass('keep-open-on-click')) { e.stopPropagation(); }
});


text:
Q: Remove Trailing zeros using xsl1.0 or xslt 2.0 I have to sum the values from xml and remove the Trailing zeros from xml.
can you help me to remove this using xsl1.0 or xslt2.0
I have tried with number(.) but its not removing the trailing zeros.
My input is below
<test>
    <loop>
        <lines>
            <linesTotal>2010</linesTotal>
        </lines>
        <lines>
            <linesTotal>20</linesTotal>
        </lines>
    </loop>
</test>

Expected output is
203
but it results 2030
Please help me!

A: I can't see why this would be useful (at least not in the given example), and I strongly suspect you don't really want to do this.
But - mainly for fun - here's a method to remove any trailing zeros from the result:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/test">
    <output>
        <xsl:call-template name="remove-trailing-zeros">
            <xsl:with-param name="number" select="sum(loop/lines/linesTotal)"/>
        </xsl:call-template>
    </output>
</xsl:template>

<xsl:template name="remove-trailing-zeros">
    <xsl:param name="number"/>
    <xsl:choose>
        <xsl:when test="$number and not($number mod 10)">
            <xsl:call-template name="remove-trailing-zeros">
                <xsl:with-param name="number" select="$number div 10"/>
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$number"/>
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

In XSLT 2.0, you could make this a function instead of a template. Or move the problem to the string domain (as suggested in another answer):
<xsl:template match="/test">
    <xsl:param name="sum" select="sum(loop/lines/linesTotal)"/>
    <output>
        <xsl:value-of select="replace(string($sum), '0+$', '')"/>
    </output>
</xsl:template>

A: You can use replace function using 2.0:
replace(string(2010+30), '0$', '')


text:
Q: Why is $\int_{0}^{2 \pi} \frac{{\sin}^2 x \, dx}{5+3 \cos x}= \frac{i}{2} \int_{|z|=1} \frac{(z^2-1)^2}{z^2(3z^2+10z+3)} \, dz$? In a solved exercise, the textbook I'm reading states $\int_{0}^{2 \pi} \frac{{\sin}^2 x \, dx}{5+3 \cos x}= \frac{i}{2} \int_{|z|=1} \frac{(z^2-1)^2}{z^2(3z^2+10z+3)} \, dz$ ?$ without offering any explanation. Why is this equality obvious?

A: First rewrite all of your trig functions as exponential functions.
$e^{ix} = \cos x + i\sin x\\
\cos x = \frac {e^{ix} + e^{-ix}}{2}\\
\sin x = \frac {e^{ix} - e^{-ix}}{2i}$
Then substitute $z = e^{ix}, dx = \frac {1}{iz} \ dz$
As $x$ ranges from zero to $2\pi, z$ will trace out the unit cicle.
$\oint_{|z|=1}\frac {(\frac {z - z^{-1}}{2i})^2}{iz(5+\frac {3z + 3z^{-1}}{2})} \ dz$
Which simplifies to what you show above.


text:
Q: Rendered Value of Text Field does not change if attribute of the object changes I am using the Date Text Field of Material UI. When I pass an attribute of an object, the rendered value of the Text Field does not change even though the value of the object attribute changes.
 const [data, setData] = useState({
    title: new Date("2014-08-18T21:11:54"),
  });

  function changeData(key, obj) {
    var duplicateData = data;
    duplicateData[key] = obj;
    setData(duplicateData);
  }

 <MuiPickersUtilsProvider utils={DateFnsUtils}>
           <KeyboardDatePicker
             disableToolbar
             id="date-picker-inline"
             label={item2}
             KeyboardButtonProps={{
                "aria-label": "change date",
                 }}
             autoOk={true}
             value={data.title}
             onChange={(date) => {
               changeData(title, date);
             }}
              />
 </MuiPickersUtilsProvider>

When I pass a constant, the rendered value changes as desired. How can I make the first case work?
 const [dateTrial, setDateTrial] = useState(new Date("2014-08-18T21:11:54"));

 <MuiPickersUtilsProvider utils={DateFnsUtils}>
           <KeyboardDatePicker
             disableToolbar
             id="date-picker-inline"
             label={item2}
             KeyboardButtonProps={{
                "aria-label": "change date",
                 }}
             autoOk={true}
             value={dateTrial}
             onChange={(date) => {
               setDateTrial(date);
               }}
              />
 </MuiPickersUtilsProvider>

A: you are just assigning the state to a new variable here var duplicateData = data;. This does not create a new object . Now both data and duplicate points to the same object . so mutating duplicateData[key] = obj; will mutate the state as well . In react mutating the state directly will cause issues . So what you need instead is to create a new copy of the state object .
const duplicateData = {...data}

The es6 spread syntax does that for you .
const [data, setData] = useState({
    title: new Date("2014-08-18T21:11:54"),
  });

  function changeData(key, obj) {
    const duplicateData = {...data};
    duplicateData[key] = obj;
    setData(duplicateData);
  }

 <MuiPickersUtilsProvider utils={DateFnsUtils}>
           <KeyboardDatePicker
             disableToolbar
             id="date-picker-inline"
             label={item2}
             KeyboardButtonProps={{
                "aria-label": "change date",
                 }}
             autoOk={true}
             value={data.title}
             onChange={(date) => {
               changeData('title', date); // change the title to string
             }}
              />
 </MuiPickersUtilsProvider>

A: Seems way easier:
onChange={(date) => {
  setData({title: date});
}}

as KeyboardDatePicker prop - no need for your own "external" function changeData and the connected hassle with types and instances. Makes no difference if you put "title" in quotes or not.


text:
Q: Get axis from stem plot I'd like to modify the axis of a stem plot, e.g. to change the grid color with ax.grid(color='gray', axis='y') in the stem plot example. How would I do that?
import matplotlib.pyplot as plt
import numpy as np

# returns 10 evenly spaced samples from 0.1 to 2*PI
x = np.linspace(0.1, 2 * np.pi, 10)

markerline, stemlines, baseline = plt.stem(x, np.cos(x), '-.')

# setting property of baseline with color red and linewidth 2
plt.setp(baseline, color='r', linewidth=2)

A: Alternatively, you can just use plt without defining ax. Although I prefer the latter (your answer).
plt.grid(color='gray', axis='y')

A: First define the axis using plt.subplots(), then call as ax.stem rather than plt.stem:
fig, ax = plt.subplots()
markerline, stemlines, baseline = ax.stem(x, np.cos(x), '-.')
ax.grid(color='gray', axis='y')

A: Per How to get a matplotlib Axes instance to plot to?, another option is adding this at the end:
ax = plt.gca()
ax.grid(color='gray', axis='y')

(ht ImportanceOfBeingErnest)


text:
Q: MVVM vs MVC in ASP.net : Either better for busy websites? I'm wondering about the underlying implementations of these design patterns specifically within asp.net. Is there a difference between the two models in terms of scalability of a website (i.e. as traffic increases might I regret following one or both of these design patterns)? I ask as someone once mentioned that MVC produces a 'lighter' website but I can find nothing to back this up.
If MVVM is as good as MVC why did MS release all the MVC tools?
Thank you

A: Yes they are both adequate and will scale appropriately.
The significant difference is that MVVM lends itself to making use of the native bi-directional binding functionality within the .NET framework. MVC is prevalent within ASP.NET whereas MVVM is prevalent within SL/WPF.
Neither is right or wrong; the underlying technology is the largest factor in the decision process.


text:
Q: Laravel 5.5 : Storage::put , file_put_contents error :failed to open stream: No such file or directory Running a dev win 7 machine.
When trying to store a file with laravel :
$file_store ='/srt/SiteName/df01c6a46702639c/0f3e86c003030527.srt
$file_data = srt file content

    Storage::put($file_store, $file_data)

I get the following error :
 file_put_contents(E:\Projects\2017\releases\storage\app\srt/SiteName/df01c6a46702639c/0f3e86c003030527.srt"): failed to open stream: No such file or directory

When I check on the local disk , it did create the following directories :
SiteName/df01c6a46702639c/

But it just will not store the file, any ideas ?

A: You can use like this:
Storage::disk('local')->put($file_store, $file_data);


text:
Q: Get target file path from custom action How can I get a path to file being installed from a WiX custom action?
I'm creating a WIX Extension, which has a custom element which can be nested under <File> component like this:
<Component Id="FooComponent">
   <File Id="filekey" Name="foo.txt">
       <myextension:Stuff />
   </File>
</Component>

The extension has its custom table which has a foreign key columns pointing to "Component" and "File" tables, and it is executed when a file's component is being installed/uninstalled (like the built-in IIS extension or SQL extension for example)
What I want to achieve is, in my deferred (sheduled) custom action, figure out the target path of the file the extension isbound to. I.e. basically in the differed custom action, I want to get value of [!filekey] (in terms of MSI formatted string). How can I go about that?
I have found a somewhat similar topic here
One of the solutions suggested was to use MsiFormatRecord from a custom action and pass that [#filekey] to that function. It resolves properly then.
I've found examples of using this approach in WiX sources, in gaming extension and NetFX extensions; they use code like this:
    StrAllocFormatted(&pwzFormattedFile, L"[#%s]", pwzFileId);
    WcaGetFormattedString(pwzFormattedFile, &pwzGamePath);

Here WcaGetFormattedString is basically a wrapper for MsiFormatRecord
Still unanswered, is this a right approach to the issue?

A: Basically you pass that [!filekey] to the deferred custom action in that format, using the CustomActionData indirect way of doing that. Then in your custom action you get the property value [CustomActionData] . This might help:
How to pass CustomActionData to a CustomAction using WiX?
To spell it out, if your type 51 custom action that is used to prepare CustomActionData has a Target of [!filekey] then when you retrieve the value of the CustomActionData property inside your custom action then it will contain the full path to the file, the entire path and filename. This demonstrably works, although it wouldn't be practical if you were doing this for many files.


text:
Q: Finite sets are dense with respect to Hausdorff distance Let $(X,d)$ be a complete metric space and consider
\begin{align*}
  BC(X)&=
     \lbrace C\subset X\;|\;C\neq\emptyset\text {, closed and bounded} \rbrace\cr
  \mathrm{Fin}(X)&=
     \lbrace F\subset X\;|\;F\text{ is finite} \rbrace\subset BC(X)\cr
  \mathcal{K}(X)&=
     \lbrace K\subset X\;|\;K\text{ is compact} \rbrace\cr
\end{align*}
Consider the metric space $(BC(X), d_H)$ where $d_H$ is the Hausdorff distance (for the definition of $d_H$ see the Wikipedia entry on $d_H$)
I don't know how to prove that $\mathrm{Fin}(X)\subset BC(X)$ is dense in $\mathcal K(X)$ (with respect to $d_H$).

A: Suppose that $K\in\mathcal{K}(X)$ and $\epsilon>0$. Since $K$ is compact, it has a finite cover by $\epsilon$-balls, say $\{B(x_1,\epsilon),\dots,B(x_n,\epsilon)\}$. Let $F=\{x_1,x_2,\dots,x_n\}$. What can you say about $d_H(F,K)$? You may find it easiest to think of $d_H$ in terms of the characterization $$d_H(X,Y)=\inf\{\epsilon>0:X\subseteq Y_\epsilon\text{ and }Y\subseteq X_\epsilon\}$$ given in the Wikipedia article right after the definition.


text:
Q: How to provide an Azure Storage CNAME as part of the connection string? All the connection strings for an Azure Storage account seem to only be the original url + account.
Is there any way to change the connection string to an Azure Storage account to be my CNAME instead?
EDIT: The answer below is awesome and a few hours AFTER the answer was posted (and ticked) I found some official documentation on this/the same answer :)

A: Great Question! I think you can but it will only work with Blob Storage as you can only specify a CNAME mapping for blob endpoint plus you will need to use your account name somewhere as it is used for authorization header computation. This is how I did it:
    static void ConnectViaCname()
    {
        var cred = new StorageCredentials("account-name", "account-key");
        var account = new CloudStorageAccount(cred, new Uri("https://cnamemapping.com"), null, null, null);
        var client = account.CreateCloudBlobClient();
        var containers = client.ListContainers();
        foreach (var container in containers)
        {
            Console.WriteLine(container.Uri.AbsoluteUri);
        }
    }

UPDATE
If you wish to use connection string, please specify the connection string in this format:
DefaultEndpointsProtocol=https;
BlobEndpoint=https://cnamemapping.com;
AccountName=account-name;
AccountKey=account-key

So the code would be:
    static void ConnectViaCname()
    {
        var connectionString = "DefaultEndpointsProtocol=https;BlobEndpoint=https://cnamemapping.com;AccountName=account-name;AccountKey=account-key";
        var account = CloudStorageAccount.Parse(connectionString);
        var client = account.CreateCloudBlobClient();
        var containers = client.ListContainers();
        foreach (var container in containers)
        {
            Console.WriteLine(container.Uri.AbsoluteUri);
        }
    }


text:
Q: Convert an int bitmask to string I am trying to find out what flags has been set a cookie. http/Cookie does the job but returns a bitmask.
How can i convert the bitmask to string so that i can know what flags(such as httponly and secure) has been set in the cookie
https://mdref.m6w6.name/http/Cookie/getFlags


text:
Q: I have a class that looks like this following: class ContUser
{
    char *display_Name;
    char *email;
    char password[10];
    const int id_user;
    char user_type;
    int badges_nr;
    char **badges;

     ContUser(char *dn, char *e, char p[10],int id,char tip) : id_utilizator(id) {
        display_Name = new char[strlen(dn) + 1];
        strcpy(display_Name, dn);

        email = new char[strlen(e) + 1];
        strcpy(email, e);
    }
};

I  have an error:

display_Name 0xcccccccc error reading character of string;

at both of objects, displayname and email, and I can't realize why. This is my error (Unable to read memory).
This is the part where i created an instance of ContUser
void main()
{
    ContUtilizator c2("Mariam31", "mariam@yahoo.com", "Passwordd", 12, 'V');
    c2.display();
}

A: You should rewrite the class using the standard template library. This could be done for the snippet you provided as follows:
class ContUser
{
    std::string display_Name;
    std::string email;
    std::string password;
    const int id_user;
    char user_type;
    int badges_nr;
    std::vector< std::string> > badges;

    ContUser(char *dn, char *e, char p[10], int id, char tip) : id_utilizator(id)
    {
        display_Name = std::string(dn);
        email = std::string(e);
    }
};


text:
Q: Setting a cell delegate in swift gives error I am trying to use MGSwipeTableCell library to make custom swipe cell. However, cell.delegate = self keep giving me error saying that

"Cannot assign value of type 'AlarmTableViewController' to type 'MGSwipeTableCellDelegate?'"

but even if I insert 'as! MGSwipeTableCellDelegate' it makes fatal error:

unexpectedly found nil while unwrapping an Optional value.

class AlarmTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let reuseIdentifier = "programmaticCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! MGSwipeTableCell

        cell.textLabel!.text = "Title"
        cell.delegate = self as! MGSwipeTableCellDelegate //optional
        return cell
    }
}

In my storyboard I've set cell's custom class as MGSwipeTableCell and its identifier as programmaticCell. Please help me. tableView is driving me crazy.

A: You need to add MGSwipeTableCellDelegate the delegate for your class.
class AlarmTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MGSwipeTableCellDelegate

and the reason for your crash is force as! conversion while its nil.

A: I agree with @TheTiger's answer. But I would also consider this option which is to use an extension rather than add it to the main brackets.
extension SomeType: SomeProtocol, AnotherProtocol {
    // implementation of protocol requirements goes here
}

Or in your case it would be
extension AlarmTableViewController: MGSwipeTableCellViewDelegate {
    //and then you can add all the methods here if any
}

This is slightly better because you can then add all the methods together in a more clear way. By splitting it up by the different delegations it will be better when you go back and need to change something
Some reading if you're interested: https://docs.swift.org/swift-book/LanguageGuide/Extensions.html
Also if this isn't clear you add in any file, but it would be best to add it at the bottom of your file with the AlarmTableViewController.


text:
Q: Prometheus is crash looping when the pod recreates We are Prometheus version 2.26.0 and kubernetes verion 1.21.7 in Azure. We mount the data in Azure storage NFS and it was working fine. From last few days Prometheus container is crash-looping and below are the logs
level=info ts=2022-01-26T08:04:14.375Z caller=main.go:418 msg="Starting Prometheus" version="(version=2.26.0, branch=HEAD, revision=3cafc58827d1ebd1a67749f88be4218f0bab3d8d)"
level=info ts=2022-01-26T08:04:14.375Z caller=main.go:423 build_context="(go=go1.16.2, user=root@a67cafebe6d0, date=20210331-11:56:23)"
level=info ts=2022-01-26T08:04:14.375Z caller=main.go:424 host_details="(Linux 5.4.0-1065-azure #68~18.04.1-Ubuntu SMP Fri Dec 3 14:08:44 UTC 2021 x86_64 prometheus-6b9d9d54f4-nc45x (none))"
level=info ts=2022-01-26T08:04:14.375Z caller=main.go:425 fd_limits="(soft=1048576, hard=1048576)"
level=info ts=2022-01-26T08:04:14.375Z caller=main.go:426 vm_limits="(soft=unlimited, hard=unlimited)"
level=info ts=2022-01-26T08:04:14.503Z caller=web.go:540 component=web msg="Start listening for connections" address=0.0.0.0:9090
level=info ts=2022-01-26T08:04:14.507Z caller=main.go:795 msg="Starting TSDB ..."
level=info ts=2022-01-26T08:04:14.509Z caller=tls_config.go:191 component=web msg="TLS is disabled." http2=false
level=info ts=2022-01-26T08:04:14.560Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641478251052 maxt=1641513600000 ulid=01FRSEHC4YHV3N26JY5AMNZFRW
level=info ts=2022-01-26T08:04:14.593Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641513600037 maxt=1641578400000 ulid=01FRVCAP2VJGDF0Z9CS24EXAJJ
level=info ts=2022-01-26T08:04:14.624Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641578400038 maxt=1641643200000 ulid=01FRXA4AQHMHAEYWRKQFGP075M
level=info ts=2022-01-26T08:04:14.651Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641643200422 maxt=1641708000000 ulid=01FRZ7XQQ4RA96DCPPBP22D71N
level=info ts=2022-01-26T08:04:14.679Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641708000020 maxt=1641772800000 ulid=01FS15QDG6BS7H6M6Y09HG3E12
level=info ts=2022-01-26T08:04:14.707Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641772800011 maxt=1641837600000 ulid=01FS33GT38PRSB9VP56YFXT2M0
level=info ts=2022-01-26T08:04:14.736Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641963555381 maxt=1641967200000 ulid=01FS6MRNZEWT1Z6P697K09KHD7
level=info ts=2022-01-26T08:04:14.763Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641837600100 maxt=1641902400000 ulid=01FS6R88C70TCD8CYC4XJ95X23
level=info ts=2022-01-26T08:04:14.810Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641967200019 maxt=1642032000000 ulid=01FS8WXQP3YJ7EXBVNYBQG4DVY
level=info ts=2022-01-26T08:04:14.836Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642032000072 maxt=1642096800000 ulid=01FSATQBR4XBQRDM72ATFS9PQ2
level=info ts=2022-01-26T08:04:14.863Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642096800059 maxt=1642161600000 ulid=01FSCRHE2YBDX7GPRPSH6BNGRX
level=info ts=2022-01-26T08:04:14.895Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642161600091 maxt=1642226400000 ulid=01FSEPB1GPGAANVCQ2VKW9BQ4G
level=info ts=2022-01-26T08:04:14.948Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642226400026 maxt=1642291200000 ulid=01FSGM4J0G1D0A6H1GD3N9C372
level=info ts=2022-01-26T08:04:14.973Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642291200005 maxt=1642356000000 ulid=01FSJHY6W0FRYDHCXBVB5XPFYG
level=info ts=2022-01-26T08:04:15.002Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642356000027 maxt=1642420800000 ulid=01FSMFR96DASV6YPN66W7C86H9
level=info ts=2022-01-26T08:04:15.077Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642420800042 maxt=1642485600000 ulid=01FSPDHGWRT65D8CKWQ2JPRHW3
level=info ts=2022-01-26T08:04:15.105Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642485600006 maxt=1642550400000 ulid=01FSRBAVP2MW71H08F32D6HGB4
level=info ts=2022-01-26T08:04:15.130Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642550400028 maxt=1642615200000 ulid=01FST9482FD0Z3PHXHNW2W616E
level=info ts=2022-01-26T08:04:15.157Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642680000018 maxt=1642687200000 ulid=01FSW00TJKJ7CGCQ7JJS3XQK8G
level=info ts=2022-01-26T08:04:15.187Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642687200018 maxt=1642694400000 ulid=01FSW6WHTSEAXHWV5J7PQP94X7
level=info ts=2022-01-26T08:04:15.213Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642615200021 maxt=1642680000000 ulid=01FSW6XYH2Y429PG5YRM0K45XS
level=info ts=2022-01-26T08:04:15.275Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642694400018 maxt=1642701600000 ulid=01FSWDR92Y7H302NDZRX1V2PX9
level=info ts=2022-01-26T08:04:21.840Z caller=head.go:696 component=tsdb msg="Replaying on-disk memory mappable chunks if any"
level=info ts=2022-01-26T08:04:22.623Z caller=head.go:710 component=tsdb msg="On-disk memory mappable chunks replay completed" duration=782.403397ms
level=info ts=2022-01-26T08:04:22.623Z caller=head.go:716 component=tsdb msg="Replaying WAL, this may take a while"
level=info ts=2022-01-26T08:04:34.169Z caller=head.go:742 component=tsdb msg="WAL checkpoint loaded"
level=info ts=2022-01-26T08:04:38.895Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=299 maxSegment=7511
level=warn ts=2022-01-26T08:04:46.423Z caller=main.go:645 msg="Received SIGTERM, exiting gracefully..."
level=info ts=2022-01-26T08:04:46.424Z caller=main.go:668 msg="Stopping scrape discovery manager..."
level=info ts=2022-01-26T08:04:46.424Z caller=main.go:682 msg="Stopping notify discovery manager..."
level=info ts=2022-01-26T08:04:46.424Z caller=main.go:704 msg="Stopping scrape manager..."
level=info ts=2022-01-26T08:04:46.424Z caller=main.go:678 msg="Notify discovery manager stopped"
level=info ts=2022-01-26T08:04:46.425Z caller=main.go:698 msg="Scrape manager stopped"
level=info ts=2022-01-26T08:04:46.426Z caller=manager.go:934 component="rule manager" msg="Stopping rule manager..."
level=info ts=2022-01-26T08:04:46.426Z caller=manager.go:944 component="rule manager" msg="Rule manager stopped"
level=info ts=2022-01-26T08:04:46.426Z caller=notifier.go:601 component=notifier msg="Stopping notification manager..."
level=info ts=2022-01-26T08:04:46.426Z caller=main.go:872 msg="Notifier manager stopped"
level=info ts=2022-01-26T08:04:46.426Z caller=main.go:664 msg="Scrape discovery manager stopped"
level=info ts=2022-01-26T08:04:46.792Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=300 maxSegment=7511
level=info ts=2022-01-26T08:04:46.870Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=301 maxSegment=7511
level=info ts=2022-01-26T08:04:46.901Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=302 maxSegment=7511
level=info ts=2022-01-26T08:04:46.946Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=303 maxSegment=7511
level=info ts=2022-01-26T08:04:46.974Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=304 maxSegment=7511
level=info ts=2022-01-26T08:04:47.008Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=305 maxSegment=7511
level=info ts=2022-01-26T08:04:47.034Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=306 maxSegment=7511
level=info ts=2022-01-26T08:04:47.067Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=307 maxSegment=7511
level=info ts=2022-01-26T08:04:47.098Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=308 maxSegment=7511
level=info ts=2022-01-26T08:04:47.124Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=309 maxSegment=7511
level=info ts=2022-01-26T08:04:47.158Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=310 maxSegment=7511
level=info ts=2022-01-26T08:04:47.203Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=311 maxSegment=7511
level=info ts=2022-01-26T08:04:47.254Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=312 maxSegment=7511
level=info ts=2022-01-26T08:04:47.486Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=313 maxSegment=7511
level=info ts=2022-01-26T08:04:47.511Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=314 maxSegment=7511
level=info ts=2022-01-26T08:04:47.539Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=315 maxSegment=7511
level=info ts=2022-01-26T08:04:47.564Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=316 maxSegment=7511

.
.
.
.
.
.
.
.
.

level=info ts=2022-01-26T08:05:15.161Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1401 maxSegment=7511
level=info ts=2022-01-26T08:05:15.182Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1402 maxSegment=7511
level=info ts=2022-01-26T08:05:15.205Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1403 maxSegment=7511
level=info ts=2022-01-26T08:05:15.229Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1404 maxSegment=7511
level=info ts=2022-01-26T08:05:15.251Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1405 maxSegment=7511
level=info ts=2022-01-26T08:05:15.274Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1406 maxSegment=7511
level=info ts=2022-01-26T08:05:15.297Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1407 maxSegment=7511
level=info ts=2022-01-26T08:05:15.323Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1408 maxSegment=7511
level=info ts=2022-01-26T08:05:15.349Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1409 maxSegment=7511
level=info ts=2022-01-26T08:05:15.372Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1410 maxSegment=7511
level=info ts=2022-01-26T08:05:15.426Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1411 maxSegment=7511
level=info ts=2022-01-26T08:05:15.452Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1412 maxSegment=7511
level=info ts=2022-01-26T08:05:15.475Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1413 maxSegment=7511
level=info ts=2022-01-26T08:05:15.498Z caller=head.go:768 component=tsdb msg="WAL segment loaded" segment=1414 maxSegment=7511
rpc error: code = NotFound desc = an error occurred when try to find container "ae14079418f59b04bb80d8413e8fdc34f167bfe762317ef674e05466d34c9e1f": not found

So I deleted the deployment and redeployed to the the same storage account, the I got new error
level=info ts=2022-01-26T11:10:11.530Z caller=main.go:418 msg="Starting Prometheus" version="(version=2.26.0, branch=HEAD, revision=3cafc58827d1ebd1a67749f88be4218f0bab3d8d)"
level=info ts=2022-01-26T11:10:11.534Z caller=main.go:423 build_context="(go=go1.16.2, user=root@a67cafebe6d0, date=20210331-11:56:23)"
level=info ts=2022-01-26T11:10:11.535Z caller=main.go:424 host_details="(Linux 5.4.0-1064-azure #67~18.04.1-Ubuntu SMP Wed Nov 10 11:38:21 UTC 2021 x86_64 prometheus-6b9d9d54f4-wnmzh (none))"
level=info ts=2022-01-26T11:10:11.536Z caller=main.go:425 fd_limits="(soft=1048576, hard=1048576)"
level=info ts=2022-01-26T11:10:11.536Z caller=main.go:426 vm_limits="(soft=unlimited, hard=unlimited)"
level=info ts=2022-01-26T11:10:14.168Z caller=web.go:540 component=web msg="Start listening for connections" address=0.0.0.0:9090
level=info ts=2022-01-26T11:10:15.385Z caller=main.go:795 msg="Starting TSDB ..."
level=info ts=2022-01-26T11:10:16.022Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641837600024 maxt=1641902400000 ulid=01FS51ANKBFTVNRPZ68FGQQ5GA
level=info ts=2022-01-26T11:10:16.309Z caller=tls_config.go:191 component=web msg="TLS is disabled." http2=false
level=info ts=2022-01-26T11:10:16.494Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641902400005 maxt=1641967200000 ulid=01FS6Z46FGXN932K7D39D9166D
level=info ts=2022-01-26T11:10:16.806Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1641967200106 maxt=1642032000000 ulid=01FS8WXRJ7Q80FKD4C8EJNR0AD
level=info ts=2022-01-26T11:10:17.011Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642032000003 maxt=1642096800000 ulid=01FSATQE1VMNR101KRW1X10Q75
level=info ts=2022-01-26T11:10:17.305Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642096800206 maxt=1642161600000 ulid=01FSCRGVT1E7562SF7EQN12JBM
level=info ts=2022-01-26T11:10:18.240Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642161600059 maxt=1642226400000 ulid=01FSEPAFP2CX03ANRB7Q1AG514
level=info ts=2022-01-26T11:10:21.046Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642226400051 maxt=1642291200000 ulid=01FSGM3WT0TKR0XW9BD4QSKPQE
level=info ts=2022-01-26T11:10:21.422Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642291200113 maxt=1642356000000 ulid=01FSJHXKHMANW0E6FXDXVM265G
level=info ts=2022-01-26T11:10:22.822Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642356000032 maxt=1642420800000 ulid=01FSMFQ6XJ97VJFKNCYQBVB4DZ
level=info ts=2022-01-26T11:10:23.536Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642420800021 maxt=1642485600000 ulid=01FSPDGM95FDDV2CDWX93BTDCS
level=info ts=2022-01-26T11:10:23.880Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642485600072 maxt=1642550400000 ulid=01FSRBA555RWY4QNP4HD9YKRBM
level=info ts=2022-01-26T11:10:25.021Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642550400031 maxt=1642615200000 ulid=01FST93N3C82K9VS20MKTMGGYC
level=info ts=2022-01-26T11:10:25.713Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642615200014 maxt=1642680000000 ulid=01FSW6X95FRNSN1XJZ2YK0MXW7
level=info ts=2022-01-26T11:10:26.634Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642680000012 maxt=1642744800000 ulid=01FSY4PXA7V1XQHHA3MC35JSWQ
level=info ts=2022-01-26T11:10:27.776Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642744800174 maxt=1642809600000 ulid=01FT02G9XGHPV8GME53ZPMYXE6
level=info ts=2022-01-26T11:10:28.760Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642809600070 maxt=1642874400000 ulid=01FT209WP8AXXVZB1NCSC55ACE
level=info ts=2022-01-26T11:10:29.618Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642874400253 maxt=1642939200000 ulid=01FT3Y3A4H72FFW318RKHEXXGA
level=info ts=2022-01-26T11:10:30.313Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1642939200047 maxt=1643004000000 ulid=01FT5VX3YC838QN5VQFAERV1QX
level=info ts=2022-01-26T11:10:30.483Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1643004000040 maxt=1643068800000 ulid=01FT7SPHC5EV0SS1R0WT04H9FR
level=info ts=2022-01-26T11:10:30.696Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1643068800035 maxt=1643133600000 ulid=01FT9QFZXBZ7EYY2CTE8WXZTB9
level=info ts=2022-01-26T11:10:31.838Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1643133600000 maxt=1643155200000 ulid=01FTA574G4M45WX97Z470DQF73
level=info ts=2022-01-26T11:10:33.686Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1643176800008 maxt=1643184000000 ulid=01FTASSZCG8V5N2VGAGFBYJBSR
level=info ts=2022-01-26T11:10:36.078Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1643184000000 maxt=1643191200000 ulid=01FTB0NP47JW5JCF808QZZ8WZQ
level=info ts=2022-01-26T11:10:36.442Z caller=repair.go:57 component=tsdb msg="Found healthy block" mint=1643155200065 maxt=1643176800000 ulid=01FTB0P9H3H09B2ADD5X1RXFW6
level=info ts=2022-01-26T11:10:40.079Z caller=main.go:668 msg="Stopping scrape discovery manager..."
level=info ts=2022-01-26T11:10:40.079Z caller=main.go:682 msg="Stopping notify discovery manager..."
level=info ts=2022-01-26T11:10:40.079Z caller=main.go:704 msg="Stopping scrape manager..."
level=info ts=2022-01-26T11:10:40.079Z caller=main.go:678 msg="Notify discovery manager stopped"
level=info ts=2022-01-26T11:10:40.079Z caller=main.go:664 msg="Scrape discovery manager stopped"
level=info ts=2022-01-26T11:10:40.079Z caller=main.go:698 msg="Scrape manager stopped"
level=info ts=2022-01-26T11:10:40.080Z caller=manager.go:934 component="rule manager" msg="Stopping rule manager..."
level=info ts=2022-01-26T11:10:40.080Z caller=manager.go:944 component="rule manager" msg="Rule manager stopped"
level=info ts=2022-01-26T11:10:40.080Z caller=notifier.go:601 component=notifier msg="Stopping notification manager..."
level=info ts=2022-01-26T11:10:40.080Z caller=main.go:872 msg="Notifier manager stopped"
level=error ts=2022-01-26T11:10:40.080Z caller=main.go:881 err="opening storage failed: lock DB directory: resource temporarily unavailable"

The yaml is provided by the Istio .Below is deployment yaml file.
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    component: "server"
    app: prometheus
    release: prometheus
    chart: prometheus-14.6.1
    heritage: Helm
  name: prometheus
  namespace: istio-system
spec:
  selector:
    matchLabels:
      component: "server"
      app: prometheus
      release: prometheus
  replicas: 1
  template:
    metadata:
      labels:
        component: "server"
        app: prometheus
        release: prometheus
        chart: prometheus-14.6.1
        heritage: Helm

        sidecar.istio.io/inject: "false"
    spec:
      enableServiceLinks: true
      serviceAccountName: prometheus
      containers:
        - name: prometheus-server-configmap-reload
          image: "jimmidyson/configmap-reload:v0.5.0"
          imagePullPolicy: "IfNotPresent"
          args:
            - --volume-dir=/etc/config
            - --webhook-url=http://127.0.0.1:9090/-/reload
          resources:
            {}
          volumeMounts:
            - name: config-volume
              mountPath: /etc/config
              readOnly: true

        - name: prometheus-server
          image: "prom/prometheus:v2.26.0"
          imagePullPolicy: "IfNotPresent"
          args:
            - --storage.tsdb.retention.time=15d
            - --config.file=/etc/config/prometheus.yml
            - --storage.tsdb.path=/data
            - --web.console.libraries=/etc/prometheus/console_libraries
            - --web.console.templates=/etc/prometheus/consoles
            - --web.enable-lifecycle
          ports:
            - containerPort: 9090
          readinessProbe:
            httpGet:
              path: /-/ready
              port: 9090
            initialDelaySeconds: 0
            periodSeconds: 5
            timeoutSeconds: 4
            failureThreshold: 3
            successThreshold: 1
          livenessProbe:
            httpGet:
              path: /-/healthy
              port: 9090
            initialDelaySeconds: 30
            periodSeconds: 15
            timeoutSeconds: 10
            failureThreshold: 3
            successThreshold: 1
          resources:
            {}
          volumeMounts:
            - name: config-volume
              mountPath: /etc/config
            - name: azurefileshare
              mountPath: /data
              subPath: ""
      hostNetwork: false
      dnsPolicy: ClusterFirst
      securityContext:
        fsGroup: 65534
        runAsGroup: 65534
        runAsNonRoot: true
        runAsUser: 65534
      terminationGracePeriodSeconds: 300
      volumes:
        - name: config-volume
          configMap:
            name: prometheus
        - name: azurefileshare
          azureFile:
            secretName: log-storage-secret
            shareName: prometheusfileshare
            readOnly: false

Expected Behavior
When I mount the data to new container, It should load the data.
Actual Behavior
Not able to load the data or not able bind the data with newly created pod when old pod dies
Help me out, to resolve the issue.

A: Thank You YwH for your suggestion, Posting this an answer so it can help other community member if they encounter the same issue in future.
As stated in this document Istio provides a basic sample installation to quickly get Prometheus up and running:
This is intended for demonstration only, and is not tuned for performance or security.

Note : Isio configuration is well-suited for small clusters and
monitoring for short time horizons, it is not suitable for large-scale
meshes or monitoring over a period of days or weeks

Solution : Prometheus is a stateful application, better deployed with a StatefulSet, not Deployment.
StatefulSets are valuable for applications that require one or more of the following.
Stable, persistent storage. Ordered, graceful deployment and scaling.
You can use this Stateful code for deployment of prometheus container.


text:
Q: Is the gerund being used in a proper way: "His job is driving a cab." I am not sure if the following sentence is grammatically correct.

His job is driving a cab.

I believe the gerund cannot be used in this way.  Am I right?
Would it mean the same to say? His job is to drive a cab
What are the differences between these two statements? Are they both possible?

A:
Driving a cab is his job.
  Playing tennis is their favorite sport.

Gerund phrases can be used as subjects in sentences with be and a predicate nominative. So, you can invert those sentences to:
His job is driving a cab.
Their favorite sport is playing tennis.
His job is to drive a cab, and not to sit around playing cards.
The emphasis is different. The meaning is basically the same but,  let's say for simplicity's sake, the use of drive a cab after to is more objective oriented and is a predicate but not a  predicate nominative. It makes a statement about his job. As opposed to just being informative.


text:
Q: Mac zsh: django-admin command not found I have zsh on my mac. I did simlink as you recommended in here django-admin command not working in Mac OS so in my directory /usr/local/bin I have another folder bin with files __pycache__     django-admin.py.
However there is still the same problem and I receive zsh: command not found for django-admin as well as django-admin.py
Any alternative guys? I am pretty new into programming and computer science :(
Python 3.8 Django 2.1

A: before going any further in your discovery of Python and Django, you should take a moment to learn about virtual environment in Python.
Virtual env are highly recommended when working with Python. Among many other advantages, they simplify the access to installed packages, or command line utilities like django-admin.
I picked a tutorial that looks ok but there are plenty of them on the web : https://realpython.com/python-virtual-environments-a-primer/
Good luck in your pydventure ;)


text:
Q: Mask repeating svg background pattern with linear gradient in css I want to mask a repeating svg background with a linear gradient like this:

These are linear gradient and repeating svg in css:
.hexgrad {
    background-image: url("data:image/svg+xml,<svg id='patternId' width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'><defs><pattern id='a' patternUnits='userSpaceOnUse' width='29' height='50.115' patternTransform='scale(1.5) rotate(0)'><rect x='0' y='0' width='100%' height='100%' fill='hsla(0, 0%, 100%, 0)'/><path d='M14.498 16.858L0 8.488.002-8.257l14.5-8.374L29-8.26l-.002 16.745zm0 50.06L0 58.548l.002-16.745 14.5-8.373L29 41.8l-.002 16.744zM28.996 41.8l-14.498-8.37.002-16.744L29 8.312l14.498 8.37-.002 16.745zm-29 0l-14.498-8.37.002-16.744L0 8.312l14.498 8.37-.002 16.745z'  stroke-width='1' stroke='hsla(27, 100%, 50%, 0.15)' fill='none'/></pattern></defs><rect width='800%' height='800%' transform='translate(0,0)' fill='url(%23a)'/></svg>"),
    linear-gradient(0deg, #F8F3F0 0%, rgba(251,146,60,0.5) 50%, #F8F3F0 100%);
}

I wish to know what's the best approach for solving this problem.
I just want to have the gradient on the paths of svg background.
I have searched a lot but it just made me more confused.
Thanks in advance

A: Use mask for this task. Added to a pseudo element to avoid masking the main content:

.hexgrad {
  height: 500px;
  position: relative;
  background: #404040;
  z-index: 0;
}
.hexgrad:before {
  content:"";
  position: absolute;
  z-index: -1;
  inset:0;
  background-image: url("data:image/svg+xml,<svg id='patternId' width='100%' height='100%' xmlns='http://www.w3.org/2000/svg'><defs><pattern id='a' patternUnits='userSpaceOnUse' width='29' height='50.115' patternTransform='scale(1.5) rotate(0)'><rect x='0' y='0' width='100%' height='100%' fill='hsla(0, 0%, 100%, 0)'/><path d='M14.498 16.858L0 8.488.002-8.257l14.5-8.374L29-8.26l-.002 16.745zm0 50.06L0 58.548l.002-16.745 14.5-8.373L29 41.8l-.002 16.744zM28.996 41.8l-14.498-8.37.002-16.744L29 8.312l14.498 8.37-.002 16.745zm-29 0l-14.498-8.37.002-16.744L0 8.312l14.498 8.37-.002 16.745z'  stroke-width='1' stroke='hsla(27, 100%, 50%, 0.15)' fill='none'/></pattern></defs><rect width='800%' height='800%' transform='translate(0,0)' fill='url(%23a)'/></svg>");
  -webkit-mask: linear-gradient(#0000,#000,#0000);
}

A: You just need to set the opacity of colors in linear-gradient property.
Like this:     background-image: linear-gradient(0deg, #f8f3f073 0%, rgb(251 146 60 / 4%) 50%, #f8f3f085 100%), url("data:image/svg+xml,");


text:
Q: How to distribute private android application to specific devices? How can I deploy an APK for android that is only available for the devices I specify beforehand?
I would like to a host a private application that is only available to workers inside the company and only for the devices that are owned by the company.
I know I can do this with Google Play, but that requires a G-Suite/Workspace subscription we do not have.
I would like to continuously deploy new versions and the devices to update automatically.
Are there any custom marketplaces that allow this? Anything else?


text:
Q: use vuex mapGetters to iterate in a state obj of users i am learning vuex at the moment and i am stuck on the mapping functionality like import { mapGetters } from 'vuex';

in my state i have a object called users where i save user data and later will add an addNewUser functionality to expand the object of users. But for this test case i just created a dummy user named "John":
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    users: [
      {
        userName: 'John',
        income: 2000,
        leftover: 0
      }
    ]
  },
  getters: {
    user: state => {
      return state.users;
    },
  },
  mutations: {},
  actions: {
    addNewUser(userName, income) {
      console.log(userName, income, 'from vuex');

    }
  },
  modules: {}
});

before i gone this way i simple called john with a this.$store.state.users and then iterated over the userNames with an forEach. But figured out this isn't the best way to do that.
how can i achieve to get the state data of users, and print them out in like a forEach loop as i did before?
In Line 129 loadAllUsers() you can see my old way to achieve this:
<template>

            Settings

          <button
            type="button"
            class="close"
            data-dismiss="modal"
            aria-label="Close"
          >
            ×
          </button>

Users:

                {{ user.userName }}

Add New User:

            <input
              v-model="userNameInput"
              type="text"
              class="form-control"
              placeholder="Username"
            >

            <input
              v-model="userIncomeInput"
              type="number"
              class="form-control"
              placeholder="Income"
            >

          <button
            type="button"
            class="btn btn-secondary"
            data-dismiss="modal"
          >
            Close
          </button>
          <button
            type="button"
            class="btn btn-primary"
            @click="createNewUser"
          >
            Save changes
          </button>

</template>

A: With you can mapGetters you can map the users in your store to a computed. that will be reactive.
So you dont even need to load the users.

Vue.config.devtools = false;
Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    users: [{
      userName: 'John',
      income: 2000,
      leftover: 0
    }]
  },
  getters: {
    users: state => {
      return state.users;
    },
  }
})

var app = new Vue({
  el: '#app',
  store,
  computed: {
    ...Vuex.mapGetters(["users"]),
  }
})

    {{ user.userName }}

https://vuex.vuejs.org/guide/getters.html#getters

A: If you can use mapState, declare userList in computed instead of data:
  computed: {
    ...mapState({
      userList: state => state.users.map(user => user.userName),
    })

and in your html code change all user.userName to user


text:
Q: Understanding Sequence and Column in spark Suppose I have a DF as following:
+-------+----------+
|  value|     group|
+-------+----------+
|      A|         X|
|      A|         X|
|      A|         X|
|      A|         X|
|      B|         Z|
|      B|         Z|
|      B|         Z|
+-------+----------+

What I am trying to do is add 5(for example) more rows of each value,group combination to the dataframe. I tried exploring sequence and explode but couldn't get the method signatures(didn't understand why they took Column as inputs). How can I achieve this task.
Edit: This can be acheived by selecting functions.explode(functions.sequence(functions.lit(1),functions.lit(5),functions.lit(1) and doing union with the original dataframe. Is there an efficient way to do it?

A: DataFrame in Spark is immutable. Therefore, you could only achieve what you want by combining 2 DataFrames (one is as you posted, the other one is your intention) in a vertical way (union), OR add the data you want into data source via a native programming language such as Python.
In this scenario, you make the intentional data manipulation via an API you are familiar with.
Scala APIs
import org.apache.spark.sql.{functions => f}
import org.apache.spark.sql.SQLImplicits

val originalDf = ... // your example DF
val addition = originalDf.select($"value").distinct()\
    .select($"value", f.explode_outer(f.sequence(f.lit(0), f.lit(5), f.lit(1))).alias("group"))
val result1 = originalDf.union(addition)

Plain SQL
val originalDf = .... // your example DF
originalDf.createOrReplaceTempView("originalDf")
val result2 = spark.sql("""
    (SELECT value, group
    FROM originalDf)
    UNION ALL
    (
    SELECT *
    FROM (SELECT DISTINCT value FROM originalDf)
        LATERAL VIEW EXPLODE(SEQUENCE(0, 5, 1)) temp_table AS group)
    """)

Analysis
result1
== Parsed Logical Plan ==
'Union
:- LogicalRDD [value#551, group#552L], false
+- Project [value#551, group#624]
   +- Generate explode(sequence(0, 5, Some(1), Some(Asia/Taipei))), true, [group#624]
      +- Deduplicate [value#551]
         +- Project [value#551]
            +- LogicalRDD [value#551, group#552L], false

== Analyzed Logical Plan ==
value: string, group: bigint
Union
:- Project [value#551, group#552L]
:  +- LogicalRDD [value#551, group#552L], false
+- Project [value#636, cast(group#637 as bigint) AS group#638L]
   +- Project [value#551 AS value#636, group#624 AS group#637]
      +- Project [value#551, group#624]
         +- Generate explode(sequence(0, 5, Some(1), Some(Asia/Taipei))), true, [group#624]
            +- Deduplicate [value#551]
               +- Project [value#551]
                  +- LogicalRDD [value#551, group#552L], false

== Optimized Logical Plan ==
Union
:- LogicalRDD [value#551, group#552L], false
+- Project [value#551, cast(group#624 as bigint) AS group#638L]
   +- Generate explode(org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@bb501947), true, [group#624]
      +- Aggregate [value#551], [value#551]
         +- Project [value#551]
            +- LogicalRDD [value#551, group#552L], false

== Physical Plan ==
Union
:- *(1) Scan ExistingRDD[value#551,group#552L]
+- *(4) Project [value#551, cast(group#624 as bigint) AS group#638L]
   +- Generate explode(org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@bb501947), [value#551], true, [group#624]
      +- *(3) HashAggregate(keys=[value#551], functions=[], output=[value#551])
         +- Exchange hashpartitioning(value#551, 200), true, [id=#2107]
            +- *(2) HashAggregate(keys=[value#551], functions=[], output=[value#551])
               +- *(2) Project [value#551]
                  +- *(2) Scan ExistingRDD[value#551,group#552L]

result2
== Parsed Logical Plan ==
'Union
:- 'Project ['value, 'group]
:  +- 'UnresolvedRelation [originalDf]
+- 'Project [*]
   +- 'Generate 'EXPLODE('SEQUENCE(0, 5, 1)), false, temp_table, ['group]
      +- 'SubqueryAlias __auto_generated_subquery_name
         +- 'Distinct
            +- 'Project ['value]
               +- 'UnresolvedRelation [originalDf]

== Analyzed Logical Plan ==
value: string, group: bigint
Union
:- Project [value#425, group#426L]
:  +- Project [value#425, group#426L]
:     +- SubqueryAlias originaldf
:        +- LogicalRDD [value#425, group#426L], false
+- Project [value#511, cast(group#512 as bigint) AS group#513L]
   +- Project [value#425 AS value#511, group#510 AS group#512]
      +- Project [value#425, group#510]
         +- Generate explode(sequence(0, 5, Some(1), Some(Asia/Taipei))), false, temp_table, [group#510]
            +- SubqueryAlias __auto_generated_subquery_name
               +- Distinct
                  +- Project [value#425]
                     +- SubqueryAlias originaldf
                        +- LogicalRDD [value#425, group#426L], false

== Optimized Logical Plan ==
Union
:- LogicalRDD [value#425, group#426L], false
+- Project [value#425, cast(group#510 as bigint) AS group#513L]
   +- Generate explode(org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@bb501947), false, temp_table, [group#510]
      +- Aggregate [value#425], [value#425]
         +- Project [value#425]
            +- LogicalRDD [value#425, group#426L], false

== Physical Plan ==
Union
:- *(1) Scan ExistingRDD[value#425,group#426L]
+- *(4) Project [value#425, cast(group#510 as bigint) AS group#513L]
   +- Generate explode(org.apache.spark.sql.catalyst.expressions.UnsafeArrayData@bb501947), [value#425], false, [group#510]
      +- *(3) HashAggregate(keys=[value#425], functions=[], output=[value#425])
         +- Exchange hashpartitioning(value#425, 200), true, [id=#1824]
            +- *(2) HashAggregate(keys=[value#425], functions=[], output=[value#425])
               +- *(2) Project [value#425]
                  +- *(2) Scan ExistingRDD[value#425,group#426L]

Some Notes You Might Find Useful

*

*If you want to make vertical combination, please do note that via function API (as you use the Scala function API in this case), unionAll is deprecated. Just keep in mind whether you want to move duplication or not after the combination. For detail, you could take a look at SPARK-14088.

*The difference between explode() and explode_outer() is that the latter one keeps null/empty values.

*There are 5 modes in explain() since Spark 3.0.0, i.e., simple, extended, codegen, cost, and simple. You'll get some insight with different modes from the last lazily-evaluated DataFrame.

*Documentation of LATERAL VIEW


text:
Q: How to Encrypt Query String in asp.net I have a GridView containing hyperlinks which can be added dynamically. Here is my .aspx code.
<asp:GridView ID="TeamGrid" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#337AB7" HeaderStyle-ForeColor="White" CssClass="table table-condensed" CellPadding="4" ForeColor="#333333" GridLines="None" Width="350px">
  <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
      <asp:HyperLinkField DataTextField="Team" DataNavigateUrlFields="Team_ID" DataNavigateUrlFormatString="Team.aspx?Team_ID={0}" HeaderText="Team" ItemStyle-Width="250">
        <ItemStyle Width="250px"></ItemStyle>
      </asp:HyperLinkField>

      <asp:BoundField DataField="Position" HeaderText="Position" ItemStyle-Width="150">
        <ItemStyle Width="150px"></ItemStyle>
     </asp:BoundField>
   </Columns>
</asp:GridView>

This is how I add data to the grid.
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Team_ID"), new DataColumn("Team"), new DataColumn("Position") });

foreach(Team team in UserTeams)
{
    if (team.Leader_ID.Equals(UserID)) //check whether user is the leader of the team.
    {
        dt.Rows.Add(team.Team_ID, team.Team_Name, "Leader");
    }
    else
    {
        dt.Rows.Add(team.Team_ID, team.Team_Name, "Member");
    }
}
TeamGrid.DataSource = dt;
TeamGrid.DataBind();

TeamGrid is the ID of Grid.
Team is a Object.
I want to hide/encrypt the parameters which I send using URL. (Parameter-Team_ID) And decrypt in the result page. (Team.aspx)
How can I do this?
(I'm new to asp.net and C#)

A: If your aim is to prevent people guessing the Team_ID parameter in your query string, you should not use Team_ID, as query strings cannot be encrypted effectively and if you're using an Identity db value for Team_ID, this can be guessed easily enough.
What you can do is create a new field in your Team object / table called something like "Team_Key". The Team_Key will be a randomized string which will always be unique. A good way of ensuring you get a unique Team_Key every time a Team object is created, is by doing something like this...
team.Team_Key = Guid.NewGuid().ToString();

You then need to replace all references to Team_ID in your code with Team_Key  instead e.g.
DataNavigateUrlFormatString="Team.aspx?Team_ID={0}"

becomes...
DataNavigateUrlFormatString="Team.aspx?Team_Key={0}"

Your grid databinding and Team.aspx codebehind will also obviously need updating.


text:
Q: How to enable guest sessions on Ubuntu 18.04 or later? Is there any way you could revive Guest Sessions in a future LTS distro?  Guest sessions are good security - they give me just enough power to do what I need to do on a daily basis without risking my system. In short, Guest sessions save me from myself.  I had upgraded from 16.04 to 18.04, gotten a problem I couldn't fix and was all to happy to wipe and rebuild my hard drive and return to 16.04.  I can't be the only one who feels this way.

A:
Is there any way you could revive Guest Sessions in a future LTS distro?

You seem to believe we can get this back into a distribution but we are just users (except for a couple of people that are also employees of Canonical).
And if you want it back: install LightDM.
sudo apt install lightdm

Create a configuration file
sudo gedit /etc/lightdm/lightdm.conf.d/50-enable-guest.conf

and copy the contents below to it:
[Seat:*]
allow-guest=true

Reboot the computer and pick lightdm at the login screen.
Do read the wiki page CustomizeGuestSession and the discussion on removing guest accounts.
Before you start using it: Guest Account is NOT secure: the data from normal users on the system is not secure from the guest. The same goes for the data from the guest. And the guest can view system files.


text:
Q: How to set the order of json properties when sending a Map object I am sending a HashMap object as response from my RestController.
@GetMapping("/balance")
    public Map<String, Object>  fetchAccountsByBalance(){
         Map<String, Object> response = new HashMap<>();
         response.put("records", totalNumberOfRecords);
         response.put("pages", totalPages);
         response.put("data", pageResponse.getContent());
}

How to control the order of JSON properties when returning a Map object?

A: LinkedHashMap maintains insertion order:
Map<String, Object> response = new LinkedHashMap<>();


text:
Q: R formula for a nested model My data is currently in a data frame with 3 columns (y, x, season) where season is a factor ("SPRING","SUMMER","FALL","WINTER")
I fit a linear model
yi = b0 + b.xi + ei ~ N(0,sig^2)

lm(y ~ x)

i want to test this against an extended model of the form
yij = b0 + bj.xij + eij

where j (= 1:4) is the SEASON of the year
Usually i would just create the design matrix, X and then b =  inv(X'X).(X'Y)
However i'd like to do this in R using lm()
How can i use lm() to fit this extended model with the data in its current format? Do i HAVE to transform my data to wide format with 5 columns (y, x1, x2, x3, x4 ) where xj represents the measurements for season j?

A: So i can keep my data in its original format: data frame with 3 columns (y, x, SEASON) where SEASON is a factor.
the model is:
yij = b0 + bj.xij + eij
where j (= 1:4) is the SEASON of the year
and the R call is:
lm(y ~ x:SEASON)

This is equivalent of fitting multiple independent lines (multiple b's) with a common intercept where each line represents a SEASONal relationship.


text:
Q: What are the right tools for me for indexing and processing big data? I'm trying to index and store big data, and I'm a bit confused on what tools to use. Let me start by saying I'm a novice here and have only theoretical knowledge on the topic. I want to:
1) use Hadoop (definitely)
2) extract log data from flat files using three different PCs
3) transform the data to structured form and load in HDFS for indexing and mapreduce.
My questions are:
a) In trying to index three fields, is it possible to map-index-map-index-map-index-reduce? if not, how is indexing done? If possible to explain in sequence (e.g index-map-reduce)
b) What are the right tools to use from extraction to storage?
c) Can Hadoop be used for a simple search, or another tool such as lucene/solr must be used?
d) Must data be converted into structured form, e.g using PDI, before going through the MapReduce phase?

A: Well if you are looking to index some data stored in hadoop then Cloudera Search is the perfect use case for you. Link: http://www.cloudera.com/content/cloudera/en/documentation/cloudera-search/v1-latest/Cloudera-Search-User-Guide/csug_introducing.html
I currently use it at Goibibo.com for indexing log data. You can use it for indexing data in real time as well as in map reduce mode. Internally it uses Solr to index and perfectly fits your use case. You can also expose the indexed collections through Hue.

A: I suggest using elastic search or solar for indexing the big data.


text:
Q: Tomcat: Class not found exception I'm developing a servlet running on Tomcat 6 using Eclipse as IDE.
The main path of the web application is "Calcolatrice" and the name of the servlet id "Calcolatrice" too.
When I try to execute a simple get operation on the servlet the following exception is throwed:
javax.servlet.ServletException: Wrapper cannot find servlet class as.unibo.Calcolatrice or a class it depends on
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:680)

root cause

java.lang.ClassNotFoundException: as.unibo.Calcolatrice
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Thread.java:680)

What I cannot understand is why the package where is the servlet is "as.unibo.polac.server" but Tomcat searches it in another package "as.unibo".
Which could be the reason of this problem?
[EDIT]
This is the content of my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Calcolatrice</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>Calcolatrice</display-name>
    <servlet-name>Calcolatrice</servlet-name>
    <servlet-class>as.unibo.Calcolatrice</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Calcolatrice</servlet-name>
    <url-pattern>/Calcolatrice</url-pattern>
  </servlet-mapping>

</web-app>

Is it correct?

A: Because your servlet is in as.unibo.polac.server package your web.xml should be:
....
  <servlet>
    <description></description>
    <display-name>Calcolatrice</display-name>
    <servlet-name>Calcolatrice</servlet-name>
    <servlet-class>as.unibo.polac.server.Calcolatrice</servlet-class>
  </servlet>

.....

The class path is wrong in your web.xml. Update it.