问:
ELK docker GCP installation
I have configured Kubernetes cluster on GCP and have reconfigured Docker based ELK.

The issue I'm facing is that I'm unable to use the kibana browser dashboard.

Where to set the URL ?

Where to get the external IP to access Kibana?

答:
The issue I'm facing is that I'm unable to use the kibana browser dashboard.
  -   Where to set the URL ?

You have to kubectl expose your kibana as LoadBalancer in order to gain external access.

LoadBalancer:

On cloud providers which support external load balancers, setting the type field to LoadBalancer provisions a load balancer for your Service.

The syntax is:

kubectl expose deployment kibana_deploy_name_here --port=5601 --target-port=5601 --name=kibana-external-url --type=LoadBalancer

Here is my reproduction:

```<code>$ kubectl get deployment
NAME                     READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/kibana   1/1     1            1           14m

$ kubectl expose deploy kibana --port=5601 --target-port=5601 --name=kibana-external-url --type=LoadBalancer
service/kibana-external-url exposed
</code>```

It will take a couple minutes in pending state:

```<code>$ kubectl get svc kibana-external-url
NAME                     TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
kibana-external-url      LoadBalancer   10.0.1.54    <pending>     5601:31781/TCP   7s
</code>```

And will automatically assign an External IP for you:

```<code>$ kubectl get svc kibana-external-url
NAME                  TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
kibana-external-url   LoadBalancer   10.0.1.54    34.68.43.17   5601:31781/TCP   17m
</code>```

Where to get the external IP to access Kibana?

Now just type the address assigned to your service + the port on your browser and you will be good to go.

(Ignore the message, It's just because I haven't configured ES.)

Let me know if you have any difficulties.

Title: ELK docker GCP installation

Body:
The issue I'm facing is that I'm unable to use the kibana browser dashboard.
  -   Where to set the URL ?

You have to kubectl expose your kibana as LoadBalancer in order to gain external access.

LoadBalancer:

On cloud providers which support external load balancers, setting the type field to LoadBalancer provisions a load balancer for your Service.

The syntax is:

kubectl expose deployment kibana_deploy_name_here --port=5601 --target-port=5601 --name=kibana-external-url --type=LoadBalancer

Here is my reproduction:

$ kubectl get deployment
NAME                     READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/kibana   1/1     1            1           14m

$ kubectl expose deploy kibana --port=5601 --target-port=5601 --name=kibana-external-url --type=LoadBalancer
service/kibana-external-url exposed

It will take a couple minutes in pending state:

$ kubectl get svc kibana-external-url
NAME                     TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
kibana-external-url      LoadBalancer   10.0.1.54    <pending>     5601:31781/TCP   7s

And will automatically assign an External IP for you:

$ kubectl get svc kibana-external-url
NAME                  TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
kibana-external-url   LoadBalancer   10.0.1.54    34.68.43.17   5601:31781/TCP   17m

Where to get the external IP to access Kibana?

Now just type the address assigned to your service + the port on your browser and you will be good to go.

(Ignore the message, It's just because I haven't configured ES.)

Let me know if you have any difficulties.


来源: stackexchange

问:
Lit-element and webpack
Is there a way to make webpack works with lit-element WebComponents? Searching around I've found some sample webpack configuration with little to nothing real-world usage. For example how can I make webpack file-loader or html-loader recognize my images?
If I have the following configuration

```<code>module.exports = {
    entry: {
      main: "./src/index.js",
    },
    module: {
            rules: [
                {
                    test: /\.html$/,
                    use: ["html-loader"]
                },
                {
                    test: /\.(png|jpe?g|gif)$/i,
                    loader: 'file-loader',
                    options: {
                        name: "[name].[hash].[ext]",
                        esModule: false,
                    },
                }
            ]
        }
}
</code>```

both loaders won't recognize the html template inside the webcomponent and they won't process it as html. Is there a way make webpack replaces my images assets with what file-loader tells to?

Minimal sample code:

index.html

```<code><body>
This is an image outside a webcomponent <img src="./assets/polymer-logo.jpg" />
<my-element></my-element>
</body>
</code>```

index.js

```<code>class MyElement extends LitElement {
  render() {
    return html`
      This image is inside a web component:
      <img src="./assets/polymer-logo.jpg" />
    `;
  }
}
customElements.define('my-element', MyElement);
</code>```

答:
The loaders only affect the behavior of JS imports, i.e. html-loader will come into play only when the bundler finds an .html import:

import html from './file.html';
```

<p>(from Webpack's html-loader docs). </p>

<p>The same goes for <code>file-loader</code>:</p>

<pre class="lang-js prettyprint-override"><code>import image from './image.png'; // This instructs Webpack to emit the
                                 // asset into the output directory
                                 // and returns the public URL...

class MyElement extends LitElement {

  render() {
    return html`
      This image is inside a web component:
      <img src=${image} /> <!-- ...that you can set as the src -->
    `;
  }

}
</code>```

As for the template, it actually depends on what you mean by "process it as html":
if you want to load it from an external html file I don't think there is currently an easy way to do that with bundlers; if you want to minify it, there is a babel plugin that allows for that. Also, there are some Webpack loaders made for lit-element you may be interested in: lit-scss-loader, lit-loader.

You may want to take a look at the Webpack section of the Open WebComponents guide for some good recommendations and base wp configurations.

ContentLicense: CC BY-SA 4.0

Title: Lit-element and webpack

Body:
Is there a way to make webpack works with lit-element WebComponents? Searching around I've found some sample webpack configuration with little to nothing real-world usage. For example how can I make webpack file-loader or html-loader recognize my images?
If I have the following configuration

module.exports = {
    entry: {
      main: "./src/index.js",
    },
    module: {
            rules: [
                {
                    test: /\.html$/,
                    use: ["html-loader"]
                },
                {
                    test: /\.(png|jpe?g|gif)$/i,
                    loader: 'file-loader',
                    options: {
                        name: "[name].[hash].[ext]",
                        esModule: false,
                    },
                }
            ]
        }
}

both loaders won't recognize the html template inside the webcomponent and they won't process it as html. Is there a way make webpack replaces my images assets with what file-loader tells to?

Minimal sample code:

index.html

This is an image outside a webcomponent
<my-element></my-element>

index.js

class MyElement extends LitElement {
  render() {
    return html`
      This image is inside a web component:

    `;
  }
}
customElements.define('my-element', MyElement);

Body:
The loaders only affect the behavior of JS imports, i.e. html-loader will come into play only when the bundler finds an .html import:

import html from './file.html';

(from Webpack's html-loader docs).

The same goes for file-loader:

import image from './image.png'; // This instructs Webpack to emit the
                                 // asset into the output directory
                                 // and returns the public URL...

class MyElement extends LitElement {

  render() {
    return html`
      This image is inside a web component:
      <img src=${image} /> <!-- ...that you can set as the src -->
    `;
  }

}

As for the template, it actually depends on what you mean by "process it as html":
if you want to load it from an external html file I don't think there is currently an easy way to do that with bundlers; if you want to minify it, there is a babel plugin that allows for that. Also, there are some Webpack loaders made for lit-element you may be interested in: lit-scss-loader, lit-loader.

You may want to take a look at the Webpack section of the Open WebComponents guide for some good recommendations and base wp configurations.


问:
Cancel firebase function
Is it possible to cancel Firebase HTTPS Callable function during it's request?
I have a function with some predictive search. It is called each time when user inputs a character in a search field.

Code:

```<code>func startSearch(_ query: String, completion: @escaping (_ results: [SearcheResults]) -> Void) {

    let data = [
        "query": query
    ]

    functions.httpsCallable("startSearch").call(data) { (result, error) in

        if error != nil {
          completion([])
      } else if let data = result?.data {
            // some data manipulations
            completion(elements)
        }
    }
}
</code>```

Or maybe somehow dismiss earlier completions? Because for now, if user is very rapid and enter text, for example "Berlin" - completion will fire 6 times. I'd like to have a way to cancel a function or cancel previous completions.

Thanks in advance.

答:
You should try debounce, basically in debounce before you fire a request you wait for short span(eg:- 2 secs), and if user types in that span again, timer is reset to again 2 secs,check the link

Once the call is made it cannot be cancelled, It will Either get executed to completition or timedout.

Title: Cancel firebase function

Body:
Is it possible to cancel Firebase HTTPS Callable function during it's request?
I have a function with some predictive search. It is called each time when user inputs a character in a search field.

Code:

func startSearch(_ query: String, completion: @escaping (_ results: [SearcheResults]) -> Void) {

    let data = [
        "query": query
    ]

    functions.httpsCallable("startSearch").call(data) { (result, error) in

        if error != nil {
          completion([])
      } else if let data = result?.data {
            // some data manipulations
            completion(elements)
        }
    }
}

Or maybe somehow dismiss earlier completions? Because for now, if user is very rapid and enter text, for example "Berlin" - completion will fire 6 times. I'd like to have a way to cancel a function or cancel previous completions.

Thanks in advance.


问:
MVC 3 data annotations turn off validation
I have Entity set and i create partial class

```<code>[Bind(Include = "ID,Note,Spec,Retired")]
  [MetadataType(typeof(SomeClass))]
  public partial class Users
  {
  }
</code>```

and in this class I have some data annotations

```<code>[Required(ErrorMessageResourceType = typeof(MyResources.Resources), ErrorMessageResourceName = "ReqField")]
    [Display(Name = "Note")]
    [StringLength(255, ErrorMessageResourceType = typeof(MyResources.Resources), ErrorMessageResourceName = "LenghtNotLonger255")]
    public string Note
    {
      get;
      set;
    }
</code>```

In View

```<code><div class="editor-field">
      @Html.EditorFor(model => model.Spec)
      @Html.ValidationMessageFor(model => model.Spec)
    </div>
    <div class="editor-label">
      @Html.LabelFor(m => m.Note)
    </div>
    <div class="editor-field">
      @Html.EditorFor(m => m.Note)
      @Html.ValidationMessageFor(model => model.Note)
</div>
</code>```

And everything works fine. But on edit I don't want to have validation on this Note field. How can I Do this.

答: The standard thing here is to do is to create a separate model (ViewModel) for that scenario without validation</p>

ContentLicense: CC BY-SA 3.0

Body:
I have Entity set and i create partial class

[Bind(Include = "ID,Note,Spec,Retired")]
  [MetadataType(typeof(SomeClass))]
  public partial class Users
  {
  }

and in this class I have some data annotations

[Required(ErrorMessageResourceType = typeof(MyResources.Resources), ErrorMessageResourceName = "ReqField")]
    [Display(Name = "Note")]
    [StringLength(255, ErrorMessageResourceType = typeof(MyResources.Resources), ErrorMessageResourceName = "LenghtNotLonger255")]
    public string Note
    {
      get;
      set;
    }

In View

      @Html.EditorFor(model => model.Spec)
      @Html.ValidationMessageFor(model => model.Spec)

      @Html.LabelFor(m => m.Note)

      @Html.EditorFor(m => m.Note)
      @Html.ValidationMessageFor(model => model.Note)

And everything works fine. But on edit I don't want to have validation on this Note field. How can I Do this.


问:
What is uiconfid in kaltura configuration
Where do I get my uiconfid, is it from my account?
Generally what is uiconfid in layman terms?

The uiConf ID is used to reference the player instance you wish to
  render when embedding a video in your pages or app views.]1

答:
UI Conf holds the player configuration. UI Confs are created automatically when you add new player in the KMC (Kaltura Management Console).

To get a UI Conf ID:

Login to KMC

Go to Studio > Universal Studio or TV Platform Studio

The Player ID that you see in those tables is the UI Conf ID.


问:
Open a page from a URL derived from a SQL query
I want to be able to use JavaScript to open a URL, however the URL has been made up from a SQL query as it is different on every page (entity). I was wondering if it was possible, was thinking something along the lines of

```<code>function opencs(ev)
{
    window.open('{sql query}');
}
</code>```

The SQL statement is

```<code>SELECT
https://www.xcweather.co.uk/forecast/' + (SUBSTRING({[postal_code], 1, CHARINDEX(' '[Postal_Code])))
FROM TABLE
</code>```

Any help would be greatly appreciated.

答: The SQL will be executed on the server, but the javascript is running on the client. That means that the javascript can't execute the SQL. You will need to execute the SQL on the server, then pass the results (in this case, the URLs) to the client.</p>

Body:
I want to be able to use JavaScript to open a URL, however the URL has been made up from a SQL query as it is different on every page (entity). I was wondering if it was possible, was thinking something along the lines of

function opencs(ev)
{
    window.open('{sql query}');
}

The SQL statement is

SELECT
https://www.xcweather.co.uk/forecast/' + (SUBSTRING({[postal_code], 1, CHARINDEX(' '[Postal_Code])))
FROM TABLE

Any help would be greatly appreciated.


问:
APIM: How to ignore invalid requests
Does anyone know how to ignore request to paths which do not exist on APIM?

If i run a scanner against APIM it will return 404 for APIs which don't exist. I would like to ignore (not respond with 404) when scans attempt to consume paths which have not corresponding API/Path on APIM.

e.g.

/api/v1/with-backing-service == Return from backing service (200, 401, 404, etc...)

/api/v1/without-backing-service === Terminates (No response)

答:
Don't think that is possible. The HTTP request (basically a TCP request) would reach the server either way and APIM will have to receive it to find out the URL path.

Returning a 404 is the right way to respond for invalid paths. Even if you were to place something like a reverse proxy before APIM, that service would have to read the request to know where it has to route it to and return something (a 404) if it doesn't recognize the path.

If the intention is to protect your APIM endpoint from the public internet, consider placing it inside a VNET if possible.

Title: APIM: How to ignore invalid requests


问:
Read a file line by line in reverse order
I have a java ee application where I use a servlet to print a log file created with log4j. When reading log files you are usually looking for the last log line and therefore the servlet would be much more useful if it printed the log file in reverse order. My actual code is:

```<code>    response.setContentType("text");
    PrintWriter out = response.getWriter();
    try {
        FileReader logReader = new FileReader("logfile.log");
        try {
            BufferedReader buffer = new BufferedReader(logReader);
            for (String line = buffer.readLine(); line != null; line = buffer.readLine()) {
                out.println(line);
            }
        } finally {
            logReader.close();
        }
    } finally {
        out.close();
    }
</code>```

The implementations I've found in the internet involve using a StringBuffer and loading all the file before printing, isn't there a code light way of seeking to the end of the file and reading the content till the start of the file?

答:
If you are in a hurry and want the simplest solution without worrying too much about performance, I would give a try to use an external process to do the dirty job (given that you are running your app in a Un*x server, as any decent person would do XD)</p>

```<code>new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("tail yourlogfile.txt -n 50 | rev").getProcess().getInputStream()))
</code>```

Body:
I have a java ee application where I use a servlet to print a log file created with log4j. When reading log files you are usually looking for the last log line and therefore the servlet would be much more useful if it printed the log file in reverse order. My actual code is:

    response.setContentType("text");
    PrintWriter out = response.getWriter();
    try {
        FileReader logReader = new FileReader("logfile.log");
        try {
            BufferedReader buffer = new BufferedReader(logReader);
            for (String line = buffer.readLine(); line != null; line = buffer.readLine()) {
                out.println(line);
            }
        } finally {
            logReader.close();
        }
    } finally {
        out.close();
    }

The implementations I've found in the internet involve using a StringBuffer and loading all the file before printing, isn't there a code light way of seeking to the end of the file and reading the content till the start of the file?

Body:
If you are in a hurry and want the simplest solution without worrying too much about performance, I would give a try to use an external process to do the dirty job (given that you are running your app in a Un*x server, as any decent person would do XD)

new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec("tail yourlogfile.txt -n 50 | rev").getProcess().getInputStream()))


问:
Visual Studio for Mac how to collapse regions and methods
I couldn't find a way to collapse/expand regions and sections from Visual Studio for Mac.

If someone could share how to do that, it would be very useful.

答:
For VS for Mac, Menu > Edit > Outlining...

Click a menu selection.

Note - Your cursor has to be clicked inside a code file before you nav to menu item or they will be grayed out.


问:
Sort with 2 conditions in java strictly using compareTo
```<code>    public int compareTo(T o){

      if (this.getId().charAt(0) < o.getId() ){
         return 1;
      }else{
         return -1;
      }

      //Id data = a, b, f, z
      //num data = 1, 2, 4, 8

      //i want to sort the list according to their id first. then also sort it with their 'num' after sorting with their id first
         //sort id first. sort according to num after
   }

}
</code>```

I want to sort the list according to their id first. and then according to num. How would i..

答:
try the following snippet.</p>

```<code>public int compareTo(Person o){

    int idResult=id.compareTo(o.getId();
    if (idResult == 0) {//same
        return Integer.compare(this.num, o.num);//compare numbers
    }
    return idResult;//else return resut of id comparison
}
</code>```

Body:
    public int compareTo(T o){

      if (this.getId().charAt(0) < o.getId() ){
         return 1;
      }else{
         return -1;
      }

      //Id data = a, b, f, z
      //num data = 1, 2, 4, 8

      //i want to sort the list according to their id first. then also sort it with their 'num' after sorting with their id first
         //sort id first. sort according to num after
   }

}

I want to sort the list according to their id first. and then according to num. How would i..

Body:
try the following snippet.

public int compareTo(Person o){

    int idResult=id.compareTo(o.getId();
    if (idResult == 0) {//same
        return Integer.compare(this.num, o.num);//compare numbers
    }
    return idResult;//else return resut of id comparison
}


问:
Map of object containing a List<Object> for sqlite
I am setting up my model classes to confirm to the docs for sqflite which suggest including a named constructor to convert to/from Maps to better handling of data between the classes and the DB.  Every example I can find is very simple, with class properties all being simple data types.

Using the constructor and method shown below, converting to/from Map is quite simple when dealing with a class such as this.

```<code>class Human{
  final String name;
  final String height;
  Final String weight;

  Human({this.name, this.height, this.weight});
}
</code>```

However, when you have a class where one of the fields is a bit more complex, I do not understand how to structure things within the named constructor and xxx method to return the map of data that I 'believe' I should get.

```<code>class Human{
      final String name;
      final String height;
      Final String weight;
      List<Child> children = [];

      Human({this.name, this.height, this.weight, this.children});
    }

Human({this.name, this.height, this.weight, this.children});

  Human.fromMap(Map<String, dynamic> map)
    : name = map['name'],
      height = map['height'],
      weight = map['weight'],
      children = map['children'];

  Map<String, dynamic> toMap() {
   return {
     'name': name,
     'height': height,
     'weight': weight,
     'children': children,
   };
  }
</code>```

The List children is the part I am struggling with.  I believe you have to get each Child object ALSO converted to a map within the parent map, but am losing the battle here.

Is my approach way off here?  Is there some other method I should be using to accomplish this?

Any assistance would be much appreciated.

答:
Here I am explaining the following

How to convert a model object into Map to use with sqlite

How to convert a Map object from sqlite into a model class.

How to parse JSON reponse properly in flutter

How to convert a model object into JSON

All of the above questions has same answer. Dart has great support for these operations. Here I am going to illustrate it with a detailed example.

```<code>class DoctorList{
  final List<Doctor> doctorList;

  DoctorList({this.doctorList});

  factory DoctorList.fromMap(Map<String, dynamic> json) {
    return DoctorList(
      doctorList: json['doctorList'] != null
          ? (json['doctorList'] as List).map((i) => Doctor.fromJson(i)).toList()
          : null,
    );
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    if (this.doctorList != null) {
      data['doctorList'] = this.doctorList.map((v) => v.toMap()).toList();
    }
    return data;
  }
}
</code>```

The above DoctorList class has a member which holds a list of 'Doctor' objects..

And see how I parsed the doctorList.

```<code> doctorList: json['doctorList'] != null
      ? (json['doctorList'] as List).map((i) => Doctor.fromMap(i)).toList()
      : null,
</code>```

You may wonder, how the Doctor class may look like. Here you go

```<code>class Doctor {
  final String doCode;
  final String doctorName;

  Doctor({this.doCode, this.doctorName});

  factory Doctor.fromMap(Map<String, dynamic> json) {
    return Doctor(
      doCode: json['doCode'],
      doctorName: json['doctorName'],
    );
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['doCode'] = this.doCode;
    data['doctorName'] = this.doctorName;
    return data;
  }

}
</code>```

That's all. Hope you got the idea. Cheers!

Body:
I am setting up my model classes to confirm to the docs for sqflite which suggest including a named constructor to convert to/from Maps to better handling of data between the classes and the DB.  Every example I can find is very simple, with class properties all being simple data types.

Using the constructor and method shown below, converting to/from Map is quite simple when dealing with a class such as this.

class Human{
  final String name;
  final String height;
  Final String weight;

  Human({this.name, this.height, this.weight});
}

However, when you have a class where one of the fields is a bit more complex, I do not understand how to structure things within the named constructor and xxx method to return the map of data that I 'believe' I should get.

class Human{
      final String name;
      final String height;
      Final String weight;
      List<Child> children = [];

      Human({this.name, this.height, this.weight, this.children});
    }

Human({this.name, this.height, this.weight, this.children});

  Human.fromMap(Map<String, dynamic> map)
    : name = map['name'],
      height = map['height'],
      weight = map['weight'],
      children = map['children'];

  Map<String, dynamic> toMap() {
   return {
     'name': name,
     'height': height,
     'weight': weight,
     'children': children,
   };
  }

The List children is the part I am struggling with.  I believe you have to get each Child object ALSO converted to a map within the parent map, but am losing the battle here.

Is my approach way off here?  Is there some other method I should be using to accomplish this?

Any assistance would be much appreciated.

Body:
Here I am explaining the following

How to convert a model object into Map to use with sqlite

How to convert a Map object from sqlite into a model class.

How to parse JSON reponse properly in flutter

How to convert a model object into JSON

All of the above questions has same answer. Dart has great support for these operations. Here I am going to illustrate it with a detailed example.

class DoctorList{
  final List<Doctor> doctorList;

  DoctorList({this.doctorList});

  factory DoctorList.fromMap(Map<String, dynamic> json) {
    return DoctorList(
      doctorList: json['doctorList'] != null
          ? (json['doctorList'] as List).map((i) => Doctor.fromJson(i)).toList()
          : null,
    );
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    if (this.doctorList != null) {
      data['doctorList'] = this.doctorList.map((v) => v.toMap()).toList();
    }
    return data;
  }
}

The above DoctorList class has a member which holds a list of 'Doctor' objects..

And see how I parsed the doctorList.

 doctorList: json['doctorList'] != null
      ? (json['doctorList'] as List).map((i) => Doctor.fromMap(i)).toList()
      : null,

You may wonder, how the Doctor class may look like. Here you go

class Doctor {
  final String doCode;
  final String doctorName;

  Doctor({this.doCode, this.doctorName});

  factory Doctor.fromMap(Map<String, dynamic> json) {
    return Doctor(
      doCode: json['doCode'],
      doctorName: json['doctorName'],
    );
  }

  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['doCode'] = this.doCode;
    data['doctorName'] = this.doctorName;
    return data;
  }

}

That's all. Hope you got the idea. Cheers!


问:
unique_ptr: what is the effect of calling reset before assignment
In c++14, what is the difference between assigning to an existing unique_ptr:

```<code>    std::unique_ptr<double> p = std::make_unique<double>(1.0);
    p = std::make_unique<double>(2.0);
</code>```

and first calling reset before assigning to it:?

    std::unique_ptr<double> p = std::make_unique<double>(1.0);
    p.reset();
    p = std::make_unique<double>(2.0);
```

I thought adding .reset() before assignment will have not a big impact on the code, but the one without reset() seems to produce different (and more) assembly code when compiled with -O3. Check the code online here:

https://godbolt.org/z/mBApWH

https://godbolt.org/z/JfStmC

答:
I believe most of the differences between compiler output are due to the fact that for one of the two snippets it was able to optimize more stuff out. After all, you just add a couple of constants to a variable. If we're to make optimizer's job a bit more difficult, outputs are nearly identical. There compiler has no idea how foo works and has to produce both calls to it and add results to x, no room to be clever.

To answer you question, the difference is small. Move-assignment operator of unique_ptr frees memory anyway, so calling reset before it is redundant. But, as evident from my link, compiler may omit that operation if it knows that the pointer was reset.

However, calling reset before may be useful if memory held by the pointer will be freed before allocation of new memory, thus reducing memory footprint of the program.

Body:
In c++14, what is the difference between assigning to an existing unique_ptr:

    std::unique_ptr<double> p = std::make_unique<double>(1.0);
    p = std::make_unique<double>(2.0);

and first calling reset before assigning to it:?

    std::unique_ptr<double> p = std::make_unique<double>(1.0);
    p.reset();
    p = std::make_unique<double>(2.0);

I thought adding .reset() before assignment will have not a big impact on the code, but the one without reset() seems to produce different (and more) assembly code when compiled with -O3. Check the code online here:

https://godbolt.org/z/mBApWH

https://godbolt.org/z/JfStmC


问:
Why can this constructor declared with two parameters be called with just one?
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

```<code>Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}
</code>```

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...

答:
The = in the constructor declaration give the parameters default values. If you don't provide a value yourself when you call the constructor, the compiler will fill in the declared default value for you. The constructor won't know the difference — it will see both parameters, and it will have no way of detecting whether the caller provided both values or whether the compiler filled in some of them, but that's usually OK. (If you need to know the difference, then declare multiple constructors, each with a distinct number of parameters, and no default values.)

Your constructor can even be called with no parameters because both of them have default values. In that case, the first parameter will have the default value 0 and the second will get 1.

Parameter values can only be omitted from the end. That is, you cannot omit the top parameter without also leaving out the bottom parameter. The first actual parameter you give will always correspond to the first formal parameter in the declaration. Likewise, default parameters can only be defined starting at the end. You cannot define a default parameter for top without also declaring one for bottom.

Body:
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this:

Rational (int top=0 , int bottom=1)
: t(top) , b(bottom) {normalize();}

Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and because that bottom initialize to value of 1 the rational for example: Rational(3) will be 3/1.

BUT !! I wonder how can we use a constructor with 1 value only if it supports 2 arguments ONLY ?

I know that in java if we have x number of argument that the constructor receive (consider no other constructor and x>0) we must transfer them all not 1 instead of 2...

Please help me solve this conflict...

thnx...


答:
There seems to be an opportunity for improvement in the GCC optimizer.

In the second version we get

```<code>        call    operator new(unsigned long)
        mov     QWORD PTR [r12], 0                     ; [r12] is 0
        mov     esi, 4
        mov     rdi, rax
        call    operator delete(void*, unsigned long)
        mov     edi, 4
        call    operator new(unsigned long)
        mov     rdi, QWORD PTR [r12]                   ; rdi=[r12] == 0 (duh)
        mov     DWORD PTR [rax], 1111
        mov     QWORD PTR [r12], rax
        test    rdi, rdi                               ; unnecesary test
        je      .L1                                    ; branch always taken
        mov     esi, 4                                 ; unreachable code
        call    operator delete(void*, unsigned long)  ;
.L1:
</code>```

clang 9 on the other hand, produces much smaller code for the second version because it is able to eliminate the first new/delete.

```<code>        push    rbx
        mov     rbx, rdi
        mov     qword ptr [rdi], 0
        mov     edi, 4
        call    operator new(unsigned long)
        mov     dword ptr [rax], 1111
        mov     qword ptr [rbx], rax
        mov     rax, rbx
        pop     rbx
        ret
</code>```

Title: unique_ptr: what is the effect of calling reset before assignment

Body:
There seems to be an opportunity for improvement in the GCC optimizer.

In the second version we get

        call    operator new(unsigned long)
        mov     QWORD PTR [r12], 0                     ; [r12] is 0
        mov     esi, 4
        mov     rdi, rax
        call    operator delete(void*, unsigned long)
        mov     edi, 4
        call    operator new(unsigned long)
        mov     rdi, QWORD PTR [r12]                   ; rdi=[r12] == 0 (duh)
        mov     DWORD PTR [rax], 1111
        mov     QWORD PTR [r12], rax
        test    rdi, rdi                               ; unnecesary test
        je      .L1                                    ; branch always taken
        mov     esi, 4                                 ; unreachable code
        call    operator delete(void*, unsigned long)  ;
.L1:

clang 9 on the other hand, produces much smaller code for the second version because it is able to eliminate the first new/delete.

        push    rbx
        mov     rbx, rdi
        mov     qword ptr [rdi], 0
        mov     edi, 4
        call    operator new(unsigned long)
        mov     dword ptr [rax], 1111
        mov     qword ptr [rbx], rax
        mov     rax, rbx
        pop     rbx
        ret


问:
Combine two datasets, based on POSIXct values
I am struggling with combining two datasets with each other.

Dataset1 is containing a "before time" and a "after time", and a "channel".

Dataset2 is containing just one "time" and a "channel" column as well.

I want to add an binary column (Yes/No) to Dataset1, with this logic:
If there is a row in Dataset2, where the channel == channel, and Time is within the "before" and "after" time, I want to have "YES". Else "NO".

Data1

```<code>ID   Channel   before_time   after_time
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00
</code>```

Data2

```<code>ID_B     Channel_B    Time_B
Hallo       A1        2019-09-02 20:23:00
Hi          B2        2019-09-02 20:05:00
Hoi         C1        2019-09-02 22:23:00
</code>```

Desired Output

```<code>ID   Channel   before_time   after_time                     Available
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00         Yes  # Channel == Channel, Time between before & after
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No  # Channel != Channel
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # Time is not between before & after
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # There is no matching data where channel is D1
</code>```

Desired Output 2 (comments Solutions)

Adding extra columns from the second data set (Data2).

```<code>ID   Channel   before_time   after_time                     Available   ID_B
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00          Yes        Hallo
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No         x
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x
</code>```

Reproducible example (the data):

```<code>ID <- c("1", "2", "3", "4")
channel <- c("A1", "B1", "C1", "D1)
#startdate <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:13:00", "2019-09-02 20:33:00", "2019-09-02 20:33:00"))
before_time <- as.POSIXct(c("2019-09-02 20:13:00", "2019-09-02 20:03:00", "2019-09-02 20:23:00", "2019-09-02 20:23:00"))
after_time  <- as.POSIXct(c("2019-09-02 20:33:00", "2019-09-02 20:23:00", "2019-09-02 20:43:00","2019-09-02 20:43:00"))
data1 <- data.frame(ID, channel,   before_time, after_time)
View(data1)

ID_B <- c("Hallo", "Hi", "Hoi")
channel_B <- c("A1", "B2", "C1")
Time_B <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:05:00", "2019-09-02 22:23:00"))
data2 <- data.frame(ID_B, channel_B, Time_B)
View(data2)
</code>```

答:
It may also make sense to look into sqldf, e.g.:

```<code>library(sqldf)

sqldf('SELECT t1.ID, t1.channel,
      t1.before_time, t1.after_time,
      CASE WHEN t2.ID_B IS NULL THEN "No" ELSE "Yes" END Available
      FROM data1 t1 LEFT JOIN data2 t2 ON t1.channel = t2.channel_B
      AND t2.Time_B BETWEEN t1.before_time AND t1.after_time')
</code>```

Output:

```<code>  ID channel         before_time          after_time Available
1  1      A1 2019-09-02 20:13:00 2019-09-02 20:33:00       Yes
2  2      B1 2019-09-02 20:03:00 2019-09-02 20:23:00        No
3  3      C1 2019-09-02 20:23:00 2019-09-02 20:43:00        No
4  4      D1 2019-09-02 20:23:00 2019-09-02 20:43:00        No
</code>```

Here is also one way of doing this in dplyr:

```<code>library(dplyr)

data1 %>%
  left_join(data2,
            by = c('channel' = 'channel_B')
            ) %>%
  mutate(
    Available = ifelse(
      !is.na(Time_B) & Time_B >= before_time & Time_B <= after_time, 'Yes', 'No')
    ) %>%
  select(-ends_with('_B'))
</code>```

Adding additional column:

```<code># sqldf

sqldf('SELECT t1.ID, t1.channel,
      t1.before_time, t1.after_time,
      CASE WHEN t2.ID_B IS NULL THEN "No" ELSE "Yes" END Available,
      CASE WHEN t2.ID_B IS NULL THEN "x" ELSE t2.ID_B END ID_B
      FROM data1 t1 LEFT JOIN data2 t2 ON t1.channel = t2.channel_B
      AND t2.Time_B BETWEEN t1.before_time AND t1.after_time')

# dplyr

data1 %>%
  left_join(data2,
            by = c('channel' = 'channel_B')
  ) %>%
  mutate(
    Available = ifelse(
      !is.na(Time_B) & Time_B >= before_time & Time_B <= after_time, 'Yes', 'No'),
    ID_B = ifelse(
      Available == 'Yes', as.character(ID_B), 'x')
  ) %>%
  select(-Time_B)
</code>```

Body:
I am struggling with combining two datasets with each other.

Dataset1 is containing a "before time" and a "after time", and a "channel".

Dataset2 is containing just one "time" and a "channel" column as well.

I want to add an binary column (Yes/No) to Dataset1, with this logic:
If there is a row in Dataset2, where the channel == channel, and Time is within the "before" and "after" time, I want to have "YES". Else "NO".

Data1

ID   Channel   before_time   after_time
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00

Data2

ID_B     Channel_B    Time_B
Hallo       A1        2019-09-02 20:23:00
Hi          B2        2019-09-02 20:05:00
Hoi         C1        2019-09-02 22:23:00

Desired Output

ID   Channel   before_time   after_time                     Available
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00         Yes  # Channel == Channel, Time between before & after
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No  # Channel != Channel
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # Time is not between before & after
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No  # There is no matching data where channel is D1

Desired Output 2 (comments Solutions)

Adding extra columns from the second data set (Data2).

ID   Channel   before_time   after_time                     Available   ID_B
1       A1  2019-09-02 20:13:00 2019-09-02 20:33:00          Yes        Hallo
2       B1  2019-09-02 20:03:00 2019-09-02 20:23:00          No         x
3       C1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x
4       D1  2019-09-02 20:23:00 2019-09-02 20:43:00          No         x

Reproducible example (the data):

ID <- c("1", "2", "3", "4")
channel <- c("A1", "B1", "C1", "D1)
#startdate <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:13:00", "2019-09-02 20:33:00", "2019-09-02 20:33:00"))
before_time <- as.POSIXct(c("2019-09-02 20:13:00", "2019-09-02 20:03:00", "2019-09-02 20:23:00", "2019-09-02 20:23:00"))
after_time  <- as.POSIXct(c("2019-09-02 20:33:00", "2019-09-02 20:23:00", "2019-09-02 20:43:00","2019-09-02 20:43:00"))
data1 <- data.frame(ID, channel,   before_time, after_time)
View(data1)

ID_B <- c("Hallo", "Hi", "Hoi")
channel_B <- c("A1", "B2", "C1")
Time_B <- as.POSIXct(c("2019-09-02 20:23:00", "2019-09-02 20:05:00", "2019-09-02 22:23:00"))
data2 <- data.frame(ID_B, channel_B, Time_B)
View(data2)

Body:
It may also make sense to look into sqldf, e.g.:

library(sqldf)

sqldf('SELECT t1.ID, t1.channel,
      t1.before_time, t1.after_time,
      CASE WHEN t2.ID_B IS NULL THEN "No" ELSE "Yes" END Available
      FROM data1 t1 LEFT JOIN data2 t2 ON t1.channel = t2.channel_B
      AND t2.Time_B BETWEEN t1.before_time AND t1.after_time')

Output:

  ID channel         before_time          after_time Available
1  1      A1 2019-09-02 20:13:00 2019-09-02 20:33:00       Yes
2  2      B1 2019-09-02 20:03:00 2019-09-02 20:23:00        No
3  3      C1 2019-09-02 20:23:00 2019-09-02 20:43:00        No
4  4      D1 2019-09-02 20:23:00 2019-09-02 20:43:00        No

Here is also one way of doing this in dplyr:

library(dplyr)

data1 %>%
  left_join(data2,
            by = c('channel' = 'channel_B')
            ) %>%
  mutate(
    Available = ifelse(
      !is.na(Time_B) & Time_B >= before_time & Time_B <= after_time, 'Yes', 'No')
    ) %>%
  select(-ends_with('_B'))

Adding additional column:

# sqldf

sqldf('SELECT t1.ID, t1.channel,
      t1.before_time, t1.after_time,
      CASE WHEN t2.ID_B IS NULL THEN "No" ELSE "Yes" END Available,
      CASE WHEN t2.ID_B IS NULL THEN "x" ELSE t2.ID_B END ID_B
      FROM data1 t1 LEFT JOIN data2 t2 ON t1.channel = t2.channel_B
      AND t2.Time_B BETWEEN t1.before_time AND t1.after_time')

# dplyr

data1 %>%
  left_join(data2,
            by = c('channel' = 'channel_B')
  ) %>%
  mutate(
    Available = ifelse(
      !is.na(Time_B) & Time_B >= before_time & Time_B <= after_time, 'Yes', 'No'),
    ID_B = ifelse(
      Available == 'Yes', as.character(ID_B), 'x')
  ) %>%
  select(-Time_B)


问:
RODBC - Query vector longer than 1
Using RODBC you can query a database like this:

```<code>library(RODBC)

dbHandle <- odbcDriverConnect('driver=SQL Server;server=SOME_SERVER;trusted_connection=true')
returnDf <- sqlQuery(dbHandle, query, stringsAsFactors = FALSE)
odbcClose(dbHandle)
</code>```

This assumes that the object query is a vector of length 1. What happens if it is not? So, if query contains two elements - is the database queried twice?

答:
Thanks @r2evans for pointing out the solution:

```<code>query <- c("select 1 as a", "select 2 as b")

dbhandle <- odbcDriverConnect('driver=SQL Server;server=SOME_SERVER;database=csn_pricing;trusted_connection=true')
df <- sqlQuery(dbhandle, query, stringsAsFactors = FALSE)
odbcClose(dbhandle)
</code>```

This results in

```<code>> df
  a
1 1
</code>```

Hence, only the first element is used.

Title: RODBC - Query vector longer than 1

Body:
Using RODBC you can query a database like this:

library(RODBC)

dbHandle <- odbcDriverConnect('driver=SQL Server;server=SOME_SERVER;trusted_connection=true')
returnDf <- sqlQuery(dbHandle, query, stringsAsFactors = FALSE)
odbcClose(dbHandle)

This assumes that the object query is a vector of length 1. What happens if it is not? So, if query contains two elements - is the database queried twice?

Body:
Thanks @r2evans for pointing out the solution:

query <- c("select 1 as a", "select 2 as b")

dbhandle <- odbcDriverConnect('driver=SQL Server;server=SOME_SERVER;database=csn_pricing;trusted_connection=true')
df <- sqlQuery(dbhandle, query, stringsAsFactors = FALSE)
odbcClose(dbhandle)

This results in

> df
  a
1 1

Hence, only the first element is used.


问:
Java persistancemanager fetch return less entities
In java fetching entities with query some time return less entities in some rare case. I am using javapersistance manager. Is it ideal to use it or need to switch to low level datastore fetch to solve it?

```<code>String query = "CUID == '" + cuidKey + "' && staffKey == '" + staffKey +"'&& StartTimeLong >= "+ startDate + " && StartTimeLong < " + endDate + " && status == 'confirmed'";

List<ResultJDO> tempResultList = jdoUtils.fetchEntitiesByQueryWithRangeOrder(ResultJDO.class, query, null, null, "StartTimeLong desc");
</code>```

The result returned 4 entities in rare case, but most time return all 5 entities.

jdoUtils is a PersistanceManager object.
Should I need to switch to low level datastore fetch for exact results.

答:
I have tried researching about the library you mentioned and for similar issues and found nothing that far. It's hard to know why this is happening or how to fix it with as little information.

On the other hand, the recommended way of programmatically interact with Google Cloud Platform products is through Google's client libraries since they are already tested and assured to work in almost all cases. Furthermore, their usage allows to open Github issue's if you find any problem so that the developers could address them. For the rare cases that you need some functionality not already covered you can open a feature request or directly call the API's.

In addition to Google's libraries there are two other options for Java that are under active development. One is Objectify and the other is Catatumbo.

I would suggest switching to Java Datastore libraries. You could find examples on how to interact with Datastore in link1 and link2. Also you could find community shared code samples in this programcreek page.

Body:
In java fetching entities with query some time return less entities in some rare case. I am using javapersistance manager. Is it ideal to use it or need to switch to low level datastore fetch to solve it?

String query = "CUID == '" + cuidKey + "' && staffKey == '" + staffKey +"'&& StartTimeLong >= "+ startDate + " && StartTimeLong < " + endDate + " && status == 'confirmed'";

List<ResultJDO> tempResultList = jdoUtils.fetchEntitiesByQueryWithRangeOrder(ResultJDO.class, query, null, null, "StartTimeLong desc");

The result returned 4 entities in rare case, but most time return all 5 entities.

jdoUtils is a PersistanceManager object.
Should I need to switch to low level datastore fetch for exact results.


问:
How to automatically install all dependendicies in cpan Bio
Hel lo, I'm actually trying to install a perl package called HMMCleaner

I ran for that the command:

```<code>cpan Bio::MUST::Apps::HmmCleaner
</code>```

but during the process I got several messages telling : Warning: prerequisite something 0 not found.

Here is a head of the output :

(/beegfs/data/me/myconda) me@pbil-deb:/beegfs/data/me/TOOLS/Bio-MUST-Apps-HmmCleaner-0.180750/bin$ cpan Test::Harness::Straps
Loading internal null logger. Install Log::Log4perl for logging messages
Reading '/beegfs/home/me/.cpan/Metadata'
  Database was generated on Fri, 14 Feb 2020 09:41:03 GMT
Running install for module 'Test::Harness::Straps'
Fetching with LWP:
http://www.cpan.org/authors/id/M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz
Fetching with LWP:
http://www.cpan.org/authors/id/M/MS/MSCHWERN/CHECKSUMS
Checksum for /beegfs/home/me/.cpan/sources/authors/id/M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz ok
Configuring M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz with Build.PL
Test::Harness::Straps is provided for backwards compatibility only.
No further development is planned.  No bugs will be fixed.

For customizable TAP parsing please use L<TAP::Parser> instead.

Created MYMETA.yml and MYMETA.json
Creating new 'Build' script for 'Test-Harness-Straps' version '0.30'
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  /beegfs/data/me/myconda/bin/perl Build.PL --installdirs site -- OK
Running Build for M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz
Building Test-Harness-Straps
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  ./Build -- OK
Running Build test
t/00compile.t ...... 1/5 # Testing Test::Harness::Straps 0.30 under Perl 5.026002 and Test::More 1.302073
t/00compile.t ...... ok
t/callback.t ....... ok
t/point-parse.t .... ok
t/point.t .......... ok
t/strap-analyze.t .. ok
t/strap.t .......... ok
All tests successful.
Files=6, Tests=425,  9 wallclock secs ( 0.12 usr  0.04 sys +  0.98 cusr  0.67 csys =  1.81 CPU)
Result: PASS
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  ./Build test -- OK
Running Build install
Building Test-Harness-Straps
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Assert.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Straps.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Results.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Point.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Iterator.pm
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Point.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Assert.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Results.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Iterator.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Straps.3
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  ./Build install  -- OK
(/beegfs/data/me/myconda) me@pbil-deb:/beegfs/data/me/TOOLS/Bio-MUST-Apps-HmmCleaner-0.180750/bin$ cpan Bio::MUST::Apps::HmmCleaner
Loading internal null logger. Install Log::Log4perl for logging messages
Reading '/beegfs/home/me/.cpan/Metadata'
  Database was generated on Fri, 14 Feb 2020 09:41:03 GMT
Running install for module 'Bio::MUST::Apps::HmmCleaner'
Checksum for /beegfs/home/me/.cpan/sources/authors/id/A/AR/ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz ok
Configuring A/AR/ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Warning: prerequisite Bio::FastParsers::Hmmer 0 not found.
Warning: prerequisite Bio::MUST::Core 0.180230 not found.
Warning: prerequisite Bio::MUST::Core::Ali 0 not found.
Warning: prerequisite Bio::MUST::Core::Constants 0 not found.
Warning: prerequisite Bio::MUST::Core::GeneticCode::Factory 0 not found.
Warning: prerequisite Bio::MUST::Core::IdList 0 not found.
Warning: prerequisite Bio::MUST::Core::Seq 0 not found.
Warning: prerequisite Bio::MUST::Core::SeqMask 0 not found.
Warning: prerequisite Bio::MUST::Core::Utils 0 not found.
Warning: prerequisite Bio::MUST::Drivers 0.180270 not found.
Warning: prerequisite Bio::MUST::Drivers::Hmmer::Model::Temporary 0 not found.
Warning: prerequisite IPC::System::Simple 0 not found.
Warning: prerequisite Smart::Comments 0 not found.
Warning: prerequisite aliased 0 not found.
Generating a Unix-style Makefile
Writing Makefile for Bio::MUST::Apps::HmmCleaner
Writing MYMETA.yml and MYMETA.json
  ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz
  /beegfs/data/me/myconda/bin/perl Makefile.PL INSTALLDIRS=site -- OK
Running make for A/AR/ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz
----     Unsatisfied dependencies detected during    ----
---- ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz ----
    Bio::FastParsers::Hmmer [requires]
    Bio::MUST::Core [requires]
    Bio::MUST::Core::Ali [requires]
    Bio::MUST::Core::Constants [requires]
    Bio::MUST::Core::GeneticCode::Factory [requires]
    Bio::MUST::Core::IdList [requires]
    Bio::MUST::Core::Seq [requires]
    Bio::MUST::Core::SeqMask [requires]
    Bio::MUST::Core::Utils [requires]
    Bio::MUST::Drivers [requires]
    Bio::MUST::Drivers::Hmmer::Model::Temporary [requires]
    IPC::System::Simple [requires]
    Smart::Comments [requires]
    aliased [requires]
Running install for module 'Bio::FastParsers::Hmmer'
Checksum for /beegfs/home/me/.cpan/sources/authors/id/D/DB/DBAURAIN/Bio-FastParsers-0.180470.tar.gz ok
Configuring D/DB/DBAURAIN/Bio-FastParsers-0.180470.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Warning: prerequisite Const::Fast 0 not found.
Warning: prerequisite Exporter::Easy 0 not found.
Warning: prerequisite Smart::Comments 0 not found.
Warning: prerequisite XML::Bare 0.53 not found.
Warning: prerequisite aliased 0 not found.
Generating a Unix-style Makefile
Writing Makefile for Bio::FastParsers
Writing MYMETA.yml and MYMETA.json
  DBAURAIN/Bio-FastParsers-0.180470.tar.gz
  /beegfs/data/me/myconda/bin/perl Makefile.PL INSTALLDIRS=site -- OK
Running make for D/DB/DBAURAIN/Bio-FastParsers-0.180470.tar.gz
---- Unsatisfied dependencies detected during ----
---- DBAURAIN/Bio-FastParsers-0.180470.tar.gz ----
    Const::Fast [requires]
    Exporter::Easy [requires]
    Smart::Comments [requires]
    XML::Bare [requires]
    aliased [requires]
Running install for module 'Const::Fast'
```

<p>So I wondered if there were a possibility to direclty allow cpan to install all the dependency needed? </p>

<p>I ask because I get the following error message when trying to execute a script using Bio::MUST::Apps::HMMCleaner.</p>

<pre class="lang-none prettyprint-override"><code>Can't locate Smart/Comments.pm in @INC (you may need to install the Smart::Comments module) (@INC contains:
    /beegfs/home/me/perl5/lib/perl5/x86_64-linux-thread-multi
    /beegfs/home/me/perl5/lib/perl5
    /beegfs/data/me/myconda/lib/site_perl/5.26.2/x86_64-linux-thread-multi
    /beegfs/data/me/myconda/lib/site_perl/5.26.2
    /beegfs/data/me/myconda/lib/5.26.2/x86_64-linux-thread-multi
    /beegfs/data/me/myconda/lib/5.26.2
    .
) at HmmCleaner.pl line 16. BEGIN failed--compilation aborted at HmmCleaner.pl line 16.
</code>```

(Line breaks added for readability.)

Some debugging information:

$ set | grep ^PERL
PERL5LIB=/beegfs/home/me/perl5/lib/perl5
PERL_LOCAL_LIB_ROOT=/beegfs/home/me/perl5
PERL_MB_OPT='--install_base "/beegfs/home/me/perl5"'
PERL_MM_OPT=INSTALL_BASE=/beegfs/home/me/perl5

$ echo 'o conf' | cpan | grep -P '^\s*(make|mbuild)'
Loading internal null logger. Install Log::Log4perl for logging messages
    make               [/usr/bin/X11/make]
    make_arg           []
    make_install_arg   []
    make_install_make_command [/usr/bin/X11/make]
    makepl_arg         [INSTALLDIRS=site]
    mbuild_arg         []
    mbuild_install_arg []
    mbuild_install_build_command [./Build]
    mbuildpl_arg       [--installdirs site]

$ which cpan
/beegfs/data/me/myconda/bin/cpan

$ head -n 1 "$( which cpan )"
#!/beegfs/data/me/myconda/bin/perl

$ which perl
/beegfs/data/me/myconda/bin/perl

$ cpan Smart::Comments
Loading internal null logger. Install Log::Log4perl for logging messages
Reading '/beegfs/home/me/.cpan/Metadata'
  Database was generated on Fri, 14 Feb 2020 09:41:03 GMT
Running install for module 'Smart::Comments'
Checksum for /beegfs/home/me/.cpan/sources/authors/id/N/NE/NEILB/Smart-Comments-1.06.tar.gz ok
Configuring N/NE/NEILB/Smart-Comments-1.06.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Generating a Unix-style Makefile
Writing Makefile for Smart::Comments
Writing MYMETA.yml and MYMETA.json
  NEILB/Smart-Comments-1.06.tar.gz
  /beegfs/data/me/myconda/bin/perl Makefile.PL INSTALLDIRS=site -- OK
Running make for N/NE/NEILB/Smart-Comments-1.06.tar.gz
cp lib/Smart/Comments.pm blib/lib/Smart/Comments.pm
Manifying 1 pod document
  NEILB/Smart-Comments-1.06.tar.gz
  /usr/bin/X11/make -- OK
Running make test
PERL_DL_NONLAZY=1 "/beegfs/data/me/myconda/bin/perl" "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/00.load.t ................. 1/1 # Testing Smart::Comments 1.06
t/00.load.t ................. ok
t/assert.t .................. ok
t/brackets.t ................ ok
t/c_like_for_loop.t ......... ok
t/check.t ................... ok
t/confirm.t ................. ok
t/ensure.t .................. ok
t/ENV_0.t ................... ok
t/ENV_1.t ................... ok
t/ENV_str.t ................. ok
t/insist.t .................. ok
t/labelled_perlish_loop.t ... ok
t/message.t ................. ok
t/perlish_for.t ............. ok
t/perlish_for_percentage.t .. ok
t/pod-coverage.t ............ skipped: Test::Pod::Coverage 1.04 required for testing POD coverage
t/pod.t ..................... skipped: Test::Pod 1.14 required for testing POD
t/require.t ................. ok
t/selective.t ............... ok
t/simple_perlish_for.t ...... ok
t/var.t ..................... ok
t/verify.t .................. ok
t/while.t ................... ok
t/while_num.t ............... ok
All tests successful.
Files=24, Tests=119, 19 wallclock secs ( 0.13 usr  0.08 sys +  2.93 cusr  1.45 csys =  4.59 CPU)
Result: PASS
  NEILB/Smart-Comments-1.06.tar.gz
  /usr/bin/X11/make test -- OK
Running make install
Manifying 1 pod document
Installing /beegfs/home/me/perl5/lib/perl5/Smart/Comments.pm
Installing /beegfs/home/me/perl5/man/man3/Smart::Comments.3
Appending installation info to /beegfs/home/me/perl5/lib/perl5/x86_64-linux-thread-multi/perllocal.pod
  NEILB/Smart-Comments-1.06.tar.gz
  /usr/bin/X11/make install  -- OK

$ perl -e'use Smart::Comments; print "ok\n"'
ok
```

Thank you for your help.

答:
That's exactly what it does.

For example, Warning: prerequisite Bio::FastParsers::Hmmer 0 not found. means an unsatisfied dependency for version 0 or higher of the Bio::FastParsers::Hmmer module was encountered. The Bio::MUST::Apps::HmmCleaner module is provided by the Bio-FastParsers distribution, and you can clearly see Bio-FastParsers being installed.

Technically, this is configurable.

$ echo 'o conf init prerequisites_policy' | cpan
...
The CPAN module can detect when a module which you are trying to build
depends on prerequisites. If this happens, it can build the
prerequisites for you automatically ('follow'), ask you for
confirmation ('ask'), or just ignore them ('ignore').  Choosing
'follow' also sets PERL_AUTOINSTALL and PERL_EXTUTILS_AUTOINSTALL for
"--defaultdeps" if not already set.

Please set your policy to one of the three values.

 <prerequisites_policy>
Policy on building prerequisites (follow, ask or ignore)? [follow] follow
...
```

But the default value is follow, and your output shows if it's following dependencies.

Body:
Hel lo, I'm actually trying to install a perl package called HMMCleaner

I ran for that the command:

cpan Bio::MUST::Apps::HmmCleaner

but during the process I got several messages telling : Warning: prerequisite something 0 not found.

Here is a head of the output :

(/beegfs/data/me/myconda) me@pbil-deb:/beegfs/data/me/TOOLS/Bio-MUST-Apps-HmmCleaner-0.180750/bin$ cpan Test::Harness::Straps
Loading internal null logger. Install Log::Log4perl for logging messages
Reading '/beegfs/home/me/.cpan/Metadata'
  Database was generated on Fri, 14 Feb 2020 09:41:03 GMT
Running install for module 'Test::Harness::Straps'
Fetching with LWP:
http://www.cpan.org/authors/id/M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz
Fetching with LWP:
http://www.cpan.org/authors/id/M/MS/MSCHWERN/CHECKSUMS
Checksum for /beegfs/home/me/.cpan/sources/authors/id/M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz ok
Configuring M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz with Build.PL
Test::Harness::Straps is provided for backwards compatibility only.
No further development is planned.  No bugs will be fixed.

For customizable TAP parsing please use L<TAP::Parser> instead.

Created MYMETA.yml and MYMETA.json
Creating new 'Build' script for 'Test-Harness-Straps' version '0.30'
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  /beegfs/data/me/myconda/bin/perl Build.PL --installdirs site -- OK
Running Build for M/MS/MSCHWERN/Test-Harness-Straps-0.30.tar.gz
Building Test-Harness-Straps
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  ./Build -- OK
Running Build test
t/00compile.t ...... 1/5 # Testing Test::Harness::Straps 0.30 under Perl 5.026002 and Test::More 1.302073
t/00compile.t ...... ok
t/callback.t ....... ok
t/point-parse.t .... ok
t/point.t .......... ok
t/strap-analyze.t .. ok
t/strap.t .......... ok
All tests successful.
Files=6, Tests=425,  9 wallclock secs ( 0.12 usr  0.04 sys +  0.98 cusr  0.67 csys =  1.81 CPU)
Result: PASS
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  ./Build test -- OK
Running Build install
Building Test-Harness-Straps
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Assert.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Straps.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Results.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Point.pm
Installing /beegfs/home/me/perl5/lib/perl5/Test/Harness/Iterator.pm
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Point.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Assert.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Results.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Iterator.3
Installing /beegfs/home/me/perl5/man/man3/Test::Harness::Straps.3
  MSCHWERN/Test-Harness-Straps-0.30.tar.gz
  ./Build install  -- OK
(/beegfs/data/me/myconda) me@pbil-deb:/beegfs/data/me/TOOLS/Bio-MUST-Apps-HmmCleaner-0.180750/bin$ cpan Bio::MUST::Apps::HmmCleaner
Loading internal null logger. Install Log::Log4perl for logging messages
Reading '/beegfs/home/me/.cpan/Metadata'
  Database was generated on Fri, 14 Feb 2020 09:41:03 GMT
Running install for module 'Bio::MUST::Apps::HmmCleaner'
Checksum for /beegfs/home/me/.cpan/sources/authors/id/A/AR/ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz ok
Configuring A/AR/ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Warning: prerequisite Bio::FastParsers::Hmmer 0 not found.
Warning: prerequisite Bio::MUST::Core 0.180230 not found.
Warning: prerequisite Bio::MUST::Core::Ali 0 not found.
Warning: prerequisite Bio::MUST::Core::Constants 0 not found.
Warning: prerequisite Bio::MUST::Core::GeneticCode::Factory 0 not found.
Warning: prerequisite Bio::MUST::Core::IdList 0 not found.
Warning: prerequisite Bio::MUST::Core::Seq 0 not found.
Warning: prerequisite Bio::MUST::Core::SeqMask 0 not found.
Warning: prerequisite Bio::MUST::Core::Utils 0 not found.
Warning: prerequisite Bio::MUST::Drivers 0.180270 not found.
Warning: prerequisite Bio::MUST::Drivers::Hmmer::Model::Temporary 0 not found.
Warning: prerequisite IPC::System::Simple 0 not found.
Warning: prerequisite Smart::Comments 0 not found.
Warning: prerequisite aliased 0 not found.
Generating a Unix-style Makefile
Writing Makefile for Bio::MUST::Apps::HmmCleaner
Writing MYMETA.yml and MYMETA.json
  ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz
  /beegfs/data/me/myconda/bin/perl Makefile.PL INSTALLDIRS=site -- OK
Running make for A/AR/ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz
----     Unsatisfied dependencies detected during    ----
---- ARNODF/Bio-MUST-Apps-HmmCleaner-0.180750.tar.gz ----
    Bio::FastParsers::Hmmer [requires]
    Bio::MUST::Core [requires]
    Bio::MUST::Core::Ali [requires]
    Bio::MUST::Core::Constants [requires]
    Bio::MUST::Core::GeneticCode::Factory [requires]
    Bio::MUST::Core::IdList [requires]
    Bio::MUST::Core::Seq [requires]
    Bio::MUST::Core::SeqMask [requires]
    Bio::MUST::Core::Utils [requires]
    Bio::MUST::Drivers [requires]
    Bio::MUST::Drivers::Hmmer::Model::Temporary [requires]
    IPC::System::Simple [requires]
    Smart::Comments [requires]
    aliased [requires]
Running install for module 'Bio::FastParsers::Hmmer'
Checksum for /beegfs/home/me/.cpan/sources/authors/id/D/DB/DBAURAIN/Bio-FastParsers-0.180470.tar.gz ok
Configuring D/DB/DBAURAIN/Bio-FastParsers-0.180470.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Warning: prerequisite Const::Fast 0 not found.
Warning: prerequisite Exporter::Easy 0 not found.
Warning: prerequisite Smart::Comments 0 not found.
Warning: prerequisite XML::Bare 0.53 not found.
Warning: prerequisite aliased 0 not found.
Generating a Unix-style Makefile
Writing Makefile for Bio::FastParsers
Writing MYMETA.yml and MYMETA.json
  DBAURAIN/Bio-FastParsers-0.180470.tar.gz
  /beegfs/data/me/myconda/bin/perl Makefile.PL INSTALLDIRS=site -- OK
Running make for D/DB/DBAURAIN/Bio-FastParsers-0.180470.tar.gz
---- Unsatisfied dependencies detected during ----
---- DBAURAIN/Bio-FastParsers-0.180470.tar.gz ----
    Const::Fast [requires]
    Exporter::Easy [requires]
    Smart::Comments [requires]
    XML::Bare [requires]
    aliased [requires]
Running install for module 'Const::Fast'

So I wondered if there were a possibility to direclty allow cpan to install all the dependency needed?

I ask because I get the following error message when trying to execute a script using Bio::MUST::Apps::HMMCleaner.

Can't locate Smart/Comments.pm in @INC (you may need to install the Smart::Comments module) (@INC contains:
    /beegfs/home/me/perl5/lib/perl5/x86_64-linux-thread-multi
    /beegfs/home/me/perl5/lib/perl5
    /beegfs/data/me/myconda/lib/site_perl/5.26.2/x86_64-linux-thread-multi
    /beegfs/data/me/myconda/lib/site_perl/5.26.2
    /beegfs/data/me/myconda/lib/5.26.2/x86_64-linux-thread-multi
    /beegfs/data/me/myconda/lib/5.26.2
    .
) at HmmCleaner.pl line 16. BEGIN failed--compilation aborted at HmmCleaner.pl line 16.

(Line breaks added for readability.)

Some debugging information:

$ set | grep ^PERL
PERL5LIB=/beegfs/home/me/perl5/lib/perl5
PERL_LOCAL_LIB_ROOT=/beegfs/home/me/perl5
PERL_MB_OPT='--install_base "/beegfs/home/me/perl5"'
PERL_MM_OPT=INSTALL_BASE=/beegfs/home/me/perl5

$ echo 'o conf' | cpan | grep -P '^\s*(make|mbuild)'
Loading internal null logger. Install Log::Log4perl for logging messages
    make               [/usr/bin/X11/make]
    make_arg           []
    make_install_arg   []
    make_install_make_command [/usr/bin/X11/make]
    makepl_arg         [INSTALLDIRS=site]
    mbuild_arg         []
    mbuild_install_arg []
    mbuild_install_build_command [./Build]
    mbuildpl_arg       [--installdirs site]

$ which cpan
/beegfs/data/me/myconda/bin/cpan

$ head -n 1 "$( which cpan )"
#!/beegfs/data/me/myconda/bin/perl

$ which perl
/beegfs/data/me/myconda/bin/perl

$ cpan Smart::Comments
Loading internal null logger. Install Log::Log4perl for logging messages
Reading '/beegfs/home/me/.cpan/Metadata'
  Database was generated on Fri, 14 Feb 2020 09:41:03 GMT
Running install for module 'Smart::Comments'
Checksum for /beegfs/home/me/.cpan/sources/authors/id/N/NE/NEILB/Smart-Comments-1.06.tar.gz ok
Configuring N/NE/NEILB/Smart-Comments-1.06.tar.gz with Makefile.PL
Checking if your kit is complete...
Looks good
Generating a Unix-style Makefile
Writing Makefile for Smart::Comments
Writing MYMETA.yml and MYMETA.json
  NEILB/Smart-Comments-1.06.tar.gz
  /beegfs/data/me/myconda/bin/perl Makefile.PL INSTALLDIRS=site -- OK
Running make for N/NE/NEILB/Smart-Comments-1.06.tar.gz
cp lib/Smart/Comments.pm blib/lib/Smart/Comments.pm
Manifying 1 pod document
  NEILB/Smart-Comments-1.06.tar.gz
  /usr/bin/X11/make -- OK
Running make test
PERL_DL_NONLAZY=1 "/beegfs/data/me/myconda/bin/perl" "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test::Harness::Switches; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/00.load.t ................. 1/1 # Testing Smart::Comments 1.06
t/00.load.t ................. ok
t/assert.t .................. ok
t/brackets.t ................ ok
t/c_like_for_loop.t ......... ok
t/check.t ................... ok
t/confirm.t ................. ok
t/ensure.t .................. ok
t/ENV_0.t ................... ok
t/ENV_1.t ................... ok
t/ENV_str.t ................. ok
t/insist.t .................. ok
t/labelled_perlish_loop.t ... ok
t/message.t ................. ok
t/perlish_for.t ............. ok
t/perlish_for_percentage.t .. ok
t/pod-coverage.t ............ skipped: Test::Pod::Coverage 1.04 required for testing POD coverage
t/pod.t ..................... skipped: Test::Pod 1.14 required for testing POD
t/require.t ................. ok
t/selective.t ............... ok
t/simple_perlish_for.t ...... ok
t/var.t ..................... ok
t/verify.t .................. ok
t/while.t ................... ok
t/while_num.t ............... ok
All tests successful.
Files=24, Tests=119, 19 wallclock secs ( 0.13 usr  0.08 sys +  2.93 cusr  1.45 csys =  4.59 CPU)
Result: PASS
  NEILB/Smart-Comments-1.06.tar.gz
  /usr/bin/X11/make test -- OK
Running make install
Manifying 1 pod document
Installing /beegfs/home/me/perl5/lib/perl5/Smart/Comments.pm
Installing /beegfs/home/me/perl5/man/man3/Smart::Comments.3
Appending installation info to /beegfs/home/me/perl5/lib/perl5/x86_64-linux-thread-multi/perllocal.pod
  NEILB/Smart-Comments-1.06.tar.gz
  /usr/bin/X11/make install  -- OK

$ perl -e'use Smart::Comments; print "ok\n"'
ok

Thank you for your help.

Body:
That's exactly what it does.

For example, Warning: prerequisite Bio::FastParsers::Hmmer 0 not found. means an unsatisfied dependency for version 0 or higher of the Bio::FastParsers::Hmmer module was encountered. The Bio::MUST::Apps::HmmCleaner module is provided by the Bio-FastParsers distribution, and you can clearly see Bio-FastParsers being installed.

Technically, this is configurable.

$ echo 'o conf init prerequisites_policy' | cpan
...
The CPAN module can detect when a module which you are trying to build
depends on prerequisites. If this happens, it can build the
prerequisites for you automatically ('follow'), ask you for
confirmation ('ask'), or just ignore them ('ignore').  Choosing
'follow' also sets PERL_AUTOINSTALL and PERL_EXTUTILS_AUTOINSTALL for
"--defaultdeps" if not already set.

Please set your policy to one of the three values.

 <prerequisites_policy>
Policy on building prerequisites (follow, ask or ignore)? [follow] follow
...

But the default value is follow, and your output shows if it's following dependencies.


问:
How to elevate to root within a python script?
I am trying to write a python script which will ask for root permissions. I have tried using elevate for python (which supposedly shows a dialog box asking for a root or "admin" password), but it gave a "No such file or directory" error when I ran it.

import os
from elevate import elevate

def is_root():
    return os.getuid() == 0

print("before ", is_root())
elevate()
print("after ", is_root())
```

Why does this happen? Are there any working alternatives that utilize the system GUI?

EDIT:
I am using Kubuntu 18 with Python 3.6, but I would like for it to work on Windows too.
FURTHER EDIT:
This is a question about dialog boxes (for basic/Windows users), not TUI.

答:
Since your working on Linux, graphical prompts are tried before sudo by default. You should therefore disable the graphical prompts by using the following command:

```<code>elevate(graphical=False)
</code>```

This Solution worked for me and is quite simple.

Source: https://pypi.org/project/elevate/

Body:
I am trying to write a python script which will ask for root permissions. I have tried using elevate for python (which supposedly shows a dialog box asking for a root or "admin" password), but it gave a "No such file or directory" error when I ran it.

import os
from elevate import elevate

def is_root():
    return os.getuid() == 0

print("before ", is_root())
elevate()
print("after ", is_root())

Why does this happen? Are there any working alternatives that utilize the system GUI?

EDIT:
I am using Kubuntu 18 with Python 3.6, but I would like for it to work on Windows too.
FURTHER EDIT:
This is a question about dialog boxes (for basic/Windows users), not TUI.

Body:
Since your working on Linux, graphical prompts are tried before sudo by default. You should therefore disable the graphical prompts by using the following command:

elevate(graphical=False)

This Solution worked for me and is quite simple.

Source: https://pypi.org/project/elevate/


问:
RSpec have_tag failing even when tag is present?
Currently doing the Ruby On Rails Tutorial by Michael Hartl, and am starting on test-driven development. The tutorial demands that tests be written to ensure that the right titles are present on our html.erb pages. There are three of these pages - home, contact and about. The tests look like so:

```<code>it "should have the right title" do
  get 'home'
  response.should have_tag("title",
                         "Ruby On Rails Sample Application | Home")
end
</code>```

My home.html.erb file looks like so:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Ruby On Rails Sample Application | Home</title>
</head>
<body>
<h1>Sample App Home</h1>
<p>This is the home page for the
<a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.</p>
</body>
</html>
</code>```

As you can see, the title tag is present and it's wrapping the correct text. However, when I run my test, I get this error message:

```<code>'PagesController GET 'home' should have the right title' FAILED
 Expected at least 1 element matching "title", found 0.
</code>```

Can anyone explain what is going wrong here? Thanks

答:
You should start by making sure the page renders correctly using

save_and_open_page

in your Rspec. Usually there's a problem with the rendering (eg maybe invalid xHTML?)

You'll also need to add the launchy gem to your project (eg gem 'launchy' in your Gemfile)

Body:
Currently doing the Ruby On Rails Tutorial by Michael Hartl, and am starting on test-driven development. The tutorial demands that tests be written to ensure that the right titles are present on our html.erb pages. There are three of these pages - home, contact and about. The tests look like so:

it "should have the right title" do
  get 'home'
  response.should have_tag("title",
                         "Ruby On Rails Sample Application | Home")
end

My home.html.erb file looks like so:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>Ruby On Rails Sample Application | Home</title>

Sample App Home

This is the home page for the
Ruby on Rails Tutorial
sample application.

As you can see, the title tag is present and it's wrapping the correct text. However, when I run my test, I get this error message:

'PagesController GET 'home' should have the right title' FAILED
 Expected at least 1 element matching "title", found 0.

Can anyone explain what is going wrong here? Thanks


问:
HTML Audio accessibility with Input Range
Minimal problem example: https://codepen.io/sidouglas/pen/LYPZaOG

When input range is focused, with either Chrome Vox or Mac's Voice over — every value of valuetext is read out continuously.

```<code><input
 ...
  v-bind:aria-valuemax="valueMax"
  v-bind:aria-valuenow="valueNow"
  v-bind:aria-valuetext="currentTime + ' of ' + totalDuration"
  ...
/>
</code>```

Contrast this to the very accessible https://plyr.io/#audio component - When focused it continues to update its aria values, yet only announce to the screen reader twice.

Does anyone know how plyr does it?

new Vue({
  el: '#range',
  data: {
    valueMax:100,
    duration:100,
    current:0,
    totalDuration:'1:40'
  },
  computed:{
    currentTime: function() {
      return this.convertTime(this.current);
    },
     valueNow() {
      return Math.round(this.current);
    },
  },
  methods: {
    convertTime(time) {
      const minutes = Math.floor(time / 60);
      const seconds = time - (minutes * 60);
      return `${minutes}:${seconds.toFixed(0).toString().padStart(2, '0')}`;
    },
  },
  mounted: function(){
   var self = this;
   setInterval(function(){
     self.current = Number(self.current) + 1;
     if(self.current >= self.valueMax){
        self.current = 0;
     }
    },2000);
  },
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.audio-file-player__slider-range{
  border:1px solid red;
  width:100%;
}

.audio-file-player__slider-range:focus {
  box-shadow: 0 0 10px blue;
}</code>```

  <input
         aria-label="Seek"
         aria-valuemin="0"
         autocomplete="off"
         class="audio-file-player__slider-range u-color-gray-111111 u-width-100"
         min="0"
         role="slider"
         step="1"
         type="range"
         v-bind:aria-valuemax="valueMax"
         v-bind:aria-valuenow="valueNow"
         v-bind:aria-valuetext="currentTime + ' of ' + totalDuration"
         v-bind:max="duration"
         v-model="current"
         />

current: {{ current }}

aria-valuenow: {{ valueNow }}

aria-valuetext: {{ currentTime + ' of ' + totalDuration }}

```

答:
For anyone who comes across this the easy solution is to override the value using aria-valuetext.

When the item is playing I would set the aria-valuetext to 'current: currentTime, remaining: remainingTime' when it first receives focus.

Then do not update the time while the item is playing (leave the aria-valuetext alone).

Then when play is paused / stopped change the aria-valuetext again to reflect the current time.

Finally I would update the current time on a throttle of say 200ms for when someone is seeking using the arrow keys.

You can decide whether to do this while playing or only when not playing as I am not sure which is the best solution in terms of information vs interruption.

I would lean towards not updating while playing as a user could always tab to the current time if you made that focusable.

By doing this you can ensure that it does not interfere with playing music or announce 200 different times.

plyr.io theory - it repeated for me too at first, then I changed my settings on announce speed. I believe the reason some people do and some people don't get announcements is the speed at which they update the current time (looks like 3-4 times a second) and I think that repeats so quickly that the Screen Reader decides not to confuse the user with it. Only a theory but my best guess as they aren't doing anything clever I can see.

Body:
Minimal problem example: https://codepen.io/sidouglas/pen/LYPZaOG

When input range is focused, with either Chrome Vox or Mac's Voice over — every value of valuetext is read out continuously.

<input
 ...
  v-bind:aria-valuemax="valueMax"
  v-bind:aria-valuenow="valueNow"
  v-bind:aria-valuetext="currentTime + ' of ' + totalDuration"
  ...
/>

Contrast this to the very accessible https://plyr.io/#audio component - When focused it continues to update its aria values, yet only announce to the screen reader twice.

Does anyone know how plyr does it?

new Vue({
  el: '#range',
  data: {
    valueMax:100,
    duration:100,
    current:0,
    totalDuration:'1:40'
  },
  computed:{
    currentTime: function() {
      return this.convertTime(this.current);
    },
     valueNow() {
      return Math.round(this.current);
    },
  },
  methods: {
    convertTime(time) {
      const minutes = Math.floor(time / 60);
      const seconds = time - (minutes * 60);
      return `${minutes}:${seconds.toFixed(0).toString().padStart(2, '0')}`;
    },
  },
  mounted: function(){
   var self = this;
   setInterval(function(){
     self.current = Number(self.current) + 1;
     if(self.current >= self.valueMax){
        self.current = 0;
     }
    },2000);
  },
});

.audio-file-player__slider-range{
  border:1px solid red;
  width:100%;
}

.audio-file-player__slider-range:focus {
  box-shadow: 0 0 10px blue;
}

  <input
         aria-label="Seek"
         aria-valuemin="0"
         autocomplete="off"
         class="audio-file-player__slider-range u-color-gray-111111 u-width-100"
         min="0"
         role="slider"
         step="1"
         type="range"
         v-bind:aria-valuemax="valueMax"
         v-bind:aria-valuenow="valueNow"
         v-bind:aria-valuetext="currentTime + ' of ' + totalDuration"
         v-bind:max="duration"
         v-model="current"
         />

current: {{ current }}

aria-valuenow: {{ valueNow }}

aria-valuetext: {{ currentTime + ' of ' + totalDuration }}


问:
Static Parsing: Tell if Two Javascript Functions are the Same
I am looking for a way, using static analysis of two JavaScript functions, to tell if they are the same. Let me define multiple definitions of "the same".

Level 1: The functions are the same except for possible different whitespace, e.g. TABS, CR, LF and SPACES.

Level 2 The functions may have different whitespace like Level 1, but also may have different variable names.

Level 3 ???

For level one, I think I could just remove all (non-literal, which may be tough) whitespace from each string containing the two JS function definitions, and then compare the strings.

For level two, I think I would need to use something like SpiderMonkey's parser to generate a two parse trees, and then write a comparer which walks the trees and allows variables to have different names.

[Edit] Williham, makes a good point below. I do mean identical. Now, I'm looking for some practical strategies, particularly with regards to using parse trees.

答:
Your approach for level 1 seems reasonable.

For level 2, how about do some rudimentary variable substitution on each function and then do approch for level 1? Start at the beginning and for each variable declaration you encounter rename them to var1, var2, ... varX.

This does not help if the functions declare variables in different orders... var i and var j may be used the same way in both functions but are declared in different orders. Then you are probably left doing a comparison of parse trees like you mention.


问:
Why is $_POST[''] not working with <form>
This is a Rock Paper Scissors game and I am just starting on it, but it will not display the $_POST['keuzen'].

So I don't get why this is not working. Tried many things but can't find a good solution.

```<code><?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>RockPaperScissor</title>
    </head>
    <body>
        <form action="RockPaperScissor.php" method="post">
            <input type="image" src="steen.jpg" alt="steen" name="keuzen" value="steen" title="Steen">
            <input type="image" src="papier.jpg" alt="papier" name="keuzen" value="papier" title="Papier">
            <input type="image" src="schaar.jpg" alt="schaar" name="keuzen" value="schaar" title="Schaar">
        </form>
        <?php
            if (isset($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '<br>';
                echo 'De computer koos ' . $computer . '<br';

                if ($keuzen == $computer) {
                    echo 'Resultaat : Draw ';
                }
            }
        ?>
    </body>
</html>
</code>```

答:
The purpose of <input type="image" name="keuzen"> is to provide a server side image map. It submits the form as a side effect, but the purpose is to select coordinates on the image.

When you click it, x and y coordinates will be sent to the server.

If I remember correctly, you'll get something like keuzen.y=123&keuzen.x=456 which PHP will use to populate $_POST['keuzen_x'] and $_POST['keuzen_y'] but not $_POST['keuzen'].

If you do a var_dump($_POST) you can see the data structure you actually get.

If you want to just have regular submit buttons which look like images, then use regular submit buttons containing images:

```<code><button name="keuzen" value="steen"><img src="steen.jpg" alt="steen"></button>
</code>```

You can style away the borders and background of the button element with CSS if you like.

Body:
This is a Rock Paper Scissors game and I am just starting on it, but it will not display the $_POST['keuzen'].

So I don't get why this is not working. Tried many things but can't find a good solution.

<?php session_start(); ?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>RockPaperScissor</title>

        <form action="RockPaperScissor.php" method="post">
            <input type="image" src="steen.jpg" alt="steen" name="keuzen" value="steen" title="Steen">
            <input type="image" src="papier.jpg" alt="papier" name="keuzen" value="papier" title="Papier">
            <input type="image" src="schaar.jpg" alt="schaar" name="keuzen" value="schaar" title="Schaar">
        </form>
        <?php
            if (isset($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '
';
                echo 'De computer koos ' . $computer . '

Body:
The purpose of <input type="image" name="keuzen"> is to provide a server side image map. It submits the form as a side effect, but the purpose is to select coordinates on the image.

When you click it, x and y coordinates will be sent to the server.

If I remember correctly, you'll get something like keuzen.y=123&keuzen.x=456 which PHP will use to populate $_POST['keuzen_x'] and $_POST['keuzen_y'] but not $_POST['keuzen'].

If you do a var_dump($_POST) you can see the data structure you actually get.

If you want to just have regular submit buttons which look like images, then use regular submit buttons containing images:

<button name="keuzen" value="steen"><img src="steen.jpg" alt="steen"></button>

You can style away the borders and background of the button element with CSS if you like.


问:
Function from class works when called directly, but returns error when called from a different class with an instance of original
I wrote a little code for a class called Game, which uses another class called Board.

One of the functions in Board is check_horizontal_win(self, row, original_col).

When I use it directly on a Board object it works fine. When I try to use it with the Game's board (Game.get_board().check_horizontal_win)) I get:

```<code>AttributeError: 'function' object has no attribute 'check_horizontal_win'
</code>```

I've checked and I don't seem to be using anything private or illegal.  And the values in the two cases were the same.

Here's the first class, Game.  The last line of code in the "main" doesn't work:

```<code>from board import *

PLAYER_A = 1
PLAYER_B = 2
INITIAL_ROW = 0
INITIAL_COLUMN = 0
FINAL_ROW = 5
FINAL_COLUMN = 6
ILLEGAL_LOCATION_MSG = "Illegal location."
ILLEGAL_MOVE_MSG = "Illegal move."
IS_GAME_WON = False
WINNER = None

class Game:

    def __init__(self):
        self.__current_player = PLAYER_A
        self.__board = Board()

    def make_move(self, column):
        """  Makes move and updates board and current player, if column is a valid choice and game is ongoing.  """
        if self.__board.is_col_illegal(column):
            raise Exception(ILLEGAL_MOVE_MSG)
        self.do_move(column)

    def do_move(self, column):
        """  Actual implementation of the move.  """
        if self.__current_player == PLAYER_A:
            self.__board.update_board(column, PLAYER_A)
            self.__current_player = PLAYER_B
        elif self.__current_player == PLAYER_B:
            self.__board.update_board(column, PLAYER_B)
            self.__current_player = PLAYER_A

    def get_winner(self):
       pass

    def get_player_at(self, row, col):
        """  Returns the player whose disc is at the given position in the game.  """
        if row < INITIAL_ROW or row > FINAL_ROW or col < INITIAL_COLUMN or col > FINAL_COLUMN:
            raise Exception(ILLEGAL_LOCATION_MSG)

        return self.__board.get_board()[row][col]

    def get_current_player(self):
        """  Returns current_player.  """
        return self.__current_player

    def get_board(self):
        """  Returns board."""
        return self.__board

if __name__ == '__main__':

    game = Game()
    game.make_move(0)
    game.make_move(1)
    game.make_move(0)
    game.make_move(2)
    game.get_board.check_horizontal_win(0, 1)
</code>```

And here's the Board class.  In this case, the function in the main does work:

```<code>NUM_ROWS = 6
NUM_COLUMNS = 7
INITIAL_VALUE = None
WIN_COUNT = 4

class Board:

    def __init__(self):
        self.__playboard = []
        self.__available_rows_list = NUM_COLUMNS*[NUM_ROWS-1]
        initial_row = NUM_COLUMNS * [INITIAL_VALUE]
        for i in range(NUM_ROWS):
            self.__playboard.append(initial_row.copy())

    def get_playboard(self):
        """  Returns board.  """
        return self.__playboard

    def update_board(self, col, val):
        """  Updates current status of board.  """
        row = self.__available_rows_list[col]
        self.__playboard[row][col] = val
        self.__update_row(col)

    def __update_row(self, col):
        """  Updates available_row_list.  """
        if self.__available_rows_list[col] > 0:
            self.__available_rows_list[col] = self.__available_rows_list[col] - 1
        else:
            self.__available_rows_list[col] = None

    def __is_col_available(self, col):
        """  Checks if given col has empty spaces left on the playboard.  """
        if self.__available_rows_list[col] == None:
            return False
        return True

    def __is_col_exist(self, col):
        """  Checks if given column is within the capacity of the playboard.  """
        if col < 0 or col >= NUM_COLUMNS:
            return False
        return True

    def is_col_illegal(self, col):
        """  Checks if given column is an illegal option.  """
        if not self.__is_col_available(col) or not self.__is_col_exist(col):
            return True
        return False

    def print_playboard(self):
        for row in self.__playboard:
            print(row)

    def check_horizontal_win(self, row, original_col):
        """  Checks if player has won in the horizontal direction.  """

        # check if row and col were valid?  Or do it somewhere else?
        count = 1
        player = self.__playboard[row][original_col]
        col = original_col
        while self.__is_col_exist(col) and self.__playboard[row][col] == player:
            count = count + 1
            if count == WIN_COUNT:
                return True
            col = col + 1
        # Then: undergo same process, this time in the opposite direction (the left).
        col = original_col - 1
        while self.__is_col_exist(col) and self.__playboard[row][col] == player:
            count = count + 1
            if count == WIN_COUNT:
                return True
            col = col - 1

if __name__ == '__main__':

    board = Board()
    board.update_board(0,1)
    board.update_board(0, 1)
    board.update_board(1, 2)
    board.update_board(2, 2)
    board.print_playboard()
    board.check_horizontal_win(0, 1)
</code>```

答:
You wrote:

```<code>game.get_board.check_horizontal_win(0, 1)
</code>```

Make that:

```<code>game.get_board().check_horizontal_win(0, 1)
</code>```

Body:
I wrote a little code for a class called Game, which uses another class called Board.

One of the functions in Board is check_horizontal_win(self, row, original_col).

When I use it directly on a Board object it works fine. When I try to use it with the Game's board (Game.get_board().check_horizontal_win)) I get:

AttributeError: 'function' object has no attribute 'check_horizontal_win'

I've checked and I don't seem to be using anything private or illegal.  And the values in the two cases were the same.

Here's the first class, Game.  The last line of code in the "main" doesn't work:

from board import *

PLAYER_A = 1
PLAYER_B = 2
INITIAL_ROW = 0
INITIAL_COLUMN = 0
FINAL_ROW = 5
FINAL_COLUMN = 6
ILLEGAL_LOCATION_MSG = "Illegal location."
ILLEGAL_MOVE_MSG = "Illegal move."
IS_GAME_WON = False
WINNER = None

class Game:

    def __init__(self):
        self.__current_player = PLAYER_A
        self.__board = Board()

    def make_move(self, column):
        """  Makes move and updates board and current player, if column is a valid choice and game is ongoing.  """
        if self.__board.is_col_illegal(column):
            raise Exception(ILLEGAL_MOVE_MSG)
        self.do_move(column)

    def do_move(self, column):
        """  Actual implementation of the move.  """
        if self.__current_player == PLAYER_A:
            self.__board.update_board(column, PLAYER_A)
            self.__current_player = PLAYER_B
        elif self.__current_player == PLAYER_B:
            self.__board.update_board(column, PLAYER_B)
            self.__current_player = PLAYER_A

    def get_winner(self):
       pass

    def get_player_at(self, row, col):
        """  Returns the player whose disc is at the given position in the game.  """
        if row < INITIAL_ROW or row > FINAL_ROW or col < INITIAL_COLUMN or col > FINAL_COLUMN:
            raise Exception(ILLEGAL_LOCATION_MSG)

        return self.__board.get_board()[row][col]

    def get_current_player(self):
        """  Returns current_player.  """
        return self.__current_player

    def get_board(self):
        """  Returns board."""
        return self.__board

if __name__ == '__main__':

    game = Game()
    game.make_move(0)
    game.make_move(1)
    game.make_move(0)
    game.make_move(2)
    game.get_board.check_horizontal_win(0, 1)

And here's the Board class.  In this case, the function in the main does work:

NUM_ROWS = 6
NUM_COLUMNS = 7
INITIAL_VALUE = None
WIN_COUNT = 4

class Board:

    def __init__(self):
        self.__playboard = []
        self.__available_rows_list = NUM_COLUMNS*[NUM_ROWS-1]
        initial_row = NUM_COLUMNS * [INITIAL_VALUE]
        for i in range(NUM_ROWS):
            self.__playboard.append(initial_row.copy())

    def get_playboard(self):
        """  Returns board.  """
        return self.__playboard

    def update_board(self, col, val):
        """  Updates current status of board.  """
        row = self.__available_rows_list[col]
        self.__playboard[row][col] = val
        self.__update_row(col)

    def __update_row(self, col):
        """  Updates available_row_list.  """
        if self.__available_rows_list[col] > 0:
            self.__available_rows_list[col] = self.__available_rows_list[col] - 1
        else:
            self.__available_rows_list[col] = None

    def __is_col_available(self, col):
        """  Checks if given col has empty spaces left on the playboard.  """
        if self.__available_rows_list[col] == None:
            return False
        return True

    def __is_col_exist(self, col):
        """  Checks if given column is within the capacity of the playboard.  """
        if col < 0 or col >= NUM_COLUMNS:
            return False
        return True

    def is_col_illegal(self, col):
        """  Checks if given column is an illegal option.  """
        if not self.__is_col_available(col) or not self.__is_col_exist(col):
            return True
        return False

    def print_playboard(self):
        for row in self.__playboard:
            print(row)

    def check_horizontal_win(self, row, original_col):
        """  Checks if player has won in the horizontal direction.  """

        # check if row and col were valid?  Or do it somewhere else?
        count = 1
        player = self.__playboard[row][original_col]
        col = original_col
        while self.__is_col_exist(col) and self.__playboard[row][col] == player:
            count = count + 1
            if count == WIN_COUNT:
                return True
            col = col + 1
        # Then: undergo same process, this time in the opposite direction (the left).
        col = original_col - 1
        while self.__is_col_exist(col) and self.__playboard[row][col] == player:
            count = count + 1
            if count == WIN_COUNT:
                return True
            col = col - 1

if __name__ == '__main__':

    board = Board()
    board.update_board(0,1)
    board.update_board(0, 1)
    board.update_board(1, 2)
    board.update_board(2, 2)
    board.print_playboard()
    board.check_horizontal_win(0, 1)

Body:
You wrote:

game.get_board.check_horizontal_win(0, 1)

Make that:

game.get_board().check_horizontal_win(0, 1)