问:
Adding Margin between EditText and keyboard
So this question has been asked few times already in here in the past years and non of the solutions worked for me.

The problem is that when I use AdjustPan to move the softkeyboard it hides part of the EditText as follows:

The solutions I tried are:

Solution 1 (2011)

Solution 2 (2014)

Solution 3 (2013)

Most of the answers include using AdjustPan/AdjustResize so I will just say that none of them give the desired solution (Showing the whole EditText when keyboard is opened).

I was thinking maybe in 2019 there is a working solution for this problem.

The xml for this layout is:

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

    <androidx.appcompat.widget.ActionMenuView
        android:id="@+id/actionbar"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/colorGrayBox"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </androidx.appcompat.widget.ActionMenuView>

    <TextView
        android:id="@+id/tv_This"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="16dp"
        android:fontFamily="@font/open_sans"
        android:text="@string/ActivityChat_This"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/actionbar" />

    <View
        android:id="@+id/v_Line"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="24dp"
        android:background="@color/colorLightGray"
        app:layout_constraintTop_toBottomOf="@+id/tv_This" />

    <androidx.cardview.widget.CardView
        android:id="@+id/imagecard"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginStart="16dp"
        app:cardCornerRadius="20dp"
        app:layout_constraintBottom_toBottomOf="@+id/actionbar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageButton
            android:id="@+id/ivPersonPic"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@null" />

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:fontFamily="@font/assistant_bold"
        android:textColor="@color/colorLightPurple"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="@+id/actionbar"
        app:layout_constraintStart_toEndOf="@+id/imagecard"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_Messages"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/constraint2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/v_Line"/>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraint2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintHeight_percent="0.1">

        <EditText
            android:id="@+id/et_Message"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginStart="12dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@drawable/et_rounded"
            android:fontFamily="@font/assistant"
            android:gravity="center_vertical"
            android:hint="@string/ActivityChat_Type"
            android:inputType="textMultiLine|textPersonName"
            android:paddingEnd="32dp"
            android:paddingStart="32dp"
            android:textSize="16sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintWidth_percent="0.85" />

        <ImageButton
            android:id="@+id/ib_Send"
            style="?android:borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_chats_send"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintWidth_percent="0.1" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:itemBackground="@color/colorWhite"
        app:itemIconTint="@drawable/btm_nav"
        app:itemTextColor="@drawable/btm_nav"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.08"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/menu_btm_nav" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
I had a lot of problems with the keyboard myself, but I prefer using android:windowSoftInputMode="adjustResize" so you can handle the changes yourself. You should add a windowInsetsListener to your root view and if you don't have a transparent navigation bar the systemWindowInsetBottom should only be the keyboard. So you can just add padding to the container you're interested in. This is an example I use:

```<code>rootContainer.setOnApplyWindowInsetsListener { view, windowInsets ->
    var containerPadding = 0
    if (windowInsets.systemWindowInsetBottom > 0) {
        val bottomBarHeight = bottomBar.bottom - bottomBar.top
        containerPadding = windowInsets.systemWindowInsetBottom - bottomBarHeight
    }

    if (containerPadding < 0) {
        containerPadding = 0
    }

    contentView.bottomPadding = containerPadding

    return@setOnApplyWindowInsetsListener windowInsets.replaceSystemWindowInsets(windowInsets.systemWindowInsetLeft, windowInsets.systemWindowInsetTop, windowInsets.systemWindowInsetRight, 0)
}
</code>```

This way you can move the container above the bottomBar up (which has your EditText in it).

For me this was the best option I've found so far. Most options rely on GlobalLayoutListeners and see how much it changes, but this is far more reliable.

Body:
So this question has been asked few times already in here in the past years and non of the solutions worked for me.

The problem is that when I use AdjustPan to move the softkeyboard it hides part of the EditText as follows:

The solutions I tried are:

Solution 1 (2011)

Solution 2 (2014)

Solution 3 (2013)

Most of the answers include using AdjustPan/AdjustResize so I will just say that none of them give the desired solution (Showing the whole EditText when keyboard is opened).

I was thinking maybe in 2019 there is a working solution for this problem.

The xml for this layout is:

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

    <androidx.appcompat.widget.ActionMenuView
        android:id="@+id/actionbar"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/colorGrayBox"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    </androidx.appcompat.widget.ActionMenuView>

    <TextView
        android:id="@+id/tv_This"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="16dp"
        android:fontFamily="@font/open_sans"
        android:text="@string/ActivityChat_This"
        android:textSize="12sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/actionbar" />

    <View
        android:id="@+id/v_Line"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_marginLeft="24dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="24dp"
        android:background="@color/colorLightGray"
        app:layout_constraintTop_toBottomOf="@+id/tv_This" />

    <androidx.cardview.widget.CardView
        android:id="@+id/imagecard"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_marginStart="16dp"
        app:cardCornerRadius="20dp"
        app:layout_constraintBottom_toBottomOf="@+id/actionbar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ImageButton
            android:id="@+id/ivPersonPic"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@null" />

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:fontFamily="@font/assistant_bold"
        android:textColor="@color/colorLightPurple"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="@+id/actionbar"
        app:layout_constraintStart_toEndOf="@+id/imagecard"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_Messages"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toTopOf="@+id/constraint2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/v_Line"/>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraint2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottom_navigation"
        app:layout_constraintHeight_percent="0.1">

        <EditText
            android:id="@+id/et_Message"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginStart="12dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:background="@drawable/et_rounded"
            android:fontFamily="@font/assistant"
            android:gravity="center_vertical"
            android:hint="@string/ActivityChat_Type"
            android:inputType="textMultiLine|textPersonName"
            android:paddingEnd="32dp"
            android:paddingStart="32dp"
            android:textSize="16sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintWidth_percent="0.85" />

        <ImageButton
            android:id="@+id/ib_Send"
            style="?android:borderlessButtonStyle"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:adjustViewBounds="true"
            android:src="@drawable/ic_chats_send"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintWidth_percent="0.1" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:itemBackground="@color/colorWhite"
        app:itemIconTint="@drawable/btm_nav"
        app:itemTextColor="@drawable/btm_nav"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="0.08"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/menu_btm_nav" />

</androidx.constraintlayout.widget.ConstraintLayout>

Body:
I had a lot of problems with the keyboard myself, but I prefer using android:windowSoftInputMode="adjustResize" so you can handle the changes yourself. You should add a windowInsetsListener to your root view and if you don't have a transparent navigation bar the systemWindowInsetBottom should only be the keyboard. So you can just add padding to the container you're interested in. This is an example I use:

rootContainer.setOnApplyWindowInsetsListener { view, windowInsets ->
    var containerPadding = 0
    if (windowInsets.systemWindowInsetBottom > 0) {
        val bottomBarHeight = bottomBar.bottom - bottomBar.top
        containerPadding = windowInsets.systemWindowInsetBottom - bottomBarHeight
    }

    if (containerPadding < 0) {
        containerPadding = 0
    }

    contentView.bottomPadding = containerPadding

    return@setOnApplyWindowInsetsListener windowInsets.replaceSystemWindowInsets(windowInsets.systemWindowInsetLeft, windowInsets.systemWindowInsetTop, windowInsets.systemWindowInsetRight, 0)
}

This way you can move the container above the bottomBar up (which has your EditText in it).

For me this was the best option I've found so far. Most options rely on GlobalLayoutListeners and see how much it changes, but this is far more reliable.


来源: stackexchange

问:
Reactor - How to use filterWhen and still pass the value for logging purposes if it doesn't pass the filter?
I am trying to figure out the right way to do the following.

I want to check if a record exists in database by name, which is a global secondary index. (Let's say the primary key is id).

If there's already an item that has name, then log the id and name and returns an error.

If there's not an item with the given name, then proceed.

Right now, the code structure looks like this.

```<code>private fun checkExistingData(name: String): Mono<QueryResponse> {
  return repo.getDataByName(name)
    .filterWhen { Mono.just(!it.hasItems()) }
    .switchIfEmpty {
      // log the existing id and name from QueryResponse
      Mono.error(SomeCustomException))
    }
    .flatMap {
      // proceed
    }
}
</code>```

As you can see, if I want to log the id in the switchIfEmpty clause, I would need to do repo.getDataByName(name) in it to be able to retrieve the item and get the id of the item. Obviously, this is inefficient as I already do that prior to switchIfEmpty.

What's the right way to do this?

答:
Pending more information on the QueryResponse API, I'm going to assume a few things:
 - getDataByName returns a Mono<QueryResponse>. This Mono is ALWAYS valued, ie it always emits exactly one QueryResponse wheter or not data could be found
 - QueryResponse#items is what I'll use in my example to access the rows proper. I'm going to also assume it returns a Flux<Item>

First off, filterWhen is not useful here since we also have a filter(boolean) method. I think that reversed filter logic is maybe a bit harder to follow.

Why not do everything in the flatMap instead?

```<code>private fun checkExistingData(name: String): Mono<QueryResponse> {
  return repo.getDataByName(name)
    .flatMap {
       if (it.hasItems())
         it.items()
           .single()
           .doOnNext(existing -> logExisting(existing.id(), existing.name())
           .then(Mono.error(SomeCustomException)
        else
          proceed()
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to figure out the right way to do the following.

I want to check if a record exists in database by name, which is a global secondary index. (Let's say the primary key is id).

If there's already an item that has name, then log the id and name and returns an error.

If there's not an item with the given name, then proceed.

Right now, the code structure looks like this.

private fun checkExistingData(name: String): Mono<QueryResponse> {
  return repo.getDataByName(name)
    .filterWhen { Mono.just(!it.hasItems()) }
    .switchIfEmpty {
      // log the existing id and name from QueryResponse
      Mono.error(SomeCustomException))
    }
    .flatMap {
      // proceed
    }
}

As you can see, if I want to log the id in the switchIfEmpty clause, I would need to do repo.getDataByName(name) in it to be able to retrieve the item and get the id of the item. Obviously, this is inefficient as I already do that prior to switchIfEmpty.

What's the right way to do this?

Body:
Pending more information on the QueryResponse API, I'm going to assume a few things:
 - getDataByName returns a Mono<QueryResponse>. This Mono is ALWAYS valued, ie it always emits exactly one QueryResponse wheter or not data could be found
 - QueryResponse#items is what I'll use in my example to access the rows proper. I'm going to also assume it returns a Flux<Item>

First off, filterWhen is not useful here since we also have a filter(boolean) method. I think that reversed filter logic is maybe a bit harder to follow.

Why not do everything in the flatMap instead?

private fun checkExistingData(name: String): Mono<QueryResponse> {
  return repo.getDataByName(name)
    .flatMap {
       if (it.hasItems())
         it.items()
           .single()
           .doOnNext(existing -> logExisting(existing.id(), existing.name())
           .then(Mono.error(SomeCustomException)
        else
          proceed()
    }
}


问:
Parameter 0 of constructor in .. required a bean of type org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate could not be found
I have written a simple todo app (based on what comes in apress pro spring boot in which we use jdbc to deal with database ,in the repository we have the following code to deal with h2 database

```<code>package com.apress.todo.repository;

import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.apress.todo.domain.ToDo;

@Repository
public class ToDoRepository implements CommonRepository<ToDo> {
    private static final String SQL_INSERT ="insert into todo (id,\r\n" +
            "description, created, modified, completed) values (:id,:description,\r\n" +
            ":created,:modified,:completed)";
    private static final String SQL_QUERY_FIND_ALL = "select id,"
            +"description, created, modified, completed from todo";
    private static final String SQL_QUERY_FIND_BY_ID = SQL_QUERY_FIND_ALL +
            " where id = :id";
    private static final String SQL_UPDATE = "update todo set description ="
            +":description, modified = :modified, completed = :completed"
            +"where id = :id";
    private static final String SQL_DELETE = "delete from todo where id = :id";
    private final NamedParameterJdbcTemplate jdbcTemplate;

    public ToDoRepository(NamedParameterJdbcTemplate jdbcTemplate) {//HERE IS WHERE THE PROBLEM IS
        System.out.println("hi masoud");
        this.jdbcTemplate = jdbcTemplate;
    }

    private RowMapper<ToDo> toDoRowMapper = (ResultSet rs, int rowNum) -> {
        ToDo toDo = new ToDo();
        toDo.setId(rs.getString("id"));
        toDo.setDescription(rs.getString("description"));
        toDo.setModified(rs.getTimestamp("modified").toLocalDateTime());
        toDo.setCreated(rs.getTimestamp("created").toLocalDateTime());
        toDo.setCompleted(rs.getBoolean("completed"));
        return toDo;
    };
</code>```

and the following is my main spring boot application runner

```<code>package com.apress.todo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TodoInMemoryApplication {

    public static void main(String[] args) {
        SpringApplication.run(TodoInMemoryApplication.class, args);
    }

}
</code>```

but when I run the application using spring boot command line interface I will get the following error:
Description:

```<code>Parameter 0 of constructor in com.apress.todo.repository.ToDoRepository required a bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' in your configuration.
</code>```

there is nothing more explained in the book .

答:
I don't know what examples in your book look like but I'll try to help you. Look, you declare a field private final NamedParameterJdbcTemplate jdbcTemplate; . Somehow you hope to spring to initilize it. In order for it you have to declare @Bean with NamedParameterJdbcTemplate type in @Configuration class or create a @Component class extending NamedParameterJdbcTemplate. Or extend NamedParameterJdbcDaoSupport and get via getNamedParameterJdbcTemplate();

Actually with your example, adding spring-boot-starter-jdbc

```<code><dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
</code>```

and adding properties e.g

```<code>spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
</code>```

should solve this problem according tutorial

Body:
I have written a simple todo app (based on what comes in apress pro spring boot in which we use jdbc to deal with database ,in the repository we have the following code to deal with h2 database

package com.apress.todo.repository;

import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.apress.todo.domain.ToDo;

@Repository
public class ToDoRepository implements CommonRepository<ToDo> {
    private static final String SQL_INSERT ="insert into todo (id,\r\n" +
            "description, created, modified, completed) values (:id,:description,\r\n" +
            ":created,:modified,:completed)";
    private static final String SQL_QUERY_FIND_ALL = "select id,"
            +"description, created, modified, completed from todo";
    private static final String SQL_QUERY_FIND_BY_ID = SQL_QUERY_FIND_ALL +
            " where id = :id";
    private static final String SQL_UPDATE = "update todo set description ="
            +":description, modified = :modified, completed = :completed"
            +"where id = :id";
    private static final String SQL_DELETE = "delete from todo where id = :id";
    private final NamedParameterJdbcTemplate jdbcTemplate;

    public ToDoRepository(NamedParameterJdbcTemplate jdbcTemplate) {//HERE IS WHERE THE PROBLEM IS
        System.out.println("hi masoud");
        this.jdbcTemplate = jdbcTemplate;
    }

    private RowMapper<ToDo> toDoRowMapper = (ResultSet rs, int rowNum) -> {
        ToDo toDo = new ToDo();
        toDo.setId(rs.getString("id"));
        toDo.setDescription(rs.getString("description"));
        toDo.setModified(rs.getTimestamp("modified").toLocalDateTime());
        toDo.setCreated(rs.getTimestamp("created").toLocalDateTime());
        toDo.setCompleted(rs.getBoolean("completed"));
        return toDo;
    };

and the following is my main spring boot application runner

package com.apress.todo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TodoInMemoryApplication {

    public static void main(String[] args) {
        SpringApplication.run(TodoInMemoryApplication.class, args);
    }

}

but when I run the application using spring boot command line interface I will get the following error:
Description:

Parameter 0 of constructor in com.apress.todo.repository.ToDoRepository required a bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate' in your configuration.

there is nothing more explained in the book .

Body:
I don't know what examples in your book look like but I'll try to help you. Look, you declare a field private final NamedParameterJdbcTemplate jdbcTemplate; . Somehow you hope to spring to initilize it. In order for it you have to declare @Bean with NamedParameterJdbcTemplate type in @Configuration class or create a @Component class extending NamedParameterJdbcTemplate. Or extend NamedParameterJdbcDaoSupport and get via getNamedParameterJdbcTemplate();

Actually with your example, adding spring-boot-starter-jdbc

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

and adding properties e.g

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

should solve this problem according tutorial


问:
ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property
I have upgraded the angular 4 application to angular 6. I have basically two projects. The parent project is packaged and referenced in the child project. The screen shot below shows parent project folder called @wtw that is referenced in the client project. The @wtw folder is under the node_modules folder.
 The child project was building the parent package fine when it was in Angular  version 4. Ever since the upgrade has been done to 6 it complains of ts files under the wtw folder seems missing from the TypeScript compilation. Do I need to explicitly include the path in the tsConfig file.

I tried to add the following in the tsConfig but no difference

```<code>"inlcude": [
    "node_modules/@wtw/**/*"
  ]
</code>```

tsConfig file

```<code>{
  "compileOnSave": false,

  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types",
      "type-definition"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "inlcude": [
    "node_modules/@wtw/**/*"
  ]
}
</code>```

angular.json file

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "irm",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "../wwwroot",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/assets",
              "src/favicon.ico",
              "src/favicon.png",
              "src/web.config",
              {
                "glob": "**/*",
                "input": "../node_modules/@wtw/platform/assets",
                "output": "./assets"
              },
              {
                "glob": "**/*",
                "input": "../assets",
                "output": "./assets"
              }
            ],
            "styles": [
              "../IRM.ClientSide/node_modules/@wtw/platform/styling/platform.scss"
            ],
            "scripts": [
              "../IRM.ClientSide/node_modules/jsoneditor/dist/jsoneditor.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "environments/environment.ts",
                  "with": "environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "test.ts",
            "polyfills": "polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts"
            ]
          }
        }
      }
    },
    "pdf": {
      "root": "src",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "irm",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "../pdf",
            "index": "pdf.html",
            "main": "pdf.ts",
            "polyfills": "polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "assets",
              "favicon.ico",
              {
                "glob": "**/*",
                "input": "../node_modules/@wtw/platform/assets",
                "output": "./assets"
              }
            ],
            "styles": [
              "./styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "environments/environment.ts",
                  "with": "environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "test.ts",
            "polyfills": "polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts"
            ]
          }
        }
      }
    },
    "app-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "app"
}
</code>```

答: I did a branch change in a git console,  but I work with Visual Studio Code. After that branch change ther error occured. Restarting Visual Studio helped.</p>

Body:
I have upgraded the angular 4 application to angular 6. I have basically two projects. The parent project is packaged and referenced in the child project. The screen shot below shows parent project folder called @wtw that is referenced in the client project. The @wtw folder is under the node_modules folder.
 The child project was building the parent package fine when it was in Angular  version 4. Ever since the upgrade has been done to 6 it complains of ts files under the wtw folder seems missing from the TypeScript compilation. Do I need to explicitly include the path in the tsConfig file.

I tried to add the following in the tsConfig but no difference

"inlcude": [
    "node_modules/@wtw/**/*"
  ]

tsConfig file

{
  "compileOnSave": false,

  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types",
      "type-definition"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  },
  "inlcude": [
    "node_modules/@wtw/**/*"
  ]
}

angular.json file

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "irm",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "../wwwroot",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/assets",
              "src/favicon.ico",
              "src/favicon.png",
              "src/web.config",
              {
                "glob": "**/*",
                "input": "../node_modules/@wtw/platform/assets",
                "output": "./assets"
              },
              {
                "glob": "**/*",
                "input": "../assets",
                "output": "./assets"
              }
            ],
            "styles": [
              "../IRM.ClientSide/node_modules/@wtw/platform/styling/platform.scss"
            ],
            "scripts": [
              "../IRM.ClientSide/node_modules/jsoneditor/dist/jsoneditor.js"
            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "environments/environment.ts",
                  "with": "environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "test.ts",
            "polyfills": "polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts"
            ]
          }
        }
      }
    },
    "pdf": {
      "root": "src",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "irm",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "../pdf",
            "index": "pdf.html",
            "main": "pdf.ts",
            "polyfills": "polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              "assets",
              "favicon.ico",
              {
                "glob": "**/*",
                "input": "../node_modules/@wtw/platform/assets",
                "output": "./assets"
              }
            ],
            "styles": [
              "./styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "environments/environment.ts",
                  "with": "environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "test.ts",
            "polyfills": "polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts",
              "**/node_modules/**/*",
              "**/src/app/api/**/*",
              "**/src/polyfills.ts"
            ]
          }
        }
      }
    },
    "app-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "app"
}


问:
Frida, hook OKHttp Library does not work with examples
I'm trying to hook functions of the OKHttp library by using then following Frida script:

```<code>setTimeout(function(){
    Java.perform(function (){
        console.log("-- Hook OKHttp library --");

        try {
            var Builder = Java.use('okhttp3.CertificatePinner$Builder');
            var Pin = Java.use('okhttp3.CertificatePinner$Pin');
            var OkHttpClient = Java.use('okhttp3.OkHttpClient$Builder');
            console.log("OkHTTP classes found");

            Builder.add.overload.implementation = function(a, b) {
                console.log("TEST ADD");
            }

            Pin.matches.overload.implementation = function (a) {
                console.log("TEST matches")
                return true;
            }

            OkHttpClient.certificatePinner.overload.implementation = function (a) {
                console.log("TEST certificatePinner");
            }

            console.log("OkHTTP functions found");
        } catch (err) {
            // If we dont have a ClassNotFoundException exception, raise the
            // problem encountered.
            console.log("OkHTTP 3.x classes/functions not Found");
        }

    });
},0);
</code>```

And I am executing the following code in my Android application:

```<code>            CertificatePinner certificatePinner = new CertificatePinner.Builder()
                    .add(certificateDNWildcard, certificateHash)
                    .build();
            //Create http client with pinned certificate
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .certificatePinner(certificatePinner)
                    .build();
</code>```

As you can see I am calling the function .add(certificateDNWildcard, certificateHash) which I am trying to hook. However, nothing is printed in the terminal when I execute this function. Furthermore, the output of my terminal is:

```<code>-- Hook OKHttp library --
OkHTTP classes found
OkHTTP functions found
</code>```

Hence, it does find the classes and functions; however, the hook itself does not work effectively. Could someone help me?

I am using:

```<code>* Frida 12.8.11
* Android 10
* ARM64
</code>```

答:
You should either:

// works if add method has a single implementation
Builder.add.implementation = function(a, b) {
    console.log("TEST ADD");
}
```

<p>or</p>

<pre class="lang-js prettyprint-override"><code>// always works
Builder.add.overload('java.lang.String', 'java.lang.String').implementation = function(a, b) {
    console.log("TEST ADD");
}
</code>```

Body:
I'm trying to hook functions of the OKHttp library by using then following Frida script:

setTimeout(function(){
    Java.perform(function (){
        console.log("-- Hook OKHttp library --");

        try {
            var Builder = Java.use('okhttp3.CertificatePinner$Builder');
            var Pin = Java.use('okhttp3.CertificatePinner$Pin');
            var OkHttpClient = Java.use('okhttp3.OkHttpClient$Builder');
            console.log("OkHTTP classes found");

            Builder.add.overload.implementation = function(a, b) {
                console.log("TEST ADD");
            }

            Pin.matches.overload.implementation = function (a) {
                console.log("TEST matches")
                return true;
            }

            OkHttpClient.certificatePinner.overload.implementation = function (a) {
                console.log("TEST certificatePinner");
            }

            console.log("OkHTTP functions found");
        } catch (err) {
            // If we dont have a ClassNotFoundException exception, raise the
            // problem encountered.
            console.log("OkHTTP 3.x classes/functions not Found");
        }

    });
},0);

And I am executing the following code in my Android application:

            CertificatePinner certificatePinner = new CertificatePinner.Builder()
                    .add(certificateDNWildcard, certificateHash)
                    .build();
            //Create http client with pinned certificate
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .certificatePinner(certificatePinner)
                    .build();

As you can see I am calling the function .add(certificateDNWildcard, certificateHash) which I am trying to hook. However, nothing is printed in the terminal when I execute this function. Furthermore, the output of my terminal is:

-- Hook OKHttp library --
OkHTTP classes found
OkHTTP functions found

Hence, it does find the classes and functions; however, the hook itself does not work effectively. Could someone help me?

I am using:

* Frida 12.8.11
* Android 10
* ARM64

Body:
You should either:

// works if add method has a single implementation
Builder.add.implementation = function(a, b) {
    console.log("TEST ADD");
}

or

// always works
Builder.add.overload('java.lang.String', 'java.lang.String').implementation = function(a, b) {
    console.log("TEST ADD");
}


问:
Tensorflow: ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory
I have recently installed tensorflow-gpu using pip. But when I am importing it it is giving the following error:

```<code>ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory
</code>```

I have gone through all the answers of stackoverflow related to this issue but none of them worked for me.

libcudnn.so.7 is present in both the following directories /usr/local/cuda/lib64 and /usr/local/cuda-9.0/lib64 .

Also, I have added the following path in my .bashrc file:

```<code>export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

export PATH=/usr/local/cuda/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
</code>```

Please help me in resolving this

答:
The reason is that some libraries are missing.
Try installing

sudo apt install libcudnn7
```

Body:
I have recently installed tensorflow-gpu using pip. But when I am importing it it is giving the following error:

ImportError: libcudnn.so.7: cannot open shared object file: No such file or directory

I have gone through all the answers of stackoverflow related to this issue but none of them worked for me.

libcudnn.so.7 is present in both the following directories /usr/local/cuda/lib64 and /usr/local/cuda-9.0/lib64 .

Also, I have added the following path in my .bashrc file:

export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

export PATH=/usr/local/cuda/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda/lib64\${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

Please help me in resolving this


问:
change location of image which is pulled in docker-compose
I have a docker-compose.yml which is pulling an image. When i am running the docker-compose file. It throws no space error. How can i specify the path where the image is downloaded. it getting downloaded it root which just has 15gb. I want it to be downloaded in /home because it has a lot of space left.</p>

答:
You can change the data root path of docker in the configuration file located by default /etc/docker/daemon.json. The property to change is data-root.

You can find out more in the official documentation.


问:
MongoDB Aggregation Data Returned
I am using MongoDB Aggregation to query two different schema collections.

```<code>Artist.aggregate([
    {
        $match: { artistID }
    },
    {
        $lookup: {
            from: "users",
            localField: "userID",
            foreignField: "_id",
            as: "UsersWithMatchedArtist"
        }
    },
    {
        $project: {
            UsersWithMatchedArtist: 1
        }
    }
}
])
</code>```

This returns a the following data structure.

```<code>[
  {
    "_id": "59f8f40686f2fa623d815256",
    "UsersWithMatchedArtist": [{Users Schema}]
  },
  {
    "_id": "59f8f40686f2f12345678901",
    "UsersWithMatchedArtist": [{Users Schema}}]
  }
]
</code>```

I wish to have the data returned in the following structure

```<code>[
  {Users Schema},
  {Users Schema}
]
</code>```

Any Suggestions on how to do this? Suggestions would be much appreciated! Cheers!

答:
To get the desired results, you can add $unwind and $group to the existing pipeline.

```<code>[
    {
        "$match": { artistID }
    },
    {
        "$lookup": {
            "from": "users",
            "localField": "userID",
            "foreignField": "_id",
            "as": "UsersWithMatchedArtist"
        }
    },
    {
        "$project": {
            "UsersWithMatchedArtist": 1
        }
    },
    {
        "$unwind": "$UsersWithMatchedArtist"
    },
    {
        "$group": {
            "_id": null,    // or add your own grouping
            "UsersWithMatchedArtist": {"$push": "$UsersWithMatchedArtist"}
        }
    }
}]
</code>```

Your output will be of the form:

```<code>{
    "_id" : null,
    "users" : [
        {Users Schema},
        {Users Schema}
    ]
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: MongoDB Aggregation Data Returned

Body:
I am using MongoDB Aggregation to query two different schema collections.

Artist.aggregate([
    {
        $match: { artistID }
    },
    {
        $lookup: {
            from: "users",
            localField: "userID",
            foreignField: "_id",
            as: "UsersWithMatchedArtist"
        }
    },
    {
        $project: {
            UsersWithMatchedArtist: 1
        }
    }
}
])

This returns a the following data structure.

[
  {
    "_id": "59f8f40686f2fa623d815256",
    "UsersWithMatchedArtist": [{Users Schema}]
  },
  {
    "_id": "59f8f40686f2f12345678901",
    "UsersWithMatchedArtist": [{Users Schema}}]
  }
]

I wish to have the data returned in the following structure

[
  {Users Schema},
  {Users Schema}
]

Any Suggestions on how to do this? Suggestions would be much appreciated! Cheers!

Body:
To get the desired results, you can add $unwind and $group to the existing pipeline.

[
    {
        "$match": { artistID }
    },
    {
        "$lookup": {
            "from": "users",
            "localField": "userID",
            "foreignField": "_id",
            "as": "UsersWithMatchedArtist"
        }
    },
    {
        "$project": {
            "UsersWithMatchedArtist": 1
        }
    },
    {
        "$unwind": "$UsersWithMatchedArtist"
    },
    {
        "$group": {
            "_id": null,    // or add your own grouping
            "UsersWithMatchedArtist": {"$push": "$UsersWithMatchedArtist"}
        }
    }
}]

Your output will be of the form:

{
    "_id" : null,
    "users" : [
        {Users Schema},
        {Users Schema}
    ]
}


问:
How to delete Firebase Cloud Messaging Token when user Log-Out of the React Native application?
I use React Native FCM for messaging, and when the user logs out the application I want to delete the FCM token so that the user doesn't get Notified again.

Below is my code for logout.

```<code>_signOutAsync = async () => {
    this.logoutEvent()
    API.post('customer/auth/logout', null, {
      headers: {
        Authorization:
          'Bearer ' + (await AsyncStorage.getItem(Config.ACCESS_TOKEN))
      }
    }).then((response) => {
      console.log(response)
    })
    this.clearData()
  }
</code>```

Thanks.

答:
Simply add below given code in your logout function -

for react-native-firebase <= v5.x.x

```<code>firebase.messaging().deleteToken()
</code>```

for > 5.x.x or using @react-native-firebase/messaging

```<code>import messaging from '@react-native-firebase/messaging';

messaging().deleteToken()
</code>```

Body:
I use React Native FCM for messaging, and when the user logs out the application I want to delete the FCM token so that the user doesn't get Notified again.

Below is my code for logout.

_signOutAsync = async () => {
    this.logoutEvent()
    API.post('customer/auth/logout', null, {
      headers: {
        Authorization:
          'Bearer ' + (await AsyncStorage.getItem(Config.ACCESS_TOKEN))
      }
    }).then((response) => {
      console.log(response)
    })
    this.clearData()
  }

Thanks.

Body:
Simply add below given code in your logout function -

for react-native-firebase <= v5.x.x

firebase.messaging().deleteToken()

for > 5.x.x or using @react-native-firebase/messaging

import messaging from '@react-native-firebase/messaging';

messaging().deleteToken()


问:
CheckBox covers text in GridView
I'm pretty new to Android, and I'm looking for a little help.
I have a GridView with the following XML in a linear layout.

```<code><GridView android:id="@+id/gridview"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:numColumns="2"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"/>
</code>```

I'm adding a series of CheckBoxes to the view with...

```<code>    public View getView(int position, View convertView, ViewGroup parent)
    {
        CheckBox checkView;
        if (convertView == null) {
            checkView = new CheckBox(context);
            checkView.setPadding(5, 5, 5, 5);
        } else {
            checkView = (CheckBox) convertView;
        }
        checkView.setText(checkNames[position]);
        checkView.setWidth(400);

        return checkView;
    }
</code>```

No matter how many different widths I try, including fill_parent and
wrap_content, the text winds up behind the box instead of next to it.
Any hints or tricks?
Thanks,
Andrew

答: Try using only wrap content for both layout width and layout height. Because the fill_parent will fill the full layout, where as wrap_content will fill only to the size of your text entered. </p>

Title: CheckBox covers text in GridView

Body:
I'm pretty new to Android, and I'm looking for a little help.
I have a GridView with the following XML in a linear layout.

<GridView android:id="@+id/gridview"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:numColumns="2"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"/>

I'm adding a series of CheckBoxes to the view with...

    public View getView(int position, View convertView, ViewGroup parent)
    {
        CheckBox checkView;
        if (convertView == null) {
            checkView = new CheckBox(context);
            checkView.setPadding(5, 5, 5, 5);
        } else {
            checkView = (CheckBox) convertView;
        }
        checkView.setText(checkNames[position]);
        checkView.setWidth(400);

        return checkView;
    }

No matter how many different widths I try, including fill_parent and
wrap_content, the text winds up behind the box instead of next to it.
Any hints or tricks?
Thanks,
Andrew


问:
I have a question with option in DNSperf tool in Linux
I tried to use the DNSperf tool that is the benchmark testing tool for an authoritative name server in Linux. This tool has various features to provide the result in many aspects.  But I would like to know some options like -c and -q.  I tried to observe it from the source code in C. But I don't get it.

-c from the manual, it's written that

-c clients Enables the local server to act as multiple clients and specifies the number of clients represented by this server. The server
  sends requests from multiple sockets. By default, the local server
  acts as a single client.

In fact, it's just trying to send many queries as many internal threads from the source code. And the maximum of the inputted value in -c option must not exceed 256 that means the length of the socket should not exceed 256?

And two:
I'm also curious about the -q option, it's written that

-q num_queries Sets the maximum number of outstanding requests. When this value is reached, dnsperf stops sending requests until either
  response is received or its requests time out. The default value is
  100.

What is the trigger runs the number reaches 100? I don't understand about this and I tried to seek out from the source code, it's quite too complex.

Could everyone help me to understand it?   I know my question is quite ambiguous, but I'm not sure how to exactly ask the right way about this so please help me.

答:
"-c" option specifies how many local source ports to use when doing queries. This is default to 1. So, you will see all queries using only one source port. Maximum value 256 means that you can use a max of 256 unique src ports to send DNS queries.

"-q" is the queue limit. There can be at most this many queries in the dnsperf queue when it stops generating new queries.

So, if the DNS server is slower than usual and takes a longer time to respond, dnsperf will only generate "-q" number of queries and wait for responses.

For example, if you set "-q" to 100, dnsperf will generate at most 100 queries and wait for their responses or timeout. If it gets 5 responses, it will generate 5 new queries, and again the queue will be full at 100.
If the dns server is fast, it may happen that the queue limit of 100 is never reached, and dnsperf will make DNS queries as fast as possible.

Be aware that using a high value for -c and -q will also likely increase the memory usage of dnsperf tool in certain network conditions.


问:
Create html table from arrays
I have managed to create two arrays from database, one for table_headers as follows

```<code>$tb_headers=array('010','011','012','013','014','015','016');
</code>```

And also generated other arrays of table _data from database as follows

```<code>$tb_data=array(
array('011','013','014','015'),
array('010','012','014','015','016'),
array('010','011','013','016'),
array('010','011','012','013','014','015','016')
);
</code>```

How do I generate table of this format??

```<code> th      010 |  011 |   012|   013|    014 |   015 |     016
row1      -  |  011 |   -  |   013|    014 |   015 |     -
row2     010 |   -  |  012 |    - |    014 |   015 |     016
row3     010 |  011 |   -  |   013|     -  |    -  |     016
row4     010 |  011 |  012 |   013|    014 |   015 |     016
</code>```

I have tried to write this script which is not working as expected

```<code><table style="width:50%;" border="1">
   <tr>
      <?php
      foreach ($tb_headers as $key => $value) {
        echo '<th>'.$value.'</th>';
      }
      echo '</tr>';
      foreach ($tb_headers as $key => $data) {
        echo '<tr>';
        if(!empty($tb_data[$key])&& $tb_data[$key]==$data ){
           echo '<td>'.$tb_data[$key].'</td>';
        }else{
         echo '<td>-</td>';
        }
        echo '</tr>';
      }
      ?>
</table>
</code>```

答:
Try this, which uses the php in_array() function.

  <?php
  // header
  foreach ($tb_headers as $value) echo '' . $value . '	';
  ?>

  <?php
  // content
  foreach ($tb_data as $line => $values) {
    echo '
';
    foreach ($tb_headers as $header) {
      echo '';
      if (in_array($header, $values)) echo $header;
      else echo '-';
      echo '	';
    }
    echo '
';
  }
  ?>

```

Title: Create html table from arrays

Body:
I have managed to create two arrays from database, one for table_headers as follows

$tb_headers=array('010','011','012','013','014','015','016');

And also generated other arrays of table _data from database as follows

$tb_data=array(
array('011','013','014','015'),
array('010','012','014','015','016'),
array('010','011','013','016'),
array('010','011','012','013','014','015','016')
);

How do I generate table of this format??

 th      010 |  011 |   012|   013|    014 |   015 |     016
row1      -  |  011 |   -  |   013|    014 |   015 |     -
row2     010 |   -  |  012 |    - |    014 |   015 |     016
row3     010 |  011 |   -  |   013|     -  |    -  |     016
row4     010 |  011 |  012 |   013|    014 |   015 |     016

I have tried to write this script which is not working as expected

      <?php
      foreach ($tb_headers as $key => $value) {
        echo ''.$value.'	';
      }
      echo '
';
      foreach ($tb_headers as $key => $data) {
        echo '
';
        if(!empty($tb_data[$key])&& $tb_data[$key]==$data ){
           echo ''.$tb_data[$key].'	';
        }else{
         echo '-	';
        }
        echo '
';
      }
      ?>

Body:
Try this, which uses the php in_array() function.

<table>
  <tr>
  <?php
  // header
  foreach ($tb_headers as $value) echo '<th>' . $value . '</th>';
  ?>
  </tr>
  <?php
  // content
  foreach ($tb_data as $line => $values) {
    echo '<tr>';
    foreach ($tb_headers as $header) {
      echo '<td>';
      if (in_array($header, $values)) echo $header;
      else echo '-';
      echo '</td>';
    }
    echo '</tr>';
  }
  ?>
</table>


问:
Vue.js 'openNav' is defined but never used / 'closeNav' is defined but never used
When starting the website it shows the errors mentioned in the title.

Here's the HTML part:

```<code><span style="font-size:30px;cursor:pointer;" onclick="openNav()">☰</span>

    <div id="mySidenav" class="sidenav">
      <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
      <a href="#">{{name1}}</a>
      <a href="#">{{name2}}</a>
      <a href="#">{{name3}}</a>
      <a href="#">{{name4}}</a>
      </div>
</code>```

And here is the js part:

```<code>//Vue App
  // eslint-disable-next-line
  var app = new Vue({
    el: '#app',
    data: {
      name1: 'name 1',
      name2: 'name 2',
      name3: 'name 3',
      name4: 'name 4'
    }
  })
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    }
  }

  //Navbar
  function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
  }
</code>```

As you can see both, closeNav and openNav are used in the HTML code.

答:
The linter isn't smart enough to know that functions you have defined in the global scope are used within the template; it's only considering the JavaScript code and it doesn't see any usage of those functions within the code.

You can silence the error by explicitly defining the functions on the window object:

window.openNav = () => {
  document.getElementById("mySidenav").style.width = "250px";
};

window.closeNav = () => {
  document.getElementById("mySidenav").style.width = "0";
};
```

onclick is archaic; nowadays we usually hook up event listeners by calling addEventListener() on the DOM element.

Body:
When starting the website it shows the errors mentioned in the title.

Here's the HTML part:

☰

      ×
      {{name1}}
      {{name2}}
      {{name3}}
      {{name4}}

And here is the js part:

//Vue App
  // eslint-disable-next-line
  var app = new Vue({
    el: '#app',
    data: {
      name1: 'name 1',
      name2: 'name 2',
      name3: 'name 3',
      name4: 'name 4'
    }
  })
  export default {
    name: 'HelloWorld',
    props: {
      msg: String
    }
  }

  //Navbar
  function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
  }

  function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
  }

As you can see both, closeNav and openNav are used in the HTML code.

Body:
The linter isn't smart enough to know that functions you have defined in the global scope are used within the template; it's only considering the JavaScript code and it doesn't see any usage of those functions within the code.

You can silence the error by explicitly defining the functions on the window object:

window.openNav = () => {
  document.getElementById("mySidenav").style.width = "250px";
};

window.closeNav = () => {
  document.getElementById("mySidenav").style.width = "0";
};

onclick is archaic; nowadays we usually hook up event listeners by calling addEventListener() on the DOM element.


问:
Erase a specific empty cell that shifts all the row names
I have a strange error on some of the data frames I'm working on, shifting all my rows by one cell so they're no more corresponding to my data:

Instead of having this:

```<code>> head(xaa.small)
                     AGCATTCGAAACATCGAGGCTAACATCCAGTACGCAAGTGGCC AGCATTCGAAACATCGCCAGTTCAATCCATCTTCACAGTGGCC
hg19_ENSG00000000003                                           0                                           0
hg19_ENSG00000000419                                           0                                           0
hg19_ENSG00000000457                                           0                                           0

</code>```

It looks like this:

```<code>> head (xab.small)
                     AGCATTCGAAACATCGAGGCTAACATCCAGTACGCAAGTGGCC AGCATTCGAAACATCGCCAGTTCAATCCATCTTCACAGTGGCC
                                                               0                                           0
hg19_ENSG00000103160                                           0                                           0
hg19_ENSG00000103168                                           0                                           0
</code>```

There's that empty space that appears on some of the dataframes.

How could I erase it and "repair" my dataframes in R? Or import it more efficiently?  fill = True when importing the dataframe works but blocks me for the further analysis that I have to do.

The data is comming from a huge tsv file that was cut in multiple parts. Maybe during the cutting process there was an error (split function was used in order to cut the initial tsv file in several 200 Mb files)

答:
I identified the error:

When the initial file was cut into several pieces, it was split by bytes and not by lines. So, it cut sometimes at the last column of the last line or something like this so it generated incomplete lines or en empty space was created ...

I corrected the error simply by using split -l (number of lines) file instead of split -b (number of bytes)

Body:
I have a strange error on some of the data frames I'm working on, shifting all my rows by one cell so they're no more corresponding to my data:

Instead of having this:

> head(xaa.small)
                     AGCATTCGAAACATCGAGGCTAACATCCAGTACGCAAGTGGCC AGCATTCGAAACATCGCCAGTTCAATCCATCTTCACAGTGGCC
hg19_ENSG00000000003                                           0                                           0
hg19_ENSG00000000419                                           0                                           0
hg19_ENSG00000000457                                           0                                           0

It looks like this:

> head (xab.small)
                     AGCATTCGAAACATCGAGGCTAACATCCAGTACGCAAGTGGCC AGCATTCGAAACATCGCCAGTTCAATCCATCTTCACAGTGGCC
                                                               0                                           0
hg19_ENSG00000103160                                           0                                           0
hg19_ENSG00000103168                                           0                                           0

There's that empty space that appears on some of the dataframes.

How could I erase it and "repair" my dataframes in R? Or import it more efficiently?  fill = True when importing the dataframe works but blocks me for the further analysis that I have to do.

The data is comming from a huge tsv file that was cut in multiple parts. Maybe during the cutting process there was an error (split function was used in order to cut the initial tsv file in several 200 Mb files)


问:
Spring restController return not found 404 on wildfly
We have a rest project with Spring RestController like this:

```<code>   @RestController("/new")
   public class NewController {
    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String testControl() {
        return "works";
    }
</code>```

But this project does not contain a boot class to start it. Instead there is a internal jar dependency that implements AbstractAnnotationConfigDispatcherServletInitializer spring class:

```<code>public class AbstractWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { AppSecurityConfig.class, DatabaseConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { ServletContextConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/*" };
    }

    @Override
    protected Filter[] getServletFilters() {
        return new Filter[] { new CORSFilter() };
    }
}
</code>```

This rest project is compiled into an .ear file to be deployed into a wildfly server:
EAR pom.xml

```<code><plugin>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.10.1</version>
                <configuration>
                    <defaultLibBundleDir>APP-INF/lib</defaultLibBundleDir>
                    <skinnyWars>true</skinnyWars>
                    <version>6</version>
                    <earSourceDirectory>src/main/app</earSourceDirectory>
                    <modules>
                        <webModule>
                            <groupId>br.coop.unimed</groupId>
                            <artifactId>cmb-rest</artifactId>
                            <contextRoot>/api</contextRoot>
                        </webModule>
                    </modules>
                </configuration>
            </plugin>
</code>```

When a deploy this ear to wildfly, log says:

17:11:10,033 INFO  [io.undertow.servlet] (ServerService Thread Pool --
  95) No Spring WebApplicationInitializer types detected on classpath
  17:11:10,620 INFO  [io.undertow.servlet] (ServerService Thread Pool --
  95) Spring WebApplicationInitializers detected on classpath:
  [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@8a0cb6a,
  br.coop.unimed.config.security.SecurityWebApplicationInitializer@457597f,
  br.coop.unimed.config.AbstractWebInitializer@1c37aaec]

and

17:11:23,815 INFO  [org.wildfly.extension.undertow] (ServerService
  Thread Pool -- 95) WFLYUT0021: Registered web context: '/api' for
  server 'default-server'

But when a try to reach http:localhost:8080/api/new/test or http:locallhost:8080/api/test, it returns 404 - Not found.

Just to make it clear, i inherited this project from another company that ran this ear on another server that was the weblogic. As the weblogic is very heavy I am trying to run the same way on the wildfly server, but I was not successful despite the ear being successfully deployed on the server and the spring context is also registered correctly.

Does anyone have any idea what may be happening?

答:
Please change your code to </p>

```<code>@RestController
@RequestMapping("/new")
public class NewController {
  @ResponseBody
  @RequestMapping(value = "/test", method = RequestMethod.GET)
  public String testControl() {
      return "works";
  }
}
</code>```

Body:
We have a rest project with Spring RestController like this:

   @RestController("/new")
   public class NewController {
    @ResponseBody
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String testControl() {
        return "works";
    }

But this project does not contain a boot class to start it. Instead there is a internal jar dependency that implements AbstractAnnotationConfigDispatcherServletInitializer spring class:

public class AbstractWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { AppSecurityConfig.class, DatabaseConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { ServletContextConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/*" };
    }

    @Override
    protected Filter[] getServletFilters() {
        return new Filter[] { new CORSFilter() };
    }
}

This rest project is compiled into an .ear file to be deployed into a wildfly server:
EAR pom.xml

<plugin>
                <artifactId>maven-ear-plugin</artifactId>
                <version>2.10.1</version>
                <configuration>
                    <defaultLibBundleDir>APP-INF/lib</defaultLibBundleDir>
                    <skinnyWars>true</skinnyWars>
                    <version>6</version>
                    <earSourceDirectory>src/main/app</earSourceDirectory>
                    <modules>
                        <webModule>
                            <groupId>br.coop.unimed</groupId>
                            <artifactId>cmb-rest</artifactId>
                            <contextRoot>/api</contextRoot>
                        </webModule>
                    </modules>
                </configuration>
            </plugin>

When a deploy this ear to wildfly, log says:

17:11:10,033 INFO  [io.undertow.servlet] (ServerService Thread Pool --
  95) No Spring WebApplicationInitializer types detected on classpath
  17:11:10,620 INFO  [io.undertow.servlet] (ServerService Thread Pool --
  95) Spring WebApplicationInitializers detected on classpath:
  [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@8a0cb6a,
  br.coop.unimed.config.security.SecurityWebApplicationInitializer@457597f,
  br.coop.unimed.config.AbstractWebInitializer@1c37aaec]

and

17:11:23,815 INFO  [org.wildfly.extension.undertow] (ServerService
  Thread Pool -- 95) WFLYUT0021: Registered web context: '/api' for
  server 'default-server'

But when a try to reach http:localhost:8080/api/new/test or http:locallhost:8080/api/test, it returns 404 - Not found.

Just to make it clear, i inherited this project from another company that ran this ear on another server that was the weblogic. As the weblogic is very heavy I am trying to run the same way on the wildfly server, but I was not successful despite the ear being successfully deployed on the server and the spring context is also registered correctly.

Does anyone have any idea what may be happening?

Body:
Please change your code to

@RestController
@RequestMapping("/new")
public class NewController {
  @ResponseBody
  @RequestMapping(value = "/test", method = RequestMethod.GET)
  public String testControl() {
      return "works";
  }
}


问:
How can I make gradle deal with multiple proxies?
I work on a project where there are multiple nexus registries behind different proxies :

How can I make sure that Gradle (or any repository related tool, such as NPM, maven, etc) can handle 3+ differents proxies at the same time to reach multiple Nexus instances ?

Until now, we were using a workaround : 1 nexus was accessed through HTTP proxy and 1 through HTTPS proxy. But now, we have 3 proxies to handle !

I think that it must be possible to add a machine (a squid instance ?) which would redirect proxy requests to the correct proxy, based on the domain name :

I'm not used to Squid and I still not managed to achieve this. Can anyone confirm if this is possible (or not) using Squid ? Does anyone would have another solution to suggest ?

Just for the background story, this network setting is due to multiple partner companies being involved in the project. We have access to each company Nexus through dedicated VPN and proxies.

答:
OK, so I managed to run a Squid in a docker with the following config :

```<code>acl host src 10.0.0.0/8
acl host src 172.0.0.0/8

http_access allow host
maximum_object_size 256 MB
maximum_object_size_in_memory 256 MB
dns_nameservers 8.8.8.8 8.8.4.4

acl SSL_ports port 443
acl Safe_ports port 80      # http
acl Safe_ports port 21      # ftp
acl Safe_ports port 443     # https
acl Safe_ports port 70      # gopher
acl Safe_ports port 210     # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280     # http-mgmt
acl Safe_ports port 488     # gss-http
acl Safe_ports port 591     # filemaker
acl Safe_ports port 777     # multiling http

acl CONNECT method CONNECT
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localhost
http_access deny all
http_port 3128

cache_peer 10.1.1.1       parent    8080  0 proxy-only no-query name=proxy1
cache_peer 10.2.1.1       parent    8080  0 proxy-only no-query name=proxy2
cache_peer 10.3.1.1       parent    8080  0 proxy-only no-query name=proxy3

acl sites_proxy1 dstdomain .domain1.com
acl sites_proxy2 dstdomain .domain2.com
acl sites_proxy3 dstdomain .domain3.com

cache_peer_access proxy1 deny !sites_proxy1
cache_peer_access proxy2 deny !sites_proxy2
cache_peer_access proxy3 deny !sites_proxy3

coredump_dir /var/spool/squid3

refresh_pattern ^ftp:       1440    20% 10080
refresh_pattern ^gopher:    1440    0%  1440
refresh_pattern -i (/cgi-bin/|\?) 0 0%  0
refresh_pattern (Release|Packages(.gz)*)$      0       20%     2880
refresh_pattern .       0   20% 4320

never_direct allow all
</code>```

Then, I run the docker using this command :

```<code>docker run --rm --volume ~/DevTools/squid/squid.conf:/etc/squid/squid.conf -v ~/DevTools/squid/logs:/var/log/squid -p 3128:3128 datadog/squid
</code>```

Body:
OK, so I managed to run a Squid in a docker with the following config :

acl host src 10.0.0.0/8
acl host src 172.0.0.0/8

http_access allow host
maximum_object_size 256 MB
maximum_object_size_in_memory 256 MB
dns_nameservers 8.8.8.8 8.8.4.4

acl SSL_ports port 443
acl Safe_ports port 80      # http
acl Safe_ports port 21      # ftp
acl Safe_ports port 443     # https
acl Safe_ports port 70      # gopher
acl Safe_ports port 210     # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280     # http-mgmt
acl Safe_ports port 488     # gss-http
acl Safe_ports port 591     # filemaker
acl Safe_ports port 777     # multiling http

acl CONNECT method CONNECT
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost manager
http_access deny manager
http_access allow localhost
http_access deny all
http_port 3128

cache_peer 10.1.1.1       parent    8080  0 proxy-only no-query name=proxy1
cache_peer 10.2.1.1       parent    8080  0 proxy-only no-query name=proxy2
cache_peer 10.3.1.1       parent    8080  0 proxy-only no-query name=proxy3

acl sites_proxy1 dstdomain .domain1.com
acl sites_proxy2 dstdomain .domain2.com
acl sites_proxy3 dstdomain .domain3.com

cache_peer_access proxy1 deny !sites_proxy1
cache_peer_access proxy2 deny !sites_proxy2
cache_peer_access proxy3 deny !sites_proxy3

coredump_dir /var/spool/squid3

refresh_pattern ^ftp:       1440    20% 10080
refresh_pattern ^gopher:    1440    0%  1440
refresh_pattern -i (/cgi-bin/|\?) 0 0%  0
refresh_pattern (Release|Packages(.gz)*)$      0       20%     2880
refresh_pattern .       0   20% 4320

never_direct allow all

Then, I run the docker using this command :

docker run --rm --volume ~/DevTools/squid/squid.conf:/etc/squid/squid.conf -v ~/DevTools/squid/logs:/var/log/squid -p 3128:3128 datadog/squid


问:
Including Weather Information, iPhone App, Weather API
I am not sure if what I want to do is possible, as i am fairly new to this.  I have signed up for a Free API account with WorldWeatherOnline.com which allows usage of free and commercial use.

What I want to do is have the 3 days weather displayed for a specific location when a user visits a certain ViewController of my app.  I'm not looking to ask them for their location via GPS, just display a set locations current weather.

I can generate a Request URL and output in XML format or JSON, but have no idea how to implement them into my app (if it is possible?)

Thanks

答:
Check for the Best Weather API,

Read the blog tutorial with sample code for

Adding Local Weather Conditions To Your App (Part 2/2: Accessing Google’s XML Weather API)

Integrating weather information in iphone


问:
_score() missing 1 required argument 'y_true'
I need to run AgglomerativeClustering method and my The code is,

```<code>model = AgglomerativeClustering()
params = {"n_clusters": [2,3,4]}
clf = GridSearchCV(model, params, n_jobs=1, cv=10, refit=False)
clf.fit(self.data, None)
</code>```

Then I get the error saying "_score() missing 1 required argument 'y_true'". However for clustering there is no y. Any solution?

答:
As you dont specifiy your scoring function in GridSearchCV it will use (based on the docs):

If None, the estimator’s score method is used.

Your estimator is model so it is: AllgomerativeClustering, and if we check up this docs, there is no scoring function in it. On top you are missing the train/test split fo this kind of algorithm. Currently GridSearchCV is not designed to use clusterign algorithm, you can have a check here how to continue.

Body:
I need to run AgglomerativeClustering method and my The code is,

model = AgglomerativeClustering()
params = {"n_clusters": [2,3,4]}
clf = GridSearchCV(model, params, n_jobs=1, cv=10, refit=False)
clf.fit(self.data, None)

Then I get the error saying "_score() missing 1 required argument 'y_true'". However for clustering there is no y. Any solution?


问:
How to execute a non-blocking script in python and get its return code?
I am trying to execute a non-blocking bash script from python and to get its return code. Here is my function so far:

```<code>def run_bash_script(script_fullname, logfile):
    my_cmd = ". " + script_fullname + " >" + logfile +" 2>&1"
    p = subprocess.Popen(my_cmd, shell=True)
    os.waitpid(p.pid, 0)
    print(p.returncode)
</code>```

As you can see, all the output is redirected into a log file, which I can monitor while the bash process is running.

However, the last command just returns 'None' instead of a useful exit code.

What am I doing wrong here?

答: You should use p.wait() rather than os.waitpid(). os.waitpid() is a low level api and it knows nothing about the Popen object so it could not touch p.

Body:
I am trying to execute a non-blocking bash script from python and to get its return code. Here is my function so far:

def run_bash_script(script_fullname, logfile):
    my_cmd = ". " + script_fullname + " >" + logfile +" 2>&1"
    p = subprocess.Popen(my_cmd, shell=True)
    os.waitpid(p.pid, 0)
    print(p.returncode)

As you can see, all the output is redirected into a log file, which I can monitor while the bash process is running.

However, the last command just returns 'None' instead of a useful exit code.

What am I doing wrong here?


问:
Youtube API v3: Searching for a video and uploading it to a playlist
I am trying to put together three individual codes I found as examples in https://developers.google.com/youtube/v3/docs:

Create a playlist in my channel (https://developers.google.com/youtube/v3/docs/playlists/insert)

Search for video(s) with a given keyword in their title (among the videos I have in the channel) (https://developers.google.com/youtube/v3/docs/search/list)

Add the videos to the playlist (https://developers.google.com/youtube/v3/docs/playlistItems/insert)

I am able to sucessfully run the codes separately, but fail to combine them. Specifically: after the playlist is created, the code needs to get the playlist ID. Likewise, when a video is found that meets the search criteria, the video ID is needed for it to be added to the playlist.
I have used Python. Please, could anyone help?

This is the code I have:

```<code>import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "client_secrets.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="snippet",
        forMine=True,
        maxResults=50,
        order="date",
        q="searchcriteria",
        type="video"
    )
    response = request.execute()

    print(response)
    vid=response['videoId']

    request2 = youtube.playlistItems().insert(
        part="snippet",
        body={
          "snippet": {
            "playlistId": "myplaylistIdcomeshere",
            "resourceId": {
              "videoId": "vid",
              "kind": "youtube#video",
              "playlistId": "myplaylistIdcomeshereagain"
            },
            "position": 0
          }
        }
    )

    respons2 = request2.execute()

    print(response2)

if __name__ == "__main__":
    main()
</code>```

From the response from the search part I have the following (edited to remove unnnecesary details):

{'kind': 'youtube#searchListResponse', 'etag': '"longetag"', 'nextPageToken': 'anotherlongtext=', 'pageInfo': {'totalResults': 1, 'resultsPerPage': 50}, 'items': [{'kind': 'youtube#searchResult', 'etag': '"theetagofthevideodfound"', 'id': {'kind': 'youtube#video', 'videoId': 'THISISWHATIWANT'}, 'snippet': {'publishedAt': '2020-02-22T19:33:03.000Z', 'channelId': 'MyChannelTitle', 'title': 'TitleOfTheVideo', 'description': '', 'thumbnails': {VideoThumbnails}}, 'channelTitle': 'MyChannelTitle', 'liveBroadcastContent': 'none'}}]}

I have tried with
vid=response['videoId']
vid=response['id']

But none of them worked

答:
The response of inserting an item to the playlist should return a playlist resource which contains the playlist ID

https://developers.google.com/youtube/v3/docs/playlists#resource

Similarly, when you search for a video you get a search_resource in response which contains a list of videos with IDs

https://developers.google.com/youtube/v3/docs/search#resource

Body:
I am trying to put together three individual codes I found as examples in https://developers.google.com/youtube/v3/docs:

Create a playlist in my channel (https://developers.google.com/youtube/v3/docs/playlists/insert)

Search for video(s) with a given keyword in their title (among the videos I have in the channel) (https://developers.google.com/youtube/v3/docs/search/list)

Add the videos to the playlist (https://developers.google.com/youtube/v3/docs/playlistItems/insert)

I am able to sucessfully run the codes separately, but fail to combine them. Specifically: after the playlist is created, the code needs to get the playlist ID. Likewise, when a video is found that meets the search criteria, the video ID is needed for it to be added to the playlist.
I have used Python. Please, could anyone help?

This is the code I have:

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "client_secrets.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="snippet",
        forMine=True,
        maxResults=50,
        order="date",
        q="searchcriteria",
        type="video"
    )
    response = request.execute()

    print(response)
    vid=response['videoId']

    request2 = youtube.playlistItems().insert(
        part="snippet",
        body={
          "snippet": {
            "playlistId": "myplaylistIdcomeshere",
            "resourceId": {
              "videoId": "vid",
              "kind": "youtube#video",
              "playlistId": "myplaylistIdcomeshereagain"
            },
            "position": 0
          }
        }
    )

    respons2 = request2.execute()

    print(response2)

if __name__ == "__main__":
    main()

From the response from the search part I have the following (edited to remove unnnecesary details):

{'kind': 'youtube#searchListResponse', 'etag': '"longetag"', 'nextPageToken': 'anotherlongtext=', 'pageInfo': {'totalResults': 1, 'resultsPerPage': 50}, 'items': [{'kind': 'youtube#searchResult', 'etag': '"theetagofthevideodfound"', 'id': {'kind': 'youtube#video', 'videoId': 'THISISWHATIWANT'}, 'snippet': {'publishedAt': '2020-02-22T19:33:03.000Z', 'channelId': 'MyChannelTitle', 'title': 'TitleOfTheVideo', 'description': '', 'thumbnails': {VideoThumbnails}}, 'channelTitle': 'MyChannelTitle', 'liveBroadcastContent': 'none'}}]}

I have tried with
vid=response['videoId']
vid=response['id']

But none of them worked


问:
HTML width 100% goes outside the page
I'm pretty newbie with HTML and CSS. So, I've got a problem with the width of 100%. It appears to go beyond the borders of the browser. Please take a look at the example below! Should I decrease the width per cents a little or is there some flaws in my code that could cause this?

I found some other posts here about the width 100%, but neither of them didn't really help me. Here's the example I made: http://jsfiddle.net/gj53jbz9/

 body{
              font-size: 15px;
              margin: 0px;
              background-color: lightgrey;  }

            #header{
              padding: 30px;
              width: 100%;
              height: 250px;
              background-color: grey;   }

            #name{
              padding: 5px;
              font-size: 25px;
              float: left;  }

            #navbar{
              float: right;
              text-align: right;    }

            #navbar a{
              background-color: black;
              display: inline-block;
              width: 120px;
              text-align: center;
              padding: 10px 0px;
              text-decoration: none;
              color: lightgrey; }

            #title{
              clear: both;
              text-align: center;
              padding-top: 100px;
              font-size: 45px;  }

            #content{
              text-align: center;
              width: 80%;
              margin: 0px auto;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>   <div id=header>
            <div id=name>Name</div>
            <div id=navbar>
                Link1
                Link2
            </div>
            <div id=title>Insert title here</div>
        </div>
        <div id=content>
            <h3>Age of aggression</h3>
            <p>We drink to our youth, to days come and gone. For the age of aggression is just about done. We'll drive out the Stormcloaks and restore what we own. With our blood and our steel we will take back our home.</p>
            <p>Down with Ulfric! The killer of kings! On the day of your death we will drink and we'll sing. We're the children of Skyrim, and we fight all our lives. And when Sovngarde beckons, every one of us dies! But this land is ours and we'll see it wiped clean. Of the scourge that has sullied our hopes and our dreams!</p>
  </div></code>```

答:
Take a look at this part of your code:

```<code>        #header{
          padding: 30px;
          width: 100%;
          height: 250px;
          background-color: grey;   }
</code>```

This is telling the browser that the width of #header should be 100% with a padding of 30px. Since padding is not counted into the width, the actual width ends up to be 100% + 60px. So, in order to make sure this fits into the page, you need to subtract 60px (30px to the left + 30px to the right) from the 100% width and it will fit into the browser. Luckily you are easily able to do this with CSS:

```<code>        #header{
          padding: 30px;
          width: calc(100% - 60px);
          height: 250px;
          background-color: grey;   }
</code>```

Title: HTML width 100% goes outside the page

Body:
I'm pretty newbie with HTML and CSS. So, I've got a problem with the width of 100%. It appears to go beyond the borders of the browser. Please take a look at the example below! Should I decrease the width per cents a little or is there some flaws in my code that could cause this?

I found some other posts here about the width 100%, but neither of them didn't really help me. Here's the example I made: http://jsfiddle.net/gj53jbz9/

 body{
              font-size: 15px;
              margin: 0px;
              background-color: lightgrey;  }

            #header{
              padding: 30px;
              width: 100%;
              height: 250px;
              background-color: grey;   }

            #name{
              padding: 5px;
              font-size: 25px;
              float: left;  }

            #navbar{
              float: right;
              text-align: right;    }

            #navbar a{
              background-color: black;
              display: inline-block;
              width: 120px;
              text-align: center;
              padding: 10px 0px;
              text-decoration: none;
              color: lightgrey; }

            #title{
              clear: both;
              text-align: center;
              padding-top: 100px;
              font-size: 45px;  }

            #content{
              text-align: center;
              width: 80%;
              margin: 0px auto;  }

Name

                Link1
                Link2

Insert title here

Age of aggression

We drink to our youth, to days come and gone. For the age of aggression is just about done. We'll drive out the Stormcloaks and restore what we own. With our blood and our steel we will take back our home.

Down with Ulfric! The killer of kings! On the day of your death we will drink and we'll sing. We're the children of Skyrim, and we fight all our lives. And when Sovngarde beckons, every one of us dies! But this land is ours and we'll see it wiped clean. Of the scourge that has sullied our hopes and our dreams!

Body:
Take a look at this part of your code:

        #header{
          padding: 30px;
          width: 100%;
          height: 250px;
          background-color: grey;   }

This is telling the browser that the width of #header should be 100% with a padding of 30px. Since padding is not counted into the width, the actual width ends up to be 100% + 60px. So, in order to make sure this fits into the page, you need to subtract 60px (30px to the left + 30px to the right) from the 100% width and it will fit into the browser. Luckily you are easily able to do this with CSS:

        #header{
          padding: 30px;
          width: calc(100% - 60px);
          height: 250px;
          background-color: grey;   }