问:
'bottomLayoutGuide' was deprecated in iOS 11.0: Use view.safeAreaLayoutGuide.bottomAnchor instead of bottomLayoutGuide.topAnchor?
bottom layout guide was showing deprecated in ios 11? while developing an apps.though i have try to using layout anchor but not works , i have attached picture of my code problem </p>

```<code> override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { (transitionCoordinatorContext) -> Void in
            let orient = UIApplication.shared.statusBarOrientation

            for (index, var layoutAnchor) in self.arrBottomAnchor.enumerated() {

                layoutAnchor.isActive = false

                switch orient {
                case .portrait:
                   layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor)

                case .landscapeLeft,.landscapeRight :
                    layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.bottomAnchor)
</code>```

答:
Use view.safeAreaLayoutGuide.bottomAnchor instead of bottomLayoutGuide.topAnchor

```<code>if #available(iOS 11.0, *) {
    layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
} else {
    layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor)
}
</code>```

Body:
bottom layout guide was showing deprecated in ios 11? while developing an apps.though i have try to using layout anchor but not works , i have attached picture of my code problem

 override open func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { (transitionCoordinatorContext) -> Void in
            let orient = UIApplication.shared.statusBarOrientation

            for (index, var layoutAnchor) in self.arrBottomAnchor.enumerated() {

                layoutAnchor.isActive = false

                switch orient {
                case .portrait:
                   layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor)

                case .landscapeLeft,.landscapeRight :
                    layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.bottomAnchor)

Body:
Use view.safeAreaLayoutGuide.bottomAnchor instead of bottomLayoutGuide.topAnchor

if #available(iOS 11.0, *) {
    layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor)
} else {
    layoutAnchor = self.arrViews[index].bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor)
}


来源: stackexchange

问:
Boost asio async handler in tcp
Maybe this is a very simple question but I did not find an answer to that. I use boost asios tcp class for handling a simple byte protocol. I do async_read_some and the handler does some work. After the handler has been completed I start another async_read_some. Let's assume this handler does a lot of computing. Is there any posibility that incoming data between the handler work and the next call to async_read_some get lost? </p>

答:
No, your OS would continue receiving data until its receive buffers/TCP receive window are full. Once the receive buffer is full, TCP's flow control will make sure that the sender doesn't send more data than the receiver can receive and such no data will be lost.

See https://www.brianstorti.com/tcp-flow-control/ for a good explanation/example.

https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Flow_control

ContentLicense: CC BY-SA 4.0

Title: Boost asio async handler in tcp


问:
Load XML file to server
I have a simple php application that uses, among others, an hourly updated external XML file.

I need to use only one of the file's fields, thus, I used simplexml_load_file().

The problem is that this function only works with files currently saved on the server and not external ones.

How can I download the XML file periodically on the server (a download on every refresh would work too)? Thanks.

答:
Try this code, it may help you</p>

```<code><?php

function getXML()
{

    // initialize the XML Parser
    $xml_parser = xml_parser_create();
    // Set the functions to handle opening and closing tags
    xml_set_element_handler($xml_parser, "startElementHandler", "endElementHandler");

    // Set the function to handle blocks of character data
    xml_set_character_data_handler($xml_parser, "characterDataHandler");

    // Open the XML file for reading
    $fp = @fopen("http://www.abc.com/mytest.xml","r");
    if(!$fp)
    {
        return "XML-Server down";
    }

    // Read the XML file 4KB at a time
    while ($data = fread($fp, 4096))
       // Parse each 4KB chunk with the XML parser created above
       if(xml_parse($xml_parser, $data, feof($fp))==0)
       {
           // Handle errors in parsing
           return  "\"XML-Server down\"";
       }

    // Close the XML file
    fclose($fp);

    // Free up memory used by the XML parser
    xml_parser_free($xml_parser);
}

function startElementHandler($parser, $tagName, $attrs)
{

}

function endElementHandler($parser, $tagName)
{

}

function characterDataHandler($parser, $data)
{

}

?>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Load XML file to server

Body:
Try this code, it may help you

<?php

function getXML()
{

    // initialize the XML Parser
    $xml_parser = xml_parser_create();
    // Set the functions to handle opening and closing tags
    xml_set_element_handler($xml_parser, "startElementHandler", "endElementHandler");

    // Set the function to handle blocks of character data
    xml_set_character_data_handler($xml_parser, "characterDataHandler");

    // Open the XML file for reading
    $fp = @fopen("http://www.abc.com/mytest.xml","r");
    if(!$fp)
    {
        return "XML-Server down";
    }

    // Read the XML file 4KB at a time
    while ($data = fread($fp, 4096))
       // Parse each 4KB chunk with the XML parser created above
       if(xml_parse($xml_parser, $data, feof($fp))==0)
       {
           // Handle errors in parsing
           return  "\"XML-Server down\"";
       }

    // Close the XML file
    fclose($fp);

    // Free up memory used by the XML parser
    xml_parser_free($xml_parser);
}

function startElementHandler($parser, $tagName, $attrs)
{

}

function endElementHandler($parser, $tagName)
{

}

function characterDataHandler($parser, $data)
{

}

?>


问:
predict method for felm from lfe package
Does anyone have a nice clean way to get predict behavior for felm models?

```<code>library(lfe)
model1 <- lm(data = iris, Sepal.Length ~ Sepal.Width + Species)
predict(model1, newdata = data.frame(Sepal.Width = 3, Species = "virginica"))
# Works

model2 <- felm(data = iris, Sepal.Length ~ Sepal.Width | Species)
predict(model2, newdata = data.frame(Sepal.Width = 3, Species = "virginica"))
# Does not work
</code>```

答:
To extend the answer from pbaylis, I created a slightly longwinded function that extends nicely to allow for more than one fixed effect. Note that you have to manually enter the original dataset used in the felm model. The function returns a list with two items: the vector of predictions, and a dataframe based on the new_data that includes the predictions and fixed effects as columns.</p>

```<code>predict_felm <- function(model, data, new_data) {

  require(dplyr)

  # Get the names of all the variables
  y <- model$lhs
  x <- rownames(model$beta)
  fe <- names(model$fe)

  # Demean according to fixed effects
  data_demeaned <- demeanlist(data[c(y, x)],
                             as.list(data[fe]),
                             na.rm = T)

  # Create formula for LM and run prediction
  lm_formula <- as.formula(
    paste(y, "~", paste(x, collapse = "+"))
  )

  lm_model <- lm(lm_formula, data = data_demeaned)
  lm_predict <- predict(lm_model,
                        newdata = new_data)

  # Collect coefficients for fe
  fe_coeffs <- getfe(model) %>%
    select(fixed_effect = effect, fe_type = fe, idx)

  # For each fixed effect, merge estimated fixed effect back into new_data
  new_data_merge <- new_data
  for (i in fe) {

    fe_i <- fe_coeffs %>% filter(fe_type == i)

    by_cols <- c("idx")
    names(by_cols) <- i

    new_data_merge <- left_join(new_data_merge, fe_i, by = by_cols) %>%
      select(-matches("^idx"))

  }

  if (length(lm_predict) != nrow(new_data_merge)) stop("unmatching number of rows")

  # Sum all the fixed effects
  all_fixed_effects <- base::rowSums(select(new_data_merge, matches("^fixed_effect")))

  # Create dataframe with predictions
  new_data_predict <- new_data_merge %>%
    mutate(lm_predict = lm_predict,
           felm_predict = all_fixed_effects + lm_predict)

  return(list(predict = new_data_predict$felm_predict,
              data = new_data_predict))

}

model2 <- felm(data = iris, Sepal.Length ~ Sepal.Width | Species)
predict_felm(model = model2, data = iris, new_data = data.frame(Sepal.Width = 3, Species = "virginica"))
# Returns prediction and data frame
</code>```

Body:
Does anyone have a nice clean way to get predict behavior for felm models?

library(lfe)
model1 <- lm(data = iris, Sepal.Length ~ Sepal.Width + Species)
predict(model1, newdata = data.frame(Sepal.Width = 3, Species = "virginica"))
# Works

model2 <- felm(data = iris, Sepal.Length ~ Sepal.Width | Species)
predict(model2, newdata = data.frame(Sepal.Width = 3, Species = "virginica"))
# Does not work

Body:
To extend the answer from pbaylis, I created a slightly longwinded function that extends nicely to allow for more than one fixed effect. Note that you have to manually enter the original dataset used in the felm model. The function returns a list with two items: the vector of predictions, and a dataframe based on the new_data that includes the predictions and fixed effects as columns.

predict_felm <- function(model, data, new_data) {

  require(dplyr)

  # Get the names of all the variables
  y <- model$lhs
  x <- rownames(model$beta)
  fe <- names(model$fe)

  # Demean according to fixed effects
  data_demeaned <- demeanlist(data[c(y, x)],
                             as.list(data[fe]),
                             na.rm = T)

  # Create formula for LM and run prediction
  lm_formula <- as.formula(
    paste(y, "~", paste(x, collapse = "+"))
  )

  lm_model <- lm(lm_formula, data = data_demeaned)
  lm_predict <- predict(lm_model,
                        newdata = new_data)

  # Collect coefficients for fe
  fe_coeffs <- getfe(model) %>%
    select(fixed_effect = effect, fe_type = fe, idx)

  # For each fixed effect, merge estimated fixed effect back into new_data
  new_data_merge <- new_data
  for (i in fe) {

    fe_i <- fe_coeffs %>% filter(fe_type == i)

    by_cols <- c("idx")
    names(by_cols) <- i

    new_data_merge <- left_join(new_data_merge, fe_i, by = by_cols) %>%
      select(-matches("^idx"))

  }

  if (length(lm_predict) != nrow(new_data_merge)) stop("unmatching number of rows")

  # Sum all the fixed effects
  all_fixed_effects <- base::rowSums(select(new_data_merge, matches("^fixed_effect")))

  # Create dataframe with predictions
  new_data_predict <- new_data_merge %>%
    mutate(lm_predict = lm_predict,
           felm_predict = all_fixed_effects + lm_predict)

  return(list(predict = new_data_predict$felm_predict,
              data = new_data_predict))

}

model2 <- felm(data = iris, Sepal.Length ~ Sepal.Width | Species)
predict_felm(model = model2, data = iris, new_data = data.frame(Sepal.Width = 3, Species = "virginica"))
# Returns prediction and data frame


问:
How to require at compile time that a type parameter be a trait (and not a class or other type value)?
I'm looking for some kind of upper bound on a generic parameter T that ensures that T is a trait.

```<code>class Foo
trait Bar

def f[A ??? IsATrait] = ???

// f[Foo] Won't compile
f[Bar] // this is fine
</code>```

答:
Is it possible to require at compile time that a type parameter is a trait (and not a class or other type value)?

No.

Body:
I'm looking for some kind of upper bound on a generic parameter T that ensures that T is a trait.

class Foo
trait Bar

def f[A ??? IsATrait] = ???

// f[Foo] Won't compile
f[Bar] // this is fine


问:
How does indirect manipulation of dynamically allocated string literals truly work in C?
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

#include <stdio.h>
#include <stdlib.h>

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}
```

<p>However, upon studying how <code>tolower()</code> and <code>toupper()</code> work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:</p>

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}
</code>```

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

答:
Thank you all for helping me understand where I went wrong, let me fix up the examples so that they are finally correct!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int
main( void )
{
  const int STR_MAX_LEN = 10;
  char *p = malloc( sizeof *p * STR_MAX_LEN );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return EXIT_FAILURE;
  }
  else
  {
    strncpy( p, "literal", STR_MAX_LEN );
    printf( "%s", p );
    strncpy( p, "test", STR_MAX_LEN );
    printf( "%s", p);
    free( p );
    p = NULL;
  }
  return EXIT_SUCCESS;
}
```

<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <ctype.h>

char
*strlower( char *str )
{
  char *temp = str;
  while ( *temp )
  {
    *temp = tolower( ( unsigned char )*temp );
    temp++;
  }
  return str;
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    strlower( argv[i] );
    printf( "%s\n", argv[i] );
  }
  return 0;
}
</code>```

If there are any other things I should consider from my answer, please let me know, and thank you all for such wonderful advice, and lessons about the C language!

Body:
As it stands, I know that dynamically allocated string literals cannot be changed during run-time, otherwise you will hit a segmentation fault.

This is due to the fact that dynamically allocated string literals are stored, from what I saw in the assembly code, in the .rodata segment, placing these literals in what I interpret as read only memory.

So in theory this should never work on what I hope is in every modern C compiler:

#include <stdio.h>
#include <stdlib.h>

int
main( void )
{
  char *p = ( char * )malloc( 10 * sizeof( char ) );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return( EXIT_FAILURE );
  }
  else
  {
    p = "literal";
    printf( "%s\n", p );
    p[0] = 't'; // <-- This should cause a segmentation fault!
    printf( "%s\n", p ); // <-- This should never reach execution!
  }
  return( EXIT_SUCCESS );
}

However, upon studying how tolower() and toupper() work. I find it rather difficult to understand how these two simple functions are able to do what I thought for a long while was impossible. Here's what I mean:

#include <stdio.h>

int
tolowercase( int c )
{
  return ( c >= 'A' && c <= 'Z' ) ? ( c + 32) : ( c );
}

int
retstrlen( char *str )
{
  int len = 0;
  while( *str != '\0' ) { len++; str++; }
  return( len );
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    for( int j = 0; j < retstrlen( argv[i] ); j++ )
    {
      argv[i][j] = tolowercase( argv[i][j] );
      printf( "%c", argv[i][j] );
    }
    printf( "\n" );
  }
  return 0;
}

How does the source code defined in my custom tolower() function not cause a segmentation fault as it normally would through manipulating dynamically allocated string literals?

My only hypothesis that I can draw is that since tolowercase() has a parameter of int, and a return type of int, then the compiler performs a type conversion which indirectly manipulates **argv.

I am pretty sure I am on the right track about this, yet I could have gotten my whole terminology wrong here, so what is really happening to **argv?

Body:
Thank you all for helping me understand where I went wrong, let me fix up the examples so that they are finally correct!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int
main( void )
{
  const int STR_MAX_LEN = 10;
  char *p = malloc( sizeof *p * STR_MAX_LEN );
  if ( p == NULL )
  {
    puts( "Bad memory allocation error!" );
    return EXIT_FAILURE;
  }
  else
  {
    strncpy( p, "literal", STR_MAX_LEN );
    printf( "%s", p );
    strncpy( p, "test", STR_MAX_LEN );
    printf( "%s", p);
    free( p );
    p = NULL;
  }
  return EXIT_SUCCESS;
}

#include <stdio.h>
#include <ctype.h>

char
*strlower( char *str )
{
  char *temp = str;
  while ( *temp )
  {
    *temp = tolower( ( unsigned char )*temp );
    temp++;
  }
  return str;
}

int
main( int argc, char **argv )
{
  for( int i = 0; i < argc; i++ )
  {
    strlower( argv[i] );
    printf( "%s\n", argv[i] );
  }
  return 0;
}

If there are any other things I should consider from my answer, please let me know, and thank you all for such wonderful advice, and lessons about the C language!


问:
UDP Client uses too much memory when sending multiple small parts of a huge array
I'm capturing the desktop with Desktop Duplication API, encoding it in h265 and sending it in parts via UDP (Can't use TCP because I need as low of a latency as possible). I'm doing all of this in C# and Visual Studio, and the memory usage goes through the roof as soon as I uncomment the udpclient.Send().

With it commented everything works great (including the frames capture, the splitting, etc..), as soon as I send it, I reach the 2gb mark in usage in less than 10 seconds and it just keeps ramping up until it crashes. Also, none of the data is lost as my server receives everything so my packet management seems to be good.

```<code>int offset = 0;
int packetSize = 200;
for (int i=0; i< clone.Length/packetSize; i++)
{
   int diff = clone.Length - offset;
   if (diff > packetSize)
      Array.ConstrainedCopy(clone, offset, subBuffer, 0, packetSize);
   else
      Array.ConstrainedCopy(clone, offset, subBuffer, 0, diff);
   udpClient.Send( subBuffer, packetSize, "255.255.255.255", 9009);
   offset += packetSize;
}
</code>```

I'm at this stage just experimenting with the splitting and everything, and as stated none of that part creates any issues (I know it could be made better). It's just the udpclient.Send() that makes everything go wrong. Any idea on what could cause this and how I could somehow force some memory management with the send?

答:
After a lot of trial and error "in the dark",  I managed to solve it by doing my own socket management.
It turns out doing as many "Send" calls as possible is permitted, but the socket doesn't respond well to it, meaning it still tries to send even when it's "clogged", and starts leaking memory if that makes sense. I ended up sending asynchronously and waiting to know that the bytes were really sent before attempting another send. Here's the code for it, works perfectly, no memory leaks, 0 packet loss. I started from the simple socket implementation I've taken from here then added the custom management part.</p>

```<code>    Boolean isAvailable = true;
    public void Send(byte[] data)
    {
            if (!isAvailable)
                return;
            isAvailable = false;
        _socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
        {
            _socket.EndSend(ar);
            isAvailable = true;
        }, state);
    }
</code>```

Body:
I'm capturing the desktop with Desktop Duplication API, encoding it in h265 and sending it in parts via UDP (Can't use TCP because I need as low of a latency as possible). I'm doing all of this in C# and Visual Studio, and the memory usage goes through the roof as soon as I uncomment the udpclient.Send().

With it commented everything works great (including the frames capture, the splitting, etc..), as soon as I send it, I reach the 2gb mark in usage in less than 10 seconds and it just keeps ramping up until it crashes. Also, none of the data is lost as my server receives everything so my packet management seems to be good.

int offset = 0;
int packetSize = 200;
for (int i=0; i< clone.Length/packetSize; i++)
{
   int diff = clone.Length - offset;
   if (diff > packetSize)
      Array.ConstrainedCopy(clone, offset, subBuffer, 0, packetSize);
   else
      Array.ConstrainedCopy(clone, offset, subBuffer, 0, diff);
   udpClient.Send( subBuffer, packetSize, "255.255.255.255", 9009);
   offset += packetSize;
}

I'm at this stage just experimenting with the splitting and everything, and as stated none of that part creates any issues (I know it could be made better). It's just the udpclient.Send() that makes everything go wrong. Any idea on what could cause this and how I could somehow force some memory management with the send?

Body:
After a lot of trial and error "in the dark",  I managed to solve it by doing my own socket management.
It turns out doing as many "Send" calls as possible is permitted, but the socket doesn't respond well to it, meaning it still tries to send even when it's "clogged", and starts leaking memory if that makes sense. I ended up sending asynchronously and waiting to know that the bytes were really sent before attempting another send. Here's the code for it, works perfectly, no memory leaks, 0 packet loss. I started from the simple socket implementation I've taken from here then added the custom management part.

    Boolean isAvailable = true;
    public void Send(byte[] data)
    {
            if (!isAvailable)
                return;
            isAvailable = false;
        _socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
        {
            _socket.EndSend(ar);
            isAvailable = true;
        }, state);
    }


问:
base64 code is not displaying image javascript/react
Fetching a list of objects. I loop through the list to retrieve an image in each object and store it in the localStorage.

```<code>// storing images in localStorage
  storeMovieImagesLocalStorage = (movieList) => {
    movieList.map(movie => {
        localStorage.setItem(movie.id, this.getBase64Image(movie.images[0].url))
    })
  };

// converting url to base64
  getBase64Image = (img) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    // create new Image to assign image url
    const image = new Image();
    image.src = img;
    image.onload = function() {
      const canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      ctx.drawImage(image, 0, 0);
    };

    const dataURL = canvas.toDataURL("image/png");

    return dataURL;
  };

</code>```

Then I apply the base64 code to my image.

```<code>      this.setState({
        movieUrl: localStorage.getItem(movie.id)
      })

        <MovieImg src={this.state.movieUrl} className="cursor-pointer" onClick={this.handleOpenVideo} />

</code>```

My localStorage is storing the right information properly:

```<code>{ 2-guns: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC" }

</code>```

Here what I find the devTools/Elements:

```<code><img class="Img-sc-10y4zbe-0 cursor-pointer sc-ifAKCX cmjWax" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC">
</code>```

All seems fine to me and I do not have any error in my console. However, my image is not displayed. and when I hover above the img[src], it shows me an invisible image, or and image that does not have content.

What have I done wrong?

答:
i attempted to convert your base64 string back to an image again, the part between "iVBOR" and "SuQmCC". but that doesnt appear to be a valid image returned from that.

i tried with another base64 string representing an image using your exact html tag with attributes and that works just fine:

```<code><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" class="Img-sc-10y4zbe-0 cursor-pointer sc-ifAKCX cmjWax">
</code>```

it seems the problem is that you have an incorrect base64 string of the image which is why nothing shows up. worth noting is that i have no idea what your specific classes do so i cant speak for their behavior.

Body:
Fetching a list of objects. I loop through the list to retrieve an image in each object and store it in the localStorage.

// storing images in localStorage
  storeMovieImagesLocalStorage = (movieList) => {
    movieList.map(movie => {
        localStorage.setItem(movie.id, this.getBase64Image(movie.images[0].url))
    })
  };

// converting url to base64
  getBase64Image = (img) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");

    // create new Image to assign image url
    const image = new Image();
    image.src = img;
    image.onload = function() {
      const canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      ctx.drawImage(image, 0, 0);
    };

    const dataURL = canvas.toDataURL("image/png");

    return dataURL;
  };

Then I apply the base64 code to my image.

      this.setState({
        movieUrl: localStorage.getItem(movie.id)
      })

        <MovieImg src={this.state.movieUrl} className="cursor-pointer" onClick={this.handleOpenVideo} />

My localStorage is storing the right information properly:

{ 2-guns: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC" }

Here what I find the devTools/Elements:

<img class="Img-sc-10y4zbe-0 cursor-pointer sc-ifAKCX cmjWax" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEYklEQVR4Xu3UAQkAAAwCwdm/9HI83BLIOdw5AgQIRAQWySkmAQIEzmB5AgIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlACBB1YxAJfjJb2jAAAAAElFTkSuQmCC">

All seems fine to me and I do not have any error in my console. However, my image is not displayed. and when I hover above the img[src], it shows me an invisible image, or and image that does not have content.

What have I done wrong?

Body:
i attempted to convert your base64 string back to an image again, the part between "iVBOR" and "SuQmCC". but that doesnt appear to be a valid image returned from that.

i tried with another base64 string representing an image using your exact html tag with attributes and that works just fine:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" class="Img-sc-10y4zbe-0 cursor-pointer sc-ifAKCX cmjWax">

it seems the problem is that you have an incorrect base64 string of the image which is why nothing shows up. worth noting is that i have no idea what your specific classes do so i cant speak for their behavior.


问:
Access to PresentationFramework and WindowsBase internal classes
I do not know if is possible to use the internal classes and methods from the assembly PresentationFramework and Windowsbase.
I want to access to the method System.Windows Thickness.IsValid internal method.
By other hand, I need to access to other classes as MS.Internal DoubleUtil class from the assembly WindowsBase.

I have tried, for example to use the following command in the AssemblyInfo but without no successful.

```<code>[assembly: InternalsVisibleTo("PresentationFramework,
PublicKey=0024000004800000940000000602000000240000525341310004000001
000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c49265
1e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f
25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97
c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
</code>```

答:
Thicknessconverter has IsValid.

https://learn.microsoft.com/en-us/dotnet/api/system.windows.thicknessconverter?view=netframework-4.8

You don't say what you want to do with doubleutil.

The code is here though:

https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Standard/DoubleUtil.cs

You could adapt the bits you need into a new class of your own.

The code for the thickness struct is here:

https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Thickness.cs,109d8135ab5a3074

Body:
I do not know if is possible to use the internal classes and methods from the assembly PresentationFramework and Windowsbase.
I want to access to the method System.Windows Thickness.IsValid internal method.
By other hand, I need to access to other classes as MS.Internal DoubleUtil class from the assembly WindowsBase.

I have tried, for example to use the following command in the AssemblyInfo but without no successful.

[assembly: InternalsVisibleTo("PresentationFramework,
PublicKey=0024000004800000940000000602000000240000525341310004000001
000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c49265
1e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f
25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97
c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]


问:
In codeigniter view page the data is not displaying from database
I am not getting the result in view page but its displaying while i am printing in controller. Its working perfect in my local but its not working in server. Please help me to get solution for this.</p>

答:
Please check your code in view page properly, As my experience any loop or condition is not closed in your code.
In localhost error is showing but code is execute after that error but on server code is not execute after error in code</p>


问:
Multiple Sort ( ORDER BY ) within Query in Google Sheets
What am I missing here?

=QUERY('STUDENT SIGN IN'!A1:K, "select K,C,F,D,E,B ORDER BY A DESC, B"

The data is sorting on Column A, but doing nothing to Column B.

Since that didn't work, I also tried building it this way, however I haven't done a vested formula  in sheets before. This formula is causing a #ERROR:

=SORT((QUERY('STUDENT SIGN IN'!A1:K, "select K,C,F,D,E,B)")Select 1,TRUE,2,FALSE))

答:
If the order for ColumnB is not changing then it is presumably already in the default (ascending) order within each ColumnA value. To reverse this as well as the order of ColumnA you might try:</p>

```<code>=QUERY('STUDENT SIGN IN'!A1:K, "select K,C,F,D,E,B ORDER BY A DESC, B desc")
</code>```

Body:
If the order for ColumnB is not changing then it is presumably already in the default (ascending) order within each ColumnA value. To reverse this as well as the order of ColumnA you might try:

=QUERY('STUDENT SIGN IN'!A1:K, "select K,C,F,D,E,B ORDER BY A DESC, B desc")


问:
How to fix ng-if not reacting?
I'm trying to display a link  when a condition is met, but the link never appears.

I have already tried to change the position (in/out of
) and the tag of the item containing the ng-if (span, div, ul...). This kind of code works on another HTML I have, so my Angular version seems okay.

Here is the form where I call the controller:

      <form ng-submit="setProfile()">
        <select ng-model="userRole"
                ng-options="role for role in roles">Role</select>
        <input type="text"
                ng-model="userName"
                placeholder="Nom"></input>
        <input type="submit"
               value="Valider"></input>
      </form>

```

<p>The condition right after:</p>

<pre class="lang-html prettyprint-override"><code><span ng-if="user.isSetup">
      href="srsApp.html">Accès aux cours
    </span>
</code>```

And the actual controller:

```<code>      var app = angular.module('srsApp', []);
      app.controller('userRole', function($scope) {
        $scope.roles = ['Professeur', 'Élève'];
        $scope.user = {role:'', name:'', isSetup: false};

        $scope.setProfile = function() {
          if ($scope.userName !== '' && $scope.userRole !== '') {
            $scope.user.role = $scope.userRole;
            $scope.user.role = $scope.userName;
            $scope.user.isSetup = true;
            $scope.userRole = '';
            $scope.userName = '';
          }
        };
      });
    </script>
</code>```

I expected the link to appear once I submit the form with a role and a name, but the link stays hidden. No error from my Firefox terminal, and I know it enters the function because the placeholders are re-initialized.

答:
As mentionned by @AnuragSrivastava, the  should be in the
. As I said I tried it, but previous circumstances (syntax errors NOT highlighted by terminal) prevented this to work.

Title: How to fix ng-if not reacting?

Body:
I'm trying to display a link  when a condition is met, but the link never appears.

I have already tried to change the position (in/out of
) and the tag of the item containing the ng-if (span, div, ul...). This kind of code works on another HTML I have, so my Angular version seems okay.

Here is the form where I call the controller:

      <form ng-submit="setProfile()">
        <select ng-model="userRole"
                ng-options="role for role in roles">Role</select>
        <input type="text"
                ng-model="userName"
                placeholder="Nom"></input>
        <input type="submit"
               value="Valider"></input>
      </form>

The condition right after:

      Accès aux cours

And the actual controller:

      var app = angular.module('srsApp', []);
      app.controller('userRole', function($scope) {
        $scope.roles = ['Professeur', 'Élève'];
        $scope.user = {role:'', name:'', isSetup: false};

        $scope.setProfile = function() {
          if ($scope.userName !== '' && $scope.userRole !== '') {
            $scope.user.role = $scope.userRole;
            $scope.user.role = $scope.userName;
            $scope.user.isSetup = true;
            $scope.userRole = '';
            $scope.userName = '';
          }
        };
      });
    </script>

I expected the link to appear once I submit the form with a role and a name, but the link stays hidden. No error from my Firefox terminal, and I know it enters the function because the placeholders are re-initialized.

Body: As mentionned by @AnuragSrivastava, the <span> should be in the <div ng-controller="userRole">. As I said I tried it, but previous circumstances (syntax errors NOT highlighted by terminal) prevented this to work.


问:
Basic HTTP Authentication on Android Phones to Rails Server
I'm trying to connect to a Rails Application Server that requires authentication. I am using the Jakarta HTTP Client for Java on a Desktop application and it works 100%. But when the exact same code is executed on the Android Emulator I get an IOException.

Here is the code, and if anyone could help me figure out why it throws the IOException that would be greatly appreciated!

```<code>private boolean login()
{
    String username, password;

    DefaultHttpClient client;
    AuthScope scope;
    Credentials myCredentials;
    CredentialsProvider provider;
    HttpEntity entity;
    String line;
    BufferedReader reader;
    InputStream instream;

    //Declare & Create the HTTP Client
    client = new DefaultHttpClient();

    //Create our AuthScope
    scope = new AuthScope("10.19.9.33", 3000);

    username = "admin"
            password = "pass"

    //Set Credentials
    myCredentials = new UsernamePasswordCredentials( username, password );

    //Set Provider
    provider = new BasicCredentialsProvider();
    provider.setCredentials(scope, myCredentials);

    //Set Credentials
    client.setCredentialsProvider( provider );

    String url = "http://10.19.9.33:3000/users/show/2";

    HttpGet get;

    //Tell where to get
    get = new HttpGet( url );

    HttpResponse response;

    try
    {
        response = client.execute( get );

        entity = response.getEntity();

        /* Check to see if it exists */
        if( entity != null )
        {
            instream = entity.getContent();

            try {

                reader = new BufferedReader(new InputStreamReader(instream));

                line = reader.readLine();

                if( line.equals( "HTTP Basic: Access denied.") )
                    return false;

                while ( line != null )
                {
                    // do something useful with the response
                    System.out.println(line);

                    line = reader.readLine();
                }

                return true;

            }
            catch (IOException ex)
            {

                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                throw ex;

            }
            catch (RuntimeException ex)
            {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection and release it back to the connection manager.
                get.abort();
                throw ex;
            }
            finally
            {
                // Closing the input stream will trigger connection release
                instream.close();
            }
        }
    }
    catch( ClientProtocolException cp_ex )
    {

    }
    catch( IOException io_ex )
    {

    }

    return false;
}
</code>```

答:
I'm using HttpPost for this kind of task, and never had any problem:

```<code>[...]
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_SERVLET_URI);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("userName", userName));
params.add(new BasicNameValuePair("password", password));

UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httppost.setEntity(p_entity);
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
[...]
</code>```

maybe this helps you out

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to connect to a Rails Application Server that requires authentication. I am using the Jakarta HTTP Client for Java on a Desktop application and it works 100%. But when the exact same code is executed on the Android Emulator I get an IOException.

Here is the code, and if anyone could help me figure out why it throws the IOException that would be greatly appreciated!

private boolean login()
{
    String username, password;

    DefaultHttpClient client;
    AuthScope scope;
    Credentials myCredentials;
    CredentialsProvider provider;
    HttpEntity entity;
    String line;
    BufferedReader reader;
    InputStream instream;

    //Declare & Create the HTTP Client
    client = new DefaultHttpClient();

    //Create our AuthScope
    scope = new AuthScope("10.19.9.33", 3000);

    username = "admin"
            password = "pass"

    //Set Credentials
    myCredentials = new UsernamePasswordCredentials( username, password );

    //Set Provider
    provider = new BasicCredentialsProvider();
    provider.setCredentials(scope, myCredentials);

    //Set Credentials
    client.setCredentialsProvider( provider );

    String url = "http://10.19.9.33:3000/users/show/2";

    HttpGet get;

    //Tell where to get
    get = new HttpGet( url );

    HttpResponse response;

    try
    {
        response = client.execute( get );

        entity = response.getEntity();

        /* Check to see if it exists */
        if( entity != null )
        {
            instream = entity.getContent();

            try {

                reader = new BufferedReader(new InputStreamReader(instream));

                line = reader.readLine();

                if( line.equals( "HTTP Basic: Access denied.") )
                    return false;

                while ( line != null )
                {
                    // do something useful with the response
                    System.out.println(line);

                    line = reader.readLine();
                }

                return true;

            }
            catch (IOException ex)
            {

                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                throw ex;

            }
            catch (RuntimeException ex)
            {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection and release it back to the connection manager.
                get.abort();
                throw ex;
            }
            finally
            {
                // Closing the input stream will trigger connection release
                instream.close();
            }
        }
    }
    catch( ClientProtocolException cp_ex )
    {

    }
    catch( IOException io_ex )
    {

    }

    return false;
}

Body:
I'm using HttpPost for this kind of task, and never had any problem:

[...]
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(LOGIN_SERVLET_URI);
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("userName", userName));
params.add(new BasicNameValuePair("password", password));

UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httppost.setEntity(p_entity);
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();
[...]

maybe this helps you out


问:
Having an error in DataBinding in kotlin app
I am trying to bind data in my kotlin android app, I was following this tutorial on codelab Link to Codelab I did everything same.

But while importing ActivityMainBinding in MainActitvity.kt file ide keeps on showing me error in red text.

I did enabled dataBinding in app level gradle file Here

```<code>dataBinding {
        enabled = true
    }
</code>```

Here I have imported and initialized dataBinding

```<code>import android.content.Context
import android.databinding.DataBindingUtil
import android.hardware.input.InputManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
//import kotlinx.android.synthetic.main.activity_main.*
import com.example.aboutme.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.done_button.setOnClickListener{
            addNickname(it)
        }
    }

    private fun addNickname(view: View) {

        binding.apply{
            nickname_text.text = binding.nickname_edit.text
            invalidateAll()
            nickname_edit.visibility = View.GONE
            done_button.visibility = View.GONE
            nickname_text.visibility = View.VISIBLE
        }

        //Hide the Keyboard

        val inn = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inn.hideSoftInputFromWindow(view.windowToken, 0)

    }
}
</code>```

Error i get while trying to build gradle anyway. I thought to give it a try.

```<code>Compilation Error
</code>```

I am new To Android.

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
</code>```

tools:context=".MainActivity">

```<code>        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    <TextView
            android:text="@string/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            style="@style/name_style"/>
    <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@android:drawable/btn_star_big_on"
            android:id="@+id/imageView2"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/nickname_edit" style="@style/name_style" android:hint="what is your nickname"/>
    <Button
            android:text="Done"
            android:layout_gravity="center_horizontal"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/done_button"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/nickname_text" style="@style/name_style"
            android:visibility="gone"/>
    <ScrollView
            android:id="@+id/bio_scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <TextView
                style="@style/name_style"
                android:text="@string/bio"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/bio_text"
                android:lineSpacingMultiplier="1.2"
        />
    </ScrollView>

</LinearLayout>
</layout>
</code>```

error in log

```<code>Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
Unresolved reference: it
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main

> Task :app:buildInfoGeneratorDebug
</code>```

答:
Move the namespace declarations to your layout tag, and remove the duplicates. It should look like this after the changes have been made:

```<code><layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".MainActivity">
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
...
</code>```

After that, make sure to clean and rebuild your project.

Body:
I am trying to bind data in my kotlin android app, I was following this tutorial on codelab Link to Codelab I did everything same.

But while importing ActivityMainBinding in MainActitvity.kt file ide keeps on showing me error in red text.

I did enabled dataBinding in app level gradle file Here

dataBinding {
        enabled = true
    }

Here I have imported and initialized dataBinding

import android.content.Context
import android.databinding.DataBindingUtil
import android.hardware.input.InputManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
//import kotlinx.android.synthetic.main.activity_main.*
import com.example.aboutme.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.done_button.setOnClickListener{
            addNickname(it)
        }
    }

    private fun addNickname(view: View) {

        binding.apply{
            nickname_text.text = binding.nickname_edit.text
            invalidateAll()
            nickname_edit.visibility = View.GONE
            done_button.visibility = View.GONE
            nickname_text.visibility = View.VISIBLE
        }

        //Hide the Keyboard

        val inn = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inn.hideSoftInputFromWindow(view.windowToken, 0)

    }
}

Error i get while trying to build gradle anyway. I thought to give it a try.

Compilation Error

I am new To Android.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"

tools:context=".MainActivity">

        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    <TextView
            android:text="@string/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textView"
            style="@style/name_style"/>
    <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:srcCompat="@android:drawable/btn_star_big_on"
            android:id="@+id/imageView2"/>
    <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/nickname_edit" style="@style/name_style" android:hint="what is your nickname"/>
    <Button
            android:text="Done"
            android:layout_gravity="center_horizontal"
            style="@style/Widget.AppCompat.Button.Colored"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/done_button"/>
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:id="@+id/nickname_text" style="@style/name_style"
            android:visibility="gone"/>
    <ScrollView
            android:id="@+id/bio_scroll"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <TextView
                style="@style/name_style"
                android:text="@string/bio"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/bio_text"
                android:lineSpacingMultiplier="1.2"
        />
    </ScrollView>

</LinearLayout>
</layout>

error in log

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
Unresolved reference: it
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main

> Task :app:buildInfoGeneratorDebug

Body:
Move the namespace declarations to your layout tag, and remove the duplicates. It should look like this after the changes have been made:

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".MainActivity">
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
...

After that, make sure to clean and rebuild your project.


问:
Print all elements of a list preceded by a given one
I want to print all the elements of this list who are directly following "apple".

With

```<code>my_list = ["apple","train","apple","bus"]
</code>```

I would expect the output:

```<code>(train,bus)
</code>```

But my current code

```<code>print (my_list[my_list.index("apple") + 1])
</code>```

only outputs the first one, "train".

How can I get all of them?

答:
```<code>my_list = ["apple","train","apple","bus"]
index = my_list.index("apple")
print(my_list[index:index+2])
</code>```

Have a look at Python's slice syntax. This will print the sublist from index to index + 2 (exclusive).
If you want it as a tuple as you indicated in your question, just wrap it in tuple()

Edit: Of course given that you already have apple you could also just do

```<code>print(("apple", my_list[my_list.index("apple") + 1)
</code>```

Body:
I want to print all the elements of this list who are directly following "apple".

With

my_list = ["apple","train","apple","bus"]

I would expect the output:

(train,bus)

But my current code

print (my_list[my_list.index("apple") + 1])

only outputs the first one, "train".

How can I get all of them?

Body:
my_list = ["apple","train","apple","bus"]
index = my_list.index("apple")
print(my_list[index:index+2])

Have a look at Python's slice syntax. This will print the sublist from index to index + 2 (exclusive).
If you want it as a tuple as you indicated in your question, just wrap it in tuple()

Edit: Of course given that you already have apple you could also just do

print(("apple", my_list[my_list.index("apple") + 1)


问:
Why I am able to modify private data of base class from derieved class
Here class d inherits class b. Since it's visibility is public so it can access public members of class b.

When I am creating newd, an object of d. there is no memory created for a (private data member of class b)

But still I am able to do get and set on that member using object of class d.

Can you please explain why this works. Also when is memory for a is allocated.

```<code>#include <iostream>
using namespace std;

class b{
    int a;
  public:
    void get(){
        cout << a << endl;
    }
    void set(int x){
        a = x;
    }
};

class d: public b{
    int c;
   public:
    void getac(){
        get();
        cout << c << endl;
    }
    void setc(int x, int y){
        set(x);
        c = y;
    }
};

int main() {
    // your code goes here
    d newd;
    newd.setc(10, 20);
    newd.getac();
    newd.setc(12, 22);
    newd.getac();
    return 0;
}
</code>```

答: Private means it can only be changed by methods declared in the same class. Your subclass is modifying that private field via a public method in that class. In other words, private data CAN be indirectly modified by functions outside that class. It just cannot be directly modified.</p>

Body:
Here class d inherits class b. Since it's visibility is public so it can access public members of class b.

When I am creating newd, an object of d. there is no memory created for a (private data member of class b)

But still I am able to do get and set on that member using object of class d.

Can you please explain why this works. Also when is memory for a is allocated.

#include <iostream>
using namespace std;

class b{
    int a;
  public:
    void get(){
        cout << a << endl;
    }
    void set(int x){
        a = x;
    }
};

class d: public b{
    int c;
   public:
    void getac(){
        get();
        cout << c << endl;
    }
    void setc(int x, int y){
        set(x);
        c = y;
    }
};

int main() {
    // your code goes here
    d newd;
    newd.setc(10, 20);
    newd.getac();
    newd.setc(12, 22);
    newd.getac();
    return 0;
}


问:
Problem of FATAL EXCEPTION: main in Android application when starting execution

android.view.InflateException: Binary XML file line #2

The error tells me that it is a fatal error in the main method but I have a splash and it runs perfect is until it enters the main and stops

Error Screenshot

This is the XML

```<code>    < ?xml version="1.0" encoding="utf-8"? >
    <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android`="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondo"
    tools:context="menu.MainActivity">

<Button
    android:id="@+id/lisaid"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="100dp"
    android:background="@drawable/fondoet"
    android:onClick="listar"
    android:text="@string/listar"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/listar" />

<Button
    android:id="@+id/consultar"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="consulta"
    android:text="@string/CONSULTA"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/lisaid"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CONSULTA" />

<Button
    android:id="@+id/crear"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="ejecucion"
    android:text="@string/CREAR"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/consultar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CREAR" />

<TextView
    android:id="@+id/textView9"
    android:layout_width="338dp"
    android:layout_height="64dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/BIENVENIDO"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="36sp"
    app:layout_constraintBottom_toTopOf="@+id/textView10"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="@string/BIENVENIDO" />

<TextView
    android:id="@+id/textView10"
    android:layout_width="322dp"
    android:layout_height="72dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="30dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/datos"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="18sp"
    app:layout_constraintBottom_toTopOf="@+id/crear"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.627"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/datos" />
</code>```

and here is the class

```<code>    public class MainActivity extends AppCompatActivity
{

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

        AdminSQLiteOpenHelper conn=new AdminSQLiteOpenHelper(this,"bd_usuarios",null,1);
    }

    public void ejecucion (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.crear:miintent=new Intent(MainActivity.this,Ejecucion.class);
            break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }

    }
    public void consulta (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.consultar:miintent=new Intent(MainActivity.this,consulta1.class);
                break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
    public void listar (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.lisaid:miintent=new Intent(MainActivity.this, listausuarios.class);

        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
}
</code>```

I'm using a SQL database, but it was working well, I do not know what happens.

答:
Just look at your XML file, there is obviously a formatting issue in line 2.

Change:

```<code> < ?xml version="1.0" encoding="utf-8"? >
</code>```

to

```<code>  <?xml version="1.0" encoding="utf-8"?>
</code>```

And remove the ` in the second line.

Body:
android.view.InflateException: Binary XML file line #2

The error tells me that it is a fatal error in the main method but I have a splash and it runs perfect is until it enters the main and stops

Error Screenshot

This is the XML

    < ?xml version="1.0" encoding="utf-8"? >
    <androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android`="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/fondo"
    tools:context="menu.MainActivity">

<Button
    android:id="@+id/lisaid"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="100dp"
    android:background="@drawable/fondoet"
    android:onClick="listar"
    android:text="@string/listar"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/listar" />

<Button
    android:id="@+id/consultar"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="consulta"
    android:text="@string/CONSULTA"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/lisaid"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CONSULTA" />

<Button
    android:id="@+id/crear"
    android:layout_width="225dp"
    android:layout_height="63dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="32dp"
    android:background="@drawable/fondoet"
    android:onClick="ejecucion"
    android:text="@string/CREAR"
    android:textColor="@color/colorPrimaryDark"
    app:layout_constraintBottom_toTopOf="@+id/consultar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.588"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/CREAR" />

<TextView
    android:id="@+id/textView9"
    android:layout_width="338dp"
    android:layout_height="64dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/BIENVENIDO"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="36sp"
    app:layout_constraintBottom_toTopOf="@+id/textView10"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:text="@string/BIENVENIDO" />

<TextView
    android:id="@+id/textView10"
    android:layout_width="322dp"
    android:layout_height="72dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="30dp"
    android:background="@drawable/fondoet"
    android:gravity="center"
    android:text="@string/datos"
    android:textColor="@color/colorPrimaryDark"
    android:textColorHighlight="@color/colorPrimary"
    android:textSize="18sp"
    app:layout_constraintBottom_toTopOf="@+id/crear"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.627"
    app:layout_constraintStart_toStartOf="parent"
    tools:text="@string/datos" />

and here is the class

    public class MainActivity extends AppCompatActivity
{

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

        AdminSQLiteOpenHelper conn=new AdminSQLiteOpenHelper(this,"bd_usuarios",null,1);
    }

    public void ejecucion (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.crear:miintent=new Intent(MainActivity.this,Ejecucion.class);
            break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }

    }
    public void consulta (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.consultar:miintent=new Intent(MainActivity.this,consulta1.class);
                break;
        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
    public void listar (View view)
    {
        Intent miintent= null;
        switch(view.getId())
        {
            case R.id.lisaid:miintent=new Intent(MainActivity.this, listausuarios.class);

        }
        if (miintent!=null)
        {
            startActivity(miintent);
        }
    }
}

I'm using a SQL database, but it was working well, I do not know what happens.

Body:
Just look at your XML file, there is obviously a formatting issue in line 2.

Change:

 < ?xml version="1.0" encoding="utf-8"? >

to

  <?xml version="1.0" encoding="utf-8"?>

And remove the ` in the second line.


答:
If you want to get all items directly following an "apple" in your list, your could use a list comprehension, like:

```<code>my_list = ["apple","train","apple","bus", "apple"]

[my_list[i+1] for i, item in enumerate(my_list)
              if item == "apple" and i+1 < len(my_list)]
# ['train', 'bus']
</code>```

We keep the next element whenever the current one is "apple" - and we're not at the end of the list.

Title: Print all elements of a list preceded by a given one

Body:
If you want to get all items directly following an "apple" in your list, your could use a list comprehension, like:

my_list = ["apple","train","apple","bus", "apple"]

[my_list[i+1] for i, item in enumerate(my_list)
              if item == "apple" and i+1 < len(my_list)]
# ['train', 'bus']

We keep the next element whenever the current one is "apple" - and we're not at the end of the list.


答:
You suffer from a misunderstanding how member access scoping works.

This statement of yours:

When I am creating newd, an object of d. there is no memory created for a (private data member of class b)

is wrong.

Access specifiers have nothing to do with memory or memory protections. When you derive from a class, all the class members of parent classes must be created as well. That is, because public and protected methods of the parent class still may be called, and may access their class' private members.

Title: Why I am able to modify private data of base class from derieved class


答:
When I am creating newd, an object of d. there is no memory created for a (private data member of class b)

That is wrong. A d is a b, and thus it has all members of b, and they take up memory. The total size of d is the size of b plus the size of the new members introduced by d. The newd object you created does have the a member (newd.a.) It just happens to be private and thus you don't have direct access to it. It doesn't mean it's not there.

You can verify this for yourself:

```<code>std::cout << "Size of b: " << sizeof(b)
          << ", size of d: " << sizeof(d) << '\n';
</code>```

This will show you that d is larger than b, because it has both the b::a member and the d::c member.

Body:
When I am creating newd, an object of d. there is no memory created for a (private data member of class b)

That is wrong. A d is a b, and thus it has all members of b, and they take up memory. The total size of d is the size of b plus the size of the new members introduced by d. The newd object you created does have the a member (newd.a.) It just happens to be private and thus you don't have direct access to it. It doesn't mean it's not there.

You can verify this for yourself:

std::cout << "Size of b: " << sizeof(b)
          << ", size of d: " << sizeof(d) << '\n';

This will show you that d is larger than b, because it has both the b::a member and the d::c member.


问:
Handle WebApi Core methods with Id as string and int
I have two methods:

```<code>    [HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }
</code>```

As you can see, i want to pass to my API routes like:

https://localhost:44365/Task/1

and

https://localhost:44365/Task/string

But my WebApi project cant handle it. When i pass route like this:

```<code>https://localhost:44365/Task/7dd2514618c4-4575b3b6f2e9731edd61
</code>```

i get an 400 http and this response:

```<code>{
"id": [
    "The value '7dd2514618c4-4575b3b6f2e9731edd61' is not valid."
]
}
</code>```

While debugging, im not hitting any methods (when i pass string instead of int)

My question is, how to verload methods with one parameters with string or int? These methods do diffrent things

EDIT

When i pass something like:

```<code>https://localhost:44365/Task/dddd
</code>```

I still get response with invalid id

答:
Use like this </p>

```<code>[HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("User/{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }
</code>```

<p>and while calling api with guid/string use </p>

```<code>https://localhost:44365/Task/User/7dd2514618c4-4575b3b6f2e9731edd61
</code>```

Body:
I have two methods:

    [HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }

As you can see, i want to pass to my API routes like:

https://localhost:44365/Task/1

and

https://localhost:44365/Task/string

But my WebApi project cant handle it. When i pass route like this:

https://localhost:44365/Task/7dd2514618c4-4575b3b6f2e9731edd61

i get an 400 http and this response:

{
"id": [
    "The value '7dd2514618c4-4575b3b6f2e9731edd61' is not valid."
]
}

While debugging, im not hitting any methods (when i pass string instead of int)

My question is, how to verload methods with one parameters with string or int? These methods do diffrent things

EDIT

When i pass something like:

https://localhost:44365/Task/dddd

I still get response with invalid id

Body:
Use like this

[HttpGet("{id}")]
    public IActionResult GetTask([FromRoute] int id)
    {
    }

    [HttpGet("User/{userId}")]
    public IActionResult GetUserTask([FromRoute] string userId)
    {
    }

and while calling api with guid/string use

https://localhost:44365/Task/User/7dd2514618c4-4575b3b6f2e9731edd61


问:
jQuery append() into new window not working with Microsoft Edge
Microsoft Edge is throwing 'No such interface supported' error when trying to append cloned content into new window.  Here is an example:

```<code>jQuery(document).ready(function() {
    jQuery('.trigger').click(function() {
        var target = jQuery(this).data('print_target');

        var w = window.open('', '', 'status=no, toolbar=no, menubar=no, location=no');
        var print_html = '<!DOCTYPE html><head><title>' + document.getElementsByTagName('title')[0].innerHTML + '</title></head><body></body></html>';
        w.document.write( print_html );

        var ua = window.navigator.userAgent;
        var ie = true;

        //.html() required for IE browsers
        if ( ua.indexOf("MSIE ") != -1) {
            //console.log('MSIE - Craptastic');
            jQuery(w.document.body).append( jQuery( target ).clone( true ).html() );
        }
        else if ( ua.indexOf("Trident/") != -1) {
            //console.log('IE 11 - Trident');
            jQuery(w.document.body).append( jQuery( target ).clone( true ).html() );
        }
        else if ( ua.indexOf("Edge/") != -1 ){
            console.log('IE 12 - Edge');
            //error: No such interface supported
            jQuery(w.document.body).append( jQuery( target ).clone( true ).html() );

            //works
            //jQuery(w.document.body).append( 'hey dude, this is some text' );

            //works
            //jQuery(w.document.body).html( jQuery( target ).clone( true ).html() );

        }
        else{
            //console.log('proper browser');
            jQuery(w.document.body).append( jQuery( target ).clone( true ) );
            ie = false;
        }
    });
});
</code>```

This is only an issue with Microsoft Edge, it works in all standards based browsers and IE browsers 7,8,9,10 and 11. A similar issue has been raised in this thread but not resolved.

here is a jsfiddle showing what's what: https://jsfiddle.net/switzerbaden/nhtywLsp/

答:
First clone the HTML, then add div before and close it after:</p>

```<code>var new_target = jQuery.trim( jQuery( target ).clone( true ).html() );
jQuery( w.document.body ).append( "<div>" + new_target + "</div>" );
</code>```

Body:
Microsoft Edge is throwing 'No such interface supported' error when trying to append cloned content into new window.  Here is an example:

jQuery(document).ready(function() {
    jQuery('.trigger').click(function() {
        var target = jQuery(this).data('print_target');

        var w = window.open('', '', 'status=no, toolbar=no, menubar=no, location=no');
        var print_html = '<!DOCTYPE html><title>' + document.getElementsByTagName('title')[0].innerHTML + '</title>';
        w.document.write( print_html );

        var ua = window.navigator.userAgent;
        var ie = true;

        //.html() required for IE browsers
        if ( ua.indexOf("MSIE ") != -1) {
            //console.log('MSIE - Craptastic');
            jQuery(w.document.body).append( jQuery( target ).clone( true ).html() );
        }
        else if ( ua.indexOf("Trident/") != -1) {
            //console.log('IE 11 - Trident');
            jQuery(w.document.body).append( jQuery( target ).clone( true ).html() );
        }
        else if ( ua.indexOf("Edge/") != -1 ){
            console.log('IE 12 - Edge');
            //error: No such interface supported
            jQuery(w.document.body).append( jQuery( target ).clone( true ).html() );

            //works
            //jQuery(w.document.body).append( 'hey dude, this is some text' );

            //works
            //jQuery(w.document.body).html( jQuery( target ).clone( true ).html() );

        }
        else{
            //console.log('proper browser');
            jQuery(w.document.body).append( jQuery( target ).clone( true ) );
            ie = false;
        }
    });
});

This is only an issue with Microsoft Edge, it works in all standards based browsers and IE browsers 7,8,9,10 and 11. A similar issue has been raised in this thread but not resolved.

here is a jsfiddle showing what's what: https://jsfiddle.net/switzerbaden/nhtywLsp/

Body:
First clone the HTML, then add div before and close it after:

var new_target = jQuery.trim( jQuery( target ).clone( true ).html() );
jQuery( w.document.body ).append( "<div>" + new_target + "</div>" );


问:
How to give a custom (id || key) for every item in flutter listview?
Is there a way to give custom id to every item in flutter's listview?

I need to update a single item in flutter listview by its id or key.

Why I want to update by Id?

because I want to update a specific item without rebuilding the entire listview items, this may boost performance of my app.

答:
You can do it like this:

```<code>return ListView.builder(
  itemCount: list.length,
  itemBuilder: (context, index) {
  return Card(
    child: ListTile(
    title: Text(list[index]),
    onTap: () { //                                  <-- onTap
      setState(() {
        list.insert(index, 'updated value');
      });
    },
    onLongPress: () { //                            <-- onLongPress
      setState(() {
        list.removeAt(index);
      });
    },
   ),
  );
 },
);
</code>```

here as you can see you can easily update and delete.

Body:
You can do it like this:

return ListView.builder(
  itemCount: list.length,
  itemBuilder: (context, index) {
  return Card(
    child: ListTile(
    title: Text(list[index]),
    onTap: () { //                                  <-- onTap
      setState(() {
        list.insert(index, 'updated value');
      });
    },
    onLongPress: () { //                            <-- onLongPress
      setState(() {
        list.removeAt(index);
      });
    },
   ),
  );
 },
);

here as you can see you can easily update and delete.


问:
How do I generate random string array urls without repeating?
I am trying to generate random string array urls in picasso, everything is working fine but it repeats, like i had 28 string array items when i start app some items are repeating but i want only 1 item at one time when random start

This is my code

```<code>     ImageView imageView = itemView.findViewById(R.id.imageview);
        random = new Random();
        int p=  random.nextInt(icons.length);
        Picasso.get().load(icons[p]).into(imageView);
</code>```

答:
try the following</p>

```<code>ImageView imageView = itemView.findViewById(R.id.imageview);
Random random = new Random();
List<Integer> cache = new ArrayList<>();
int p = 0;
do {
     p = random.nextInt(icons.length);
} while(cache.contains(p));
cache.add(p);

Picasso.get().load(icons[p]).into(imageView);
</code>```

Body:
I am trying to generate random string array urls in picasso, everything is working fine but it repeats, like i had 28 string array items when i start app some items are repeating but i want only 1 item at one time when random start

This is my code

     ImageView imageView = itemView.findViewById(R.id.imageview);
        random = new Random();
        int p=  random.nextInt(icons.length);
        Picasso.get().load(icons[p]).into(imageView);

Body:
try the following

ImageView imageView = itemView.findViewById(R.id.imageview);
Random random = new Random();
List<Integer> cache = new ArrayList<>();
int p = 0;
do {
     p = random.nextInt(icons.length);
} while(cache.contains(p));
cache.add(p);

Picasso.get().load(icons[p]).into(imageView);


问:
How to read in a column of data in an IF-THEN statement or in a PROC SQL statement, SAS
I have a SAS data step statement –

```<code>Data work.CABGothers2;
  set work.CABGothers1;

  IF proc_p in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
    and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;

  IF proc2 in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
    and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;

  IF proc3 in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
    and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;

 ...
run;
</code>```

This IF-THEN section goes on 21 times, so you can imagine how HUGE and cumbersome this sas code file gets, especially when it comes to any modifications to the ICD10 code list.  It would have to be changed individually in all the proc1,proc2... columns.

Also, the ICD10 lists are very huge with over 7000 codes, I was wondering if someone could show me a better SAS code that might take as input a column of data (ICD10 codes) from a file.

I would like a proc sql or Data step procedure.  Whichever is more efficient.

Current code-

```<code>Data work.CABGothers2;
  set work.CABGothers1;

  IF proc_p in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
     and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;
run;
</code>```

UPDATE--

I got this to work if the list is small...however I have a column with 8000 unique ICD10 codes.  So I get an error message as shown below.

```<code>proc sql;
select quote(icd10) into :cabgvalexcl separated by ','
from newlink.cabgvalexcl2019;
quit;

Data work.test1;
    set WORK.cabgpddcol;

    IF proc_p in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1;
    IF oproc1 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1 ;
    IF oproc2 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1;
    IF oproc3 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1 ;
    IF oproc4 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1;

run;
</code>```

**> ERROR message- ERROR: The length of the value of the macro variable

CABGVALEXCL (65540) exceeds the maximum length (65534). The value has
  been
         truncated to 65534 characters.**

UPDATE --
eXAMPLE (JUST FEW ROWS) of ONLY 1 column (I do not have multiple columns.  I did that in the macro example because macro variable was running out of max space.) containing ICD10 codes and the data file in which I have to tag rows that have any of the ICD10 codes -

OUTPUT table-
LOgic - If any of the ICD10 codes listed in cabgvalexcl2019 (shown here in RED) is found in the table CABGOTHERS1, create a column called - EXCLUDE - and put a value of 1 for that record.

答:
Here's a hash-based example. It doesn't use macro variables, so it should work for any number of ICD10 codes:

```<code>data cabgvalexcl2019;
input (icd1-icd3) (:$2.);
datalines;
1 2 3
4 5 6
7 8 9
;
run;

/*Generate some dummy data*/
data cabgpddcol;
    array keys[*] $2 proc_p oproc1-oproc20;
    call streaminit(1); /*Set random number seed*/
    do i = 1 to 20;
        do j = 1 to dim(keys);
            keys[j] = put(int(rand('uniform') * 11 + 9), 2.); /*Chosen so we get a few rows with no exclusion codes*/
        end;
        PDDCABG = rand('uniform') < 0.75;
        output;
    end;
    drop i j;
run;

/*  CABGval_Excl = Identify CABG+VALVE exclusions which are "CABG OTHERS".  This is the 2019 CABG+VALVE exclusion list. */

/*  If the RECORD IN following table has CABGVAL_Excl = 1 then it is a CABG+valve WITH EXCLUSION*/
Data work.CABGval_Excl;  /* CABG OTHERS prior to refinement into non-iso CABG WITH Valve and non-iso CABG WITHOUT Valve */

    /*Create hash object to hold list of ICD codes*/
    length icd $ 2;
    if _n_ = 1 then do;
        declare hash h();
        rc = h.definekey('icd');
        rc = h.definedone();
        do until(eof);
            set cabgvalexcl2019 end = eof;
            /*Consider using an array here if you have lots of ICD columns*/
            do icd = icd1, icd2, icd3;
                rc = h.add();
            end;
        end;
    end;

    set cabgpddcol;

    /*Loop through all the keys and stop if we find one in the hash*/
    array keys[*] proc_p oproc1-oproc20;
    rc = -1;
    do i = 1 to dim(keys) until(rc = 0);
        rc = h.find(key:keys[i]); /*This sets rc = 0 if a match is found*/
    end;

    drop i rc icd:;

    CABGVAL_Excl = rc ne 0 and PDDCABG = 1;
run;
</code>```

Constructing the hash object is a little bit fiddly if you have multiple columns holding all the distinct ICD10 codes you care about - if they're all in one column then there's a simpler way of doing this:

```<code>        declare hash h(dataset:'cabgvalexcl2019');
        rc = h.definekey('icd');
        rc = h.definedone();
</code>```

Body:
I have a SAS data step statement –

Data work.CABGothers2;
  set work.CABGothers1;

  IF proc_p in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
    and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;

  IF proc2 in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
    and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;

  IF proc3 in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
    and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;

 ...
run;

This IF-THEN section goes on 21 times, so you can imagine how HUGE and cumbersome this sas code file gets, especially when it comes to any modifications to the ICD10 code list.  It would have to be changed individually in all the proc1,proc2... columns.

Also, the ICD10 lists are very huge with over 7000 codes, I was wondering if someone could show me a better SAS code that might take as input a column of data (ICD10 codes) from a file.

I would like a proc sql or Data step procedure.  Whichever is more efficient.

Current code-

Data work.CABGothers2;
  set work.CABGothers1;

  IF proc_p in (a HUGE LIST OF ICD10 CODES) and PDDCABG = 1
     and TypeofCABG_PDDTemp = . then TypeofCABG_PDDTemp = 4;
run;

UPDATE--

I got this to work if the list is small...however I have a column with 8000 unique ICD10 codes.  So I get an error message as shown below.

proc sql;
select quote(icd10) into :cabgvalexcl separated by ','
from newlink.cabgvalexcl2019;
quit;

Data work.test1;
    set WORK.cabgpddcol;

    IF proc_p in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1;
    IF oproc1 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1 ;
    IF oproc2 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1;
    IF oproc3 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1 ;
    IF oproc4 in (&cabgvalexcl.) and PDDCABG = 1 then CABGVAL_Excl = 1;

run;

**> ERROR message- ERROR: The length of the value of the macro variable

CABGVALEXCL (65540) exceeds the maximum length (65534). The value has
  been
         truncated to 65534 characters.**

UPDATE --
eXAMPLE (JUST FEW ROWS) of ONLY 1 column (I do not have multiple columns.  I did that in the macro example because macro variable was running out of max space.) containing ICD10 codes and the data file in which I have to tag rows that have any of the ICD10 codes -

OUTPUT table-
LOgic - If any of the ICD10 codes listed in cabgvalexcl2019 (shown here in RED) is found in the table CABGOTHERS1, create a column called - EXCLUDE - and put a value of 1 for that record.

Body:
Here's a hash-based example. It doesn't use macro variables, so it should work for any number of ICD10 codes:

data cabgvalexcl2019;
input (icd1-icd3) (:$2.);
datalines;
1 2 3
4 5 6
7 8 9
;
run;

/*Generate some dummy data*/
data cabgpddcol;
    array keys[*] $2 proc_p oproc1-oproc20;
    call streaminit(1); /*Set random number seed*/
    do i = 1 to 20;
        do j = 1 to dim(keys);
            keys[j] = put(int(rand('uniform') * 11 + 9), 2.); /*Chosen so we get a few rows with no exclusion codes*/
        end;
        PDDCABG = rand('uniform') < 0.75;
        output;
    end;
    drop i j;
run;

/*  CABGval_Excl = Identify CABG+VALVE exclusions which are "CABG OTHERS".  This is the 2019 CABG+VALVE exclusion list. */

/*  If the RECORD IN following table has CABGVAL_Excl = 1 then it is a CABG+valve WITH EXCLUSION*/
Data work.CABGval_Excl;  /* CABG OTHERS prior to refinement into non-iso CABG WITH Valve and non-iso CABG WITHOUT Valve */

    /*Create hash object to hold list of ICD codes*/
    length icd $ 2;
    if _n_ = 1 then do;
        declare hash h();
        rc = h.definekey('icd');
        rc = h.definedone();
        do until(eof);
            set cabgvalexcl2019 end = eof;
            /*Consider using an array here if you have lots of ICD columns*/
            do icd = icd1, icd2, icd3;
                rc = h.add();
            end;
        end;
    end;

    set cabgpddcol;

    /*Loop through all the keys and stop if we find one in the hash*/
    array keys[*] proc_p oproc1-oproc20;
    rc = -1;
    do i = 1 to dim(keys) until(rc = 0);
        rc = h.find(key:keys[i]); /*This sets rc = 0 if a match is found*/
    end;

    drop i rc icd:;

    CABGVAL_Excl = rc ne 0 and PDDCABG = 1;
run;

Constructing the hash object is a little bit fiddly if you have multiple columns holding all the distinct ICD10 codes you care about - if they're all in one column then there's a simpler way of doing this:

        declare hash h(dataset:'cabgvalexcl2019');
        rc = h.definekey('icd');
        rc = h.definedone();


问:
How can I test whether a number is a power of 2?
I need a function like this:

```<code>// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);
</code>```

Can anyone suggest how I could write this?

答:
In C++20 there is std::has_single_bit which you can use for exactly this purpose if you don't need to implement it yourself:

```<code>#include <bit>
static_assert(std::has_single_bit(16));
static_assert(!std::has_single_bit(15));
</code>```

Note that this requires the argument to be an unsigned integer type.

OwnerDisplayName: Ant

Body:
I need a function like this:

// return true if 'n' is a power of 2, e.g.
// is_power_of_2(16) => true
// is_power_of_2(3) => false
bool is_power_of_2(int n);

Can anyone suggest how I could write this?

LastEditorDisplayName: Gaius

Body:
In C++20 there is std::has_single_bit which you can use for exactly this purpose if you don't need to implement it yourself:

#include <bit>
static_assert(std::has_single_bit(16));
static_assert(!std::has_single_bit(15));

Note that this requires the argument to be an unsigned integer type.


问:
No dimensions set for key window
I am having some issues with react native. It keeps giving me the following error.

What could be causing this?

答: For anyone that runs into this. Check to confirm the window passed to get() is a string Dimensions.get('window') .

Title: No dimensions set for key window