Sunday, September 26, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How do I copy multiple files in another directory in python?

Posted: 26 Sep 2021 08:06 AM PDT

I have a dataset including images in ascending order, like

images_0001.png images_0002.png . . images_0500.png

and so on. I want to copy specific range of this images into another directory. For example, 100 images will be coppied between images_0210.png to images_0310.png. Does anybody have any idea how to do that? Thank you in advance

Trouble grasping "error due to conversion" in single-precision IEEE-754

Posted: 26 Sep 2021 08:06 AM PDT

Let me preface the question by saying that I understand why values such as 0.1, 3.14, 0.2, and other values not composable of combinations of powers of two are ultimately unrepresentable by IEEE-754 formats, and that they may only be approximated as best as the precision allows.

What I am having trouble understanding is why attempting to represent the value 2-23 results in a slight margin of error.

2-23 is exactly equal to 1.1920928955078e-7, or 0.00000011920928955078. In single-precision IEEE-754, it can be constructed as follows:

  • The sign bit is 0
  • The biased exponent is 104 (or 0b01101000 in binary) to account for the 127-bias, leading to -23 being the final exponent value
  • The mantissa's bit field is entirely composed of 0s, its ultimate value being 1.0 when the implicit 1-bit is accounted for

However, storing this particular bit sequence in memory and printing it out in decimal notation, with 25 digits of precision past the decimal point results in the following:

0.0000001192092895507812500                        ^                        |                        margin of error starts here  

This value contains an error of exactly 1.25e-21. On this interactive website, this error value is referred to as an "Error due to conversion".

I am having trouble grasping this - because I understand, for example, why a value such as +2.76 cannot be exactly represented by a single-precision bitfield. No combination of negative powers of two in the mantissa scaled by the value in the exponent can exactly represent 2.76, so the next closest approximation is chosen. Contrary to that, the value 2-23 is able to be stored exactly in a single-precision bitfield, yet when converted back to a decimal notation, an error appears.

There's clearly some sort of misunderstanding on my part, but I can't figure out where exactly.

Iterating over NumPy array for timestep

Posted: 26 Sep 2021 08:06 AM PDT

I have 5 columns in an array that are datetime type values. There are 100k+ values in each column

The values are the datetime for a timeline going from 2015-01-15 00:30 to 2020-12-31 23:00 in 30 minute increments.

Basically what I want to do is to loop through values in the array, and check if the current value is an exact 30 minute timestep from the last value. In an array with columns this would be the value above the current value being investigated

Theres probably a few ways to do this, but I've included a pseudocode sample of how I'm thinking about it

  for row in _the_whole_array :          for cell in row:              if cell == to the 30 minute timestep of the cell above it                continue iterating              else:                store that value  return the smallest timestep found, and the biggest timestep found     

I have looked at for loops as well as nditer but I'm getting errors with iterating over datetimes, and I'm also wondering how I can find the cell value above the current cell value above it.

Any help hugely appreciated

In Django E-commerce app, how I send user wishlist (when user is not logged in) data to cart after user logged in, I used session for Wishlist

Posted: 26 Sep 2021 08:06 AM PDT

For that I used session to store product information for the wishlist and bu can't send when user is logged in/.

Google Material You: How can we use the same Color Accent than system+Google Apps?

Posted: 26 Sep 2021 08:05 AM PDT

I have read the "documentation" to find the reference to accent color: https://developer.android.com/reference/android/R.color#system_accent1_0

But after implementing it in my application, I am not happy with the results and really like the Google implementation. (See screenshot below)

I have tried to display all colors in a sample application (the one on the left) and cannot find the same color than Google apps on the right (Phone, Gmail, Drive)

Is Google implementing a custom / proprietary implementation? Did I missed something?

Thank a lot for any help to find the right colors to use for my ActionBar, FAB, and other items.

enter image description here

Django backward foreign key query not working

Posted: 26 Sep 2021 08:07 AM PDT

hi i am working on a chat application on django with django channels and i am trying to query all the first messages of the user here when i do

user.message_set.all()  

it is throwing

AttributeError at /  'User' object has no attribute 'message_set'  

full traceback:

Traceback (most recent call last):    File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner      response = get_response(request)    File "/home/__neeraj__/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response      response = wrapped_callback(request, *callback_args, **callback_kwargs)    File "/home/__neeraj__/Documents/chat/home/views.py", line 10, in index      print(i.messages_set.all())  AttributeError: 'User' object has no attribute 'message_set'  

my models.py

class Message(models.Model):      sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender")      receiver = models.ForeignKey(          User, on_delete=models.CASCADE, related_name="receiver"      )      text = models.CharField(max_length=2000)      created_on = models.DateTimeField(auto_now=True)  

my view :

def index(request):      users = User.objects.all()      context = {"users": users}      for user in users:          print(user.message_set.all())      return render(request, "index.html", context=context)  

is this because i have double foreign key reference of user model on message table?

Why mapped items states are affecting on each other in React?

Posted: 26 Sep 2021 08:05 AM PDT

I mapped an array of products, each of them have, I am managing state with redux, each mapped item has quantity if I increase quantity, price should also increase, so when I am changing quantity of one item second array price also changes based on previous item quantity, so why are different items affecting on each other? here is the code:

const handleProductQuantity = (event) => {      dispatch(setProductQuantity(event.target.value));  }     <div className='cart'>          <div className='products-in-cart-wrapper'>          { productsInCart ? (               productsInCart.map(productInCart => (                      <div className='product-in-cart'>                          <div className="product-in-cart-name">                              <div className="label label-title">                                Title:                              </div>                              <div className="value value-title">                                  {productInCart.title}                               </div>                          </div>                            <div className="product-in-cart-price">                               <div className="label label-price">                                  Price:                               </div>                               <div className="value value-price">                                  {productQuantity * productInCart.price}                               </div>                          </div>                            <div className="product-in-cart-price">                               <div className="label label-price">                                  Quantity:                               </div>                               <div className="value value-quantity">                                  <input onChange={handleProductQuantity} type="number" placeholder='1'/>                               </div>                          </div>                          <div className="button-cont">                              <button className="buy-button" onClick={test}>                                  Buy now                              </button>                          </div>                      </div>              ))          ) : (              <div> Loading... </div>          )          }          <div className="total-price-button-cont">              <button>Buy all for: 100$</button>          </div>          </div>      </div>  

Power Automate , Export Sharepoint Excel file to local

Posted: 26 Sep 2021 08:05 AM PDT

I am trying to set up a reoccurrence to export an excel file automatically to my local drive.

However I am running into problems with Get Items part as I cannot correctly link to the sharepoint excel.

Can anyone help with this?

My flow

enter image description here

Getting url from the parent path:

enter image description here

Is there a way of only printing the counter totals

Posted: 26 Sep 2021 08:05 AM PDT

I am counting the total occurrences of each item:

from collections import Counter    colors = ['green', 'blue', 'green', 'white', 'white']  colorTotals = Counter(colours)    print(colorTotals)  

Running the code prints: Counter({'green': 2, 'white': 2, 'blue': 1}) but I only want to print the dictionary, something like: {'green': 2, 'white': 2, 'blue': 1}

How can I achieve this?

Code box that shows html and lets you copy to clipboard

Posted: 26 Sep 2021 08:05 AM PDT

I'd like to put a code box similar to ones here

like this

that contains HTML within it and lets you copy that html to clipboard.

Can anyone direct me to something like this or help me figure out how to do it? I've plugged in a codepen that lets me copy text to clipboard, but it won't work html inside of it. I hope this makes sense.

How to add kableExtra table into RMarkdown Powerpoint slides

Posted: 26 Sep 2021 08:05 AM PDT

I'm attempting to add a table into an RMarkdown Powerpoint Presentation using the kableExtra package. Initially, I tried to run the code without always_use_html in my YAML and the following error appeared.

Error: Functions that produce HTML output found in document targeting pptx output.  Please change the output type of this document to HTML. Alternatively, you can allow  HTML output in non-HTML formats by adding this option to the YAML front-matter of  your rmarkdown file:      always_allow_html: true    Note however that the HTML output will not be visible in non-HTML formats.    Execution halted    

After adding always_allow_html to my YAML, my table is still not appearing as desired in my slide Slide Image.

My table should look something like this

Kable

Does anyone perhaps know how to embed a kableExtra table in Rmarkdown slides?

Here is my full code

---  title: "Untitled"  output: powerpoint_presentation  always_use_html: true  ---    ```{r setup, include=FALSE}  knitr::opts_chunk$set(echo = FALSE)  ```      ## Table    ```{r table}  library(kableExtra)  data <- data.frame(a = c(1,2,3), b = c(4,5,6))    data %>%     kable() %>%     kable_styling()    ```  

My javascript is not working, kindly help. below is my code

Posted: 26 Sep 2021 08:06 AM PDT

const hamburger = document.querySelector(".header .nav-bar .navlist .hamburger");  const mobile_menu = document.querySelector(".header .nav-bar .navlist ul");  const header = document.querySelector(".header .container");    hamburger.addEventListener("click", () => {  hamburger.classList.toggle("active");  mobile_menu.classList.toggle("active");  });  

html code

<section id="header">    <div class="header container">      <div class="nav-bar">        <div class="brand">          <a href="#hero"><h1>OUR WEBSITE</h1></a>        </div>        <div class="nav-list">          <div class="hamburger"><div class="bar"></div></div>          <ul>            <li><a href="#" data-after="Home">Home</a></li>            <li><a href="#" data-after="Services">Services</a></li>            <li><a href="#" data-after="Projects">Projects</a></li>            <li><a href="#" data-after="Our C.E.O">About Us</a></li>            <li><a href="#" data-after="Contact Us">Contact Us</a></li>          </ul>        </div>      </div>    </div>  </section>  

CSS Code

             #header .hamburger .bar::after,               #header .hamburger .bar::before {               content: "";               position: absolute;               height: 100%;               width: 100%;               left: 0;               background-color: white;               transition: 0.3s ease;               transition-property: top, bottom;               }               #header .hamburger .bar::after {               top: 8px;               }               #header .hamburger .bar::before {               bottom: 8px;               }               #header .hamburger.active .bar::before {               bottom: 0;               }               #header .hamburger.active .bar::after {               top: 0;               }  

When I open this code in live server, the hamburger click is not responding, my JavaScript is already linked to the html. I need a solution to help my js work/respond.

When I open this code in live server, the hamburger click is not responding, my JavaScript is already linked to the html. I need a solution to help my js work/respond.

How to calculate max value using python 3 object oriented programming?

Posted: 26 Sep 2021 08:06 AM PDT

Is it true like this? I try to print the output of my array, but it seems doesn't work

class student:      name = 0      gpa = 0      def countGpa(self):          self.gpa = listGpa          listGpa.append(self.gpa)          print(listGpa)    def main():      objek = student()      n = int(input("n: "))      for i in range(n):          objek.name = str(input("name: "))          objek.gpa = int(input("gpa: "))      objek.countGpa()  main()```    but why i can't print my array , output is like this ```[[...]]```  

Control the URL bar with JavaScript

Posted: 26 Sep 2021 08:05 AM PDT

Is there some function in javascript or React.js to tell if a user tries to access an existing page through the URL bar?

Laplacian filter returning very black image

Posted: 26 Sep 2021 08:05 AM PDT

I'm trying to apply a local Laplacian filter to an image using blockproc but the result I get is far darker than the result in the textbook. I've seen some other posts about this same problem but I'm not sure what exactly I'm failing to grasp.

My code:

img1 = im2double(imread('Fig0352(a)(blurry_moon).tif'));  kernel = [0 1 0; 1 -4 1; 0 1 0];    %generate laplacian image  fun = @(block_struct)laplacian_kernel(block_struct.data, kernel);  img2 = blockproc(img1, [3 3], fun, 'PadPartialBlocks', true, 'TrimBorder', true);  img3 = img2(:, 1:end-2);%crop extra two columns added by last passthrough of blockproc  img4 = imsubtract(img1,img3);%get enhanced image    %display  figure;  subplot(2,2,1);  imshow(img1)  subplot(2,2,2);  imshow(img3);  subplot(2,2,3);  imshow(img4);      function f = laplacian_kernel(img, kernal)  %want to pad this 3x3 chunk of the image so we don't exceed the bounds of  %the array when doing laplacian  img1 = padarray(img, [1 1]);  out = zeros(size(img1));  for i = 2 : (length(img1)-1)     for j = 2 : (length(img1)-1)         neighborhood = img1(i-1: i+1, j-1: j+1);%get neighborhood         out(i,j)= sum(neighborhood .* kernal, 'all');      end  end  f = out(2:length(img1)-1, 2:length(img1)-1);%remove padding  end  

And the image I'm getting is

enter image description here

The laplacian is the image on the top right, which is far darker than what is shown in the book.

The image from the book looks much more like this:

enter image description here

I know it's still very dark (and a small image, sorry) but there is much more detail to it than what I'm producing with my custom code. What am I doing wrong with my laplacian? I've tried rewriting the code multiple times but always get more or less the same result.

If I use nlfilter, my result matches that in the book. However, it takes so much more time I don't like to use it. I'm clearly stumbling when piecing the blocks back together with blockproc but I can't conceptualize where I'm going wrong. Here are my results when using nlfilter:

img1 = im2double(imread('Fig0352(a)(blurry_moon).tif'));    kernel = [0 1 0; 1 -4 1; 0 1 0];  k2 = [1 1 1; 1 -8 1; 1 1 1];    fun = @(x)laplacian_kernel(x, kernel);  img2 = nlfilter(img1, 'indexed', [3 3], fun);    img3 = imsubtract(img1, img2);    figure;  subplot(1,3,1);  imshow(img1);  title('original image');  subplot(1,3,2);  imshow(img2);  title('laplacian using nlfilter');  subplot(1,3,3);  imshow(img3);  title('enhanced image');    function f = laplacian_kernel(img, kernal)  f = sum(img.*kernal, 'all');  end  

With output:

enter image description here

Clearly, the results from nlfilter are much better. I'm just not sure where I'm going wrong with blockproc.

PHP - How to use config file variables in a function's array?

Posted: 26 Sep 2021 08:05 AM PDT

I could not find an example of what I'm trying to accomplish. I guess I don't know the proper search words to use. I have a working script but I want to make it more flexible by adding a main, admin editable config file.

I have the following function:

    function ip_is_mobile($ip) {          $pri_addrs = array(                               '66.87.0.0-66.87.255.255',  // Sprint mobile              '174.192.0.0-174.255.255.255'   // Verizon mobile          );                $long_ip = ip2long($ip);                if($long_ip != -1) {                foreach($pri_addrs AS $pri_addr) {                  list($start, $end) = explode('-', $pri_addr);                    // IF IS a mobile IP                  if($long_ip >= ip2long($start) && $long_ip <= ip2long($end))                      return true;              }          }          return false;      }  

I would like to replace the hard-coded IP address ranges, in the function, with variables or definitions which will be set in the main config file so that the config file has something similar to the following:

// Mobile IP address ranges. Add as many as needed.  $MobileIPs['0']="66.87.0.0-66.87.255.255";  $MobileIPs['1']="174.192.0.0-174.255.255.255";  $MobileIPs['2']="85.110.50.0/24";  

My goal is to give the admin an easy to read and understand way of adding as many IP address ranges as necessary (probably 20 max). I'm not opposed to totally rewriting the function if there is a better, more efficient way. In addition to IP ranges, it would be advantageous if CIDR's could also be specified; as indicated in the last code line above.

What edits do I need to make to the function and what would the corresponding lines in the main config file be so that the user can add any number of ranges or CIDR's?

Select max query returning all the rows in a table in Apache Hive

Posted: 26 Sep 2021 08:06 AM PDT

I am querying my data using this query

SELECT date_col,max(rate) FROM crypto group by date_col ;

I am expecting a single row but it is returning all the rows in the table. What is the mistake in this query?

Cannot access the property of an object - getting undefined

Posted: 26 Sep 2021 08:06 AM PDT

Now i have seen the other questions of this type and tried the solutions and it didnt work.

So now whats the problem?

Im using redux dispatching same data, an object with a label and userID, im then putting that data in a const pharmas with useSelector, when i log the const i get an object in the console containing the dispatched data and that is fine.

Now the problem is when i try to log pharmas.userID i get undefined for some reason.

Heres how it looks like when i log it normally console.log(pharmas) and this isJSON.stringify(pharmas)

Can someone please explain why am i getting cannot read property of undefined

and what can i do to extract userID since i need it to filter out some data?

Thanks in advance!

Heres the code, getting data and and logging it

const pharmas = useSelector ((state) => state.pharmacies.filteredPharmacies)    console.log('pharmas', pharmas)    

Dispatching the data:

const handleOnChange = (value) => {   dispatch(getPharmacie(value))      console.log('HERE',value)  };  

Heres what the "value" looks like in the console Exactly like i get it in pharmas:

heres the reducer:

  export function pharmacies(    state = { pharmacies: [], selectedPharmacies: [], filterPharmacies: [] },    action  ) {    switch (action.type) {      case SET_PHARMACIES_DATA:        return {          ...state,          pharmacies: action.payload,      };      case SET_PHARMACIE:        return{          ...state,          filterPharmacies: action.payload,      }      case GET_PHARMACIE:       return{        ...state,        filteredPharmacies: action.payload,       }      case SET_PHARMACIES:  

Using GET_PHARMACIE case:

But when i console.log(pharmas.userID) i get the error undefined.

Heres the GET_PHARMACIE in store from redux extension state

I don't know the syntax error in this xquery code

Posted: 26 Sep 2021 08:05 AM PDT

let $d := doc('mondial.xml')  let $airports := $d/mondial/airport  let $countries := $d/mondial/country    for $data1 in $countries      let $count :=xs:integer("0")      let $name :=$data1/name      let $car_code :=$data1/@car_code      for $data2 in $airports          where $car_code = $data2/@country               $count:= $count+ 1      where xs:integer($count)>25           return              <country>                  <name>{data($name)}</name>                  <count>{data($count)}</count>              </country>  

This is my code, when I ran this code, there is syntax error: error: syntax error, unexpected $[err:XPST0003] $count:=$count+1

Read New File While Doing Processing For A Field In Spring Batch

Posted: 26 Sep 2021 08:05 AM PDT

I have a fixedlength input file reading by using SPRING BATCH. I have already implemented Job, Step, Processor, etc. Here are the sample code.

@Configuration  public class BatchConfig {            private JobBuilderFactory jobBuilderFactory;      private StepBuilderFactory stepBuilderFactory;            @Value("${inputFile}")       private Resource resource;            @Autowired      public BatchConfig(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {          this.jobBuilderFactory = jobBuilderFactory;          this.stepBuilderFactory = stepBuilderFactory;      }            @Bean      public Job job() {          return this.jobBuilderFactory.get("JOB-Load")                  .start(fileReadingStep())                  .build();      }            @Bean      public Step fileReadingStep() {          return stepBuilderFactory.get("File-Read-Step1")                  .<Employee,EmpOutput>chunk(1000)                  .reader(itemReader())                  .processor(new CustomFileProcesser())                  .writer(new CustomFileWriter())                  .faultTolerant()                  .skipPolicy(skipPolicy())                  .build();      }                        @Bean      public FlatFileItemReader<Employee> itemReader() {          FlatFileItemReader<Employee> flatFileItemReader = new FlatFileItemReader<Employee>();          flatFileItemReader.setResource(resource);          flatFileItemReader.setName("File-Reader");          flatFileItemReader.setLineMapper(LineMapper());          return flatFileItemReader;      }        @Bean      public LineMapper<Employee> LineMapper() {          DefaultLineMapper<Employee> defaultLineMapper = new DefaultLineMapper<Employee>();          FixedLengthTokenizer fixedLengthTokenizer = new FixedLengthTokenizer();          fixedLengthTokenizer.setNames(new String[] { "employeeId", "employeeName", "employeeSalary" });          fixedLengthTokenizer.setColumns(new Range[] { new Range(1, 9), new Range(10, 20), new Range(20, 30)});          fixedLengthTokenizer.setStrict(false);            defaultLineMapper.setLineTokenizer(fixedLengthTokenizer);          defaultLineMapper.setFieldSetMapper(new CustomFieldSetMapper());            return defaultLineMapper;      }            @Bean      public JobSkipPolicy skipPolicy() {          return new JobSkipPolicy();      }        }  

For Processing I have added some sample code What I need, But if I add BufferedReader here then it's taking more times to do the job.

@Component  public class CustomFileProcesser implements ItemProcessor<Employee, EmpOutput> {        @Override      public EmpOutput process(Employee item) throws Exception {          EmpOutput emp = new EmpOutput();          emp.setEmployeeSalary(checkSal(item.getEmployeeSalary()));          return emp;      }        public String checkSal(String sal) {                    // need to read the another file           // required to do some kind of validation          // after that final result need to return            File f1 = new File("C:\\Users\\John\\New\\salary.txt");        FileReader fr;      try {          fr = new FileReader(f1);          BufferedReader br = new BufferedReader(fr);          String s = br.readLine();                    while (s != null) {              String value = s.substring(5, 7);              if(value.equals(sal))                  sal = value;              else                  sal = "5000";              s = br.readLine();          }                } catch (Exception e) {          e.printStackTrace();      }                    return sal;      }            // other fields need to check by reading different different file.      // These new files contains more than 30k records.       // all are fixedlength file.       // I need to get the field by giving the index      }  

While doing the processing for one or more field, I need to check In another file by reading that file (it's a file I will read from fileSystem/Cloud).

While processing the data for 5 fields I need to read 5 different different file again, I will check the fields details inside those file and then I will gererate the result , That result will process forther.

PIC16 not updating ADC values

Posted: 26 Sep 2021 08:06 AM PDT

Can somebody help to explain why my code or setup not updating the ADC values of a 10K-potentiometer please?

I use MPLAB XPRESS PIC16F18877 board and MPLAB MCC to generate the code. The voltage result only gets updated once after resetting the board.

main.c

#include "mcc_generated_files/mcc.h"    void display_result(float v);    void main(void) {      adc_result_t convResult = 0;      float v = 0;        // initialize the device      SYSTEM_Initialize();        ADCC_StartConversion(POT);          while (1) {          // Convert ADC values          while (!ADCC_IsConversionDone());          convResult = ADCC_GetConversionResult();          v = convResult * 3.3 / 1023;            // send the value to display          display_result(v);      }  }    void display_result(float v) {      if (v > 1.65) {          LED_SetHigh();      } else {          LED_SetLow();      }  }

Output to the TableView

Posted: 26 Sep 2021 08:07 AM PDT

It is necessary to draw a conclusion from MySQL in the tableView. Created an entity:

@Getter  @Setter  @ToString  @NoArgsConstructor  @AllArgsConstructor  //  @Entity  @Table(name = "users2")  //создание бд и таблицы юзеров  public class User  {      @Id      @GeneratedValue(strategy = GenerationType.IDENTITY)      private Long id;            @Column(nullable = false, unique = true)      private String login;            @Column(nullable = false, length = 16)      private String password;            @Column(nullable = false, length = 50)      private String surname;            @Column(nullable = false, length = 50)      private String name;  //equals, hashcode, toString  }  

Based on the entity, I made a controller:

public class Controller implements Initializable  {      private Stage stage;            public void setStage(Stage stage)      {          this.stage = stage;      }            ObservableList<User> usersData = FXCollections.observableArrayList();            @Autowired      private UserRepository userRepository;            @FXML      private TableView<User> tableUsers;            @FXML      private TableColumn<User, Long> userIdColumn;            @FXML      private TableColumn<User, String> userLoginColumn;            @FXML      private TableColumn<User, String> userPassColumn;            @FXML      private TableColumn<User, String> userSurnameColumn;            @FXML      private TableColumn<User, String> userNameColumn;            @Override      public void initialize(URL location, ResourceBundle resources)      {          //id, login, password, surname, name          userIdColumn.setCellValueFactory(new PropertyValueFactory<>("id"));          userLoginColumn.setCellValueFactory(new PropertyValueFactory<>("login"));          userPassColumn.setCellValueFactory(new PropertyValueFactory<>("password"));          userSurnameColumn.setCellValueFactory(new PropertyValueFactory<>("surname"));          userNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));      }            @FXML      private void displayData() throws IOException      {          fillTable();      }            private void fillTable()      {          for (User usersDatum : userRepository.findAll())          {              usersData.add(new User(                      usersDatum.getId(),                      usersDatum.getLogin(),                      usersDatum.getPassword(),                      usersDatum.getSurname(),                      usersDatum.getName()));          }          tableUsers.setItems(usersData);      }  }  

Then I made a repository and a database query and tried to output it to the console. Happened!

@Repository  public interface UserRepository extends JpaRepository<User, Long>  {      @Query(value = "select * from users2", nativeQuery = true)      List<User> findAll();  }  
<Button mnemonicParsing="false" prefHeight="30.0" prefWidth="75.0"  text="Load" onAction="#displayData">  

We are connecting to the database using Spring. Can you please tell me how in this situation, when you click on the button, display all the data in the tableview?

Android developer: how to detect when WiFI hotspot is turned on/off

Posted: 26 Sep 2021 08:06 AM PDT

I have registered ConnectivityManager NetworkCallback as follows:

val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager          val builder = NetworkRequest.Builder()              .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)  cm.registerNetworkCallback(                  builder.build(),                  object : ConnectivityManager.NetworkCallback() {                        override fun onAvailable(network: Network) {                          super.onAvailable(network)                          Log.i(TAG, "Network $network is available")                      }                        override fun onLosing(network: Network, maxMsToLive: Int) {                          super.onLosing(network, maxMsToLive)                          Log.i(TAG, "Network $network is losing after $maxMsToLive ms")                      }                        override fun onLost(network: Network) {                          super.onLost(network)                          Log.i(TAG, "Network $network is lost")                      }                        override fun onCapabilitiesChanged(network: Network, caps: NetworkCapabilities) {                          super.onCapabilitiesChanged(network, caps)                          Log.i(TAG, "Network $network capabilities changed: $caps")                      }                        override fun onLinkPropertiesChanged(network: Network, props: LinkProperties) {                          super.onLinkPropertiesChanged(network, props)                          Log.i(TAG, "Network $network link properties changed: $props")                      }                  }      }  

When I turn hotspot on/off in my Android 11 device, none of the CallBack functions are called, i.e., I don't get any messages to logcat, when I turn WiFi hotspot on/off.

When hotspot is off, device has these addresses:

PAN_sprout:/ $ ip addr                                                          1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1      link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00      inet 127.0.0.1/8 scope host lo         valid_lft forever preferred_lft forever      inet6 ::1/128 scope host         valid_lft forever preferred_lft forever  2: dummy0: <BROADCAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default qlen 1000      link/ether 46:85:2d:8f:9a:8e brd ff:ff:ff:ff:ff:ff      inet6 fe80::4485:2dff:fe8f:9a8e/64 scope link         valid_lft forever preferred_lft forever  3: ip_vti0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1      link/ipip 0.0.0.0 brd 0.0.0.0  4: ip6_vti0@NONE: <NOARP> mtu 1500 qdisc noop state DOWN group default qlen 1      link/tunnel6 :: brd ::  5: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1      link/sit 0.0.0.0 brd 0.0.0.0  6: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1      link/tunnel6 :: brd ::  8: rmnet0: <UP,LOWER_UP> mtu 2000 qdisc pfifo_fast state UNKNOWN group default qlen 1000      link/[530]  9: rmnet_data0: <UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 1000      link/[530]      inet6 fe80::9e2:b3d5:84e6:14c/64 scope link         valid_lft forever preferred_lft forever  10: rmnet_data1: <UP,LOWER_UP> mtu 1464 qdisc htb state UNKNOWN group default qlen 1000      link/[530]      inet 10.140.85.190/30 scope global rmnet_data1         valid_lft forever preferred_lft forever      inet6 2001:14bb:a0:5545:818d:5109:4166:b991/64 scope global dynamic mngtmpaddr         valid_lft forever preferred_lft forever      inet6 fe80::818d:5109:4166:b991/64 scope link         valid_lft forever preferred_lft forever  ...  25: r_rmnet_data8: <> mtu 1500 qdisc noop state DOWN group default qlen 1000      link/[530]  

and when I turn it on, device has these addresses:

PAN_sprout:/ $ ip addr                                                          1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1      link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00      inet 127.0.0.1/8 scope host lo         valid_lft forever preferred_lft forever      inet6 ::1/128 scope host         valid_lft forever preferred_lft forever  2: dummy0: <BROADCAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN group default qlen 1000      link/ether 46:85:2d:8f:9a:8e brd ff:ff:ff:ff:ff:ff      inet6 fe80::4485:2dff:fe8f:9a8e/64 scope link         valid_lft forever preferred_lft forever  3: ip_vti0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1      link/ipip 0.0.0.0 brd 0.0.0.0  4: ip6_vti0@NONE: <NOARP> mtu 1500 qdisc noop state DOWN group default qlen 1      link/tunnel6 :: brd ::  5: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1      link/sit 0.0.0.0 brd 0.0.0.0  6: ip6tnl0@NONE: <NOARP> mtu 1452 qdisc noop state DOWN group default qlen 1      link/tunnel6 :: brd ::  8: rmnet0: <UP,LOWER_UP> mtu 2000 qdisc pfifo_fast state UNKNOWN group default qlen 1000      link/[530]  9: rmnet_data0: <UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 1000      link/[530]      inet6 fe80::9e2:b3d5:84e6:14c/64 scope link         valid_lft forever preferred_lft forever  10: rmnet_data1: <UP,LOWER_UP> mtu 1464 qdisc htb state UNKNOWN group default qlen 1000      link/[530]      inet 10.140.85.190/30 scope global rmnet_data1         valid_lft forever preferred_lft forever      inet6 2001:14bb:a0:5545:818d:5109:4166:b991/64 scope global dynamic mngtmpaddr         valid_lft forever preferred_lft forever      inet6 fe80::818d:5109:4166:b991/64 scope link         valid_lft forever preferred_lft forever  ...  25: r_rmnet_data8: <> mtu 1500 qdisc noop state DOWN group default qlen 1000      link/[530]  176: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000      link/ether 7a:d1:a3:76:b8:8a brd ff:ff:ff:ff:ff:ff      inet 192.168.214.149/24 brd 192.168.214.255 scope global wlan0         valid_lft forever preferred_lft forever      inet6 2001:14bb:a0:5545::5a/64 scope global         valid_lft forever preferred_lft forever      inet6 fe80::78d1:a3ff:fe76:b88a/64 scope link         valid_lft forever preferred_lft forever  

As you see, wlan0 was added, but no callback function was called. Callback functions do work otherwise, for example, when I turn cellular network on/off.

Question is: what do I need to do in order to get callback functions called when WiFi hotspot is turned on/off.

Edit: Based on Sergio Pardo's answer, I created this:

val hotSpotReceiver = object : BroadcastReceiver() {              override fun onReceive(contxt: Context, intent: Intent) {                  val action = intent.action                  if ("android.net.wifi.WIFI_AP_STATE_CHANGED" == action) {                      val state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0)                      if (WifiManager.WIFI_STATE_ENABLED == state % 10)                          Log.d(TAG, "HotSpot is enabled")                      else                          Log.d(TAG, "HotSpot is disabled")                      }                  }              }          }  this.registerReceiver(hotSpotReceiver,      IntentFilter("android.net.wifi.WIFI_AP_STATE_CHANGED"))  

It can be used to detect when WiFi hotspot is enabled or disabled and answers the title of the question. But it does not help in getting the NetworkCallbacks called.

The callbacks would have allowed me to learn hotspot's local IP address and interface name. Is there some other way to figure that out?

Edit: It turned out that when the above hotSpotReceiver logs "Hotspot is enabled", there is delay before the hotspot interface gets its IP addresses and routes. The missing network callbacks would help.

List of natural numbers = > returns booleans

Posted: 26 Sep 2021 08:07 AM PDT

Write a function that receives a list of natural numbers as a parameter and returns a list of Booleans. If a number in the list is even, then we will add True to the final list; for odd numbers we add False.

My attempt:

def my_int_list(list):      new_list= []      for num in list:          if num % 2 == 0:              num = True              new_list.append(num)          elif num % 2 != 0:              num = False              new_list.append(num)        my_list=[2,5,8]    print(my_int_list(my_list))  

Calculating R2 Score and RMSE using K-Fold Cross Validation

Posted: 26 Sep 2021 08:06 AM PDT

In the below mentioned code, I am performing a Non-Linear Regression using Random Forest Regressor.

I am taking Train, Test, Split to Evaluate my Model using R2 Score, RMSE and MAPE. Now, I want to Evaluate my Model using K-Fold Cross Validation which I have divided into 4 Splits. Can you please help me out as to how shall I calculate the Mean R2 Score, RMSE and MAPE of the 4 Splits which I have done as part of the K-Fold Cross Validation?

# STEP 1: IMPORTING THE REQUIRED LIBRARIES AND MODULES  import pandas as pd  import numpy as np  from sklearn.tree import DecisionTreeRegressor  from sklearn.metrics import r2_score  from sklearn.model_selection import train_test_split  from sklearn.metrics import mean_squared_error  from sklearn import preprocessing  from sklearn.metrics import mean_absolute_percentage_error  from sklearn.ensemble import RandomForestRegressor  from sklearn.model_selection import KFold  import matplotlib.pyplot as plt  import seaborn as sns  from sklearn.svm import SVR  from sklearn.feature_selection import RFE, SelectFromModel  from sklearn.model_selection import cross_val_score  from sklearn import model_selection  import math    # STEP 2: READING THE DATA AND PERFORMING BASIC DATA CHECKS  path = "C:/AKHIL/OTHER/MISSION_INTERNSHIP/Space4Good/DATA_FOR_MODELING_2.xlsx"  sheet_1 = pd.read_excel(path, sheet_name='Model Development')  sheet_2 = pd.read_excel(path, sheet_name='Validation Data')  x_validation = sheet_2.drop(['ID'], axis=1).values  print("STATISTICAL DESCRIPTION:")  print(sheet_1.describe(), "\n")    # STEP 3: CREATING ARRAYS FOR THE FEATURES AND THE RESPONSE VARIABLE  target_column = ['y', 'ID']  predictors = list(set(list(sheet_1.columns)) - set(target_column))    # STEP 4: PERFORMING NORMALIZATION VIA SCALING OF THE PREDICTORS BETWEEN 0 AND 1  scaler = preprocessing.MinMaxScaler(feature_range=(0, 1))  names = sheet_1[predictors].columns  d = scaler.fit_transform(sheet_1[predictors])  sheet_1[predictors] = pd.DataFrame(d, columns=names)  print("STATISTICAL DESCRIPTION AFTER NORMALIZATION:")  print(sheet_1.describe())    # STEP 5: CREATING TRAINING AND TEST DATASETS  X = sheet_1[predictors]  # ALL THESE VALUES ARE NORMALIZED  y = sheet_1['y']  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)  print(X_train.shape)  print(X_test.shape)    # STEP 6: BUILD, PREDICT AND EVALUATE THE MODELS USING DECISION TREE ALGORITHM  dtree = RandomForestRegressor(n_estimators=500, oob_score=True, random_state=0)  print(dtree.fit(X_train, y_train))  pred_test_tree = dtree.predict(X_test)  print("EVALUATION ON TEST SET:", "\n")  print("RMSE:", np.sqrt(mean_squared_error(y_test, pred_test_tree)))  print("R2 SCORE:", r2_score(y_test, pred_test_tree))  print("MAPE:", mean_absolute_percentage_error(y_test, pred_test_tree), "\n")    # STEP 7: K-FOLD CROSS VALIDATION  kf = KFold(n_splits=4)    for train_index, test_index in kf.split(X):      print("TRAIN:", train_index, "TEST:", test_index)  

Change header name for each column in tableau

Posted: 26 Sep 2021 08:05 AM PDT

I have a data with ID's and their qualification such as certifications, Advance degree only, Multiple degrees and Single certification in a Yes/No format

I am trying to show the data in 4 bar charts like 1) No Certifications (3) 2) Only Advance Degree (6) 3) Single certifications (17) and 4) Multiple Degree (19). Counts are mentioned in the bracket.

I need to rename each column with the above-mentioned header name. However, if change name of one column, the other column name also changes. Kindly suggest adding an individual name for each column.

The graph looks like below.

enter image description here

ID  Certifications  AdvanceDegree only  Single Cert  MutipleDegree  1       Yes                No                No         Yes  2       Yes                No                Yes        No  3       Yes                No                No         Yes  4       Yes                No                No         Yes  5       Yes                No                No         Yes  6       Yes                No                No         Yes  

how to open file:///private/var/mobile/Containers/Shared/AppGroup/ folder on mac

Posted: 26 Sep 2021 08:05 AM PDT

I'm trying to use fileProvider in iOS 11, and I have a database on device at file:///private/var/mobile/Containers/Shared/AppGroup/xxxx/xxx.db

I would like to open this folder in order to open this database by SQLite manage. How to do this?

thanks a lot

Error while building bundle in maven

Posted: 26 Sep 2021 08:05 AM PDT

I am trying to build a bundle from existing maven project which is in eclipse. I have most of the repository dependencies, still though it tries to download a few dependencies. after that it give list of errors which is below.Can anybody tell how to remove existing errors and build a bundle successfully. I am building the bundle for Adobe Aem aq5 tool where it accepts jar files as bundles to be installed.

    [ERROR] Unresolveable build extension: Plugin org.apache.felix:maven-bundle-plug  in:2.3.7 or one of its dependencies could not be resolved: The following artifac  ts could not be resolved: org.apache.maven:maven-core:jar:2.0.7, org.apache.mave  n:maven-settings:jar:2.0.7, org.apache.maven:maven-plugin-parameter-documenter:j  ar:2.0.7, org.apache.maven:maven-profile:jar:2.0.7, org.apache.maven:maven-model  :jar:2.0.7, org.apache.maven:maven-artifact:jar:2.0.7, org.codehaus.plexus:plexu  s-container-default:jar:1.0-alpha-9-stable-1, org.apache.maven:maven-repository-  metadata:jar:2.0.7, org.apache.maven:maven-error-diagnostics:jar:2.0.7, org.apac  he.maven:maven-project:jar:2.0.7, org.apache.maven:maven-plugin-registry:jar:2.0  .7, org.apache.maven:maven-plugin-descriptor:jar:2.0.7, org.apache.maven:maven-a  rtifact-manager:jar:2.0.7, org.apache.maven:maven-monitor:jar:2.0.7, classworlds  :classworlds:jar:1.1: Could not transfer artifact org.apache.maven:maven-core:ja  r:2.0.7 from/to adobe (http://repo.adobe.com/nexus/content/groups/public/): sun.  security.validator.ValidatorException: PKIX path building failed: sun.security.p  rovider.certpath.SunCertPathBuilderException: unable to find valid certification   path to requested target @  [ERROR] Unknown packaging: bundle @ com.lundbeck.master.nohmatters:nohmatters-bu  ndle:[unknown-version], D:\CODEBASE\nohmatters\bundle\pom.xml, line 19, column 1  6   @  [ERROR] The build could not read 1 project -> [Help 1]  [ERROR]  [ERROR]   The project com.lundbeck.master.nohmatters:nohmatters-bundle:1.0.0-SNA  PSHOT (D:\CODEBASE\nohmatters\bundle\pom.xml) has 2 errors  [ERROR]     Unresolveable build extension: Plugin org.apache.felix:maven-bundle-  plugin:2.3.7 or one of its dependencies could not be resolved: The following art  ifacts could not be resolved: org.apache.maven:maven-core:jar:2.0.7, org.apache.  maven:maven-settings:jar:2.0.7, org.apache.maven:maven-plugin-parameter-document  er:jar:2.0.7, org.apache.maven:maven-profile:jar:2.0.7, org.apache.maven:maven-m  odel:jar:2.0.7, org.apache.maven:maven-artifact:jar:2.0.7, org.codehaus.plexus:p  lexus-container-default:jar:1.0-alpha-9-stable-1, org.apache.maven:maven-reposit  ory-metadata:jar:2.0.7, org.apache.maven:maven-error-diagnostics:jar:2.0.7, org.  apache.maven:maven-project:jar:2.0.7, org.apache.maven:maven-plugin-registry:jar  :2.0.7, org.apache.maven:maven-plugin-descriptor:jar:2.0.7, org.apache.maven:mav  en-artifact-manager:jar:2.0.7, org.apache.maven:maven-monitor:jar:2.0.7, classwo  rlds:classworlds:jar:1.1: Could not transfer artifact org.apache.maven:maven-cor  e:jar:2.0.7 from/to adobe (http://repo.adobe.com/nexus/content/groups/public/):  sun.security.validator.ValidatorException: PKIX path building failed: sun.securi  ty.provider.certpath.SunCertPathBuilderException: unable to find valid certifica  tion path to requested target -> [Help 2]    [ERROR]     Unknown packaging: bundle @ com.lundbeck.master.nohmatters:nohmatter  s-bundle:[unknown-version], D:\CODEBASE\nohmatters\bundle\pom.xml, line 19, colu  mn 16  

my pom.xml is as following:

<?xml version="1.0" encoding="UTF-8"?>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">      <modelVersion>4.0.0</modelVersion>      <!-- ====================================================================== -->      <!-- P A R E N T P R O J E C T D E S C R I P T I O N -->      <!-- ====================================================================== -->      <parent>          <groupId>com.lundbeck.master.nohmatters</groupId>          <artifactId>nohmatters</artifactId>          <version>1.0.0-SNAPSHOT</version>      </parent>        <!-- ====================================================================== -->      <!-- P R O J E C T D E S C R I P T I O N -->      <!-- ====================================================================== -->        <artifactId>nohmatters-bundle</artifactId>      <packaging>bundle</packaging>      <name>nohmatters Bundle</name>        <dependencies>          <dependency>              <groupId>org.osgi</groupId>              <artifactId>org.osgi.compendium</artifactId>          </dependency>          <dependency>              <groupId>org.osgi</groupId>              <artifactId>org.osgi.core</artifactId>          </dependency>          <dependency>              <groupId>org.apache.felix</groupId>              <artifactId>org.apache.felix.scr.annotations</artifactId>          </dependency>          <dependency>              <groupId>biz.aQute</groupId>              <artifactId>bndlib</artifactId>          </dependency>          <dependency>              <groupId>org.slf4j</groupId>              <artifactId>slf4j-api</artifactId>          </dependency>          <dependency>              <groupId>junit</groupId>              <artifactId>junit</artifactId>          </dependency>          <dependency>              <groupId>javax.servlet</groupId>              <artifactId>servlet-api</artifactId>          </dependency>          <dependency>              <groupId>javax.jcr</groupId>              <artifactId>jcr</artifactId>          </dependency>           <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.api</artifactId>          </dependency>          <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.jcr.api</artifactId>          </dependency>          <dependency>              <groupId>com.day.cq.wcm</groupId>              <artifactId>cq-wcm-workflow-api</artifactId>              <version>5.3.0</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>com.day.cq.wcm</groupId>              <artifactId>cq-wcm-api</artifactId>              <version>5.5.0</version>          </dependency>          <dependency>              <groupId>com.day.cq</groupId>              <artifactId>cq-commons</artifactId>              <version>5.5.0</version>          </dependency>          <dependency>              <groupId>commons-lang</groupId>              <artifactId>commons-lang</artifactId>              <version>2.4</version>          </dependency>          <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.commons.json</artifactId>              <version>2.0.6</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>com.day.cq</groupId>              <artifactId>cq-mailer</artifactId>              <version>5.5.0</version>           </dependency>            <dependency>              <groupId>com.day.cq</groupId>              <artifactId>cq-search</artifactId>              <version>5.5.4</version>          </dependency>          <dependency>              <groupId>com.adobe.granite</groupId>              <artifactId>com.adobe.granite.xssprotection</artifactId>          </dependency>          <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.resourceresolver</artifactId>          </dependency>          <dependency>                  <groupId>org.apache.sling</groupId>                  <artifactId>org.apache.sling.api</artifactId>                  <version>2.9.0</version>                  <scope>provided</scope>              </dependency>                 <dependency>                          <groupId>com.itextpdf</groupId>                          <artifactId>itextpdf</artifactId>                          <version>5.5.6</version>                  </dependency>                  <dependency>                          <groupId>com.itextpdf.tool</groupId>                          <artifactId>xmlworker</artifactId>                          <version>5.5.6</version>                  </dependency>                  <dependency>             <groupId>com.jcraft</groupId>             <artifactId>jsch</artifactId>             <version>0.1.53</version>             <scope>compile</scope>          </dependency>              <dependency>      <groupId>com.jcraft</groupId>      <artifactId>jzlib</artifactId>      <version>1.1.3</version>  </dependency>   <dependency>      <groupId>org.apache.commons</groupId>      <artifactId>commons-io</artifactId>      <version>1.3.2</version>  </dependency>  <dependency>      <groupId>com.google.code.gson</groupId>      <artifactId>gson</artifactId>      <version>2.3</version>  </dependency>  <dependency>      <groupId>com.adobe.aem</groupId>      <artifactId>uber-jar</artifactId>      <version>6.1.0</version>      <classifier>obfuscated-apis</classifier>      <scope>provided</scope>  </dependency>      </dependencies>        <!-- ====================================================================== -->      <!-- B U I L D D E F I N I T I O N -->      <!-- ====================================================================== -->      <build>          <plugins>              <plugin>                  <groupId>org.apache.felix</groupId>                  <artifactId>maven-scr-plugin</artifactId>                  <executions>                      <execution>                          <id>generate-scr-descriptor</id>                          <goals>                              <goal>scr</goal>                          </goals>                      </execution>                  </executions>              </plugin>              <plugin>                  <groupId>org.apache.felix</groupId>                  <artifactId>maven-bundle-plugin</artifactId>                  <extensions>true</extensions>                  <configuration>                      <instructions>                          <Bundle-SymbolicName>com.lundbeck.master.nohmatters.nohmatters-bundle</Bundle-SymbolicName>                          <Import-Package>org.osgi.framework,*</Import-Package>                          <Export-Package>com.lundbeck.master.nohmatters.*,com.lundbeck.master.nohmatters.servlet.EmailServlet,com.jcraft.*;com.jcraft.jzlib</Export-Package>                          <Include-Resource>{maven-resources}</Include-Resource>                          <Import-Bundle>*</Import-Bundle>                          <Embed-Dependency>gson</Embed-Dependency>                          <Embed-Transitive>true</Embed-Transitive>                          <Private-Package>com.lundbeck.master.nohmatters.servlet.*,com.jcraft.*</Private-Package>                      </instructions>                  </configuration>              </plugin>              <plugin>                  <groupId>org.apache.sling</groupId>                  <artifactId>maven-sling-plugin</artifactId>                  <configuration>                      <slingUrl>http://${crx.host}:${crx.port}/apps/nohmatters/install</slingUrl>                      <usePut>true</usePut>                  </configuration>              </plugin>              <plugin>                  <groupId>org.apache.maven.plugins</groupId>                  <artifactId>maven-javadoc-plugin</artifactId>                   <configuration>                      <excludePackageNames>                          *.impl                      </excludePackageNames>                   </configuration>              </plugin>          </plugins>      </build>  </project>  <?xml version="1.0" encoding="UTF-8"?>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">      <modelVersion>4.0.0</modelVersion>      <!-- ====================================================================== -->      <!-- P A R E N T P R O J E C T D E S C R I P T I O N -->      <!-- ====================================================================== -->      <parent>          <groupId>com.lundbeck.master.nohmatters</groupId>          <artifactId>nohmatters</artifactId>          <version>1.0.0-SNAPSHOT</version>      </parent>        <!-- ====================================================================== -->      <!-- P R O J E C T D E S C R I P T I O N -->      <!-- ====================================================================== -->        <artifactId>nohmatters-bundle</artifactId>      <packaging>bundle</packaging>      <name>nohmatters Bundle</name>        <dependencies>          <dependency>              <groupId>org.osgi</groupId>              <artifactId>org.osgi.compendium</artifactId>          </dependency>          <dependency>              <groupId>org.osgi</groupId>              <artifactId>org.osgi.core</artifactId>          </dependency>          <dependency>              <groupId>org.apache.felix</groupId>              <artifactId>org.apache.felix.scr.annotations</artifactId>          </dependency>          <dependency>              <groupId>biz.aQute</groupId>              <artifactId>bndlib</artifactId>          </dependency>          <dependency>              <groupId>org.slf4j</groupId>              <artifactId>slf4j-api</artifactId>          </dependency>          <dependency>              <groupId>junit</groupId>              <artifactId>junit</artifactId>          </dependency>          <dependency>              <groupId>javax.servlet</groupId>              <artifactId>servlet-api</artifactId>          </dependency>          <dependency>              <groupId>javax.jcr</groupId>              <artifactId>jcr</artifactId>          </dependency>           <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.api</artifactId>          </dependency>          <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.jcr.api</artifactId>          </dependency>          <dependency>              <groupId>com.day.cq.wcm</groupId>              <artifactId>cq-wcm-workflow-api</artifactId>              <version>5.3.0</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>com.day.cq.wcm</groupId>              <artifactId>cq-wcm-api</artifactId>              <version>5.5.0</version>          </dependency>          <dependency>              <groupId>com.day.cq</groupId>              <artifactId>cq-commons</artifactId>              <version>5.5.0</version>          </dependency>          <dependency>              <groupId>commons-lang</groupId>              <artifactId>commons-lang</artifactId>              <version>2.4</version>          </dependency>          <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.commons.json</artifactId>              <version>2.0.6</version>              <scope>provided</scope>          </dependency>          <dependency>              <groupId>com.day.cq</groupId>              <artifactId>cq-mailer</artifactId>              <version>5.5.0</version>           </dependency>            <dependency>              <groupId>com.day.cq</groupId>              <artifactId>cq-search</artifactId>              <version>5.5.4</version>          </dependency>          <dependency>              <groupId>com.adobe.granite</groupId>              <artifactId>com.adobe.granite.xssprotection</artifactId>          </dependency>          <dependency>              <groupId>org.apache.sling</groupId>              <artifactId>org.apache.sling.resourceresolver</artifactId>          </dependency>          <dependency>                  <groupId>org.apache.sling</groupId>                  <artifactId>org.apache.sling.api</artifactId>                  <version>2.9.0</version>                  <scope>provided</scope>              </dependency>                 <dependency>                          <groupId>com.itextpdf</groupId>                          <artifactId>itextpdf</artifactId>                          <version>5.5.6</version>                  </dependency>                  <dependency>                          <groupId>com.itextpdf.tool</groupId>                          <artifactId>xmlworker</artifactId>                          <version>5.5.6</version>                  </dependency>                  <dependency>             <groupId>com.jcraft</groupId>             <artifactId>jsch</artifactId>             <version>0.1.53</version>             <scope>compile</scope>          </dependency>              <dependency>      <groupId>com.jcraft</groupId>      <artifactId>jzlib</artifactId>      <version>1.1.3</version>  </dependency>   <dependency>      <groupId>org.apache.commons</groupId>      <artifactId>commons-io</artifactId>      <version>1.3.2</version>  </dependency>  <dependency>      <groupId>com.google.code.gson</groupId>      <artifactId>gson</artifactId>      <version>2.3</version>  </dependency>  <dependency>      <groupId>com.adobe.aem</groupId>      <artifactId>uber-jar</artifactId>      <version>6.1.0</version>      <classifier>obfuscated-apis</classifier>      <scope>provided</scope>  </dependency>      </dependencies>        <!-- ====================================================================== -->      <!-- B U I L D D E F I N I T I O N -->      <!-- ====================================================================== -->      <build>          <plugins>              <plugin>                  <groupId>org.apache.felix</groupId>                  <artifactId>maven-scr-plugin</artifactId>                  <executions>                      <execution>                          <id>generate-scr-descriptor</id>                          <goals>                              <goal>scr</goal>                          </goals>                      </execution>                  </executions>              </plugin>              <plugin>                  <groupId>org.apache.felix</groupId>                  <artifactId>maven-bundle-plugin</artifactId>                  <extensions>true</extensions>                  <configuration>                      <instructions>                          <Bundle-SymbolicName>com.lundbeck.master.nohmatters.nohmatters-bundle</Bundle-SymbolicName>                          <Import-Package>org.osgi.framework,*</Import-Package>                          <Export-Package>com.lundbeck.master.nohmatters.*,com.lundbeck.master.nohmatters.servlet.EmailServlet,com.jcraft.*;com.jcraft.jzlib</Export-Package>                          <Include-Resource>{maven-resources}</Include-Resource>                          <Import-Bundle>*</Import-Bundle>                          <Embed-Dependency>gson</Embed-Dependency>                          <Embed-Transitive>true</Embed-Transitive>                          <Private-Package>com.lundbeck.master.nohmatters.servlet.*,com.jcraft.*</Private-Package>                      </instructions>                  </configuration>              </plugin>              <plugin>                  <groupId>org.apache.sling</groupId>                  <artifactId>maven-sling-plugin</artifactId>                  <configuration>                      <slingUrl>http://${crx.host}:${crx.port}/apps/nohmatters/install</slingUrl>                      <usePut>true</usePut>                  </configuration>              </plugin>              <plugin>                  <groupId>org.apache.maven.plugins</groupId>                  <artifactId>maven-javadoc-plugin</artifactId>                   <configuration>                      <excludePackageNames>                          *.impl                      </excludePackageNames>                   </configuration>              </plugin>          </plugins>      </build>  </project>  

What do we mean by contextually autoescaping?

Posted: 26 Sep 2021 08:06 AM PDT

While reading about the Closure Templates I encountered the following statement:

Closure Templates are contextually autoescaped to reduce the risk of XSS.

As far as I know escaping is removing ambiguity in the input string as described here.

I am not sure what really that means, perhaps an explanation with real world example would be really helpful.

org.si.web.client.ResourceAccessException: I/O err: Connection refused

Posted: 26 Sep 2021 08:05 AM PDT

Exception in thread "main" org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://localhost:8081/FootballerShirt/footballerShirts": Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:525) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:473) at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:238) at com.aucklanduni.spring.hibernate.HibernateFootballerShirtDaoMain.main(HibernateFootballerShirtDaoMain.java:44) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at java.net.Socket.connect(Socket.java:528) at sun.net.NetworkClient.doConnect(NetworkClient.java:180) at sun.net.www.http.HttpClient.openServer(HttpClient.java:432) at sun.net.www.http.HttpClient.openServer(HttpClient.java:527) at sun.net.www.http.HttpClient.(HttpClient.java:211) at sun.net.www.http.HttpClient.New(HttpClient.java:308) at sun.net.www.http.HttpClient.New(HttpClient.java:326) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:996) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:932) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:850) at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76) at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:49) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:510) ... 3 more

No comments:

Post a Comment