问:
Spring Boot - log4j2.properties creating log files but not writing the logs in file
I have used log4j2.properties file with springboot application. Log file was creating but logs are not written into the file.

Please find the details as below:

log4j2.properties

```<code>name=PropertiesConfig
property.filename = C:/Logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/app.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=com.java.app //Parent Package name for the application
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
</code>```

POM.XML

```<code><!-- Logging -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
         </dependency>

         <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.11.1</version>
    </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.11.1</version>
    </dependency>
</code>```

DemoApplication.java

```<code>package com.java.app;

    @SpringBootApplication
    public class DemoApplication extends SpringBootServletInitializer {

      private final static Logger log = LogManager.getLogger(DemoApplication.class);

      @Override
      protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

        return application.sources(DemoApplication.class);
      }

      public static void main(String[] args) {

        log.info("Logger enabled: Entering main \\n\\n");
        SpringApplication.run(DemoApplication.class, args);
        log.info("**** Demo Application Started *****");

      }

    }
</code>```

Logs are appearing in the console but not written into file as i am not getting the issue.

It's strange, parent package logger "Logger enabled: Entering main \n\n" is written into the file and the other parent logger "**** Demo Application Started *****" is not written into the file as the code is shown above. and also checked for the sub package i.e com.java.app.endpoint loggers even those also not written into the file.

and also identified that the console log is coming like as

2018-08-03 12:55:18.302  INFO 11440 --- [nio-8088-exec-1] c.j.c.e.Classname : logger message

If c.j.c.e. coming as prefix to the class name in logs those are not written into the file why?

I might be doing something wrong. Can anyone please help on this.

答:
Spring Boot supports Log4j 2 for logging configuration, you can get how to configure from Configure Log4j for Logging

First you need to exclude spring boot logging

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
</code>```

Then have log4j2.json or log4j2.xml or log4j2.yaml in your src/main/resources

Body:
I have used log4j2.properties file with springboot application. Log file was creating but logs are not written into the file.

Please find the details as below:

log4j2.properties

name=PropertiesConfig
property.filename = C:/Logs
appenders = console, file

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LOGFILE
appender.file.fileName=${filename}/app.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

loggers=file
logger.file.name=com.java.app //Parent Package name for the application
logger.file.level = debug
logger.file.appenderRefs = file
logger.file.appenderRef.file.ref = LOGFILE

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

POM.XML

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
         </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.11.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.11.1</version>
    </dependency>

DemoApplication.java

package com.java.app;

    @SpringBootApplication
    public class DemoApplication extends SpringBootServletInitializer {

      private final static Logger log = LogManager.getLogger(DemoApplication.class);

      @Override
      protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

        return application.sources(DemoApplication.class);
      }

      public static void main(String[] args) {

        log.info("Logger enabled: Entering main \\n\\n");
        SpringApplication.run(DemoApplication.class, args);
        log.info("**** Demo Application Started *****");

      }

    }

Logs are appearing in the console but not written into file as i am not getting the issue.

It's strange, parent package logger "Logger enabled: Entering main \n\n" is written into the file and the other parent logger "**** Demo Application Started *****" is not written into the file as the code is shown above. and also checked for the sub package i.e com.java.app.endpoint loggers even those also not written into the file.

and also identified that the console log is coming like as

2018-08-03 12:55:18.302  INFO 11440 --- [nio-8088-exec-1] c.j.c.e.Classname : logger message

If c.j.c.e. coming as prefix to the class name in logs those are not written into the file why?

I might be doing something wrong. Can anyone please help on this.

Body:
Spring Boot supports Log4j 2 for logging configuration, you can get how to configure from Configure Log4j for Logging

First you need to exclude spring boot logging

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Then have log4j2.json or log4j2.xml or log4j2.yaml in your src/main/resources


来源: stackexchange

问:
How can I find the location visited by all employees in this sql table?
I have a sql table that looks like this:

```<code>CREATE TABLE `location_visits` (
  `employee1_name` varchar(255) NOT NULL,
  `employee2_name` varchar(255) NOT NULL,
  `region_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee1_name`,`employee2_name`),
  CONSTRAINT `location_visits_fk1` FOREIGN KEY (`employee1_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `location_visits_fk2` FOREIGN KEY (`employee2_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
)
</code>```

Employees go to places together in pairs, sort of like a buddy system. I want to find the region(s) that has been visited by all employees.

If it helps, I also have a table that lists all of my employees:

```<code>CREATE TABLE `employees` (
  `employee_name` varchar(255) NOT NULL,
  PRIMARY KEY ('employee_name')
)
</code>```

All these tables are loaded with data, of course. So, an example for data that would be valid for location_visits table is (John, Chris, Maine), (John, Adam, New Hampshire), (Adam, Chris, Maine). In this scenario, the location visited by all employees Adam, Chris, John is Maine.

What kind of sql command would do this for me?

答:
You need to get the count of all distinct employees from each region and get the regions that have the total number of employees equal to the ones present in the employee table. Your query should look something like this:

```<code>SELECT COUNT(employee1_name), region_name FROM
  (SELECT DISTINCT employee1_name, region_name FROM
  (SELECT DISTINCT employee1_name, region_name FROM location_visits
UNION
SELECT DISTINCT employee2_name, region_name FROM location_visits))
GROUP BY region_name
HAVING COUNT(employee1_name) =
       (SELECT COUNT(DISTINCT employee_name) FROM employees);
</code>```

Hope this helps!

ContentLicense: CC BY-SA 4.0

Body:
I have a sql table that looks like this:

CREATE TABLE `location_visits` (
  `employee1_name` varchar(255) NOT NULL,
  `employee2_name` varchar(255) NOT NULL,
  `region_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`employee1_name`,`employee2_name`),
  CONSTRAINT `location_visits_fk1` FOREIGN KEY (`employee1_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `location_visits_fk2` FOREIGN KEY (`employee2_name`) REFERENCES `employees` (`employee_name`) ON DELETE CASCADE ON UPDATE CASCADE,
)

Employees go to places together in pairs, sort of like a buddy system. I want to find the region(s) that has been visited by all employees.

If it helps, I also have a table that lists all of my employees:

CREATE TABLE `employees` (
  `employee_name` varchar(255) NOT NULL,
  PRIMARY KEY ('employee_name')
)

All these tables are loaded with data, of course. So, an example for data that would be valid for location_visits table is (John, Chris, Maine), (John, Adam, New Hampshire), (Adam, Chris, Maine). In this scenario, the location visited by all employees Adam, Chris, John is Maine.

What kind of sql command would do this for me?

Body:
You need to get the count of all distinct employees from each region and get the regions that have the total number of employees equal to the ones present in the employee table. Your query should look something like this:

SELECT COUNT(employee1_name), region_name FROM
  (SELECT DISTINCT employee1_name, region_name FROM
  (SELECT DISTINCT employee1_name, region_name FROM location_visits
UNION
SELECT DISTINCT employee2_name, region_name FROM location_visits))
GROUP BY region_name
HAVING COUNT(employee1_name) =
       (SELECT COUNT(DISTINCT employee_name) FROM employees);

Hope this helps!


问:
How to find value from data’s index?
I have the data:

```<code>0101400
0102500
0103300
0202500
0205600
etc
</code>```

How to get value from index data in javascript

```<code>0101 value 400
0102 value 500
0103 value 300
0202 value 500
0205 value 600
</code>```

Please help, thank you..

答:
You can use the followingRegExp with String.protoype.replace

let data = '0101400 0102500 0103300 0202500 0205600';
let output = data.replace(/(\d{4})(\d{3})\s?/g, '$1 value $2 \n');
console.log(output)```

Title: How to find value from data’s index?

Body:
I have the data:

0101400
0102500
0103300
0202500
0205600
etc

How to get value from index data in javascript

0101 value 400
0102 value 500
0103 value 300
0202 value 500
0205 value 600

Please help, thank you..


问:
Use different library module for each android flavor
I want to use a different library module for each flavor.

For example:

free flavor -> I need to use the free library module

paid flavor -> I need to use the paid library module

My flavors

```<code>productFlavors {
    free{
     .......
     }
    paid{
     .......
     }
   }
</code>```

What I tried

```<code>freeImplementation  project(path:':freeLib', configuration: 'free')//for free

paidImplementation  project(path:':paidLib', configuration: 'paid')//for paid
</code>```

But I got compile error not able to use this

Note: It's not a duplicate question. I already tried some StackOverflow questions. It's outdated (they are using compile)

Reference - Multi flavor app based on multi flavor library in Android Gradle

Solution (from Gabriele Mariotti comments)

```<code> freeImplementation project(path:':freeLib')
 paidImplementation project(path:':paidLib')
</code>```

答:
If you have a library with multiple product flavors, in your lib/build.gradle you can define:

```<code>android {
    ...
    //flavorDimensions is mandatory with flavors.
    flavorDimensions "xxx"
    productFlavors {
        free{
            dimension "xxx"
        }
        paid{
            dimension "xxx"
        }
    }
    ...
}
</code>```

In your app/build.gradle define:

```<code>android {
    ...

    flavorDimensions "xxx"
    productFlavors {
        free{
            dimension "xxx"

            // App and library's flavor have the same name.
            // MatchingFallbacks can be omitted
            matchingFallbacks = ["free"]
        }
        paid{
            dimension "xxx"

            matchingFallbacks = ["paid"]
        }
    }
    ...
}
dependencies {
    implementation project(':mylib')
}
</code>```

Instead, if you have separate libraries you can simply use in your app/build.gradle something like:

```<code>dependencies {
    freeImplementation project(':freeLib')
    paidImplementation project(':paidLib')
}
</code>```

Body:
I want to use a different library module for each flavor.

For example:

free flavor -> I need to use the free library module

paid flavor -> I need to use the paid library module

My flavors

productFlavors {
    free{
     .......
     }
    paid{
     .......
     }
   }

What I tried

freeImplementation  project(path:':freeLib', configuration: 'free')//for free

paidImplementation  project(path:':paidLib', configuration: 'paid')//for paid

But I got compile error not able to use this

Note: It's not a duplicate question. I already tried some StackOverflow questions. It's outdated (they are using compile)

Reference - Multi flavor app based on multi flavor library in Android Gradle

Solution (from Gabriele Mariotti comments)

 freeImplementation project(path:':freeLib')
 paidImplementation project(path:':paidLib')

Body:
If you have a library with multiple product flavors, in your lib/build.gradle you can define:

android {
    ...
    //flavorDimensions is mandatory with flavors.
    flavorDimensions "xxx"
    productFlavors {
        free{
            dimension "xxx"
        }
        paid{
            dimension "xxx"
        }
    }
    ...
}

In your app/build.gradle define:

android {
    ...

    flavorDimensions "xxx"
    productFlavors {
        free{
            dimension "xxx"

            // App and library's flavor have the same name.
            // MatchingFallbacks can be omitted
            matchingFallbacks = ["free"]
        }
        paid{
            dimension "xxx"

            matchingFallbacks = ["paid"]
        }
    }
    ...
}
dependencies {
    implementation project(':mylib')
}

Instead, if you have separate libraries you can simply use in your app/build.gradle something like:

dependencies {
    freeImplementation project(':freeLib')
    paidImplementation project(':paidLib')
}


问:
KeyEvent to change photos dosen't work, how to activate it?
I want to make switching photo program, using imageView and keyEvent, but when I try to use keyEvent it dosen't work, I was trying add scene.getRoot().requestFocus(); but didn't help, so my question is, why it dosen't work any how could I activate it?

MenuScreenController.java

```<code>    @FXML
public void getNewImageHandler(KeyEvent event) {
    System.out.println(singleFile.getName());
    imgFieldView.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.N) {
            photoSwipCounter++;
            System.out.println("P clicked");
        } else if (e.getCode() == KeyCode.P) {
            photoSwipCounter--;
        }
    });

//        if (event.getCode().equals(KeyCode.N)) {
//            photoSwipCounter++;
//        }
//        if (event.getCode().equals(KeyCode.P)) {
//            photoSwipCounter--;
//        }

    if (photoSwipCounter < 0) {
        singleFile = selectedImgsList.get(selectedImgsList.size() - photoSwipCounter);
    } else {
        singleFile = selectedImgsList.get(photoSwipCounter);
    }

    image = new Image(singleFile.toURI().toString(),
            900, 400,
            true, true, true);
    imgFieldView.setImage(image);
}
</code>```

As you can see I was trying many methods, by stream, or classic, but it dosen't make change.

MenuScreen.fxml

```<code><Pane fx:id="menuPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="screensaverfxml.Controllers.MenuScreenController">
   <children>
      <ImageView fx:id="imgFieldView" fitHeight="400.0" fitWidth="900.0" layoutX="66.0" layoutY="62.0" onKeyPressed="#getNewImageHandler" onMouseClicked="#imgDoubleClick" pickOnBounds="true" preserveRatio="true" />
   </children>
</Pane>
</code>```

ScreenSaverFXML.java

```<code>    @Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/screensaverfxml/fxmlConfig/MainScreen.fxml"));
    Pane mainPane = loader.load();
    Scene scene = new Scene(mainPane, 1000, 700);
    primaryStage.setScene(scene);
    primaryStage.setTitle("Screen Saver");

    primaryStage.show();

   scene.getRoot().requestFocus();
}
</code>```

And ofc I have method to load first photo on imageView and it's work by load it from the folder to the list, but switching to next nope

答:
Only nodes that have the focus receive key events. Since you have scene.getRoot().requestFocus() it's the root that receives the events. However, you're adding your EventHandler to imgFieldView and since that node is a descendant of the root it never sees any key events. You need to either have your imgFieldView obtain the focus or add your handler to the root node instead.

Note: You can only request focus once the target Node is part of a Scene.

The other problem is your call to imgFieldView.setOnKeyPressed(...) in the getNewImageHandler method. When you add an event handler via FXML, for instance by using onKeyPressed="#getNewImageHandler", it sets the corresponding onXXX property of the node. In your case, it's setting the onKeyPressed property of imgFieldView. However, in that handler you also set that property which replaces the handler set by the FXMLLoader. Your new handler simply increments or decrements the photoSwipeCounter field but does nothing with the new value. Your method should look more like:

```<code>@FXML
public void getNewImageHandler(KeyEvent event) {
    if (event.getCode().equals(KeyCode.N)) {
        photoSwipeCounter++;
    }
    if (event.getCode().equals(KeyCode.P)) {
        photoSwipeCounter--;
    }

    // wrap around logic
    if (photoSwipeCounter < 0) {
        photoSwipeCounter = selectedImgsList.size() - 1;
    } else if (photoSwipeCounter >= selectedImgsList.size()) {
        photoSwipeCounter = 0;
    }

    singleFile = selectedImgsList.get(photoSwipeCounter);

    image = new Image(singleFile.toURI().toString(),
            900, 400,
            true, true, true);
    imgFieldView.setImage(image);
}
</code>```

Body:
I want to make switching photo program, using imageView and keyEvent, but when I try to use keyEvent it dosen't work, I was trying add scene.getRoot().requestFocus(); but didn't help, so my question is, why it dosen't work any how could I activate it?

MenuScreenController.java

    @FXML
public void getNewImageHandler(KeyEvent event) {
    System.out.println(singleFile.getName());
    imgFieldView.setOnKeyPressed(e -> {
        if (e.getCode() == KeyCode.N) {
            photoSwipCounter++;
            System.out.println("P clicked");
        } else if (e.getCode() == KeyCode.P) {
            photoSwipCounter--;
        }
    });

//        if (event.getCode().equals(KeyCode.N)) {
//            photoSwipCounter++;
//        }
//        if (event.getCode().equals(KeyCode.P)) {
//            photoSwipCounter--;
//        }

    if (photoSwipCounter < 0) {
        singleFile = selectedImgsList.get(selectedImgsList.size() - photoSwipCounter);
    } else {
        singleFile = selectedImgsList.get(photoSwipCounter);
    }

    image = new Image(singleFile.toURI().toString(),
            900, 400,
            true, true, true);
    imgFieldView.setImage(image);
}

As you can see I was trying many methods, by stream, or classic, but it dosen't make change.

MenuScreen.fxml

<Pane fx:id="menuPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="700.0" prefWidth="1000.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="screensaverfxml.Controllers.MenuScreenController">
   <children>
      <ImageView fx:id="imgFieldView" fitHeight="400.0" fitWidth="900.0" layoutX="66.0" layoutY="62.0" onKeyPressed="#getNewImageHandler" onMouseClicked="#imgDoubleClick" pickOnBounds="true" preserveRatio="true" />
   </children>
</Pane>

ScreenSaverFXML.java

    @Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/screensaverfxml/fxmlConfig/MainScreen.fxml"));
    Pane mainPane = loader.load();
    Scene scene = new Scene(mainPane, 1000, 700);
    primaryStage.setScene(scene);
    primaryStage.setTitle("Screen Saver");

    primaryStage.show();

   scene.getRoot().requestFocus();
}

And ofc I have method to load first photo on imageView and it's work by load it from the folder to the list, but switching to next nope

Body:
Only nodes that have the focus receive key events. Since you have scene.getRoot().requestFocus() it's the root that receives the events. However, you're adding your EventHandler to imgFieldView and since that node is a descendant of the root it never sees any key events. You need to either have your imgFieldView obtain the focus or add your handler to the root node instead.

Note: You can only request focus once the target Node is part of a Scene.

The other problem is your call to imgFieldView.setOnKeyPressed(...) in the getNewImageHandler method. When you add an event handler via FXML, for instance by using onKeyPressed="#getNewImageHandler", it sets the corresponding onXXX property of the node. In your case, it's setting the onKeyPressed property of imgFieldView. However, in that handler you also set that property which replaces the handler set by the FXMLLoader. Your new handler simply increments or decrements the photoSwipeCounter field but does nothing with the new value. Your method should look more like:

@FXML
public void getNewImageHandler(KeyEvent event) {
    if (event.getCode().equals(KeyCode.N)) {
        photoSwipeCounter++;
    }
    if (event.getCode().equals(KeyCode.P)) {
        photoSwipeCounter--;
    }

    // wrap around logic
    if (photoSwipeCounter < 0) {
        photoSwipeCounter = selectedImgsList.size() - 1;
    } else if (photoSwipeCounter >= selectedImgsList.size()) {
        photoSwipeCounter = 0;
    }

    singleFile = selectedImgsList.get(photoSwipeCounter);

    image = new Image(singleFile.toURI().toString(),
            900, 400,
            true, true, true);
    imgFieldView.setImage(image);
}


问:
i am webscraping with bs4 and the urls wont show up
i am new to webscaping and wanted to scape all the charackterportraits from the lol site and when i examined one of the pictures in the browser it was in a "img scr="url" tag and i want to get the url to download the picture but when i do soup.select('img[src]') or soup.select('img') it returns an empty list and i dont know why

here is the code:

```<code>data=requests.get(website)
data.raise_for_status()

soup = bs4.BeautifulSoup(data.text,"lxml")
print(soup)
#soup returns html

elems = soup.select('img[src]')
print(elems)
#elems returns an empty list
</code>```

答:
It might be possible to do with request, but it seems that your get request does not get the full pageSource.

You can overcome this issue using selenium to just get the content.

```<code>from selenium import webdriver
import bs4

driver = webdriver.Chrome()
driver.get('https://na.leagueoflegends.com/en/game-info/champions/')
page_source = driver.page_source
driver.close()
soup = bs4.BeautifulSoup(page_source, "lxml")
print(soup)

elems = soup.find_all('img')
for elem in elems:
    print(elem.attrs['src'])
</code>```

Output:

```<code>https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Aatrox.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Ahri.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Akali.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Alistar.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Amumu.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Anivia.png
...
</code>```

Body:
i am new to webscaping and wanted to scape all the charackterportraits from the lol site and when i examined one of the pictures in the browser it was in a "img scr="url" tag and i want to get the url to download the picture but when i do soup.select('img[src]') or soup.select('img') it returns an empty list and i dont know why

here is the code:

data=requests.get(website)
data.raise_for_status()

soup = bs4.BeautifulSoup(data.text,"lxml")
print(soup)
#soup returns html

elems = soup.select('img[src]')
print(elems)
#elems returns an empty list

Body:
It might be possible to do with request, but it seems that your get request does not get the full pageSource.

You can overcome this issue using selenium to just get the content.

from selenium import webdriver
import bs4

driver = webdriver.Chrome()
driver.get('https://na.leagueoflegends.com/en/game-info/champions/')
page_source = driver.page_source
driver.close()
soup = bs4.BeautifulSoup(page_source, "lxml")
print(soup)

elems = soup.find_all('img')
for elem in elems:
    print(elem.attrs['src'])

Output:

https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Aatrox.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Ahri.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Akali.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Alistar.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Amumu.png
https://ddragon.leagueoflegends.com/cdn/9.11.1/img/champion/Anivia.png
...


问:
Skip Rows in Column Sum in Excel using C#
I am trying to calculate the column sum by skipping specific rows with excel interop in C#.i am not able to figure out how to do that please help. I want to sum highlighted rows and skip the others in the attached image.

答:
Excel array indices are generally 1-based, not 0-based (i.e. lowest element is number 1).</p>

```<code>var xl = new Microsoft.Office.Interop.Excel.Application();
var b = xl.Workbooks.Open("C:\\Junk\\Junk.xlsx");
Microsoft.Office.Interop.Excel.Worksheet s = b.Worksheets[1]; //1-based
var r = s.Range["A1", "E4"];
int sum = 0;
for (var row = 1; row <= 4; row += 2)
{
    sum += r.Value2[row, 1]; //also 1-based
}
xl.Quit();
</code>```

Body:
Excel array indices are generally 1-based, not 0-based (i.e. lowest element is number 1).

var xl = new Microsoft.Office.Interop.Excel.Application();
var b = xl.Workbooks.Open("C:\\Junk\\Junk.xlsx");
Microsoft.Office.Interop.Excel.Worksheet s = b.Worksheets[1]; //1-based
var r = s.Range["A1", "E4"];
int sum = 0;
for (var row = 1; row <= 4; row += 2)
{
    sum += r.Value2[row, 1]; //also 1-based
}
xl.Quit();


问:
Overloading, Referencing, and everything in between
This is a big one and I apologize.

I am practicing to make my coding more modular.
We are tasked to create a Shipyard system.
There are Containers in the Shipyard and Packages in the Containers.

There is a LinkedList program provided that can be imported. I added it on the bottom.

IMPORTANT: I CANNOT ALTER THE SORTED LINKED LIST PROGRAM IN ANY WAY HENCE WHY I USE OVERLOADERS

I have another program which is non-modular. It is specifically made for the assignment at hand and it works for the most part.

Python 3.5

```<code>from SortedLList import *

class Shipyard:
    def __init__(self):
        self._container = SortedLList()

    def add(self, owner, destination, weight):
        """
        This function does:
        1. Adds a container for a specific destination if doesn't exist.
        2. Adds a package in a container given that the total weight
        doesn't exceed 2000 lbs
        3. If it does, it creates another container headed in the same
        direction and then the package is inserted there instead.
        """
        self._container.insert(Self.Container(destination))

    class Container:
        def __init__(self, destination):
            self._package = SortedLList()
            self._dest = destination
            self._weight = 0
            self._max = 2000

       def add_pack(self, owner, destination, weight):
           """
           This function adds the weight of the package to the total
           container weight. And inserts a Package Singly Linked List
           object inside the container.
           """
           self._weight += weight
           self._package.insert(Self.Package(destination))

       def __lt__(self, other):
           return self._dest < other._dest

       def __ge__(self, other):
           return self._dest >= other._dest

       def __eq__(self, other):
           return self._dest == other._dest

       class Package:
           def __init__(self, owner, destination, weight):
               self._owner = owner
               self._dest = destination
               self._weight = weight

           def __lt__(self, other):
               return self._weight < other._weight

           def __ge__(self, other):
               return self._weight >= other._weight

           def __eq__(self, other):
              return self._weight == other._weight

class SortedLList :
    class _Node :
        def __init__(self, elem, next) :
            self._elem = elem
            self._next = next

    def __init__(self) :
        self._first = None
        self._size = 0

    def __len__(self) :
        return self._size

    def isEmpty(self) :
        return len(self) == 0

    def first(self):
        return self._elem._first

    def insert(self, val) :
        if (self.isEmpty() or val <self._first._elem):
            self._size+=1
        self._first = self._Node(val,self._first)

        tmpRef=self._first

        while(tmpRef._next!=None and val>=tmpRef._next._elem):
            tmpRef=tmpRef._next

        if val==tmpRef._elem:
            return
        self._size+=1
        tmpRef._next=self._Node(val,tmpRef._next)
        return

    def isPresent(self, elem) :
        tmpRef=self._first
        while(tmpRef!=None):
            if tmpRef._elem==elem:
                return True
            tmpRef=tmpRef._next
        return False

    def delete(self, elem) :
        if self.isEmpty() :
            return
        if elem == self._first._elem :
            self._size -= 1
            self._first = self._first._next
            return

        tmpRef = self._first
        while (tmpRef._next != None and elem > tmpRef._next._elem) :
            tmpRef = tmpRef._next

        if tmpRef._next == None : return

        if tmpRef._next._elem != elem : return

        self._size -= 1
        tmpRef._next = tmpRef._next._next
        return

    def traversePrint(self) :
        tmpRef = self._first
        while tmpRef != None :
            print(tmpRef._elem)
            tmpRef = tmpRef._next

    class Empty(Exception) :
        pass
</code>```

I want to be able to use the methods in the SortedLList program to be able to display information that I have in the main program.

Is there any way around typing:
print(self._cont._first._elem._dest) or print(self._cont._first._elem._package._first._elem._owner) by using traversePrint() without altering the helper code?

答:
You can inherit SortedLList in a new class and overload the methods you want.

```<code>class MySortedLList(SortedLList):
    def traversePrint(self):
        # Your custom implementation
</code>```

and then using that instead of SortedLLIst, e.g:

```<code>class Shipyard:
    def __init__(self):
        self._container = MySortedLList()
</code>```

However,, you asked if you can use the SortedLList.traversePrint to print information about your main program, presumable Shipyard. This probably doesn't make sense because you'd break encapsulation. SortedLList knows about its elements and can only know about Shipyard if you give it a reference to Shipyard. So rather let Shipyard tell you about itself.

Body:
This is a big one and I apologize.

I am practicing to make my coding more modular.
We are tasked to create a Shipyard system.
There are Containers in the Shipyard and Packages in the Containers.

There is a LinkedList program provided that can be imported. I added it on the bottom.

IMPORTANT: I CANNOT ALTER THE SORTED LINKED LIST PROGRAM IN ANY WAY HENCE WHY I USE OVERLOADERS

I have another program which is non-modular. It is specifically made for the assignment at hand and it works for the most part.

Python 3.5

from SortedLList import *

class Shipyard:
    def __init__(self):
        self._container = SortedLList()

    def add(self, owner, destination, weight):
        """
        This function does:
        1. Adds a container for a specific destination if doesn't exist.
        2. Adds a package in a container given that the total weight
        doesn't exceed 2000 lbs
        3. If it does, it creates another container headed in the same
        direction and then the package is inserted there instead.
        """
        self._container.insert(Self.Container(destination))

    class Container:
        def __init__(self, destination):
            self._package = SortedLList()
            self._dest = destination
            self._weight = 0
            self._max = 2000

       def add_pack(self, owner, destination, weight):
           """
           This function adds the weight of the package to the total
           container weight. And inserts a Package Singly Linked List
           object inside the container.
           """
           self._weight += weight
           self._package.insert(Self.Package(destination))

       def __lt__(self, other):
           return self._dest < other._dest

       def __ge__(self, other):
           return self._dest >= other._dest

       def __eq__(self, other):
           return self._dest == other._dest

       class Package:
           def __init__(self, owner, destination, weight):
               self._owner = owner
               self._dest = destination
               self._weight = weight

           def __lt__(self, other):
               return self._weight < other._weight

           def __ge__(self, other):
               return self._weight >= other._weight

           def __eq__(self, other):
              return self._weight == other._weight

class SortedLList :
    class _Node :
        def __init__(self, elem, next) :
            self._elem = elem
            self._next = next

    def __init__(self) :
        self._first = None
        self._size = 0

    def __len__(self) :
        return self._size

    def isEmpty(self) :
        return len(self) == 0

    def first(self):
        return self._elem._first

    def insert(self, val) :
        if (self.isEmpty() or val <self._first._elem):
            self._size+=1
        self._first = self._Node(val,self._first)

        tmpRef=self._first

        while(tmpRef._next!=None and val>=tmpRef._next._elem):
            tmpRef=tmpRef._next

        if val==tmpRef._elem:
            return
        self._size+=1
        tmpRef._next=self._Node(val,tmpRef._next)
        return

    def isPresent(self, elem) :
        tmpRef=self._first
        while(tmpRef!=None):
            if tmpRef._elem==elem:
                return True
            tmpRef=tmpRef._next
        return False

    def delete(self, elem) :
        if self.isEmpty() :
            return
        if elem == self._first._elem :
            self._size -= 1
            self._first = self._first._next
            return

        tmpRef = self._first
        while (tmpRef._next != None and elem > tmpRef._next._elem) :
            tmpRef = tmpRef._next

        if tmpRef._next == None : return

        if tmpRef._next._elem != elem : return

        self._size -= 1
        tmpRef._next = tmpRef._next._next
        return

    def traversePrint(self) :
        tmpRef = self._first
        while tmpRef != None :
            print(tmpRef._elem)
            tmpRef = tmpRef._next

    class Empty(Exception) :
        pass

I want to be able to use the methods in the SortedLList program to be able to display information that I have in the main program.

Is there any way around typing:
print(self._cont._first._elem._dest) or print(self._cont._first._elem._package._first._elem._owner) by using traversePrint() without altering the helper code?

Body:
You can inherit SortedLList in a new class and overload the methods you want.

class MySortedLList(SortedLList):
    def traversePrint(self):
        # Your custom implementation

and then using that instead of SortedLLIst, e.g:

class Shipyard:
    def __init__(self):
        self._container = MySortedLList()

However,, you asked if you can use the SortedLList.traversePrint to print information about your main program, presumable Shipyard. This probably doesn't make sense because you'd break encapsulation. SortedLList knows about its elements and can only know about Shipyard if you give it a reference to Shipyard. So rather let Shipyard tell you about itself.


问:
How I write a:hover::before in less file?
I have some CSS rules and just I need to write them in my LESS CSS file.

This is my CSS -

```<code>div.files a > div,
div.files a:before {
    transition: background-color 350ms;
}

div.files a:hover > div {
    background-color: #000;
}

div.files a:hover::before {
    background-color: #017BC6;
}
</code>```

This is how I tried it in my less css file. But can't get it to work.

UPDATE:

```<code>> .files {
    margin-top: 18px;
    ....

    a {
        position: relative;
        text-decoration: none;
        margin-bottom: 10px;
        .....

        &:last-child {
            margin-bottom: 0;
        }

        &:before {
            background-color: #000;
            transition: background-color 350ms;
            ....
        }

        &:hover {
            content: "";
            .block {
                background-color: #000;
            }

            &::before {
                background-color: #017BC6;
            }
        }

        .block {
            background-color: #017BC6;
            transition: background-color 350ms;
            ....

            .name {
                ....
            }

            .meta {
                ......

                &:after {
                    ....
                }

                .date {
                    ...
                }

                .format {
                    ...

                    &:before {
                        ...;
                    }
                }
            }
        }
    }

    div {
        ......
    }
}
</code>```

This is my HTML -

```<code><div class="files">
    <a href="#">
        <div class="block">
            <div class="name">.......</div>
            <div class="meta">
                <div class="date">.....</div>
                <div class="format">....</div>
            </div>
        </div>
    </a>
</div>
</code>```

I am confusing how to write this kind of rules in less (a:hover::before).

Hope someone may help me out.
Thank You.

答:
if before and after element doesnot have content they not be visible at all</p>

```<code>.x{
    &:before{content: '';}
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some CSS rules and just I need to write them in my LESS CSS file.

This is my CSS -

div.files a > div,
div.files a:before {
    transition: background-color 350ms;
}

div.files a:hover > div {
    background-color: #000;
}

div.files a:hover::before {
    background-color: #017BC6;
}

This is how I tried it in my less css file. But can't get it to work.

UPDATE:

> .files {
    margin-top: 18px;
    ....

    a {
        position: relative;
        text-decoration: none;
        margin-bottom: 10px;
        .....

        &:last-child {
            margin-bottom: 0;
        }

        &:before {
            background-color: #000;
            transition: background-color 350ms;
            ....
        }

        &:hover {
            content: "";
            .block {
                background-color: #000;
            }

            &::before {
                background-color: #017BC6;
            }
        }

        .block {
            background-color: #017BC6;
            transition: background-color 350ms;
            ....

            .name {
                ....
            }

            .meta {
                ......

                &:after {
                    ....
                }

                .date {
                    ...
                }

                .format {
                    ...

                    &:before {
                        ...;
                    }
                }
            }
        }
    }

    div {
        ......
    }
}

This is my HTML -

.......

.....

....

I am confusing how to write this kind of rules in less (a:hover::before).

Hope someone may help me out.
Thank You.

Body:
if before and after element doesnot have content they not be visible at all

.x{
    &:before{content: '';}
}


问:
Guarding resources with Singleton?
I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:

Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).

Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).

My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Is my choice of making this class a singleton class a bad decision?

答:
Is my choice of making this class a singleton class a bad decision?

Yes.

Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).

That doesn't make it necessary to access the camera via a Singleton class.

Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).

Using a Singleton class will not buy you anything that saves you from those problem that you cannot also do in a non-Singleton class.

My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).

Then there's no need to create a God-like Singleton class.

Furthermore, those little nifty helper functionalities you added to the Singleton class and their interactions with other pieces of code cannot easily be unit tested when residing in a singleton class with global state that cannot properly be set up and torn down between tests.

By proper use of dependency injection in the application composition root, the concrete object lifetime can be managed as if it was a singleton, but the individual clients of that object doesn't need to know that.

Title: Guarding resources with Singleton?


问:
RabbitMQ - Need Channel per Machine?
We have multiple backend machines. The goal is to have each machine pick up each message sent to a single RabbitMQ exchange.

The FooExchange is set to fanout (so it sends a message to all the queues connected to it). FooExchange has one queue, FooQueue, which is bound to it. All our machines are consumers of FooQueue.

This works fine locally, but when we have multiple machines in play, it appears that only ONE machine picks up the message at a time. It picks up the message specifically 1 time / however many machines there are. This is corroborated by an old answer here.

I have several questions:

Is creating a queue per machine the best way to proceed?

The "machines" are actually going to be K8S pods - what should I use as a unique machine identifier in the queue name? Or just make instantiate a GUID and call it a day?

Finally, how do I handle pod restarts (if unfamiliar with K8S, think of a cloud load balancer spinning up new VM instances) - this will leave dead queue as the replacement pods/VMs create new ones to consume from.

答:
1) A fanout exchange routes all messages to all bound queues. So the answer to your first question depends on what you want to achieve. If you want every consumer to receive every message, use a fantout exchange, create a queue for every consumer, bind it to the exchange. The let each consumer exclusively consume the messages from his queue.

If on the other hand you want every message to be consumed by only once, use a single queue and let all consumers consume messages from it. This will use the default round-robin behaviour: the consumers are taking turns and every message is consumed exactly once.

2) If you use the first approach, you can let the queue names be automatically generated for every consumer upon queue creation. This name will be fine and unique.

3) RabbitMQ supports temporary queues which are deleted when the consumer goes away. If you require every message to be consumed at least once, make sure to declare a dead letter exchange for messages that could not be consumed by a consumer that went away. This will enable you to reroute such messages.

Title: RabbitMQ - Need Channel per Machine?


答:
I found this solution, to avoid the shuffling due to the join.

What do you guys think?

Any improvement or scala shortcuts I can use?

    def func_union_name(myCols: Set[String], allCols: Set[String]) = {
        allCols.toList.map(x => x match {
          case x if myCols.contains(x) => col(x)
          case _ => lit(null).as(x)
        })
      }
```
<p>After defining the function above i do:</p>
<pre class="lang-scala prettyprint-override"><code>          val upper_col = tableToUpdate.columns.toSet
          val bottom_col = miniJoin.columns.toSet
          val union_cols = tableToUpdate_col ++ miniJoin_col

              upper
                .select(func_union_name(tableToUpdate_col, union_cols): _*)
                .union(bottom.select(func_union_name(bottom_col, union_cols): _*))
                .withColumn("max_lu",max(col("last_update"))
                                      .over(Window.partitionBy(col("uid"))))
                .filter(col("last_update").geq(col("max_lu")))
                .drop(col("max_lu"))
</code>```

Title: Spark Join dataframes and conditionally update columns

Body:
Hi I have 2 spark dataframes.

The first one:

+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+
|cluster_socio_6|cluster_socio_7|country|latitude|longitude|last_update|         uid|segment_comp_11|cluster_comp_170|
+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+
|              2|              2|     IT|  41.884|  13.5204| 2019-04-15|d@rNdBkkN-p3|             10|               3|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|Ie2Bbs9PUR8h|             15|               4|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|Jk2Bbs9PUR8h|             15|               4|
+---------------+---------------+-------+--------+---------+-----------+------------+---------------+----------------+

and second one:

+---------------+---------------+-------+--------+---------+-----------+------------+
|cluster_socio_6|cluster_socio_7|country|latitude|longitude|last_update|         uid|
+---------------+---------------+-------+--------+---------+-----------+------------+
|              4|             17|     IT| 40.8413|  14.2008| 2019-04-16|ASBuzjKa6nIB|
|              2|              2|     IT|  41.884|  15.5204| 2019-04-16|d@rNdBkkN-p3|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-16|Ie2Bbs9PUR8h|
|             16|             15|     IT| 45.5298|  9.03813| 2019-04-15|xyzBbs9PUR8h|
+---------------+---------------+-------+--------+---------+-----------+------------+

apart country,latitude,longitude,last_update and uid, the bottom Df could have different columns added.

The idea is to make a full join by uid, update the common columns and keep the uncommon columns.

How could I accomplish this task?
Thanks.

Body:
I found this solution, to avoid the shuffling due to the join.

What do you guys think?

Any improvement or scala shortcuts I can use?

    def func_union_name(myCols: Set[String], allCols: Set[String]) = {
        allCols.toList.map(x => x match {
          case x if myCols.contains(x) => col(x)
          case _ => lit(null).as(x)
        })
      }

After defining the function above i do:

          val upper_col = tableToUpdate.columns.toSet
          val bottom_col = miniJoin.columns.toSet
          val union_cols = tableToUpdate_col ++ miniJoin_col

              upper
                .select(func_union_name(tableToUpdate_col, union_cols): _*)
                .union(bottom.select(func_union_name(bottom_col, union_cols): _*))
                .withColumn("max_lu",max(col("last_update"))
                                      .over(Window.partitionBy(col("uid"))))
                .filter(col("last_update").geq(col("max_lu")))
                .drop(col("max_lu"))


问:
Work out the type of c# application a class contained in a DLL is being used by
Is there any way to know in C# the type of application that is running.

Windows Service
ASP.NET
Windows Form
Console

I would like to react to the application type but cannot find a way to determine it.

答:
Try checking Application.MessageLoop. It should be true for Windows Forms applications (that have a WinForms message loop), and false for windows services. I don't know what it would return for ASP.NET.

As for console applications, they would have no message loop so they would return false. You can check for that using most properties in the Console class, but I warn you that it's a HACK. If you must, I'd go with:

```<code>bool isConsole = Console.In != StreamReader.Null;
</code>```

Note, that a console app could still call Console.SetIn(StreamReader.Null) or a windows app could call Console.SetIn(something else), so this is easily tricked.

OwnerDisplayName: John Selkirk

ContentLicense: CC BY-SA 2.5

Body:
Try checking Application.MessageLoop. It should be true for Windows Forms applications (that have a WinForms message loop), and false for windows services. I don't know what it would return for ASP.NET.

As for console applications, they would have no message loop so they would return false. You can check for that using most properties in the Console class, but I warn you that it's a HACK. If you must, I'd go with:

bool isConsole = Console.In != StreamReader.Null;

Note, that a console app could still call Console.SetIn(StreamReader.Null) or a windows app could call Console.SetIn(something else), so this is easily tricked.

OwnerDisplayName: configurator


问:
regular expression to parse html title tag
I need to parse a lot of html files in order to know which ones contain specific text within title tag.

Let's suppose that titles are

```<code>file1.htm
<title>100 text other text</title>
file2.htm
<title>text 100 text other text</title>
file3.htm
<title>text 1000 text other text</title>
file4.htm
<title>text one hundred text other text</title>
</code>```

Following my example I need to find files name that contain 100 or one hundred, that is files 1,2 and 4.

My problem is that I don't know how to write regular expression

```<code>gci "c:\my_folder" | ? {$_.extension -eq ".htm"} |
select-string -pattern '<title>*100*</title>' |
Select-Object -Unique Path
</code>```

Please note, if this may be important for regexp, that title tag is not at the beginning of a row but in the middle.
Thanks in advance.

答:
This should do it.</p>

```<code>^.*<title>(.*(100|one\shundred)[^0].*)?</title>.*$
</code>```

Body:
I need to parse a lot of html files in order to know which ones contain specific text within title tag.

Let's suppose that titles are

file1.htm
<title>100 text other text</title>
file2.htm
<title>text 100 text other text</title>
file3.htm
<title>text 1000 text other text</title>
file4.htm
<title>text one hundred text other text</title>

Following my example I need to find files name that contain 100 or one hundred, that is files 1,2 and 4.

My problem is that I don't know how to write regular expression

gci "c:\my_folder" | ? {$_.extension -eq ".htm"} |
select-string -pattern '<title>*100*</title>' |
Select-Object -Unique Path

Please note, if this may be important for regexp, that title tag is not at the beginning of a row but in the middle.
Thanks in advance.

Body:
This should do it.

^.*<title>(.*(100|one\shundred)[^0].*)?</title>.*$


问:
How to hide a border?
I have a div class .text-center and I'm trying to hide the border for a button.

The css is:

```<code>.text-center:nth-of-type(even){border-radius: 10px; box-shadow: 0px 0px 10px; border: none;}
</code>```

This gives it a 10px border radius, but won't allow 20px border-radius or allow me to hide the border which is obscuring the button.

Also tried:

```<code>.text-center a {border: none !important; box-shadow : none;}
</code>```

But this hides the border for other buttons. How is that possible when the a is only listed under that div class?

Could this be a specificity issue? Tried framing .text-center within the div class above it-nothing

Html:

```<code>    <div class="event_registration registration">

    <input type="button" class="registration_button button" value="Register for event" />

    <div class="registration_details">
        <p>To register for this event please visit the following URL: <a href="https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779" target="_blank" rel="nofollow">https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779 →</a></p>     </div>
        </div>
                 <!-- For more details information start -->
                          <div class="text-center">
                <a class="link-button" data-toggle="modal" href="https://www.theunderworldcamden.co.uk/event/camden-rocks-festival-2019/"  target="_blank" >View More Details</a>
              </div>

         <!-- For more details infomation end-->
         <!-- Video popup box section start -->
                     <!-- Video popup box section end -->

 <!-- Event Location and Time start-->

    <h3 class="section-title">When & Where</h3>
      <ul class="when-where">
        <li class="event-start-date">
         From:2019-06-01   12:00 PM            </li>
        <li class="event-end-date">
         To:2019-06-02 12:00 AM            </li>
        <li class="event-location">
         Location:
                       <span class="venue-name">
            The Underworld
</code>```

https://adsler.co.uk/event/camden-rocks-festival/

答:
Try this</p>

```<code>.entry-content a {
display: inline-block;
border: none;
text-decoration: none;
box-shadow: none;
}
</code>```

Title: How to hide a border?

Body:
I have a div class .text-center and I'm trying to hide the border for a button.

The css is:

.text-center:nth-of-type(even){border-radius: 10px; box-shadow: 0px 0px 10px; border: none;}

This gives it a 10px border radius, but won't allow 20px border-radius or allow me to hide the border which is obscuring the button.

Also tried:

.text-center a {border: none !important; box-shadow : none;}

But this hides the border for other buttons. How is that possible when the a is only listed under that div class?

Could this be a specificity issue? Tried framing .text-center within the div class above it-nothing

Html:

    <input type="button" class="registration_button button" value="Register for event" />

To register for this event please visit the following URL: https://dice.fm/festival/camden-rocks-festival?_branch_match_id=655373442484550779 →

                View More Details

When & Where

         From:2019-06-01   12:00 PM

         To:2019-06-02 12:00 AM

         Location:

            The Underworld

https://adsler.co.uk/event/camden-rocks-festival/

Body:
Try this

.entry-content a {
display: inline-block;
border: none;
text-decoration: none;
box-shadow: none;
}


问:
Using OpenCV Mat for reading text using tesseract (Java)
I need to read text using tesseract, for my processed image which is done using OpenCV. I have already tried the methods mentioned in the following link, but to no avail:

Method 1

Converting using MatOfBytes SO Link

```<code>public static PIX convertMatToPix(Mat mat) {

        LOGGER.info("Size of image: " + mat.size());
        MatOfByte bytes = new MatOfByte();
        Imgcodecs.imencode(".jpg", mat, bytes);
        ByteBuffer buff = ByteBuffer.wrap(bytes.toArray());
        LOGGER.info("Size for pixReadMem: " + new NativeSize(buff.capacity()).intValue());
        return pixReadMem(buff, new NativeSize(buff.capacity()).intValue());
    }
</code>```

This method creates a white image out of my input image.

Method 2

Converting using Byte Array

```<code>byte[] imageBuffer = new byte[(int) (input.rows()*input.cols()*input.channels())];
        input.get(0, 0, imageBuffer);
PIX image = pixReadMem(imageBuffer, (int) (input.rows()*input.cols()*input.channels()));
</code>```

This method fails to create an image, as I am outputting image using:

```<code>int writingFromPix = pixWriteAutoFormat("/home/abhishekkeshri/Pictures/ocr/pixOutput.jpg", image);
LOGGER.info("Writing from PIX returns: " + writingFromPix);
</code>```

And it is returning 1, which signifies an error in writing image.

Method 3

Copying pixel-by-pixel value (SO link)

```<code>PIX mat8ToPix(Mat mat8)
    {
        PIX pixd = pixCreate(mat8.width(), mat8.height(), mat8.depth());
        for(int y=0; y<mat8.rows(); y++) {
            for(int x=0; x<mat8.cols(); x++) {
                double[] pixelDouble = mat8.get(y,x);
                int[] pixelInt = new int[pixelDouble.length];
                for(int i=0;i<pixelDouble.length;i++) {
                    pixelInt[i] = (int) pixelDouble[i];
                }
                pixSetPixel(pixd, y, x, pixelInt[0]);
            }
        }
        return pixd;
    }
</code>```

The problem in this method is that get method returns an array of pixel, which depends on the channel. So just using the 0th value should be wrong. The logic seems correct but what am I doing wrong in this method?

Method 4

Directly using Mat to setImage in Tesseract

```<code>api.SetImage(imageBuffer, input.width(), input.height(), input.channels(), (int)input.step1());
</code>```

This method also fails to get any output from Tesseract, as the output printed is blank.

Method 5

By simply reading the preprocessed image, and reading it using tesseract the output given is correct:

```<code>PIX image = pixRead("/home/abhishekkeshri/Pictures/ocr/clean.jpg");
api.SetImage(image);
</code>```

This gives the correct result. But I can't use this as disk operations will be quite costly (writing output of opencv and saving it in a file, the opening that file using PIX)

Any help will be appreciated, as I am stuck in this problem since 2 days.

My maven dependencies:

```<code>    <dependency>
        <groupId>org.bytedeco.javacpp-presets</groupId>
        <artifactId>tesseract-platform</artifactId>
        <version>4.0.0-rc2-1.4.3</version>
    </dependency>
    <dependency>
        <groupId>org.openpnp</groupId>
        <artifactId>opencv</artifactId>
        <version>3.4.2-1</version>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.lept4j</groupId>
        <artifactId>lept4j</artifactId>
        <version>1.10.0</version>
    </dependency>
</code>```

答:
I have used below code for convert Mat to BufferImage.

Tesseract Code:

```<code>Tesseract tesseract1 = new Tesseract();
tesseract1.setDatapath(datapath);
tesseract1.doOCR(Mat2BufferedImage(mat);
</code>```

Mat to BufferdImage Convert code:

```<code>static BufferedImage Mat2BufferedImage(Mat matrix) throws Exception {
    MatOfByte mob = new MatOfByte();
    Imgcodecs.imencode(".jpg", matrix, mob);
    byte ba[] = mob.toArray();

    BufferedImage bi = ImageIO.read(new ByteArrayInputStream(ba));
    return bi;
}
</code>```

Using this code getting expected output.

Body:
I need to read text using tesseract, for my processed image which is done using OpenCV. I have already tried the methods mentioned in the following link, but to no avail:

Method 1

Converting using MatOfBytes SO Link

public static PIX convertMatToPix(Mat mat) {

        LOGGER.info("Size of image: " + mat.size());
        MatOfByte bytes = new MatOfByte();
        Imgcodecs.imencode(".jpg", mat, bytes);
        ByteBuffer buff = ByteBuffer.wrap(bytes.toArray());
        LOGGER.info("Size for pixReadMem: " + new NativeSize(buff.capacity()).intValue());
        return pixReadMem(buff, new NativeSize(buff.capacity()).intValue());
    }

This method creates a white image out of my input image.

Method 2

Converting using Byte Array

byte[] imageBuffer = new byte[(int) (input.rows()*input.cols()*input.channels())];
        input.get(0, 0, imageBuffer);
PIX image = pixReadMem(imageBuffer, (int) (input.rows()*input.cols()*input.channels()));

This method fails to create an image, as I am outputting image using:

int writingFromPix = pixWriteAutoFormat("/home/abhishekkeshri/Pictures/ocr/pixOutput.jpg", image);
LOGGER.info("Writing from PIX returns: " + writingFromPix);

And it is returning 1, which signifies an error in writing image.

Method 3

Copying pixel-by-pixel value (SO link)

PIX mat8ToPix(Mat mat8)
    {
        PIX pixd = pixCreate(mat8.width(), mat8.height(), mat8.depth());
        for(int y=0; y<mat8.rows(); y++) {
            for(int x=0; x<mat8.cols(); x++) {
                double[] pixelDouble = mat8.get(y,x);
                int[] pixelInt = new int[pixelDouble.length];
                for(int i=0;i<pixelDouble.length;i++) {
                    pixelInt[i] = (int) pixelDouble[i];
                }
                pixSetPixel(pixd, y, x, pixelInt[0]);
            }
        }
        return pixd;
    }

The problem in this method is that get method returns an array of pixel, which depends on the channel. So just using the 0th value should be wrong. The logic seems correct but what am I doing wrong in this method?

Method 4

Directly using Mat to setImage in Tesseract

api.SetImage(imageBuffer, input.width(), input.height(), input.channels(), (int)input.step1());

This method also fails to get any output from Tesseract, as the output printed is blank.

Method 5

By simply reading the preprocessed image, and reading it using tesseract the output given is correct:

PIX image = pixRead("/home/abhishekkeshri/Pictures/ocr/clean.jpg");
api.SetImage(image);

This gives the correct result. But I can't use this as disk operations will be quite costly (writing output of opencv and saving it in a file, the opening that file using PIX)

Any help will be appreciated, as I am stuck in this problem since 2 days.

My maven dependencies:

    <dependency>
        <groupId>org.bytedeco.javacpp-presets</groupId>
        <artifactId>tesseract-platform</artifactId>
        <version>4.0.0-rc2-1.4.3</version>
    </dependency>
    <dependency>
        <groupId>org.openpnp</groupId>
        <artifactId>opencv</artifactId>
        <version>3.4.2-1</version>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.lept4j</groupId>
        <artifactId>lept4j</artifactId>
        <version>1.10.0</version>
    </dependency>

Body:
I have used below code for convert Mat to BufferImage.

Tesseract Code:

Tesseract tesseract1 = new Tesseract();
tesseract1.setDatapath(datapath);
tesseract1.doOCR(Mat2BufferedImage(mat);

Mat to BufferdImage Convert code:

static BufferedImage Mat2BufferedImage(Mat matrix) throws Exception {
    MatOfByte mob = new MatOfByte();
    Imgcodecs.imencode(".jpg", matrix, mob);
    byte ba[] = mob.toArray();

    BufferedImage bi = ImageIO.read(new ByteArrayInputStream(ba));
    return bi;
}

Using this code getting expected output.


问:
How to create EditText with cross(x) button at end of it?
Is there any widget like EditText which contains a cross button, or is there any property for EditText by which it is created automatically? I want the cross button to delete whatever text written in EditText.

答:
2020 solution via Material Design Components for Android:

Add Material Components to your gradle setup:

Look for latest version from here: https://maven.google.com/

```<code>implementation 'com.google.android.material:material:1.3.0'
</code>```

or if you havent updated to using AndroidX libs, you can add it this way:

```<code>implementation 'com.android.support:design:28.0.0'
</code>```

Then

```<code><com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_text"
    app:endIconMode="clear_text">

  <com.google.android.material.textfield.TextInputEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>
</code>```

Pay attention to: app:endIconMode="clear_text"

As discussed here Material design docs

Body:
2020 solution via Material Design Components for Android:

Add Material Components to your gradle setup:

Look for latest version from here: https://maven.google.com/

implementation 'com.google.android.material:material:1.3.0'

or if you havent updated to using AndroidX libs, you can add it this way:

implementation 'com.android.support:design:28.0.0'

Then

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/hint_text"
    app:endIconMode="clear_text">

  <com.google.android.material.textfield.TextInputEditText
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

</com.google.android.material.textfield.TextInputLayout>

Pay attention to: app:endIconMode="clear_text"

As discussed here Material design docs


问:
configure the jest moduleNameMapper not work
I want to apply a jest test to react component and I get an error that says:

Jest encountered an unexpected token

When I try to:

```<code>import moment from 'moment';
import './style.css';   //<----here
</code>```

I try to mock css files and image objects and change the configuration:

```<code>// package.json
{
"jest": {
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
  "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
</code>```

My styleMock.js is:

```<code>module.exports = {};
</code>```

My fileMock.js is:

```<code>module.exports = 'test-file-stub';
</code>```

But I still get the error:

Jest encountered an unexpected token

and the error is in the same place as it was previously.

My jest is the latest version "24.8.0".

Anyone knows why?

答:
i use this lib for that identity-obj-proxy

```<code>npm install identity-obj-proxy
</code>```

change this line:

```<code>"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
</code>```

to this:

```<code>"\\.(css|less)$": "identity-obj-proxy"
</code>```

Body:
I want to apply a jest test to react component and I get an error that says:

Jest encountered an unexpected token

When I try to:

import moment from 'moment';
import './style.css';   //<----here

I try to mock css files and image objects and change the configuration:

// package.json
{
"jest": {
"moduleNameMapper": {
  "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
  "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}

My styleMock.js is:

module.exports = {};

My fileMock.js is:

module.exports = 'test-file-stub';

But I still get the error:

Jest encountered an unexpected token

and the error is in the same place as it was previously.

My jest is the latest version "24.8.0".

Anyone knows why?

Body:
i use this lib for that identity-obj-proxy

npm install identity-obj-proxy

change this line:

"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"

to this:

"\\.(css|less)$": "identity-obj-proxy"


问:
IIS rewrite rule not triggered when file-name plus extension is in the url
I am struggling getting an IIS rewrite rule working.

The old urls look like:
https://wwww.testserver.com/package.aspx?TrackingNumber=number

The new web app is expecting the urls in this format:
https://wwww.testserver.com/package/number

Currently I have the following rule setup, which is not working.

<rule name="Rewrite to new Package site" stopProcessing="true">
      <match url="^package\.aspx\?TrackingNumber=([_0-9a-z-]+)" />
      <action type="Redirect" url="https://www.testserver.com/package/{R:1}" logRewrittenUrl="true" />
    </rule>

The interesting part is, if I remove package.aspx\? from the rule, urls like these https://wwww.testserver.com/oldwebsite/TrackingNumber=number are getting matched.

In my test calls I replaced package.aspx with package.html and these urls are not getting matched as well. It looks like IIS ignores urls with filenames in the url.

答:
You could use below url rewrite rule to redirect  https://wwww.testserver.com/package.aspx?TrackingNumber=number to https://wwww.testserver.com/package/number:

```<code><rule name="test" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" pattern="package(.aspx)" />
                    <add input="{QUERY_STRING}" pattern="TrackingNumber=(.*)" />
                </conditions>
                <action type="Redirect" url="http://localhost:2568/package/{C:1}" appendQueryString="false" />
            </rule>
</code>```

Note: You could modify hostname as per your requirement.

Regards,
Jalpa

Body:
You could use below url rewrite rule to redirect  https://wwww.testserver.com/package.aspx?TrackingNumber=number to https://wwww.testserver.com/package/number:

<rule name="test" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" pattern="package(.aspx)" />
                    <add input="{QUERY_STRING}" pattern="TrackingNumber=(.*)" />
                </conditions>
                <action type="Redirect" url="http://localhost:2568/package/{C:1}" appendQueryString="false" />
            </rule>

Note: You could modify hostname as per your requirement.

Regards,
Jalpa


问:
youtube-dl DASH video and audio in highest quality without human intervention
With youtube-dl I first look what video quality is available and then in second step I download highest possible quality (in this example -f 137+140). Youtube-dl will automatically merge audio and video stream (DASH format)

How to automate that with shell script? With every URL, choose highest audio and video quality?

```<code>> youtube-dl -F 'https://www.youtube.com/watch?v=VAdRBLyjLRQ&feature=youtu.be&t=8m14s'
[youtube] Downloading login page
[youtube] Logging in
[youtube] VAdRBLyjLRQ: Downloading webpage
[youtube] VAdRBLyjLRQ: Downloading video info webpage
[youtube] VAdRBLyjLRQ: Extracting video information
[youtube] VAdRBLyjLRQ: Downloading DASH manifest
[youtube] VAdRBLyjLRQ: Downloading DASH manifest
[info] Available formats for VAdRBLyjLRQ:
format code  extension  resolution note
249          webm       audio only DASH audio , opus @ 50k
250          webm       audio only DASH audio , opus @ 70k
251          webm       audio only DASH audio , opus @160k
171          webm       audio only DASH audio  117k , vorbis@128k (44100Hz), 7.68MiB
140          m4a        audio only DASH audio  128k , m4a_dash container, aac  @128k (44100Hz), 11.58MiB
160          mp4        256x144    DASH video  112k , avc1.4d400c, 15fps, video only, 9.94MiB
278          webm       256x144    DASH video  136k , webm container, VP9, 15fps, video only, 9.10MiB
133          mp4        426x240    DASH video  248k , avc1.4d4015, 30fps, video only, 22.27MiB
242          webm       426x240    DASH video  316k , vp9, 30fps, video only, 22.20MiB
243          webm       640x360    DASH video  557k , vp9, 30fps, video only, 41.05MiB
134          mp4        640x360    DASH video  609k , avc1.4d401e, 30fps, video only, 52.94MiB
244          webm       854x480    DASH video 1021k , vp9, 30fps, video only, 74.05MiB
135          mp4        854x480    DASH video 1115k , avc1.4d401f, 30fps, video only, 97.02MiB
247          webm       1280x720   DASH video 2011k , vp9, 30fps, video only, 150.61MiB
136          mp4        1280x720   DASH video 2282k , avc1.4d401f, 30fps, video only, 189.40MiB
248          webm       1920x1080  DASH video 3838k , vp9, 30fps, video only, 286.61MiB
137          mp4        1920x1080  DASH video 4209k , avc1.640028, 30fps, video only, 354.19MiB
17           3gp        176x144
36           3gp        320x240
5            flv        400x240
43           webm       640x360
18           mp4        640x360
22           mp4        1280x720   (best)
> youtube-dl -f 137+140 'https://www.youtube.com/watch?v=VAdRBLyjLRQ&feature=youtu.be&t=8m14s'
[youtube] Downloading login page
[youtube] Logging in
[youtube] VAdRBLyjLRQ: Downloading webpage
[youtube] VAdRBLyjLRQ: Downloading video info webpage
[youtube] VAdRBLyjLRQ: Extracting video information
(...)
</code>```

答:
Since the numbers of format are limited I did:

```<code>youtube-dl -f 299+140 "http://www.youtube.com/watch?v=P9pzm5b6FFY"
youtube-dl -f 137+140 "http://www.youtube.com/watch?v=P9pzm5b6FFY"
youtube-dl -f best "http://www.youtube.com/watch?v=P9pzm5b6FFY"
</code>```

If the 299+140 has been downloaded the 137+140 won't be and if none of those have you'll have the best starting with 22. The only problem is that you'll have the best in webm as a duplicate but you can use the ext!=webm to avoid this.

Of course you can start at 313+140 or whatever higher format you want.

Body:
With youtube-dl I first look what video quality is available and then in second step I download highest possible quality (in this example -f 137+140). Youtube-dl will automatically merge audio and video stream (DASH format)

How to automate that with shell script? With every URL, choose highest audio and video quality?

> youtube-dl -F 'https://www.youtube.com/watch?v=VAdRBLyjLRQ&feature=youtu.be&t=8m14s'
[youtube] Downloading login page
[youtube] Logging in
[youtube] VAdRBLyjLRQ: Downloading webpage
[youtube] VAdRBLyjLRQ: Downloading video info webpage
[youtube] VAdRBLyjLRQ: Extracting video information
[youtube] VAdRBLyjLRQ: Downloading DASH manifest
[youtube] VAdRBLyjLRQ: Downloading DASH manifest
[info] Available formats for VAdRBLyjLRQ:
format code  extension  resolution note
249          webm       audio only DASH audio , opus @ 50k
250          webm       audio only DASH audio , opus @ 70k
251          webm       audio only DASH audio , opus @160k
171          webm       audio only DASH audio  117k , vorbis@128k (44100Hz), 7.68MiB
140          m4a        audio only DASH audio  128k , m4a_dash container, aac  @128k (44100Hz), 11.58MiB
160          mp4        256x144    DASH video  112k , avc1.4d400c, 15fps, video only, 9.94MiB
278          webm       256x144    DASH video  136k , webm container, VP9, 15fps, video only, 9.10MiB
133          mp4        426x240    DASH video  248k , avc1.4d4015, 30fps, video only, 22.27MiB
242          webm       426x240    DASH video  316k , vp9, 30fps, video only, 22.20MiB
243          webm       640x360    DASH video  557k , vp9, 30fps, video only, 41.05MiB
134          mp4        640x360    DASH video  609k , avc1.4d401e, 30fps, video only, 52.94MiB
244          webm       854x480    DASH video 1021k , vp9, 30fps, video only, 74.05MiB
135          mp4        854x480    DASH video 1115k , avc1.4d401f, 30fps, video only, 97.02MiB
247          webm       1280x720   DASH video 2011k , vp9, 30fps, video only, 150.61MiB
136          mp4        1280x720   DASH video 2282k , avc1.4d401f, 30fps, video only, 189.40MiB
248          webm       1920x1080  DASH video 3838k , vp9, 30fps, video only, 286.61MiB
137          mp4        1920x1080  DASH video 4209k , avc1.640028, 30fps, video only, 354.19MiB
17           3gp        176x144
36           3gp        320x240
5            flv        400x240
43           webm       640x360
18           mp4        640x360
22           mp4        1280x720   (best)
> youtube-dl -f 137+140 'https://www.youtube.com/watch?v=VAdRBLyjLRQ&feature=youtu.be&t=8m14s'
[youtube] Downloading login page
[youtube] Logging in
[youtube] VAdRBLyjLRQ: Downloading webpage
[youtube] VAdRBLyjLRQ: Downloading video info webpage
[youtube] VAdRBLyjLRQ: Extracting video information
(...)

Body:
Since the numbers of format are limited I did:

youtube-dl -f 299+140 "http://www.youtube.com/watch?v=P9pzm5b6FFY"
youtube-dl -f 137+140 "http://www.youtube.com/watch?v=P9pzm5b6FFY"
youtube-dl -f best "http://www.youtube.com/watch?v=P9pzm5b6FFY"

If the 299+140 has been downloaded the 137+140 won't be and if none of those have you'll have the best starting with 22. The only problem is that you'll have the best in webm as a duplicate but you can use the ext!=webm to avoid this.

Of course you can start at 313+140 or whatever higher format you want.


问:
Classification - Usage of factor levels
I am currently working on a predictive model for a churn problem.

Whenever I try to run the following model, I get this error: At least one of the class levels is not a valid R variable name. This will cause errors when class probabilities are generated because the variables names will be converted to X0, X1. Please use factor levels that can be used as valid R variable names.

```<code>fivestats <- function(...) c( twoClassSummary(...), defaultSummary(...))
fitControl.default    <- trainControl(
    method  = "repeatedcv"
  , number  = 10
  , repeats = 1
  , verboseIter = TRUE
  , summaryFunction  = fivestats
  , classProbs = TRUE
  , allowParallel = TRUE)
set.seed(1984)

rpartGrid             <-  expand.grid(cp = seq(from = 0, to = 0.1, by = 0.001))
rparttree.fit.roc <- train(
    churn ~ .
  , data      = training.dt
  , method    = "rpart"
  , trControl = fitControl.default
  , tuneGrid  = rpartGrid
  , metric = 'ROC'
  , maximize = TRUE
)
</code>```

In the attached picture you see my data, I already transformed some data from chr to factor variable.

I do not get what my problem is, if I would transform the entire data into factors, then for instance the variable total_airtime_out will probably have around 9000 factors.

Thanks for any kind of help!

答:
Adding to the correct answer of @einar, here's the dplyr syntax of converting the factor levels:

```<code>training.dt  %>%
  mutate(churn = factor(churn,
          levels = make.names(levels(churn))))
</code>```

I slightly prefer to change only the labels of the factor levels, as the levels change the underlying data, like this:

```<code>training.dt  %>%
  mutate(churn = factor(churn,
          labels = make.names(levels(churn))))
</code>```

Title: Classification - Usage of factor levels

Body:
I am currently working on a predictive model for a churn problem.

Whenever I try to run the following model, I get this error: At least one of the class levels is not a valid R variable name. This will cause errors when class probabilities are generated because the variables names will be converted to X0, X1. Please use factor levels that can be used as valid R variable names.

fivestats <- function(...) c( twoClassSummary(...), defaultSummary(...))
fitControl.default    <- trainControl(
    method  = "repeatedcv"
  , number  = 10
  , repeats = 1
  , verboseIter = TRUE
  , summaryFunction  = fivestats
  , classProbs = TRUE
  , allowParallel = TRUE)
set.seed(1984)

rpartGrid             <-  expand.grid(cp = seq(from = 0, to = 0.1, by = 0.001))
rparttree.fit.roc <- train(
    churn ~ .
  , data      = training.dt
  , method    = "rpart"
  , trControl = fitControl.default
  , tuneGrid  = rpartGrid
  , metric = 'ROC'
  , maximize = TRUE
)

In the attached picture you see my data, I already transformed some data from chr to factor variable.

I do not get what my problem is, if I would transform the entire data into factors, then for instance the variable total_airtime_out will probably have around 9000 factors.

Thanks for any kind of help!

Body:
Adding to the correct answer of @einar, here's the dplyr syntax of converting the factor levels:

training.dt  %>%
  mutate(churn = factor(churn,
          levels = make.names(levels(churn))))

I slightly prefer to change only the labels of the factor levels, as the levels change the underlying data, like this:

training.dt  %>%
  mutate(churn = factor(churn,
          labels = make.names(levels(churn))))


问:
Sorting Functionality
I have a dropdown menu with values Sort by Laggards & Sort
     by: Achievers
    which should get sorted with ascending data for (laggards) & descending data for (Achievers)

HTML Code:

```<code><select ng-model="sortValueDropdown" ng-change="sortBy()">
  <option value="Sort by:Laggards" selected>Sort by: {{ Laggards | order }}
  </option>
  <option value="Sort by:Achievers">Sort by: Achievers
  </option>
</select>
</code>```

JavaScript code:

```<code>$scope.laggards = [
  {"name":"NOP","No":"1000"},
  {"name":"NOP","No":"1200"},
  {"name":"NOP","No":"5000"}
];

$scope.achievers = [
  {"name":"NOP","No":"2500"},
  {"name":"NOP","No":"1280"},
  {"name":"NOP","No":"5600"}
];

$scope.sortBy = function() {
  $scope.sortVal = $scope.sortValueDropdown;

  alert($scope.sortVal);

  if($scope.sortVal == 'Laggards') {

  } else if($scope.sortVal == 'Achievers') {

  }
}
</code>```

I have the above code. Please let me know how to sort this data with sort function. I am new to this.

答:
You can use Array#sort function of javascript to achieve this.
example:
For Laggards:

```<code> $scope.laggards.sort(function (a, b) {
    return a.No - b.No;
 });
</code>```

For Achievers:

```<code> $scope.achievers.sort(function (a, b) {
    return a.No - b.No;
 });
</code>```

Title: Sorting Functionality

Body:
I have a dropdown menu with values Sort by Laggards & Sort
     by: Achievers
    which should get sorted with ascending data for (laggards) & descending data for (Achievers)

HTML Code:

<select ng-model="sortValueDropdown" ng-change="sortBy()">
  <option value="Sort by:Laggards" selected>Sort by: {{ Laggards | order }}
  </option>
  <option value="Sort by:Achievers">Sort by: Achievers
  </option>
</select>

JavaScript code:

$scope.laggards = [
  {"name":"NOP","No":"1000"},
  {"name":"NOP","No":"1200"},
  {"name":"NOP","No":"5000"}
];

$scope.achievers = [
  {"name":"NOP","No":"2500"},
  {"name":"NOP","No":"1280"},
  {"name":"NOP","No":"5600"}
];

$scope.sortBy = function() {
  $scope.sortVal = $scope.sortValueDropdown;

  alert($scope.sortVal);

  if($scope.sortVal == 'Laggards') {

  } else if($scope.sortVal == 'Achievers') {

  }
}

I have the above code. Please let me know how to sort this data with sort function. I am new to this.

Body:
You can use Array#sort function of javascript to achieve this.
example:
For Laggards:

 $scope.laggards.sort(function (a, b) {
    return a.No - b.No;
 });

For Achievers:

 $scope.achievers.sort(function (a, b) {
    return a.No - b.No;
 });


问:
what is the “%1$d” output meaning?
im using ubuntu to run this code. but what does the code mean?

running ubuntu code:
gcc name.c -o name

/name

#include <stdio.h>
int main(void)
{
  printf("%d %1$d %2$d",5);
}
```

the output is "5 5 random number ". So, what meaning of %2$d?

答:
The 1$ and 2$ specifies the position of the argument. It's only specified by POSIX, it is not in C standard.

According to the C standard the behavior of printf here is undefined anyway, as the $ is not a valid printf conversion specification.

According to fprintf posix:

[...] In format strings containing the "%n$" form of a conversion
  specification, a field width or precision may be indicated by the
  sequence "*m$", where m is a decimal integer in the range
  [1,{NL_ARGMAX}] giving the position in the argument list (after the
  format argument) of an integer argument containing the field width or
  precision, for example:

printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);

So:

```<code>printf("%d %1$d %2$d",5);
</code>```

%d - specifies that the next int argument should be converted to a signed decimal.

%1$d - specifies that the first after format string int argument should be converted to a signed decimal

%2$d - specifies that the second after format string int argument should be converted to a signed decimal

You gave only two arguments to the printf function (the format string and 5). The result is undefined, because 2$ expects another argument.

Title: what is the “%1$d” output meaning?

Body:
im using ubuntu to run this code. but what does the code mean?

running ubuntu code:
gcc name.c -o name

/name

#include <stdio.h>
int main(void)
{
  printf("%d %1$d %2$d",5);
}

the output is "5 5 random number ". So, what meaning of %2$d?

Body:
The 1$ and 2$ specifies the position of the argument. It's only specified by POSIX, it is not in C standard.

According to the C standard the behavior of printf here is undefined anyway, as the $ is not a valid printf conversion specification.

According to fprintf posix:

[...] In format strings containing the "%n$" form of a conversion
  specification, a field width or precision may be indicated by the
  sequence "*m$", where m is a decimal integer in the range
  [1,{NL_ARGMAX}] giving the position in the argument list (after the
  format argument) of an integer argument containing the field width or
  precision, for example:

printf("%1$d:%2$.*3$d:%4$.*3$d\n", hour, min, precision, sec);

So:

printf("%d %1$d %2$d",5);

%d - specifies that the next int argument should be converted to a signed decimal.

%1$d - specifies that the first after format string int argument should be converted to a signed decimal

%2$d - specifies that the second after format string int argument should be converted to a signed decimal

You gave only two arguments to the printf function (the format string and 5). The result is undefined, because 2$ expects another argument.


问:
How to add pod as a target?
I created a pod(Rkeyboard) at GitHub. it was about to custom keyboard. when we want to add custom keyboard in project then it is necessary that we must create a target. But when I install the pod it doesn't create the target as i did not include any target in pod. Please tell me the way how to add pod as a target that can run with main target.
The link of pod is https://github.com/dineshsharma1/Rkeyboard
Any direction or help will appreciate.
Thanks in advance

tried to edit pod file with installer

tried to edit run script
but not succeed

project is running successfully but can't see keyboard in setting because of target

答:
Go to your Podfile and add the following code

```<code>target 'TargetName' do
 // add any pods to be installed for target
end
</code>```

Dont forget to pod install

Before all the steps above, your XCode needs to have the target matched with name you give in your Podfile. Good luck!

Title: How to add pod as a target?

Body:
Go to your Podfile and add the following code

target 'TargetName' do
 // add any pods to be installed for target
end

Dont forget to pod install

Before all the steps above, your XCode needs to have the target matched with name you give in your Podfile. Good luck!


问:
UWP Desktop Bridge app crashes on double click
I'm working on a UWP Desktop Bridge App. I have created the packaging project and created an app package for sideloading.When I click on the App
Icon once, the app launches successfully.But on double click of the Icon, the app crashes.

I have created the packaging project following the link :
https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net
The App runs normally on single click of the app icon. Is it because on double click, the .exe is being invoked twice and that's the reason for the crash?

Here is the Main method of the Background process

```<code>   private static void Main(string[] args)
    {
        try
        {
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            // hook up the connection event handlers
            connection.ServiceClosed += Connection_ServiceClosed;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus result = AppServiceConnectionStatus.Unknown;

            // static void Main cannot be async until C# 7.1, so put this on the thread pool
            Task.Run(async () =>
            {
                // open a connection to the UWP AppService
                result = await connection.OpenAsync();

            }).GetAwaiter().GetResult();

            if (result == AppServiceConnectionStatus.Success)
            {
                while (true)
                {

                }
            }
        }
        catch (Exception)
        {
        }
    }
</code>```

The code to call:

```<code>    private async Task StartBackgroundProcess()
    {
        try
        {
            // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution
            await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
        catch (Exception)
        {
            MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
            await dialog.ShowAsync();
        }
    }
</code>```

Also,inside package manifest:

```<code><desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="CommunicationService" />
    </uap:Extension>
</code>```

and

```<code><rescap:Capability Name="runFullTrust" />
</code>```

Is it possible to avoid the crash issue?

答:
if it's a connection, if you try to connect it twice, it may be crashed.  you can make u app only start up once, if it started, then switch to started process.</p>

```<code>public partial class App : Application
   {
       /// <summary>
       /// Application Entry Point.
       /// </summary>
       static Mutex muetx = new Mutex(true, "{666666666}");

       [System.STAThreadAttribute()]
       [System.Diagnostics.DebuggerNonUserCodeAttribute()]
       [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
       public static void Main()
       {
           if (muetx.WaitOne(TimeSpan.Zero, true))
           {
               TestBeginInvoke.App app = new TestBeginInvoke.App();
               app.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
               app.Run();
           }
           else
           {
               var pro = System.Diagnostics.Process.GetProcessesByName(nameof(TestBeginInvoke));
               var handle = pro.FirstOrDefault().MainWindowHandle;
               ShowWindow(handle, 1);
               ShowWindow(handle, 9);
               SetForegroundWindow(handle);
           }
       }

       [DllImport("USER32.DLL")]
       public static extern bool SetForegroundWindow(IntPtr hWnd);

       [DllImport("user32.dll")]
       private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

   }
</code>```

Body:
I'm working on a UWP Desktop Bridge App. I have created the packaging project and created an app package for sideloading.When I click on the App
Icon once, the app launches successfully.But on double click of the Icon, the app crashes.

I have created the packaging project following the link :
https://learn.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net
The App runs normally on single click of the app icon. Is it because on double click, the .exe is being invoked twice and that's the reason for the crash?

Here is the Main method of the Background process

   private static void Main(string[] args)
    {
        try
        {
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            // hook up the connection event handlers
            connection.ServiceClosed += Connection_ServiceClosed;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus result = AppServiceConnectionStatus.Unknown;

            // static void Main cannot be async until C# 7.1, so put this on the thread pool
            Task.Run(async () =>
            {
                // open a connection to the UWP AppService
                result = await connection.OpenAsync();

            }).GetAwaiter().GetResult();

            if (result == AppServiceConnectionStatus.Success)
            {
                while (true)
                {

                }
            }
        }
        catch (Exception)
        {
        }
    }

The code to call:

    private async Task StartBackgroundProcess()
    {
        try
        {
            // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution
            await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
        catch (Exception)
        {
            MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
            await dialog.ShowAsync();
        }
    }

Also,inside package manifest:

<desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="CommunicationService" />
    </uap:Extension>

and

<rescap:Capability Name="runFullTrust" />

Is it possible to avoid the crash issue?

Body:
if it's a connection, if you try to connect it twice, it may be crashed.  you can make u app only start up once, if it started, then switch to started process.

public partial class App : Application
   {
       /// <summary>
       /// Application Entry Point.
       /// </summary>
       static Mutex muetx = new Mutex(true, "{666666666}");

       [System.STAThreadAttribute()]
       [System.Diagnostics.DebuggerNonUserCodeAttribute()]
       [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
       public static void Main()
       {
           if (muetx.WaitOne(TimeSpan.Zero, true))
           {
               TestBeginInvoke.App app = new TestBeginInvoke.App();
               app.StartupUri = new Uri("MainWindow.xaml", UriKind.Relative);
               app.Run();
           }
           else
           {
               var pro = System.Diagnostics.Process.GetProcessesByName(nameof(TestBeginInvoke));
               var handle = pro.FirstOrDefault().MainWindowHandle;
               ShowWindow(handle, 1);
               ShowWindow(handle, 9);
               SetForegroundWindow(handle);
           }
       }

       [DllImport("USER32.DLL")]
       public static extern bool SetForegroundWindow(IntPtr hWnd);

       [DllImport("user32.dll")]
       private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

   }