问:
rxJava better way to wait on a specific sequence of values
I wondered what would be the proper way to filter for a certain sequence of values coming through a observable pipe. For example:

I had a problem where I needed to do something after the pipe becomes false but only directly after being true.

```<code>Observable x = Observable.just(false, false, false, true, false);
</code>```

My first approach:

```<code>x
.filter(state -> state)
.switchMap(x)
.filter(state -> !state)
.subscribe(x -> doSomething())

</code>```

Second approach:

```<code>private boolean globalState = false;

private void someFunction() {
   x.map(this::hasTurnedOffAgain)
   .filter(state -> state)
   .subscribe(doSomething)
}

...

private boolean hasTurnedOggAgain(Boolean state) {
    boolean hasTurnedOff= !state && peeping;
    globalState = state;
    return hasFinished;
}
</code>```

I had a third version using the scan operator but I think it was to complex for this simple problem.

Is there a better way to implement something like this? And even more complex  sequences?

Thank you and have a great day!

答:
You can use the buffer() method to build an observable which have the previous and current item from the original observable. Use a count value of 2 as you want to check two adjacent values and a skip value of 1 as you want to go a single step forward.

```<code>Observable<Boolean> original = Observable.just(false, false, false, true, false, false, true, true, false);

Observable<List<Boolean>> buffered = original.buffer(2, 1);

buffered.subscribe(new Consumer<List<Boolean>>() {

    @Override
    public void accept(List<Boolean> t) throws Exception {
        System.out.println("Direct:"+t);
    }
});
</code>```

This will generate the following output:

Direct:[false, false]
Direct:[false, false]
Direct:[false, true]
Direct:[true, false]
Direct:[false, false]
Direct:[false, true]
Direct:[true, true]
Direct:[true, false]
Direct:[false]
```

<p>You can use this new observable and use <code>filter()</code> to get only these values where the previous entry was <code>true</code> and the current entry is <code>false</code>, so you see a "falling edge":</p>

```Observable<List<Boolean>> filtered = buffered.filter(l -> l.size() == 2 &&
                                                          l.get(0) == true &&
                                                          l.get(1) == false);

filtered.subscribe(new Consumer<List<Boolean>>() {

    @Override
    public void accept(List<Boolean> t) throws Exception {
        System.out.println("Filtered: "+t);
    }
});
```

<p>This will generate the following output:</p>

<pre class="lang-none prettyprint-override"><code>Filtered: [true, false]
Filtered: [true, false]
</code>```

Body:
I wondered what would be the proper way to filter for a certain sequence of values coming through a observable pipe. For example:

I had a problem where I needed to do something after the pipe becomes false but only directly after being true.

Observable x = Observable.just(false, false, false, true, false);

My first approach:

x
.filter(state -> state)
.switchMap(x)
.filter(state -> !state)
.subscribe(x -> doSomething())

Second approach:

private boolean globalState = false;

private void someFunction() {
   x.map(this::hasTurnedOffAgain)
   .filter(state -> state)
   .subscribe(doSomething)
}

...

private boolean hasTurnedOggAgain(Boolean state) {
    boolean hasTurnedOff= !state && peeping;
    globalState = state;
    return hasFinished;
}

I had a third version using the scan operator but I think it was to complex for this simple problem.

Is there a better way to implement something like this? And even more complex  sequences?

Thank you and have a great day!

Body:
You can use the buffer() method to build an observable which have the previous and current item from the original observable. Use a count value of 2 as you want to check two adjacent values and a skip value of 1 as you want to go a single step forward.

Observable<Boolean> original = Observable.just(false, false, false, true, false, false, true, true, false);

Observable<List<Boolean>> buffered = original.buffer(2, 1);

buffered.subscribe(new Consumer<List<Boolean>>() {

    @Override
    public void accept(List<Boolean> t) throws Exception {
        System.out.println("Direct:"+t);
    }
});

This will generate the following output:

Direct:[false, false]
Direct:[false, false]
Direct:[false, true]
Direct:[true, false]
Direct:[false, false]
Direct:[false, true]
Direct:[true, true]
Direct:[true, false]
Direct:[false]

You can use this new observable and use filter() to get only these values where the previous entry was true and the current entry is false, so you see a "falling edge":

Observable<List<Boolean>> filtered = buffered.filter(l -> l.size() == 2 &&
                                                          l.get(0) == true &&
                                                          l.get(1) == false);

filtered.subscribe(new Consumer<List<Boolean>>() {

    @Override
    public void accept(List<Boolean> t) throws Exception {
        System.out.println("Filtered: "+t);
    }
});

This will generate the following output:

Filtered: [true, false]
Filtered: [true, false]


来源: stackexchange

问:
VBA Deleting Active Sheet
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?</p>

```<code>Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
</code>```

答:
Test the next code, please:</p>

```<code>Sub deleteExceptTheLastSh()
    If ActiveWorkbook.Sheets.count > 1 Then
        Application.DisplayAlerts = False
         ActiveSheet.Delete
        Application.DisplayAlerts = True
    Else
        MsgBox "This is the last sheet and it cannot be deleted!"
    End If
End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: VBA Deleting Active Sheet

Body:
I am trying to create a macro that deletes the active sheet without displaying the prompt. Which is what the code below does...This works great until the last sheet. I get the prompt no matter what. I do not want to delete the last sheet and at the same time, I don't want the error '1004' message to come up. Is there a way to change the code above to not delete my last sheet and not display the error message at the same time?

Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True

Body:
Test the next code, please:

Sub deleteExceptTheLastSh()
    If ActiveWorkbook.Sheets.count > 1 Then
        Application.DisplayAlerts = False
         ActiveSheet.Delete
        Application.DisplayAlerts = True
    Else
        MsgBox "This is the last sheet and it cannot be deleted!"
    End If
End Sub


问:
Laravel Eloquent: I cannot get the id I want, instead I get another one from a joined table
This is my first question here, so I hope I don't mess anything up on my first try.

Okay, to the topic in hand: I am trying to do a function in my controller which allows me to both fetch some data from my database in a template and then generate a downloadable PDF file with the data I was passing to it. I managed to do so, and it works perfectly fine.

What's wrong is, I am using a database where all my identifiers are named 'id', and when I try to access the one I want, I get another from the joined tables. The obvious solution would be changing the name of the identifiers, so there are no duplicated names, but due to some external factors, I cannot do that thing, at least for now. That is something programming cannot do.

So, I was wondering if there is a way I can retrieve the id I want, without changing the database.

This is my function:

```<code>public function descargarPDF(Request $request)
    {
        $fecha1 = $request->get('fecha1');
        $fecha2 = $request->get('fecha2');
        $categoria = $request->get('categoria');
        // These are filters I had to apply before fetching data to my PDF file, they work fine.
        $tickets = DB::table('tickets')
        -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
        -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
        -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
        -> where('tickets.estado' ,'=', $categoria)
        -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
        -> get();
        $pdf = PDF::loadView('/admin/pdf', compact('tickets'));
        return $pdf->download('tickets.pdf');
    }
</code>```

And this is my blade template:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF</title>
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Código</th>
                <th>Nombre</th>
                <th>Email</th>
                <th>Empresa</th>
                <th>Requerimiento</th>
                <th>Estado</th>
            </tr>
        </thead>
        <tbody>
            @foreach($tickets as $value)
            <tr>
                <td>{{ $value->id }}</td>
                <td>{{ $value->name }}</td>
                <td>{{ $value->email }}</td>
                <td>{{ $value->empresa }}</td>
                <td>{{ $value->nombre }}</td>
                <td>{{ $value->estado }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</body>
</html>
</code>```

Thanks in advance for your help! Have a nice day :)

答:
You can specify just the fields you need:

```<code> $tickets = DB::table('tickets')
    ->select('tickets.id as id', 'tickets.name as name', '...')
    -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
    -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
    -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
    -> where('tickets.estado' ,'=', $categoria)
    -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
    -> get();
</code>```

To get more information, use xdebug or write dd($tickets);  to see what's inside the variable.

Body:
This is my first question here, so I hope I don't mess anything up on my first try.

Okay, to the topic in hand: I am trying to do a function in my controller which allows me to both fetch some data from my database in a template and then generate a downloadable PDF file with the data I was passing to it. I managed to do so, and it works perfectly fine.

What's wrong is, I am using a database where all my identifiers are named 'id', and when I try to access the one I want, I get another from the joined tables. The obvious solution would be changing the name of the identifiers, so there are no duplicated names, but due to some external factors, I cannot do that thing, at least for now. That is something programming cannot do.

So, I was wondering if there is a way I can retrieve the id I want, without changing the database.

This is my function:

public function descargarPDF(Request $request)
    {
        $fecha1 = $request->get('fecha1');
        $fecha2 = $request->get('fecha2');
        $categoria = $request->get('categoria');
        // These are filters I had to apply before fetching data to my PDF file, they work fine.
        $tickets = DB::table('tickets')
        -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
        -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
        -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
        -> where('tickets.estado' ,'=', $categoria)
        -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
        -> get();
        $pdf = PDF::loadView('/admin/pdf', compact('tickets'));
        return $pdf->download('tickets.pdf');
    }

And this is my blade template:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF</title>

                Código
                Nombre
                Email
                Empresa
                Requerimiento
                Estado

            @foreach($tickets as $value)

                {{ $value->id }}
                {{ $value->name }}
                {{ $value->email }}
                {{ $value->empresa }}
                {{ $value->nombre }}
                {{ $value->estado }}

            @endforeach

Thanks in advance for your help! Have a nice day :)

Body:
You can specify just the fields you need:

 $tickets = DB::table('tickets')
    ->select('tickets.id as id', 'tickets.name as name', '...')
    -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
    -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
    -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
    -> where('tickets.estado' ,'=', $categoria)
    -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
    -> get();

To get more information, use xdebug or write dd($tickets);  to see what's inside the variable.


问:
Heroku Deployment Continues to Fail at "Pruning devDependencies" Step
I continue to have issues deploying to Heroku and I can't find out what is going wrong for the life of me. The Heroku error log tells me this after it successfully builds my react app:

```<code>-----> Caching build
       - node_modules

-----> Pruning devDependencies
       npm ERR! Cannot read property 'match' of undefined
</code>```

Here is my package.json

```<code>{
  "name": "test",
  "version": "1.0.0",
  "homepage": "./",
  "description": "test",
  "main": "server.js",
  "node": "v12.13.1",
  "npm": "6.13.7",
  "scripts": {
    "heroku": "node server.js",
    "client-install": "npm install --prefix client",
    "build": "cd client && react-scripts build",
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
  "author": "John Doe",
  "license": "MIT",
  "dependencies": {
    "@material-ui/core": "^4.8.0",
    "axios": "^0.19.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.18.3",
    "classnames": "^2.2.6",
    "concurrently": "^5.1.0",
    "date-fns": "^2.8.1",
    "debug": "^4.1.1",
    "depcheck": "^0.9.1",
    "eslint-plugin-flowtype": "^4.6.0",
    "express": "^4.16.4",
    "fibers": "^4.0.2",
    "growl": "^1.10.5",
    "heroku": "^7.35.1",
    "history": "^4.10.1",
    "is-empty": "^1.2.0",
    "jquery": "^3.4.1",
    "jsonwebtoken": "^8.3.0",
    "jwt-decode": "^2.2.0",
    "material-table": "^1.54.2",
    "material-ui": "^0.20.2",
    "minimatch": "^3.0.4",
    "moment": "^2.23.0",
    "mongodb": "^3.5.3",
    "mongoose": "^5.8.9",
    "mongoose-global": "^1.0.1",
    "morgan": "^1.9.1",
    "node-sass": "^4.13.0",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "plaid": "^4.6.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-ga": "^2.7.0",
    "react-plaid-link-button": "0.0.4",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^3.3.0",
    "react-slick": "^0.25.2",
    "react-stripe-elements": "^6.0.1",
    "react-vis": "^1.11.7",
    "redux-thunk": "^2.3.0",
    "sass": "^1.24.0",
    "slick": "^1.12.2",
    "slick-carousel": "^1.8.1",
    "typescript": "^3.7.4",
    "update-mongo": "0.0.4",
    "validator": "^12.2.0",
    "vis": "^4.21.0-EOL"
  },
  "devDependencies": {},
  "engines": {
    "node": "12.x"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

What is perhaps most frustrating, is that I was able to deploy successfully once the other day but I am not sure what changed. Going back through my git I can't see anything that would have made any difference.

Things I have tried:

removing package.json

adding "devDependencies": {} to my    package.json (although I
deployed successfully without it)

updating node and adding the engines section to my package.json to
match.

running npm prune locally

ensuring that all packages are updated and referenced appropriately in package.json

Things that I suspect could be the issue:

Maybe somehow the current version of my app that is actively deployed on heroku is interfering with my new deployment? That being said i have tried scaling down dynos and deploying. Additionally the npm ERR! Cannot read property 'match' of undefined seems to indicate something else?

答:
Just run into this after my deploys inexplicably started failing after a number of successful ones.

Stopping heroku from caching node_modules seemed to do the trick for me.

heroku config:set NODE_MODULES_CACHE=false

Then git push heroku master

I don't have package-lock.json committed after hearing Heroku doesn't get on well with lockfiles, but wondering if that's the problem.

Body:
I continue to have issues deploying to Heroku and I can't find out what is going wrong for the life of me. The Heroku error log tells me this after it successfully builds my react app:

-----> Caching build
       - node_modules

-----> Pruning devDependencies
       npm ERR! Cannot read property 'match' of undefined

Here is my package.json

{
  "name": "test",
  "version": "1.0.0",
  "homepage": "./",
  "description": "test",
  "main": "server.js",
  "node": "v12.13.1",
  "npm": "6.13.7",
  "scripts": {
    "heroku": "node server.js",
    "client-install": "npm install --prefix client",
    "build": "cd client && react-scripts build",
    "start": "node server.js",
    "server": "nodemon server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  },
  "author": "John Doe",
  "license": "MIT",
  "dependencies": {
    "@material-ui/core": "^4.8.0",
    "axios": "^0.19.0",
    "bcryptjs": "^2.4.3",
    "body-parser": "^1.18.3",
    "classnames": "^2.2.6",
    "concurrently": "^5.1.0",
    "date-fns": "^2.8.1",
    "debug": "^4.1.1",
    "depcheck": "^0.9.1",
    "eslint-plugin-flowtype": "^4.6.0",
    "express": "^4.16.4",
    "fibers": "^4.0.2",
    "growl": "^1.10.5",
    "heroku": "^7.35.1",
    "history": "^4.10.1",
    "is-empty": "^1.2.0",
    "jquery": "^3.4.1",
    "jsonwebtoken": "^8.3.0",
    "jwt-decode": "^2.2.0",
    "material-table": "^1.54.2",
    "material-ui": "^0.20.2",
    "minimatch": "^3.0.4",
    "moment": "^2.23.0",
    "mongodb": "^3.5.3",
    "mongoose": "^5.8.9",
    "mongoose-global": "^1.0.1",
    "morgan": "^1.9.1",
    "node-sass": "^4.13.0",
    "passport": "^0.4.0",
    "passport-jwt": "^4.0.0",
    "plaid": "^4.6.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-ga": "^2.7.0",
    "react-plaid-link-button": "0.0.4",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^3.3.0",
    "react-slick": "^0.25.2",
    "react-stripe-elements": "^6.0.1",
    "react-vis": "^1.11.7",
    "redux-thunk": "^2.3.0",
    "sass": "^1.24.0",
    "slick": "^1.12.2",
    "slick-carousel": "^1.8.1",
    "typescript": "^3.7.4",
    "update-mongo": "0.0.4",
    "validator": "^12.2.0",
    "vis": "^4.21.0-EOL"
  },
  "devDependencies": {},
  "engines": {
    "node": "12.x"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

What is perhaps most frustrating, is that I was able to deploy successfully once the other day but I am not sure what changed. Going back through my git I can't see anything that would have made any difference.

Things I have tried:

removing package.json

adding "devDependencies": {} to my    package.json (although I
deployed successfully without it)

updating node and adding the engines section to my package.json to
match.

running npm prune locally

ensuring that all packages are updated and referenced appropriately in package.json

Things that I suspect could be the issue:

Maybe somehow the current version of my app that is actively deployed on heroku is interfering with my new deployment? That being said i have tried scaling down dynos and deploying. Additionally the npm ERR! Cannot read property 'match' of undefined seems to indicate something else?


问:
github: how to reference an issue in a commit from a different repository?
I have two repositories:

Repository A

Repository B

I also have a project:

Project X

This Project X has Repository A and Repository B as linked repositories.

In Repository A I created several issues:

Issue 1

Issue 2

Issue 3

All these issues are appearing on the kanban board of Project X.
When I now do a commit on Repository B:

```<code>closes #1
</code>```

The commit wont get linked to the Issue 1 of Repository A.
Can I configure the project in a way that I can create such references from commits from different Repositories? Or do I use this wrong?

答:
#1 refers to issue 1 in this repo.

repoA#1 refers to issue 1 in repoA. You would use this.

org/repoA#1 refers to issue 1 in org's repoA.

See Mastering Markdown.

Body:
I have two repositories:

Repository A

Repository B

I also have a project:

Project X

This Project X has Repository A and Repository B as linked repositories.

In Repository A I created several issues:

Issue 1

Issue 2

Issue 3

All these issues are appearing on the kanban board of Project X.
When I now do a commit on Repository B:

closes #1

The commit wont get linked to the Issue 1 of Repository A.
Can I configure the project in a way that I can create such references from commits from different Repositories? Or do I use this wrong?


问:
Telerik RadSpreadsheet to PDF
I’m currently using web forms and VB.NET I’ve tried following the examples and docs on Teleriks website, however the results are not as expected. It appears that Telerik is taking a screen capture and turning that into a PDF.

What I’m needing is to export the spreadsheet that is displayed in the RadSpreadsheet control into a PDF document such that the results are identical to what’s being displayed.

I’m starting to wonder if Telerik doesn’t actually do anything but take screen shots and save them as a PDF. Even their demo does that. Does anyone know how to go about exporting the Excel file into a PDF? Again their documentation to me isn’t really clear.

答:
there are several libraries used to process documents. They are called Telerik Document Processing. You can use them to generate, modify or convert documents. You could use the RadSpreadProcessing library to export your grid data and then convert the Workbook to a PDF document. Here is the documentation of the PDF export feature https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/formats-and-conversion/pdf/pdfformatprovider

The PDF documents generated this way are not screenshot, they are real PDF documents.

Title: Telerik RadSpreadsheet to PDF


问:
Dagger/MissingBinding. Outputter cannot be provided without an @Provides-annotated method
I'm learning Dagger2 via their tutorial but am blocked at part 5. I've implemented everything in Kotlin (jvm) and the logic/behavior matches the tutorial in working order to this point.

However, I'm unable to create SystemOutModule and unsure whether I'm mistaken somewhere with Dagger, or in my translation of their module class.

```<code>/**
* Tutorial's Java.
*/
@Module
abstract class SystemOutModule {
    @Provides
    static Outputter textOutputter() {
        return System.out::println;
    }
}
</code>```

```<code>/**
* My Kotlin.
*/
@Module
object SystemOutModule {
    @JvmSuppressWildcards
    @Provides
    fun textOutputter(): (String) -> Unit = { println(it) }
}
</code>```

The build fails with this error:

```<code>~~ ./gradlew clean build

> Task :app:kaptKotlin FAILED
e: /Users/eric/IdeaProjects/atm/app/build/tmp/kapt3/stubs/main/com/es0329/atm/CommandRouterFactory.java:7: error: [Dagger/MissingBinding] com.es0329.atm.Outputter cannot be provided without an @Provides-annotated method.
public abstract interface CommandRouterFactory {
                ^
      com.es0329.atm.Outputter is injected at
          com.es0329.atm.HelloWorldCommand(outputter)
      com.es0329.atm.HelloWorldCommand is injected at
          com.es0329.atm.HelloWorldModule.helloWorldCommand(command)
      com.es0329.atm.Command is injected at
          com.es0329.atm.CommandRouter(command)
      com.es0329.atm.CommandRouter is provided at
          com.es0329.atm.CommandRouterFactory.router()

FAILURE: Build failed with an exception.
</code>```

答:
Your HelloWorldCommand expects an Outputter, but you are providing a (String) -> Unit instead.  There are a few ways to bridge this gap:

Option 1: Inject the functional type

Instead of an Outputter, your HelloWorldCommand can ask for a (String) -> Unit directly.

```<code>class HelloWorldCommand @Inject constructor(private val outputter: (String) -> Unit)
</code>```

This will work, but you might want to provide a different type of (String) -> Unit elsewhere in your app.  If you do, you will have to use some sort of @Qualifier.

Fortunately, this is the only injected lambda in the entire tutorial as far as I can tell, so it won't be a problem here.

Option 2: Make Outputter a typealias

You can use a typealias to make Outputter the same type as (String) -> Unit.  This works identically to option 1, but is more expressive.  Unfortunately, it has the same issue if you ever want to have another (String) -> Unit in your dependency graph later.

```<code>typealias Outputter = (String) -> Unit
</code>```

Option 3: Provide an implementation of the Outputter interface

Rather than provide a lambda, you can provide an object implementing Outputter.  This is less idiomatic for a simple function, since Kotlin can't assign lambdas directly to SAM interfaces defined in Kotlin.

```<code>@Provides
fun textOutputter() = object : Outputter {
    override fun output(output: String) = println(output)
}
</code>```

Body:
I'm learning Dagger2 via their tutorial but am blocked at part 5. I've implemented everything in Kotlin (jvm) and the logic/behavior matches the tutorial in working order to this point.

However, I'm unable to create SystemOutModule and unsure whether I'm mistaken somewhere with Dagger, or in my translation of their module class.

/**
* Tutorial's Java.
*/
@Module
abstract class SystemOutModule {
    @Provides
    static Outputter textOutputter() {
        return System.out::println;
    }
}

/**
* My Kotlin.
*/
@Module
object SystemOutModule {
    @JvmSuppressWildcards
    @Provides
    fun textOutputter(): (String) -> Unit = { println(it) }
}

The build fails with this error:

~~ ./gradlew clean build

> Task :app:kaptKotlin FAILED
e: /Users/eric/IdeaProjects/atm/app/build/tmp/kapt3/stubs/main/com/es0329/atm/CommandRouterFactory.java:7: error: [Dagger/MissingBinding] com.es0329.atm.Outputter cannot be provided without an @Provides-annotated method.
public abstract interface CommandRouterFactory {
                ^
      com.es0329.atm.Outputter is injected at
          com.es0329.atm.HelloWorldCommand(outputter)
      com.es0329.atm.HelloWorldCommand is injected at
          com.es0329.atm.HelloWorldModule.helloWorldCommand(command)
      com.es0329.atm.Command is injected at
          com.es0329.atm.CommandRouter(command)
      com.es0329.atm.CommandRouter is provided at
          com.es0329.atm.CommandRouterFactory.router()

FAILURE: Build failed with an exception.

Body:
Your HelloWorldCommand expects an Outputter, but you are providing a (String) -> Unit instead.  There are a few ways to bridge this gap:

Option 1: Inject the functional type

Instead of an Outputter, your HelloWorldCommand can ask for a (String) -> Unit directly.

class HelloWorldCommand @Inject constructor(private val outputter: (String) -> Unit)

This will work, but you might want to provide a different type of (String) -> Unit elsewhere in your app.  If you do, you will have to use some sort of @Qualifier.

Fortunately, this is the only injected lambda in the entire tutorial as far as I can tell, so it won't be a problem here.

Option 2: Make Outputter a typealias

You can use a typealias to make Outputter the same type as (String) -> Unit.  This works identically to option 1, but is more expressive.  Unfortunately, it has the same issue if you ever want to have another (String) -> Unit in your dependency graph later.

typealias Outputter = (String) -> Unit

Option 3: Provide an implementation of the Outputter interface

Rather than provide a lambda, you can provide an object implementing Outputter.  This is less idiomatic for a simple function, since Kotlin can't assign lambdas directly to SAM interfaces defined in Kotlin.

@Provides
fun textOutputter() = object : Outputter {
    override fun output(output: String) = println(output)
}


问:
How to fetch the MIME type from byte array in Java 6?
I have been trying to figure out how to fetch the MIME type from byte array in Java 6, but unfortunately have not been able fetch the MIME type yet.

Can someone help me get out of this?

答:
Good working library https://github.com/overview/mime-types

Import (via gradle.kts):

```<code>implementation("org.overviewproject:mime-types:0.1.3")
</code>```

Usage

```<code>// input
final var fileName = "somefile.html";
final var content = "<html></html>".getBytes();

final var mimeTypeDetector = new MimeTypeDetector(); // initialize only once, reuse!
final var mimeType = mimeTypeDetector.detectMimeType(fileName, () -> content);

System.out.println(mimeType); // prints: text/html
</code>```

Body:
Good working library https://github.com/overview/mime-types

Import (via gradle.kts):

implementation("org.overviewproject:mime-types:0.1.3")

Usage

// input
final var fileName = "somefile.html";
final var content = "<html></html>".getBytes();

final var mimeTypeDetector = new MimeTypeDetector(); // initialize only once, reuse!
final var mimeType = mimeTypeDetector.detectMimeType(fileName, () -> content);

System.out.println(mimeType); // prints: text/html


问:
Request with Symfony HttpClient returns code 0, when the same request with postman works fine
I have a weird problem where a request I make (to my mercure hub) with postman works fine, however the Publisher class (from the Symfony mercure bundle), which uses the Symfony HttpClient will yield in a response code 0.
According to my research that means that the URL can't be found, or no Response was returned?

I first thought it might have to do something with the Publisher class itself, which is why opened this Issue on Github, but after some playing around I thought that maybe there is a communication error with my containers? I tried giving my mercure container "networks: internal", which some other containers use aswell, but that didn't help either.

Any ideas are greatly appreciated..

/e: my docker-compose:

```<code>version: "3"

services:
  traefik:
    image: traefik:v1.7
    ports:
      - 80:80
      - 443:443
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./.docker/traefik/traefik.toml:/etc/traefik/traefik.toml
    networks:
      - proxy
    labels:
      - traefik.enable=true
      - traefik.docker.network=proxy
      - traefik.frontend.rule=Host:traefik.heracles.local
      - traefik.port=8080

  nginx:
    image: nginx:1.17-alpine
    volumes:
      - ./Source:/var/www
      - ./.docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
    links:
      - php
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:heracles.local
      - traefik.basic.port=80

  php:
    build:
      args:
        USER_ID: ${USER_ID}
      context: ./.docker/php
    volumes:
      - ./Source:/var/www
      - ./.docker/php/conf/cli.ini:/etc/php/7.4/cli/conf.d/zz-symfony.ini
      - ./.docker/php/conf/fpm.ini:/etc/php/7.4/fpm/conf.d/zz-symfony.ini
      - ./.docker/php/conf/xdebug.ini:/etc/php/7.4/fpm/conf.d/zz-xdebug.ini
      - ./.docker/php/conf/opcache.ini:/etc/php/7.4/fpm/conf.d/zz-opcache.ini
      - ./.docker/php/conf/pool.conf:/etc/php/7.4/fpm/pool.d/www.conf
    networks:
      - internal
    labels:
      - traefik.enable=false

  db:
    image: mysql:5.7
    env_file:
      - .env
    volumes:
      - db_data:/var/lib/mysql
      - ./.docker/mysql/conf.d:/etc/mysql/conf.d
    command:
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
      - --skip-character-set-client-handshake
    networks:
      - internal
    labels:
      - traefik.enable=false
    restart: always

  adminer:
    image: adminer
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:db.heracles.local
      - traefik.basic.port=8080

  blackfire:
    image: blackfire/blackfire
    networks:
      - internal
    labels:
      - traefik.enable=false

  mailhog:
    image: mailhog/mailhog
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:mail.heracles.local
      - traefik.basic.port=8025

  mercure:
    image: dunglas/mercure
    environment:
      - ALLOW_ANONYMOUS=1
      - CORS_ALLOWED_ORIGINS=*
      - JWT_KEY=ASD
      - PUBLISH_ALLOWED_ORIGINS=http://heracles.local
      - ADDR=:3000
    ports:
      - 3000:3000

networks:
  internal:
  proxy:
    external: true

volumes:
  db_data:
</code>```

答:
Alright guys it's working now. In fact the correct url is
MERCURE_PUBLISH_URL=http://mercure:3000/.well-known/mercure
So if you're using Docker Containers make sure to pass the correct host + the port and give your mercure containers the network of your other containers (internal in my case). </p>

Body:
I have a weird problem where a request I make (to my mercure hub) with postman works fine, however the Publisher class (from the Symfony mercure bundle), which uses the Symfony HttpClient will yield in a response code 0.
According to my research that means that the URL can't be found, or no Response was returned?

I first thought it might have to do something with the Publisher class itself, which is why opened this Issue on Github, but after some playing around I thought that maybe there is a communication error with my containers? I tried giving my mercure container "networks: internal", which some other containers use aswell, but that didn't help either.

Any ideas are greatly appreciated..

/e: my docker-compose:

version: "3"

services:
  traefik:
    image: traefik:v1.7
    ports:
      - 80:80
      - 443:443
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./.docker/traefik/traefik.toml:/etc/traefik/traefik.toml
    networks:
      - proxy
    labels:
      - traefik.enable=true
      - traefik.docker.network=proxy
      - traefik.frontend.rule=Host:traefik.heracles.local
      - traefik.port=8080

  nginx:
    image: nginx:1.17-alpine
    volumes:
      - ./Source:/var/www
      - ./.docker/nginx/conf/nginx.conf:/etc/nginx/nginx.conf
    links:
      - php
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:heracles.local
      - traefik.basic.port=80

  php:
    build:
      args:
        USER_ID: ${USER_ID}
      context: ./.docker/php
    volumes:
      - ./Source:/var/www
      - ./.docker/php/conf/cli.ini:/etc/php/7.4/cli/conf.d/zz-symfony.ini
      - ./.docker/php/conf/fpm.ini:/etc/php/7.4/fpm/conf.d/zz-symfony.ini
      - ./.docker/php/conf/xdebug.ini:/etc/php/7.4/fpm/conf.d/zz-xdebug.ini
      - ./.docker/php/conf/opcache.ini:/etc/php/7.4/fpm/conf.d/zz-opcache.ini
      - ./.docker/php/conf/pool.conf:/etc/php/7.4/fpm/pool.d/www.conf
    networks:
      - internal
    labels:
      - traefik.enable=false

  db:
    image: mysql:5.7
    env_file:
      - .env
    volumes:
      - db_data:/var/lib/mysql
      - ./.docker/mysql/conf.d:/etc/mysql/conf.d
    command:
      - --character-set-server=utf8mb4
      - --collation-server=utf8mb4_unicode_ci
      - --skip-character-set-client-handshake
    networks:
      - internal
    labels:
      - traefik.enable=false
    restart: always

  adminer:
    image: adminer
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:db.heracles.local
      - traefik.basic.port=8080

  blackfire:
    image: blackfire/blackfire
    networks:
      - internal
    labels:
      - traefik.enable=false

  mailhog:
    image: mailhog/mailhog
    networks:
      - internal
      - proxy
    labels:
      - traefik.docker.network=proxy
      - traefik.enable=true
      - traefik.basic.frontend.rule=Host:mail.heracles.local
      - traefik.basic.port=8025

  mercure:
    image: dunglas/mercure
    environment:
      - ALLOW_ANONYMOUS=1
      - CORS_ALLOWED_ORIGINS=*
      - JWT_KEY=ASD
      - PUBLISH_ALLOWED_ORIGINS=http://heracles.local
      - ADDR=:3000
    ports:
      - 3000:3000

networks:
  internal:
  proxy:
    external: true

volumes:
  db_data:


问:
Python: Remove exponential in Strings
I have been trying to remove the exponential in a string for the longest time to no avail.

The column involves strings with alphabets in it and also long numbers of more than 24 digits. I tried converting the column to string with .astype(str) but it just reads the line as "1.234123E+23". An example of the table is

```<code>A

345223423dd234324

1.234123E+23
</code>```

how do i get the table to show the full string of digits in pandas?

答:
```<code>b = "1.234123E+23"
str(int(float(b)))

</code>```

output is '123412299999999992791040'
no idea how to do it in pandas with mixed data type in column

Title: Python: Remove exponential in Strings

Body:
I have been trying to remove the exponential in a string for the longest time to no avail.

The column involves strings with alphabets in it and also long numbers of more than 24 digits. I tried converting the column to string with .astype(str) but it just reads the line as "1.234123E+23". An example of the table is

A

345223423dd234324

1.234123E+23

how do i get the table to show the full string of digits in pandas?

Body:
b = "1.234123E+23"
str(int(float(b)))

output is '123412299999999992791040'
no idea how to do it in pandas with mixed data type in column


问:
How can ls see the future when using bash redirection?
I meet the following code in a book and still not understand why. Anyone can help to explain it please?</p>

```<code>[root@wd00070319 test]# ls
[root@wd00070319 test]# touch file1
[root@wd00070319 test]# ls
file1
[root@wd00070319 test]# ls > file2
[root@wd00070319 test]# ls
file1  file2
[root@wd00070319 test]# cat file2
file1
file2
[root@wd00070319 test]#
</code>```

答:
```<code>[root@wd00070319 test]# ls            # list the files. (directory is empty!)
[root@wd00070319 test]# touch file1   # create an empty file called "file1"
[root@wd00070319 test]# ls            # list the files again (to see "file1")
file1
[root@wd00070319 test]# ls > file2    # list the files, put the result in "file2"
[root@wd00070319 test]# ls            # list the files again,
file1  file2
[root@wd00070319 test]# cat file2     # show content of file2
file1
file2                                 # <-- Note that "file2" is present as well.
[root@wd00070319 test]#
</code>```

The lesson here is probably that a command like ls > file2 creates the output-file (file2) before actually executing the ls command.

This behavior is confirmed by the bash reference manual:

3.6 Redirections

[...] Before a command is executed, its input and output may be redirected
  using a special notation interpreted by the shell. [...]

ContentLicense: CC BY-SA 3.0

Body:
I meet the following code in a book and still not understand why. Anyone can help to explain it please?

[root@wd00070319 test]# ls
[root@wd00070319 test]# touch file1
[root@wd00070319 test]# ls
file1
[root@wd00070319 test]# ls > file2
[root@wd00070319 test]# ls
file1  file2
[root@wd00070319 test]# cat file2
file1
file2
[root@wd00070319 test]#

Body:
[root@wd00070319 test]# ls            # list the files. (directory is empty!)
[root@wd00070319 test]# touch file1   # create an empty file called "file1"
[root@wd00070319 test]# ls            # list the files again (to see "file1")
file1
[root@wd00070319 test]# ls > file2    # list the files, put the result in "file2"
[root@wd00070319 test]# ls            # list the files again,
file1  file2
[root@wd00070319 test]# cat file2     # show content of file2
file1
file2                                 # <-- Note that "file2" is present as well.
[root@wd00070319 test]#

The lesson here is probably that a command like ls > file2 creates the output-file (file2) before actually executing the ls command.

This behavior is confirmed by the bash reference manual:

3.6 Redirections

[...] Before a command is executed, its input and output may be redirected
  using a special notation interpreted by the shell. [...]


问:
Adding a number to certain elements of an array
I have an array in numpy:

```<code>[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]
</code>```

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

答:
You could do something like this:

>>> import numpy as np
>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
>>> (x >= 3) * (x <= 8) * 100
array([[  0,   0, 100],
       [100, 100, 100],
       [100, 100,   0],
       [  0,   0,   0]])
```

and then add that to your array. Note that (x >= 3) * (x <= 8) contains boolean values that are cast to 0 or 1 once you multiply them with the integer 100.

Body:
I have an array in numpy:

[1  2  3]
[4  5  6]
[7  8  9]
[10 11 12]

I would like to add 100 to all values that are greater than or equal to 3 and less than or equal to 8. How can I do this?

Body:
You could do something like this:

>>> import numpy as np
>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
>>> (x >= 3) * (x <= 8) * 100
array([[  0,   0, 100],
       [100, 100, 100],
       [100, 100,   0],
       [  0,   0,   0]])

and then add that to your array. Note that (x >= 3) * (x <= 8) contains boolean values that are cast to 0 or 1 once you multiply them with the integer 100.


答:
So, it seems all I needed were aliases:

```<code>public function descargarPDF(Request $request)
    {
        $fecha1 = $request->get('fecha1');
        $fecha2 = $request->get('fecha2');
        $categoria = $request->get('categoria');
        $tickets = DB::table('tickets')
        -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
        -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
        -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
        -> select ('tickets.id as id_ticket',
                   'users.name as nombre',
                   'users.email as email',
                   'users.empresa as empresa',
                   'areas.nombre as requerimiento',
                   'tickets.estado as estado')
        -> where('tickets.estado' ,'=', $categoria)
        -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
        -> get();
        $pdf = PDF::loadView('/admin/pdf', compact('tickets'));
        return $pdf->download('tickets.pdf');
    }
</code>```

Cheers to Felipe for solving that in the comments!

Title: Laravel Eloquent: I cannot get the id I want, instead I get another one from a joined table

Body:
So, it seems all I needed were aliases:

public function descargarPDF(Request $request)
    {
        $fecha1 = $request->get('fecha1');
        $fecha2 = $request->get('fecha2');
        $categoria = $request->get('categoria');
        $tickets = DB::table('tickets')
        -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
        -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
        -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
        -> select ('tickets.id as id_ticket',
                   'users.name as nombre',
                   'users.email as email',
                   'users.empresa as empresa',
                   'areas.nombre as requerimiento',
                   'tickets.estado as estado')
        -> where('tickets.estado' ,'=', $categoria)
        -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
        -> get();
        $pdf = PDF::loadView('/admin/pdf', compact('tickets'));
        return $pdf->download('tickets.pdf');
    }

Cheers to Felipe for solving that in the comments!


问:
Recv() in Winsock requires signed buffer
I use recv() on Linux with unsigned char buffer and it works well.

But recv() on Windows requires signed char and I don't know why.

I thought the packet can be only ASCII character.

Should I use something like this (char)buffer?

答:
char, unsigned char and signed char are different types but all are 8 bit. In theory, all "buffers" should be unsigned char*. In practise, many functions use a plain char* including most Win32 APIs. In all such cases it is a plain 8-bit array.

In short, cast it freely.

Cases that actually need a char rather than an unsigned char should be obvious to detect and handle.

As per @JJ comment, you also have std::byte for raw 8-bit stuff without character characteristics, similar to BYTE in Win32.


问:
Replace all strings with numbers based on conditions
I have a column of data that describes possible diseases. I am trying to change these qualitative values into quantitative ones. So for example setting conditions such as "if a row contains words "blood pressure" delete all characters and replace to be 3, if row contains "heart" replace to be 2, if the row contains "diabetes" or "kidney disease" replace to be 1, if any other condition replace to be 0.5"

For example my data looks like:

```<code>Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease
Gene4    Name=Childhood ear infection
Gene5    NA
Gene6    Name=kidney disease
</code>```

The output I am trying to reach based on my mentioned conditions is:

```<code>Gene Condition
Gene1    0.5
Gene2    3
Gene3    2
Gene4    0.5
Gene5    NA
Gene6    1
</code>```

I am new to R and so not sure if the way I'm trying is the best, but I'm trying to run  my conditions to replace the specific strings (but not all characters), producing multiple numbers in a row (mixed with strings) if more than 1 condition is met, then applying a getmaxfunction for each row to get the largest number available. However I am stuck on setting up conditions to perform the string to number conversation.
I've been trying to do:

```<code>data$condition[data$condition == "blood pressure"] <- "3"
data$condition[data$condition == "heart disease"] <- "2"
data$condition[data$condition == "diabetes" | "kidney disease"] <- "1"
data$condition[data$condition == "Name" && !"diabetes" | "kidney disease" | "blood pressure" | "heart disease"] <- "0.5"
</code>```

However this gives an error that ' 'object of type 'closure' is not subsettable', and for this approach at least, I can't find the solution for this error online. Any help would be appreciated.

Example data (first time trying to give data, please let me know if something is amiss):

```<code>structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"    Name=blood pressure, Name=diabetes", "Name=heart disease",
"Name=Childhood ear infection", NA, "Name=kidney disease")), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000001bea99a1ef0>)
</code>```

答:
Now, the matching operation can be represented as a complex join in SQL.  First create numDF which is a two column data frame with the names to match in the first column and their numbers in the second column.  Then perform the join.

```<code>library(sqldf)

nums <- c("blood pressure" = 3, heart = 2, diabetes = 1, "kidney disease" = 1)
numDF <- data.frame(Name = names(nums), Value = as.vector(nums))

sqldf("select
    a.Gene,
    max(case when a.Condition is not Null then coalesce(b.Value, 0.5) end) Condition
  from DF a
  left join numDF b on a.Condition like '%' || b.Name || '%'
  group by Gene", method = "raw")
</code>```

giving:

```<code>   Gene Condition
1 Gene1       0.5
2 Gene2       3.0
3 Gene3       2.0
4 Gene4       0.5
5 Gene5        NA
6 Gene6       1.0
</code>```

Note

One cannot use dput on an object with an internal pointer so I have modified the dput output to be useable:

```<code>DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("    Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"    Name=blood pressure, Name=diabetes", "Name=heart disease",
"Name=Childhood ear infection", NA, "Name=kidney disease")),
row.names = c(NA, -6L), class = "data.frame")
</code>```

EDIT

Have modified to add the max condition.

Body:
I have a column of data that describes possible diseases. I am trying to change these qualitative values into quantitative ones. So for example setting conditions such as "if a row contains words "blood pressure" delete all characters and replace to be 3, if row contains "heart" replace to be 2, if the row contains "diabetes" or "kidney disease" replace to be 1, if any other condition replace to be 0.5"

For example my data looks like:

Gene     Condition
Gene1    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker
Gene2    Name=blood pressure, Name=diabetes
Gene3    Name=heart disease
Gene4    Name=Childhood ear infection
Gene5    NA
Gene6    Name=kidney disease

The output I am trying to reach based on my mentioned conditions is:

Gene Condition
Gene1    0.5
Gene2    3
Gene3    2
Gene4    0.5
Gene5    NA
Gene6    1

I am new to R and so not sure if the way I'm trying is the best, but I'm trying to run  my conditions to replace the specific strings (but not all characters), producing multiple numbers in a row (mixed with strings) if more than 1 condition is met, then applying a getmaxfunction for each row to get the largest number available. However I am stuck on setting up conditions to perform the string to number conversation.
I've been trying to do:

data$condition[data$condition == "blood pressure"] <- "3"
data$condition[data$condition == "heart disease"] <- "2"
data$condition[data$condition == "diabetes" | "kidney disease"] <- "1"
data$condition[data$condition == "Name" && !"diabetes" | "kidney disease" | "blood pressure" | "heart disease"] <- "0.5"

However this gives an error that ' 'object of type 'closure' is not subsettable', and for this approach at least, I can't find the solution for this error online. Any help would be appreciated.

Example data (first time trying to give data, please let me know if something is amiss):

structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("    Name=Asymmetrical dimethylarginine level, Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"    Name=blood pressure, Name=diabetes", "Name=heart disease",
"Name=Childhood ear infection", NA, "Name=kidney disease")), row.names = c(NA,
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x000001bea99a1ef0>)

Body:
Now, the matching operation can be represented as a complex join in SQL.  First create numDF which is a two column data frame with the names to match in the first column and their numbers in the second column.  Then perform the join.

library(sqldf)

nums <- c("blood pressure" = 3, heart = 2, diabetes = 1, "kidney disease" = 1)
numDF <- data.frame(Name = names(nums), Value = as.vector(nums))

sqldf("select
    a.Gene,
    max(case when a.Condition is not Null then coalesce(b.Value, 0.5) end) Condition
  from DF a
  left join numDF b on a.Condition like '%' || b.Name || '%'
  group by Gene", method = "raw")

giving:

   Gene Condition
1 Gene1       0.5
2 Gene2       3.0
3 Gene3       2.0
4 Gene4       0.5
5 Gene5        NA
6 Gene6       1.0

Note

One cannot use dput on an object with an internal pointer so I have modified the dput output to be useable:

DF <-
structure(list(Gene = c("Gene1", "Gene2", "Gene3", "Gene4", "Gene5",
"Gene6"), Condition = c("    Name=Asymmetrical dimethylarginine leve,l Name=Bipolar disorder and schizophrenia, Name=3-hydroxypropylmercapturic acid levels in smoker",
"    Name=blood pressure, Name=diabetes", "Name=heart disease",
"Name=Childhood ear infection", NA, "Name=kidney disease")),
row.names = c(NA, -6L), class = "data.frame")

EDIT

Have modified to add the max condition.


问:
Hide Android keyboard in Nativescript on input field blur
I have a registration form which contains several TextFields and other inputs. When a user taps one of the fields the Android soft keyboard will always show as expected. If I tap outside of the field though the keyboard does not hide. Is there a way to capture this event so that I can hide the keyboard when ever a user taps outside of any of the inputs?

It looks like doing the following allows me to hide the keyboard

```<code>var pageContainer = page.getViewById('registration-container');
if(pageContainer.android) {
    pageContainer.android.clearFocus();
}
</code>```

But I'm unsure how to capture every tap event that blurs the forms inputs. I'm not even sure if this is possible with Android.

答:
I found this to be more elegant:</p>

```<code>import * as utils from "tns-core-modules/utils/utils";
import { isIOS, isAndroid } from "tns-core-modules/platform";
import { frame } from "tns-core-modules/ui/frame";

export function hideKeyboard() {
    if (isIOS) {
        frame.topmost().nativeView.endEditing(true);
    }
    if (isAndroid) {
        utils.ad.dismissSoftInput();
    }
}
</code>```

Body:
I have a registration form which contains several TextFields and other inputs. When a user taps one of the fields the Android soft keyboard will always show as expected. If I tap outside of the field though the keyboard does not hide. Is there a way to capture this event so that I can hide the keyboard when ever a user taps outside of any of the inputs?

It looks like doing the following allows me to hide the keyboard

var pageContainer = page.getViewById('registration-container');
if(pageContainer.android) {
    pageContainer.android.clearFocus();
}

But I'm unsure how to capture every tap event that blurs the forms inputs. I'm not even sure if this is possible with Android.

Body:
I found this to be more elegant:

import * as utils from "tns-core-modules/utils/utils";
import { isIOS, isAndroid } from "tns-core-modules/platform";
import { frame } from "tns-core-modules/ui/frame";

export function hideKeyboard() {
    if (isIOS) {
        frame.topmost().nativeView.endEditing(true);
    }
    if (isAndroid) {
        utils.ad.dismissSoftInput();
    }
}


问:
Programmatically detect SQL Server Edition
I'm using C# with SMO and attempting to detect what edition of SQL Server (e.g., enterprise, standard) I'm connecting to.  I know how to get the version information, but that only tells me what version of SQL Server (e.g., SQL Server 2008 vs SQL Server 2005).

Does anyone know how to get the actual product edition (e.g., enterprise, standard)?

I need this information because some SQL Server features are only enterprise.  Thus, I could just try to call them and catch the exception, but I'd much prefer an upfront detection.

Thanks!

答:
```<code>select @@version
</code>```

Returns version and which edition. Here:

```
Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
    Nov 24 2008 13:01:59
    Copyright (c) 1988-2005 Microsoft Corporation
    Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 2)
```

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

Body:
select @@version

Returns version and which edition. Here:

Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
    Nov 24 2008 13:01:59
    Copyright (c) 1988-2005 Microsoft Corporation
    Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 2)

OwnerDisplayName: Richard


问:
PHP How to hit a url and download its xml
I am trying to send this query:

```<code>http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK
</code>```

To a web service and pull down and parse a bunch of fields there, namely these:

```<code>// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.
</code>```

I am doing this:

```<code>$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
</code>```

Could someone please provide the right code to loop through the results and get values?

答:
Since the response is XML, you can use SimpleXML:

```<code>$url = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
$xml = new SimpleXMLElement($url, null, true);

echo "totalResultsCount: " . $xml->totalResultsCount . "<br />";

foreach($xml->geoname as $geoname) {
    echo $geoname->toponymName . "<br />";
    echo $geoname->lat . "<br />";
    echo $geoname->countryCode . "<br />";
    echo $geoname->countryName . "<br />";
    echo $geoname->adminName1 . "<br />";
    echo $geoname->adminName2 . "<br />";
}
</code>```

Which will displays the results as follows:

```<code>totalResultsCount: 225
Glacier Bay National Park and Preserve
58.50056
US
United States
Alaska
US.AK.232

...
</code>```

Body:
I am trying to send this query:

http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK

To a web service and pull down and parse a bunch of fields there, namely these:

// 1) totalResultsCount
// 2) name
// 3) lat
// 4) lng
// 5) countryCode
// 6) countryName
// 7) adminName1 - gives full state name
// 8) adminName2 - owner of the park.

I am doing this:

$query_string = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";

Could someone please provide the right code to loop through the results and get values?

Body:
Since the response is XML, you can use SimpleXML:

$url = "http://api.geonames.org/search?featureCode=PRK&maxRows=10&username=demo&country=US&style=full&adminCode1=AK";
$xml = new SimpleXMLElement($url, null, true);

echo "totalResultsCount: " . $xml->totalResultsCount . "<br />";

foreach($xml->geoname as $geoname) {
    echo $geoname->toponymName . "<br />";
    echo $geoname->lat . "<br />";
    echo $geoname->countryCode . "<br />";
    echo $geoname->countryName . "<br />";
    echo $geoname->adminName1 . "<br />";
    echo $geoname->adminName2 . "<br />";
}

Which will displays the results as follows:

totalResultsCount: 225
Glacier Bay National Park and Preserve
58.50056
US
United States
Alaska
US.AK.232

...


问:
Increased Global Batch in Data Parallelism size Causes OOM Error
I am increasing the batch size as I increase the number of GPUs when training the AlexNet Model on ImageNet dataset. It works fine up to 4096 when I get OOM errors. I start with a batch size of 1024 on 4 GPUs, then 2048 on 8 GPUs. However, when I attempt 4096 on 16 GPUs, I get OOM. Ideally, this shouldn't happen because, in data parallelism, samples per GPU remain the same. I am using ChainerMN for the training. </p>

答: Figured this out finally. Dont increase the batch size as you increase the number of GPUs. If you set batch size at say 32, each GPU will have a batch size of 32. </p>


问:
Joi validate self-referencing nested schema
I am trying to validate a schema that, along other fields, has an array of self-referenced objects like this:

```<code>export const answer = answerModel.concat(Joi.object().keys({
    childAnswers: Joi.array().items(answer),
    numArray: Joi.array().items(Joi.number()).required()
}))
</code>```

My problem is that I cannot reference answer schema inside answers schema Joi.array().items(answer) since I cannot use it before I declare it.

Question is "is there any way to self-reference in this nested format for validation"?

答:
You can use Joi.link() for this purpose:

```<code>const person = Joi.object({
  firstName: Joi.string().required(),
  lastName: Joi.string().required(),
  friends: Joi.array().items(Joi.link('#person'))
}).id('person');
</code>```

Body:
I am trying to validate a schema that, along other fields, has an array of self-referenced objects like this:

export const answer = answerModel.concat(Joi.object().keys({
    childAnswers: Joi.array().items(answer),
    numArray: Joi.array().items(Joi.number()).required()
}))

My problem is that I cannot reference answer schema inside answers schema Joi.array().items(answer) since I cannot use it before I declare it.

Question is "is there any way to self-reference in this nested format for validation"?

Body:
You can use Joi.link() for this purpose:

const person = Joi.object({
  firstName: Joi.string().required(),
  lastName: Joi.string().required(),
  friends: Joi.array().items(Joi.link('#person'))
}).id('person');


问:
Refactor out long if-else block using a mapping of two columns from a pandas DataFrame
I am building a chatbot using Selenium and it has two short answers by now. When user sends '/help' the bot sends 'You asked for help', when user sends '/more', bot sends 'You asked more'...

def conversation():
    if last_msg() == '/help':
        msg = 'You asked help'
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys(msg)
    elif last_msg() =='/more':
        msg = 'You asked more'
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys(msg)
    else:
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys('Sorry, input not listed')
    time.sleep(1)
    driver.find_element_by_class_name("_3M-N-").click()```
</div>
</div>
</p>

<p>How can i escalate this using pandas? Assuming i have an csv with 2 columns, one named 'msg' and the other 'reply'. I would like to add many rows to this csv, without needing to change the code.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    msg    reply
0   /help  you_asked_for_help
1   /more  you_asked_for_more</code>```

df_with_reply = pd.read_csv(r'C:\Users...')

How can i make this:

        if last_msg() == '/help':
            msg = 'You asked help'
            input_field = driver.find_element_by_class_name("_3u328")
            input_field.send_keys(msg)
        elif last_msg() =='/more':
            msg = 'You asked more'
            input_field = driver.find_element_by_class_name("_3u328")
            input_field.send_keys(msg)```
</div>
</div>
</p>

<p><strong>Turn into this:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>        if last_msg() == IS IN df COLUMN 'msg'
        RETURN ACCORDING TEXT FROM df COLUMN 'reply' as X

        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys(X)

        else:
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys('Sorry, input not listed')
           </code>```

答:
Setup a default dictionary mapping messages to replies.

```<code>from collections import defaultdict

d = defaultdict(lambda: 'Sorry, input not listed')
d.update(df.set_index('msg')['reply'].to_dict())
</code>```

Now d can be accessed inside your function:

```<code>def conversation():
    input_field = driver.find_element_by_class_name("_3u328")
    input_field.send_keys(d[last_msg()])

    time.sleep(1)

    driver.find_element_by_class_name("_3M-N-").click()
</code>```

Body:
I am building a chatbot using Selenium and it has two short answers by now. When user sends '/help' the bot sends 'You asked for help', when user sends '/more', bot sends 'You asked more'...

def conversation():
    if last_msg() == '/help':
        msg = 'You asked help'
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys(msg)
    elif last_msg() =='/more':
        msg = 'You asked more'
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys(msg)
    else:
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys('Sorry, input not listed')
    time.sleep(1)
    driver.find_element_by_class_name("_3M-N-").click()

How can i escalate this using pandas? Assuming i have an csv with 2 columns, one named 'msg' and the other 'reply'. I would like to add many rows to this csv, without needing to change the code.

    msg    reply
0   /help  you_asked_for_help
1   /more  you_asked_for_more

df_with_reply = pd.read_csv(r'C:\Users...')

How can i make this:

        if last_msg() == '/help':
            msg = 'You asked help'
            input_field = driver.find_element_by_class_name("_3u328")
            input_field.send_keys(msg)
        elif last_msg() =='/more':
            msg = 'You asked more'
            input_field = driver.find_element_by_class_name("_3u328")
            input_field.send_keys(msg)

Turn into this:

        if last_msg() == IS IN df COLUMN 'msg'
        RETURN ACCORDING TEXT FROM df COLUMN 'reply' as X

        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys(X)

        else:
        input_field = driver.find_element_by_class_name("_3u328")
        input_field.send_keys('Sorry, input not listed')

Body:
Setup a default dictionary mapping messages to replies.

from collections import defaultdict

d = defaultdict(lambda: 'Sorry, input not listed')
d.update(df.set_index('msg')['reply'].to_dict())

Now d can be accessed inside your function:

def conversation():
    input_field = driver.find_element_by_class_name("_3u328")
    input_field.send_keys(d[last_msg()])

    time.sleep(1)

    driver.find_element_by_class_name("_3M-N-").click()


问:
How to avoid string repetition
I have two different string String A="example"; String B="example";
if concat both the string i am getting examplexample. Is there any possibility to avoid repetition of string with same name..??

答:
Just create a Set (It has mathematics set behaviour, it won't accept the duplicate objects)

```<code>Set<String> strings = new HashSet<String>();
</code>```

//Fill this set with all the String objects

```<code>strings.add(A)
Strings.add(B)
</code>```

//Now iterate this set and create a String Object

```<code>StringBuilder resultBuilder = new StringBuilder();

for(String string:Strings){
resultBuilder.append(string);
}
return resultBuilder.toString()
</code>```

`

Title: How to avoid string repetition

Body:
Just create a Set (It has mathematics set behaviour, it won't accept the duplicate objects)

Set<String> strings = new HashSet<String>();

//Fill this set with all the String objects

strings.add(A)
Strings.add(B)

//Now iterate this set and create a String Object

StringBuilder resultBuilder = new StringBuilder();

for(String string:Strings){
resultBuilder.append(string);
}
return resultBuilder.toString()

`


问:
POST api authentication in vba
I am trying to connect excel (through vba) to the "teamleader" api v1, via post calls.
api docs here

I tried some solutions which I have found, regarding post calls in vba, but seem to be getting nowhere.

This is what I have so far:

```<code>Sub test2()
    Dim url As String
    Dim objhttp As Object
    Set objhttp = CreateObject("MSXML2.ServerXMLHTTP")

    url = "https://app.teamleader.eu/api/helloWorld.php"

    With objhttp
        .Open "POST", url, False
        .setRequestHeader "api_group", "xxx"
        .setRequestHeader "api_secret", "xxx"
        .send
        Debug.Print .responseText
    End With
End Sub
</code>```

This however gives me this response:

```<code>{"status":"failed","reason":"Please set api_group."}
</code>```

Does anyone have any idea how to get this to work?

答: Turns out I needed the put all the authentication in the url itself, this question can be closed.</p>

Title: POST api authentication in vba

Body:
I am trying to connect excel (through vba) to the "teamleader" api v1, via post calls.
api docs here

I tried some solutions which I have found, regarding post calls in vba, but seem to be getting nowhere.

This is what I have so far:

Sub test2()
    Dim url As String
    Dim objhttp As Object
    Set objhttp = CreateObject("MSXML2.ServerXMLHTTP")

    url = "https://app.teamleader.eu/api/helloWorld.php"

    With objhttp
        .Open "POST", url, False
        .setRequestHeader "api_group", "xxx"
        .setRequestHeader "api_secret", "xxx"
        .send
        Debug.Print .responseText
    End With
End Sub

This however gives me this response:

{"status":"failed","reason":"Please set api_group."}

Does anyone have any idea how to get this to work?


问:
Where do I find anaconda 3.6
I want to downgrade my anaconda
I have anaconda installed in my local machine and the installed version is 4.8.0 when i checked in anaconda prompt, but i want to install anaconda version 3.6, iv'e tried anaconda website and found anaconda archive but unable to find anaconda 3.6 can anyone guide me with the solution? On anaconda 3.6 does exist?

答:
There isn't - and never was - Anaconda 3.6 (all thanks to somewhat weird numbering they're using). I guess what you mean is Anaconda with Python 3.6.

Two tips first:

There's rarely a good reason to stick with an obsolete Anaconda version.

Create new environment rather than modify the default environment (unless that's really what you want).

To create a new environment named py36 with Python 3.6:

```<code>conda create -n py36 python=3.6
</code>```

To install Python 3.6 to the default:

```<code>conda install python=3.6
</code>```

Title: Where do I find anaconda 3.6

Body:
There isn't - and never was - Anaconda 3.6 (all thanks to somewhat weird numbering they're using). I guess what you mean is Anaconda with Python 3.6.

Two tips first:

There's rarely a good reason to stick with an obsolete Anaconda version.

Create new environment rather than modify the default environment (unless that's really what you want).

To create a new environment named py36 with Python 3.6:

conda create -n py36 python=3.6

To install Python 3.6 to the default:

conda install python=3.6


问:
How to find the array index with a value?
Say I've got this

imageList = [100,200,300,400,500];
```

Which gives me

[0]100 [1]200 etc.

Is there any way in JavaScript to return the index with the value?

I.e. I want the index for 200, I get returned 1.

答:
In a multidimensional array.

Reference array:

```<code>var array = [
    { ID: '100' },
    { ID: '200' },
    { ID: '300' },
    { ID: '400' },
    { ID: '500' }
];
</code>```

Using filter and indexOf:

```<code>var index = array.indexOf(array.filter(function(item) { return item.ID == '200' })[0]);
</code>```

Looping through each item in the array using indexOf:

```<code>for (var i = 0; i < array.length; i++) {
    var item = array[i];
    if (item.ID == '200') {
        var index = array.indexOf(item);
    }
}
</code>```

Body:
Say I've got this

imageList = [100,200,300,400,500];

Which gives me

[0]100 [1]200 etc.

Is there any way in JavaScript to return the index with the value?

I.e. I want the index for 200, I get returned 1.

Body:
In a multidimensional array.

Reference array:

var array = [
    { ID: '100' },
    { ID: '200' },
    { ID: '300' },
    { ID: '400' },
    { ID: '500' }
];

Using filter and indexOf:

var index = array.indexOf(array.filter(function(item) { return item.ID == '200' })[0]);

Looping through each item in the array using indexOf:

for (var i = 0; i < array.length; i++) {
    var item = array[i];
    if (item.ID == '200') {
        var index = array.indexOf(item);
    }
}


问:
ValueError: time data 'Date' does not match format '%m/%d/%Y' (Python)
```<code>import glob
import pandas as pd
import datetime

my_dates = ['Date']
sorted(my_dates, key=lambda x :datetime.datetime.strptime(x,'%m/%d/%Y'))
</code>```

Getting the error in title. Not sure why. the date format in excel sheet is 1/2/2020 (m/d/yyyy)
Tried many methods off google search and getting same error. Checked excel sheet to see if any dates written wrong but nope.

Python lists the column as object/list

答: In the first loop you've got x = 'Date' which can't be parsed as date, but it will when my_dates = ['10/28/2020']

Body:
import glob
import pandas as pd
import datetime

my_dates = ['Date']
sorted(my_dates, key=lambda x :datetime.datetime.strptime(x,'%m/%d/%Y'))

Getting the error in title. Not sure why. the date format in excel sheet is 1/2/2020 (m/d/yyyy)
Tried many methods off google search and getting same error. Checked excel sheet to see if any dates written wrong but nope.

Python lists the column as object/list


问:
VueCropper does not get loaded correctly
So I wanted to use VueCropper in my Component, but I get some issues:

It displays the sourceImg, but there is no cropbox und also no preview.

The output of console.log(this.$refs) and console.log(this.$refs.cropper) are paradox (see below)

Here is the code:

```<code><template>
    <div class="img-selector">
        <template v-if="!fileSelected">
            <b-form-file
                v-model="imgFile"
                placeholder="Choose a file..."
                no-drop
                accept="image/*"
            ></b-form-file>
            <b-button @click="onNext">Next</b-button>
        </template>
        <template v-else>
            <div class="img_container">
                <vue-cropper
                    ref="cropper"
                    :aspect-ratio="16/9"
                    :guides="true"
                    :view-mode="2"
                    drag-mode="crop"
                    :background="true"
                    :zoomable="true"
                    :src="imageUrl"
                    preview=".destination"
                    :minCropBoxWidth="160"
                    :minCropBoxHeight="90"
                    :img-style="{ 'width': '400px', 'height': '300px'}"
                ></vue-cropper>
            </div>
            <div class="img_container">
                <!--
                <b-img fluid-grow class="image" class="destination"></b-img>
                -->
                <div class="destination"></div>
            </div>
            <b-button @click="onBack">Back</b-button>
            <b-button @click="onSelect">Select</b-button>
        </template>
        <b-button @click="$emit('canceled')">Cancel</b-button>
    </div>
</template>

<script>
import VueCropper from 'vue-cropperjs'
import 'cropperjs/dist/cropper.css'

export default {
    name: 'img-selector',
    data: () => ({
        imageUrl: '',
        croppedImageUrl: '',
        imgFile: null,
        fileSelected: false
    }),
    components: {
        'vue-cropper': VueCropper
    },
    methods: {
        onNext() {
            if(!!this.imgFile) {
                let reader = new FileReader()
                reader.addEventListener('loadend', () => {
                    this.imageUrl = reader.result
                })
                reader.readAsDataURL(this.imgFile)
            } else {
                alert('You must first choose a File!')
                return
            }

            console.log(this.$refs)
            // Output:
            // (i) value below was evaluated just now
            // >{}
            //   > cropper: vue-cropper
            //   > __proto__: Object
            console.log(this.$refs.cropper)
            // Output:
            // undefined

            this.fileSelected = true
        },
        onBack() {
            this.imgFile = null
            this.fileSelected = false
            this.croppedImageUrl = null
            this.imageUrl = null
        },
        onSelect() {
            this.$refs.cropper.getCroppedCanvas().toBlob(blob => {
                const file = new File(blob, this.imgFile.name)
                this.$emit('selected', {data: file})
            })
        }
    }
}
</script>

<style type="scss">
.image {
    display: block;
    max-width: 100%;
}

.image_container {
    width: 400px;
    height: 300px;
    display: inline-block;
}
</style>
</code>```

Also if I write:
components: { VueCropper}
this.$refs is an empty Object and the sourceImage doesnt get displayed.

I think the problem is, that somehow VueCropper doesnt get loaded correctly. Sadly, I have no clue how to fix this error.

I am thankful for every help!

答:
Ok, I found out that it works after I replaced the v-if v-else statements with v-show.

The documentation said, that v-if only renders the elements when needed, so VueCropper wasnt rendered at the beginning and wasnt added to $refs.
In comparision v-show always renders the elements and only enable/disable their visibility.

Body:
So I wanted to use VueCropper in my Component, but I get some issues:

It displays the sourceImg, but there is no cropbox und also no preview.

The output of console.log(this.$refs) and console.log(this.$refs.cropper) are paradox (see below)

Here is the code:

<template>

        <template v-if="!fileSelected">

            Next
        </template>
        <template v-else>

                <vue-cropper
                    ref="cropper"
                    :aspect-ratio="16/9"
                    :guides="true"
                    :view-mode="2"
                    drag-mode="crop"
                    :background="true"
                    :zoomable="true"
                    :src="imageUrl"
                    preview=".destination"
                    :minCropBoxWidth="160"
                    :minCropBoxHeight="90"
                    :img-style="{ 'width': '400px', 'height': '300px'}"
                ></vue-cropper>

            Back
            Select
        </template>
        Cancel

</template>

Also if I write:
components: { VueCropper}
this.$refs is an empty Object and the sourceImage doesnt get displayed.

I think the problem is, that somehow VueCropper doesnt get loaded correctly. Sadly, I have no clue how to fix this error.

I am thankful for every help!