问:
Java jsp sends servlet null variables
So I have this piece of code in my .jsp file

```<code><table border="0" style="width:400px;">
    <form class="Credentials" action="SellerServlet" method="post">
        <tr style="height: 40px">method
            #User name
            <td style="width: 20%; text-align: right;">
                <label for="Name"><b>Name:</b></label>
            </td>
            <td>
                <input type="text" id="Name" name="Name" required>
            </td>
        </tr>

        #Surname
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;" >
                <label for="surname"><b>Surname:</b></label>
            </td>
            <td>
                <input type="text" id="Surname" name="Surname" required>
            </td>
        </tr>

        #Username
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;">
                <label for="username"><b>Username:</b></label>
            </td>
            <td>
                <input  type="text" id="username" name="user" required>
            </td>
        </tr>
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;" >
                <label for="password"><b>Password:</b></label>
            </td>
            <td>
                <input type="password" id="password" name="pass" required>
            </td>
        </tr>

        #User Type
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;" >
                <label for="type"><b>Type:</b></label>
            </td>
            <td>
                <input type="text" id="type" placeholder="Client" readonly>
            </td>
        </tr>

        #User Program
        <tr style="height: 40px">
            <td style="width: 20%; text-align: right;"  >
                <label for="program"><b>Program:</b></label>
            </td>
            <td>
                <select style="width: 150px" id="program" name="program" >
                    <option value="" selected disabled hidden>Επιλέξτε πρόγραμμα</option>
                    <option>asdfs</option>
                    <option>asdfas</option>
                    <option>asfdas</option>
                </select>
            </td>
        </tr>

        #Submit Button
        <tr style="height: 100px;">
            <td colspan="2" style="width: 50%">
                <center>
                    <button type="submit" name="Register" >Register</button>
                </center>
            </td>
        </tr>
    </form>
</table>
</code>```

And my servlet code is

```<code>@WebServlet(name = "SellerServlet" , urlPatterns = {"/SellerServlet"})
public class SellerServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String registerButton = request.getParameter("register");
        if(registerButton!=null){
            //request.getRequestDispatcher("/index.jsp").forward(request, response);
            String Username=request.getParameter("user");
            String Password=request.getParameter("pass");
            System.out.println(Username+Password);
            Seller CreateClient= new Seller();
            CreateClient.CreateClientAccount(Username,Password);
        }
    }
}
</code>```

What the servlet here is supposed to do is pass the 2 values (user and pass) to an object of the class Seller to later do something with them, I didn't include that following part because it works it just gets the value of null from both and I have broken my head for 2 hours now trying to figure out why

In case needed: Using java 14 and tomcat 9

答:
in the jsp code you have

```<code><input type="password" id="password" name="pwd" required>
</code>```

so in the servlet code you have to respect the name in the tag, which is pwd

```<code>String Password=request.getParameter("pwd");
</code>```

and for the button Register, you have to respect the cases. in jsp the name is "Register" with a capital R

```<code>String registerButton = request.getParameter("Register");
</code>```

also try to add to a value to the button register

```<code><button type="submit" name="Register" value="clicked">Register</button>
</code>```

Title: Java jsp sends servlet null variables

Body:
So I have this piece of code in my .jsp file

    <form class="Credentials" action="SellerServlet" method="post">

method
            #User name

                Name:

                <input type="text" id="Name" name="Name" required>

        #Surname

                Surname:

                <input type="text" id="Surname" name="Surname" required>

        #Username

                Username:

                <input  type="text" id="username" name="user" required>

                Password:

                <input type="password" id="password" name="pass" required>

        #User Type

                Type:

                <input type="text" id="type" placeholder="Client" readonly>

        #User Program

                Program:

                <select style="width: 150px" id="program" name="program" >
                    <option value="" selected disabled hidden>Επιλέξτε πρόγραμμα</option>
                    <option>asdfs</option>
                    <option>asdfas</option>
                    <option>asfdas</option>
                </select>

        #Submit Button

                    <button type="submit" name="Register" >Register</button>

    </form>

And my servlet code is

@WebServlet(name = "SellerServlet" , urlPatterns = {"/SellerServlet"})
public class SellerServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String registerButton = request.getParameter("register");
        if(registerButton!=null){
            //request.getRequestDispatcher("/index.jsp").forward(request, response);
            String Username=request.getParameter("user");
            String Password=request.getParameter("pass");
            System.out.println(Username+Password);
            Seller CreateClient= new Seller();
            CreateClient.CreateClientAccount(Username,Password);
        }
    }
}

What the servlet here is supposed to do is pass the 2 values (user and pass) to an object of the class Seller to later do something with them, I didn't include that following part because it works it just gets the value of null from both and I have broken my head for 2 hours now trying to figure out why

In case needed: Using java 14 and tomcat 9

Body:
in the jsp code you have

<input type="password" id="password" name="pwd" required>

so in the servlet code you have to respect the name in the tag, which is pwd

String Password=request.getParameter("pwd");

and for the button Register, you have to respect the cases. in jsp the name is "Register" with a capital R

String registerButton = request.getParameter("Register");

also try to add to a value to the button register

<button type="submit" name="Register" value="clicked">Register</button>


来源: stackexchange

问:
add mvc3 Unobtrusive validation Min/max validators
I'm trying to implement client validation for my custom type, however i'm not sure how to do it for min/max validators.

model:

```<code>[MultilanguagePropertyRequired(ErrorMessageResourceName = "fld_Description_val_Required", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]
[MultilanguagePropertyStringLength(1000, MinimumLength = 150, ErrorMessageResourceName = "fld_Description_val_MinLength_lbl", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]
[Display(Name = "fld_Description_lbl", ResourceType = typeof(Resources.Service.Controllers.Firm))]
public MultilanguageProperty<string> Description
{
    get
    {
        return this.GetMultilanguageProperty("Description", string.Empty, this);
    }

    set
    {
        this.SetMultilanguageProperty("Description", value);
    }
}
</code>```

this is my custom string length attribute that extends "StringLegth":

```<code>[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class MultilanguagePropertyStringLengthAttribute : StringLengthAttribute, IClientValidatable
{
    public MultilanguagePropertyStringLengthAttribute(int length) : base(length)
    {
    }

    public override bool IsValid(object value)
    {
        string strValue = (string)(value as MultilanguageProperty<string>).Value;

        return base.IsValid(strValue);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule() { ValidationType = "multilanguagestringlength", ErrorMessage = this.ErrorMessageString };
    }
}
</code>```

then on my view I have this:
..

```<code><script type="text/javascript">
    (function ($) {
        $.validator.unobtrusive.adapters.addBool("multilanguagerequired", "required");
        $.validator.unobtrusive.adapters.addMinMax("multilanguagestringlength", "minlength", "maxlength");
    } (jQuery));
</script>
</code>```

..

which doesn't work. am i missing something here?
thanks

答:
I too am having the same problem.  You are missing ValidationParameters in your GetClientValidationRules:

```<code>    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
                     {
                         ErrorMessage = this.ErrorMessage,
                         ValidationType = "dayrange"
                     };
    rule.ValidationParameters.Add("min", _minimumDays);
    rule.ValidationParameters.Add("max", _maximumDays);
    yield return rule;
}
</code>```

I still having problems with the wiring between the jQuery.validator and jQuery.validator.unobtrusive.adapters but here's the code.  Hope it helps:

```<code>    $(function () {
      jQuery.validator.addMethod('dayRange', function (value, element, param) {
         if (!value) return false;
         var valueDateParts = value.split(param.seperator);
         var minDate = new Date();
         var maxDate = new Date();
         var now = new Date();
         var dateValue = new Date(valueDateParts[2],
                            (valueDateParts[1] - 1),
                             valueDateParts[0],
                             now.getHours(),
                             now.getMinutes(),
                             (now.getSeconds()+5));

         minDate.setDate(minDate.getDate() - parseInt(param.min));
         maxDate.setDate(maxDate.getDate() + parseInt(param.max));

         return dateValue >= minDate && dateValue <= maxDate;
    });

    jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', 'minlength', 'maxlength', 'dayrange');

  }(jQuery));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to implement client validation for my custom type, however i'm not sure how to do it for min/max validators.

model:

[MultilanguagePropertyRequired(ErrorMessageResourceName = "fld_Description_val_Required", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]
[MultilanguagePropertyStringLength(1000, MinimumLength = 150, ErrorMessageResourceName = "fld_Description_val_MinLength_lbl", ErrorMessageResourceType = typeof(Resources.Service.Controllers.Firm))]
[Display(Name = "fld_Description_lbl", ResourceType = typeof(Resources.Service.Controllers.Firm))]
public MultilanguageProperty<string> Description
{
    get
    {
        return this.GetMultilanguageProperty("Description", string.Empty, this);
    }

    set
    {
        this.SetMultilanguageProperty("Description", value);
    }
}

this is my custom string length attribute that extends "StringLegth":

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)]
public class MultilanguagePropertyStringLengthAttribute : StringLengthAttribute, IClientValidatable
{
    public MultilanguagePropertyStringLengthAttribute(int length) : base(length)
    {
    }

    public override bool IsValid(object value)
    {
        string strValue = (string)(value as MultilanguageProperty<string>).Value;

        return base.IsValid(strValue);
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule() { ValidationType = "multilanguagestringlength", ErrorMessage = this.ErrorMessageString };
    }
}

then on my view I have this:
..

..

which doesn't work. am i missing something here?
thanks

Body:
I too am having the same problem.  You are missing ValidationParameters in your GetClientValidationRules:

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
    var rule = new ModelClientValidationRule
                     {
                         ErrorMessage = this.ErrorMessage,
                         ValidationType = "dayrange"
                     };
    rule.ValidationParameters.Add("min", _minimumDays);
    rule.ValidationParameters.Add("max", _maximumDays);
    yield return rule;
}

I still having problems with the wiring between the jQuery.validator and jQuery.validator.unobtrusive.adapters but here's the code.  Hope it helps:

    $(function () {
      jQuery.validator.addMethod('dayRange', function (value, element, param) {
         if (!value) return false;
         var valueDateParts = value.split(param.seperator);
         var minDate = new Date();
         var maxDate = new Date();
         var now = new Date();
         var dateValue = new Date(valueDateParts[2],
                            (valueDateParts[1] - 1),
                             valueDateParts[0],
                             now.getHours(),
                             now.getMinutes(),
                             (now.getSeconds()+5));

         minDate.setDate(minDate.getDate() - parseInt(param.min));
         maxDate.setDate(maxDate.getDate() + parseInt(param.max));

         return dateValue >= minDate && dateValue <= maxDate;
    });

    jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', 'minlength', 'maxlength', 'dayrange');

  }(jQuery));

ContentLicense: CC BY-SA 3.0


问:
How to execute logic on Optional if not present?
I want to replace the following code using java8 Optional:

```<code>public Obj getObjectFromDB() {
    Obj obj = dao.find();
    if (obj != null) {
        obj.setAvailable(true);
    } else {
        logger.fatal("Object not available");
    }

    return obj;
}
</code>```

The following pseudocode does not work as there is no orElseRun method, but anyways it illustrates my purpose:

```<code>public Optional<Obj> getObjectFromDB() {
    Optional<Obj> obj = dao.find();
    return obj.ifPresent(obj.setAvailable(true)).orElseRun(logger.fatal("Object not available"));
}
</code>```

答:
ifPresentOrElse can handle cases of nullpointers as well. Easy approach.

```<code>   Optional.ofNullable(null)
            .ifPresentOrElse(name -> System.out.println("my name is "+ name),
                    ()->System.out.println("no name or was a null pointer"));
</code>```

Body:
I want to replace the following code using java8 Optional:

public Obj getObjectFromDB() {
    Obj obj = dao.find();
    if (obj != null) {
        obj.setAvailable(true);
    } else {
        logger.fatal("Object not available");
    }

    return obj;
}

The following pseudocode does not work as there is no orElseRun method, but anyways it illustrates my purpose:

public Optional<Obj> getObjectFromDB() {
    Optional<Obj> obj = dao.find();
    return obj.ifPresent(obj.setAvailable(true)).orElseRun(logger.fatal("Object not available"));
}

Body:
ifPresentOrElse can handle cases of nullpointers as well. Easy approach.

   Optional.ofNullable(null)
            .ifPresentOrElse(name -> System.out.println("my name is "+ name),
                    ()->System.out.println("no name or was a null pointer"));

ContentLicense: CC BY-SA 4.0


问:
How to plot selected lines from a hdf5 file format in matplotlib
My subcode in matplotlib  is

```<code>from matplotlib import pyplot as plt

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'
        ax.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax.legend()
</code>```

It plots all data while I want to restrict to nbnd only (nbnd < 3) and want to control size of AB, BC, CD as defined in lbl.

答:
It is plotting all data because your plot command is outside the if (nbnd<3): condition. If you only want to plot the data for nbnd<3, then what is the purpose of else? In my opinion, all you need to do is to move the plot command inside the if statement and you don't need the else command at all. So do the following

```<code>if (nbnd<3):
    color=f'C{nbnd}'
    ax.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)
</code>```

To change the fontsize in the legend and to control its position, you can use the following where the loc takes the x and the y coordinates in relative coordinates. 0 to 1 will put the legend within the plot area and anything else will put it out of the plot area.

```<code>plt.legend(loc=(0.5, 0.7), fontsize=20)
</code>```

Body:
My subcode in matplotlib  is

from matplotlib import pyplot as plt

lbl = {0:'AB', 1:'BC', 2:'CD', 3:'fourth'}

for i, section in enumerate(dist):
    for nbnd, _ in enumerate(freq[i][0]):
        x = section # to_list() you may need to convert sample to list.
        y = (freq[i, :, nbnd] + offset*nbnd) * scale

        if (nbnd<3):
            color=f'C{nbnd}'
        else:
            color='black'
        ax.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

ax.legend()

It plots all data while I want to restrict to nbnd only (nbnd < 3) and want to control size of AB, BC, CD as defined in lbl.

Body:
It is plotting all data because your plot command is outside the if (nbnd<3): condition. If you only want to plot the data for nbnd<3, then what is the purpose of else? In my opinion, all you need to do is to move the plot command inside the if statement and you don't need the else command at all. So do the following

if (nbnd<3):
    color=f'C{nbnd}'
    ax.plot(x, y, c=color, lw=2.0, alpha=0.8, label = lbl[nbnd] if nbnd < 3 and i == 0 else None)

To change the fontsize in the legend and to control its position, you can use the following where the loc takes the x and the y coordinates in relative coordinates. 0 to 1 will put the legend within the plot area and anything else will put it out of the plot area.

plt.legend(loc=(0.5, 0.7), fontsize=20)


问:
YAML Multi-Line Arrays
In YAML, you can easily create multi-line strings. However, I would like the ability to create a multi-line array (mainly for readibility within config files) using the | character.

A YAML array can be represented as: ['key1', 'key2', 'key3'].

A YAML sequence uses a dash followed by a space and then a string:

```<code>- String1
- String2
- String3
</code>```

This would evaluate to: ['string1', 'string2', 'string3'].

A YAML mapping is an array of key and value pairs that we see all the time in YAML:

```<code>Key1: string1
Key2: string2
Key3: string3
</code>```

This is all well and good, but I can't for the life of me see how to do a multi-line array. Something like this:

```<code>|
['string1', 'string2', 'string3']
['string4', 'string5', 'string6']
</code>```

Short of creating multiple array mappings in YAML and merging them in my programming language of choice, is there any way to achieve multi-line arrays, maybe with { } like Python has but in YAML?

答:
If what you are needing is an array of arrays, you can do this way:

key:
  - [ 'value11', 'value12', 'value13' ]
  - [ 'value21', 'value22', 'value23' ]
```

Title: YAML Multi-Line Arrays

Body:
In YAML, you can easily create multi-line strings. However, I would like the ability to create a multi-line array (mainly for readibility within config files) using the | character.

A YAML array can be represented as: ['key1', 'key2', 'key3'].

A YAML sequence uses a dash followed by a space and then a string:

- String1
- String2
- String3

This would evaluate to: ['string1', 'string2', 'string3'].

A YAML mapping is an array of key and value pairs that we see all the time in YAML:

Key1: string1
Key2: string2
Key3: string3

This is all well and good, but I can't for the life of me see how to do a multi-line array. Something like this:

|
['string1', 'string2', 'string3']
['string4', 'string5', 'string6']

Short of creating multiple array mappings in YAML and merging them in my programming language of choice, is there any way to achieve multi-line arrays, maybe with { } like Python has but in YAML?


问:
Python and performance of list comprehensions
Suppose you have got a list comprehension in python, like

```<code>Values = [ f(x) for x in range( 0, 1000 ) ]
</code>```

with f being just a function without side effects. So all the entries can be computed independently.

Is Python able to increase the performance of this list comprehension compared with the "obvious" implementation; e.g. by shared-memory-parallelization on multicore CPUs?

答:
No, Python will not magically parallelize this for you. In fact, it can't, since it cannot prove the independence of the entries; that would require a great deal of program inspection/verification, which is impossible to get right in the general case.

If you want quick coarse-grained multicore parallelism, I recommend joblib instead:

```<code>from joblib import delayed, Parallel
values = Parallel(n_jobs=NUM_CPUS)(delayed(f)(x) for x in range(1000))
</code>```

Not only have I witnessed near-linear speedups using this library, it also has the great feature of signals such as the one from Ctrl-C onto its worker processes, which cannot be said of all multiprocess libraries.

Note that joblib doesn't really support shared-memory parallelism: it spawns worker processes, not threads, so it incurs some communication overhead from sending data to workers and results back to the master process.

Body:
Suppose you have got a list comprehension in python, like

Values = [ f(x) for x in range( 0, 1000 ) ]

with f being just a function without side effects. So all the entries can be computed independently.

Is Python able to increase the performance of this list comprehension compared with the "obvious" implementation; e.g. by shared-memory-parallelization on multicore CPUs?

Body:
No, Python will not magically parallelize this for you. In fact, it can't, since it cannot prove the independence of the entries; that would require a great deal of program inspection/verification, which is impossible to get right in the general case.

If you want quick coarse-grained multicore parallelism, I recommend joblib instead:

from joblib import delayed, Parallel
values = Parallel(n_jobs=NUM_CPUS)(delayed(f)(x) for x in range(1000))

Not only have I witnessed near-linear speedups using this library, it also has the great feature of signals such as the one from Ctrl-C onto its worker processes, which cannot be said of all multiprocess libraries.

Note that joblib doesn't really support shared-memory parallelism: it spawns worker processes, not threads, so it incurs some communication overhead from sending data to workers and results back to the master process.


问:
How to invoke conan in docker container by jenkins? error Failed to execute script conan
Using Docker as a build environment, My jenkinsfile starting specified docker container and invoking CMake which trigger build process using conan and so on. Unfortunately pipeline failed with the following output:

```<code>-- Conan: checking conan executable
-- Conan: Found program /usr/bin/conan
-- Conan: Version found [148] Failed to execute script conan
 Traceback (most recent call last):
  File "conan/conans/conan.py", line 11, in <module>
 File "conan/conans/conan.py", line 7, in run
 File "conan/conans/client/command.py", line 2151, in main
 File "conan/conans/client/conan_api.py", line 222, in factory
 File "conan/conans/client/conan_api.py", line 234, in __init__
 File "conan/conans/client/migrations.py", line 26, in __init__
 File "conan/conans/client/cache/cache.py", line 78, in __init__
File "conan/conans/client/cache/cache.py", line 150, in config
  File "conan/conans/util/files.py", line 190, in save
 FileNotFoundError: [Errno 2] No such file or directory: '/.conan/conan.conf'
-- Conan executing: /usr/bin/conan install . -s build_type=Release -s compiler=clang -s compiler.version=10 -s compiler.libcxx=libstdc++11 -g=cmake --build=missing
[176] Failed to execute script conan
 Traceback (most recent call last):
</code>```

I do not know what the problem is. If I start container and build it manually it works.
If I create it manually then I am getting following error:

```<code>Conan: Version found ERROR: Can't write version file in /.conan/version.txt
</code>```

答:
I added the following environment variable to my jenkinsfile. Then it simply works!. I was trying to define env variables in docker container that was my fail</p>

```<code>  environment {
        CONAN_USER_HOME = "${env.WORKSPACE}/"
        CONAN_NON_INTERACTIVE = 1
    }
</code>```

Body:
Using Docker as a build environment, My jenkinsfile starting specified docker container and invoking CMake which trigger build process using conan and so on. Unfortunately pipeline failed with the following output:

-- Conan: checking conan executable
-- Conan: Found program /usr/bin/conan
-- Conan: Version found [148] Failed to execute script conan
 Traceback (most recent call last):
  File "conan/conans/conan.py", line 11, in <module>
 File "conan/conans/conan.py", line 7, in run
 File "conan/conans/client/command.py", line 2151, in main
 File "conan/conans/client/conan_api.py", line 222, in factory
 File "conan/conans/client/conan_api.py", line 234, in __init__
 File "conan/conans/client/migrations.py", line 26, in __init__
 File "conan/conans/client/cache/cache.py", line 78, in __init__
File "conan/conans/client/cache/cache.py", line 150, in config
  File "conan/conans/util/files.py", line 190, in save
 FileNotFoundError: [Errno 2] No such file or directory: '/.conan/conan.conf'
-- Conan executing: /usr/bin/conan install . -s build_type=Release -s compiler=clang -s compiler.version=10 -s compiler.libcxx=libstdc++11 -g=cmake --build=missing
[176] Failed to execute script conan
 Traceback (most recent call last):

I do not know what the problem is. If I start container and build it manually it works.
If I create it manually then I am getting following error:

Conan: Version found ERROR: Can't write version file in /.conan/version.txt

Body:
I added the following environment variable to my jenkinsfile. Then it simply works!. I was trying to define env variables in docker container that was my fail

  environment {
        CONAN_USER_HOME = "${env.WORKSPACE}/"
        CONAN_NON_INTERACTIVE = 1
    }


问:
UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>
I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error:

Traceback (most recent call last):
  File "SCRIPT LOCATION", line NUMBER, in <module>
    text = file.read()
  File "C:\Python31\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2907500: character maps to `<undefined>`
```

After reading this Q&A, see How to determine the encoding of text if you need help figuring out the encoding of the file you are trying to open.

答:
Stop wasting your time, just add the following encoding="cp437" and errors='ignore' to your code in both read and write:

```<code>open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')
</code>```

Godspeed

Body:
I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error:

Traceback (most recent call last):
  File "SCRIPT LOCATION", line NUMBER, in <module>
    text = file.read()
  File "C:\Python31\lib\encodings\cp1252.py", line 23, in decode
    return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2907500: character maps to `<undefined>`

After reading this Q&A, see How to determine the encoding of text if you need help figuring out the encoding of the file you are trying to open.

Body:
Stop wasting your time, just add the following encoding="cp437" and errors='ignore' to your code in both read and write:

open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')

Godspeed


问:
Are methods that modify reference type parameters bad?
I've seen methods like this:

```<code>public void Foo(List<string> list)
{
    list.Add("Bar");
}
</code>```

Is this good practice to modify parameters in a method?

Wouldn't this be better?

```<code>public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}
</code>```

It just feels like the first example has unexpected side effects.

答:
In the example you've given, the first seems a lot nicer to me than the second. If I saw a method that accepted a list and also returned a list, my first assumption would be that it was returning a new list and not touching the one it was given. The second method, therefore, is the one with unexpected side effects.

As long as your methods are named appropriately there's little danger in modifying the parameter. Consider this:

```<code>public void Fill<T>(IList<T> list)
{
    // add a bunch of items to list
}
</code>```

With a name like "Fill" you can be pretty certain that the method will modify the list.

OwnerDisplayName: Jonathan Parker

Body:
I've seen methods like this:

public void Foo(List<string> list)
{
    list.Add("Bar");
}

Is this good practice to modify parameters in a method?

Wouldn't this be better?

public List<string> Foo(List<string> list)
{
    // Edit
    List<string> newlist = new List<string>(list);
    newlist.Add("Bar");
    return newlist;
}

It just feels like the first example has unexpected side effects.

LastEditorDisplayName: Jonathan Parker

Body:
In the example you've given, the first seems a lot nicer to me than the second. If I saw a method that accepted a list and also returned a list, my first assumption would be that it was returning a new list and not touching the one it was given. The second method, therefore, is the one with unexpected side effects.

As long as your methods are named appropriately there's little danger in modifying the parameter. Consider this:

public void Fill<T>(IList<T> list)
{
    // add a bunch of items to list
}

With a name like "Fill" you can be pretty certain that the method will modify the list.

OwnerDisplayName: Matt Hamilton


问:
Protobufs import from another directory
While trying to compile a proto file named UserOptions.proto which has an import named Account.proto using the below command

```<code>protoc --proto_path=/home/project_new1/account --java_out=/home/project_new1/source   /home/project_new1/settings/Useroptions.proto
</code>```

I get the following error :

```<code>/home/project_new1/settings/UserOptions.proto: File does not reside within any path specified using --proto_path (or -I). You must specify a --proto_path which encompasses this file.
</code>```

PS: UserOptions.proto present in the directory /home/project_new1/settings

imports Account.proto present in the directory
/home/project_new1/account

Proto descriptor files:

UserOptions.proto

```<code>package settings;

import "Account.proto";

option java_outer_classname = "UserOptionsVOProto";
</code>```

Account.proto

```<code>package account;

option java_outer_classname = "AccountVOProto";

message Object
{
    optional string userId = 1;
    optional string service = 2;
}
</code>```

答:
For my environment, Windows 10 Pro operating system and C++ programming languaje, I used the protoc-3.12.2-win64.zip that you can downloat it from here. You should open a Windows PowerShell inside the protoc-3.12.2-win64\bin path and then you must execute one of the next commands:

```<code>.\protoc.exe -I=C:\Users\UserName\Desktop\SRC --cpp_out=C:\Users\UserName\Desktop\DST C:\Users\UserName\Desktop\SRC\addressbook.proto
</code>```

Or

```<code>.\protoc.exe --proto_path=C:\Users\UserName\Desktop\SRC --cpp_out=C:\Users\UserName\Desktop\DST C:\Users\UserName\Desktop\SRC\addressbook.proto
</code>```

Note:

1- My source folder is in: C:\Users\UserName\Desktop\SRC

2- My destination folder is in: C:\Users\UserName\Desktop\DST

3- My .proto file is in: C:\Users\UserName\Desktop\SRC\addressbook.proto

Title: Protobufs import from another directory

Body:
While trying to compile a proto file named UserOptions.proto which has an import named Account.proto using the below command

protoc --proto_path=/home/project_new1/account --java_out=/home/project_new1/source   /home/project_new1/settings/Useroptions.proto

I get the following error :

/home/project_new1/settings/UserOptions.proto: File does not reside within any path specified using --proto_path (or -I). You must specify a --proto_path which encompasses this file.

PS: UserOptions.proto present in the directory /home/project_new1/settings

imports Account.proto present in the directory
/home/project_new1/account

Proto descriptor files:

UserOptions.proto

package settings;

import "Account.proto";

option java_outer_classname = "UserOptionsVOProto";

Account.proto

package account;

option java_outer_classname = "AccountVOProto";

message Object
{
    optional string userId = 1;
    optional string service = 2;
}

Body:
For my environment, Windows 10 Pro operating system and C++ programming languaje, I used the protoc-3.12.2-win64.zip that you can downloat it from here. You should open a Windows PowerShell inside the protoc-3.12.2-win64\bin path and then you must execute one of the next commands:

.\protoc.exe -I=C:\Users\UserName\Desktop\SRC --cpp_out=C:\Users\UserName\Desktop\DST C:\Users\UserName\Desktop\SRC\addressbook.proto

Or

.\protoc.exe --proto_path=C:\Users\UserName\Desktop\SRC --cpp_out=C:\Users\UserName\Desktop\DST C:\Users\UserName\Desktop\SRC\addressbook.proto

Note:

1- My source folder is in: C:\Users\UserName\Desktop\SRC

2- My destination folder is in: C:\Users\UserName\Desktop\DST

3- My .proto file is in: C:\Users\UserName\Desktop\SRC\addressbook.proto


问:
Bitbucket API for updating the build status for a pull request
I see the docs for updating the build status for a commit:
https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build

For a pull request, isn't there a unique commit associated with it? Is there no API for updating a PR's build status? Or do we just need to discover which commit is associated with the PR, and then just update the build status for that commit?

For example this view:

You can see on the right that the commit to the temp branch has a passing build status - but the way it works is it should merge temp into master into some new commit/branch and I need to be able to test that.

The view that I want to update is at url:

```<code>https://bitbucket.org/<user>/<repo>/pull-requests/1/<commit-message>/diff
</code>```

答:
Bitbucket does not have Builds on PRs (Check here), What you need is one Successful Build on the LAST Commit:

Then, you can use the API to push the build to that one after you have done what you need to test it.

This guide is really simple to use:
https://developer.atlassian.com/server/bitbucket/how-tos/updating-build-status-for-commits/

The only recommendation I have on the guide is that it didn't work for me with curl, then, what I did was to do it with Postman and then exported the command to curl and that's it...

```<code>curl --location --request POST 'https://bitbucket.org/api/2.0/repositories/{your space}/{Your Repo}/commit/{The long hash of your commit}/statuses/build?Content-Type=application/json' \
--header 'Authorization: Basic {your token}=' \
--header 'Content-Type: application/json' \
--data-raw '{
    "state": "SUCCESSFUL",
    "key": "MANUAL-BUILD",
    "name": "Manual Build",
    "url": "http://this.really.doesnt.matter/",
    "description": "Successful Build done manually"
}'
</code>```

Body:
I see the docs for updating the build status for a commit:
https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build

For a pull request, isn't there a unique commit associated with it? Is there no API for updating a PR's build status? Or do we just need to discover which commit is associated with the PR, and then just update the build status for that commit?

For example this view:

You can see on the right that the commit to the temp branch has a passing build status - but the way it works is it should merge temp into master into some new commit/branch and I need to be able to test that.

The view that I want to update is at url:

https://bitbucket.org/<user>/<repo>/pull-requests/1/<commit-message>/diff

Body:
Bitbucket does not have Builds on PRs (Check here), What you need is one Successful Build on the LAST Commit:

Then, you can use the API to push the build to that one after you have done what you need to test it.

This guide is really simple to use:
https://developer.atlassian.com/server/bitbucket/how-tos/updating-build-status-for-commits/

The only recommendation I have on the guide is that it didn't work for me with curl, then, what I did was to do it with Postman and then exported the command to curl and that's it...

curl --location --request POST 'https://bitbucket.org/api/2.0/repositories/{your space}/{Your Repo}/commit/{The long hash of your commit}/statuses/build?Content-Type=application/json' \
--header 'Authorization: Basic {your token}=' \
--header 'Content-Type: application/json' \
--data-raw '{
    "state": "SUCCESSFUL",
    "key": "MANUAL-BUILD",
    "name": "Manual Build",
    "url": "http://this.really.doesnt.matter/",
    "description": "Successful Build done manually"
}'


问:
GAS: Error 401 while connecting to an API
I'm trying to connect to Cloud Waitress API, a solution for restaurants,

Documentation: https://apidocs.cloudwaitress.com/#orderpromos

It's documentation gives an example on how to connect to the API:

```<code>curl https://api.cloudwaitress.com/v1/orders \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: YOUR_API_KEY" \
  -d `
    {
      "restaurant_id": "xxxxxxx",
      "limit": 10,
      "page": 1,
      "sort": { "created": -1 },
    }
</code>```

I tried to create a Script in GAS to get the information back to a Spreadsheet.

Based on this question:

How curl maps onto Google App Script URLFetchApp

I have changed my code as follows:

```<code>function getAuthHeader(){
  var apiKey = "SOME-API-KEY";
  var authHeader = Utilities.base64Encode(apiKey);
  return {
    headers: {Authorization: authHeader}
   }
}

function GetOrders(){
  var url = "https://api.cloudwaitress.com/v1/orders";

  var data = {
    "restaurant_id":"SOME-RESTAURANT-ID",
    "limit": 10,
    "page": 1,
    "sort": { "created": 1 }
  };

  var result = goPost(url ,data);

}

function goPost(url,data){
   var options = {
   'method' : 'post',
   'payload' : data,
   'headers': getAuthHeader()['headers']
   };

   var response;

   try{
     response = JSON.parse(UrlFetchApp.fetch(url,options).getContentText());
   }catch(err){
    Logger.log(err);
   }

   return response;
 }
</code>```

Right now the new error that I'm getting is:

Exception: Request failed for https://api.cloudwaitress.com returned
code 401. Truncated server response: {"outcome":1,"message":"Invalid
Authentication"} (use muteHttpExceptions option to examine full
response)

Which I believe is quite a progress since I was getting an 500 error before.

I have asked the cloudwaitress team their assistance, however I wonder if there is something else I can try.

答:
How about this modification?

Modification points:

At your sample curl, "Content-Type: application/json" is used, and the JSON object is converted to the string.

The thread you refered uses the basic authorization like -u testtoken123:. By this, Utilities.base64Encode is required be used. But in your sample curl, the API key is directly used.

I thought that this might be the reason of the error message.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

```<code>var options = {
'method' : 'post',
'payload' : data,
'headers': getAuthHeader()['headers']
};
</code>```

To:

```<code>var apiKey = "SOME-API-KEY";
var options = {
  'method' : 'post',
  'payload' : JSON.stringify(data),
  'headers': {Authorization: apiKey},
  'contentType': "application/json",
};
</code>```

In this case, getAuthHeader() is not used.

Note:

The request of this modified script is the same with your sample curl command. But in this modified script, it supposes that your apiKey and data can be used for this API. Please be careful this.

Reference:

Class UrlFetchApp

Body:
I'm trying to connect to Cloud Waitress API, a solution for restaurants,

Documentation: https://apidocs.cloudwaitress.com/#orderpromos

It's documentation gives an example on how to connect to the API:

curl https://api.cloudwaitress.com/v1/orders \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: YOUR_API_KEY" \
  -d `
    {
      "restaurant_id": "xxxxxxx",
      "limit": 10,
      "page": 1,
      "sort": { "created": -1 },
    }

I tried to create a Script in GAS to get the information back to a Spreadsheet.

Based on this question:

How curl maps onto Google App Script URLFetchApp

I have changed my code as follows:

function getAuthHeader(){
  var apiKey = "SOME-API-KEY";
  var authHeader = Utilities.base64Encode(apiKey);
  return {
    headers: {Authorization: authHeader}
   }
}

function GetOrders(){
  var url = "https://api.cloudwaitress.com/v1/orders";

  var data = {
    "restaurant_id":"SOME-RESTAURANT-ID",
    "limit": 10,
    "page": 1,
    "sort": { "created": 1 }
  };

  var result = goPost(url ,data);

}

function goPost(url,data){
   var options = {
   'method' : 'post',
   'payload' : data,
   'headers': getAuthHeader()['headers']
   };

   var response;

   try{
     response = JSON.parse(UrlFetchApp.fetch(url,options).getContentText());
   }catch(err){
    Logger.log(err);
   }

   return response;
 }

Right now the new error that I'm getting is:

Exception: Request failed for https://api.cloudwaitress.com returned
code 401. Truncated server response: {"outcome":1,"message":"Invalid
Authentication"} (use muteHttpExceptions option to examine full
response)

Which I believe is quite a progress since I was getting an 500 error before.

I have asked the cloudwaitress team their assistance, however I wonder if there is something else I can try.

Body:
How about this modification?

Modification points:

At your sample curl, "Content-Type: application/json" is used, and the JSON object is converted to the string.

The thread you refered uses the basic authorization like -u testtoken123:. By this, Utilities.base64Encode is required be used. But in your sample curl, the API key is directly used.

I thought that this might be the reason of the error message.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

var options = {
'method' : 'post',
'payload' : data,
'headers': getAuthHeader()['headers']
};

To:

var apiKey = "SOME-API-KEY";
var options = {
  'method' : 'post',
  'payload' : JSON.stringify(data),
  'headers': {Authorization: apiKey},
  'contentType': "application/json",
};

In this case, getAuthHeader() is not used.

Note:

The request of this modified script is the same with your sample curl command. But in this modified script, it supposes that your apiKey and data can be used for this API. Please be careful this.

Reference:

Class UrlFetchApp


答:
Return the value of count and assign it back to the variable.

const move = (n, source, destination, buffer, count) => {

  // Verify that there are disks.
  if (n > 0) {

    // Move one disk to buffer rod.
    count = move(n - 1, source, buffer, destination, ++count);

    // Move nth disk from source to destination.
    destination.push(source.pop())

    // Display progress
    console.log(count, JSON.stringify(A), JSON.stringify(B), JSON.stringify(C), "\n--------------------------")

    // Move the disk (n - 1) from the buffer to the destination.
    count = move(n - 1, buffer, destination, source, ++count);

  }
  return count;
};

// Invocate
const A = [5, 4, 3, 2, 1]
const B = []
const C = []

move(5, A, C, B, 0);```

Title: Is there a way to incrementally increase count in a recursion?

Body:
Is there a way to incrementally increase the count for the Tower of Hanoi challenge?

At the moment, the count isn't incrementally increasing. Interestingly, it starts at five and hops around. See the output below.

I tried adding a let count = 0 within the function and adding ++count within the IF statement and outside the recursive function to no avail.

Working code block:

const move = (n, source, destination, buffer, count) => {

  // Verify that there are disks.
  if (n > 0) {

    // Move one disk to buffer rod.
    move(n - 1, source, buffer, destination, ++count);

    // Move nth disk from source to destination.
    destination.push(source.pop())

    // Display progress
    console.log(count, A, B, C, "\n--------------------------")

    // Move the disk (n - 1) from the buffer to the destination.
    move(n - 1, buffer, destination, source, ++count);
  }
};

// Disk starting position
const A = [5, 4, 3, 2, 1]
const B = []
const C = []

// Invoke
move(5, A, C, B, 0);

Output:

5 [ 5, 4, 3, 2 ] [] [ 1 ]
--------------------------
4 [ 5, 4, 3 ] [ 2 ] [ 1 ]
--------------------------
6 [ 5, 4, 3 ] [ 2, 1 ] []
--------------------------
3 [ 5, 4 ] [ 2, 1 ] [ 3 ]
--------------------------
6 [ 5, 4, 1 ] [ 2 ] [ 3 ]
--------------------------
5 [ 5, 4, 1 ] [] [ 3, 2 ]
--------------------------
7 [ 5, 4 ] [] [ 3, 2, 1 ]
--------------------------
2 [ 5 ] [ 4 ] [ 3, 2, 1 ]
--------------------------
6 [ 5 ] [ 4, 1 ] [ 3, 2 ]
--------------------------
5 [ 5, 2 ] [ 4, 1 ] [ 3 ]
--------------------------
7 [ 5, 2, 1 ] [ 4 ] [ 3 ]
--------------------------
4 [ 5, 2, 1 ] [ 4, 3 ] []
--------------------------
7 [ 5, 2 ] [ 4, 3 ] [ 1 ]
--------------------------
6 [ 5 ] [ 4, 3, 2 ] [ 1 ]
--------------------------


问:
Read lines until certain string and remove it
I have a small python code, that opens a file, read it until certain string, print it.

The code is below:

```<code>filename = 'teste.txt'

with open(filename, 'r') as input:
   for line in input:
     print(line)
     if '**==**' in line:
       break
</code>```

After the print, I need to erase it from the file, basically removing the lines until **==**, leaving the other lines untouched.

I've tried:

```<code>search = '**==**'
for i, line in enumerate(lines):
  print(line)
  if search in line:
      break

if i < len(lines) - 1:
    with open('teste.txt', 'w') as f:
        f.write('\n'.join(lines[i + 1:]))
</code>```

But each time that I run the code, the "next line block" starts to have a lot of spaces between then.

The file can have between 6 - 10 MB

Any suggestions on how I can do it?

答:
This should do the job:

with open('teste.txt') as f:
    lines = f.readlines()

for i, line in enumerate(lines):
    if search in line:
        lines = lines[i + 1:]
        break

with open('teste.txt', 'w') as f:
    f.writelines(lines)
```

Body:
I have a small python code, that opens a file, read it until certain string, print it.

The code is below:

filename = 'teste.txt'

with open(filename, 'r') as input:
   for line in input:
     print(line)
     if '**==**' in line:
       break

After the print, I need to erase it from the file, basically removing the lines until **==**, leaving the other lines untouched.

I've tried:

search = '**==**'
for i, line in enumerate(lines):
  print(line)
  if search in line:
      break

if i < len(lines) - 1:
    with open('teste.txt', 'w') as f:
        f.write('\n'.join(lines[i + 1:]))

But each time that I run the code, the "next line block" starts to have a lot of spaces between then.

The file can have between 6 - 10 MB

Any suggestions on how I can do it?


问:
Call a chosen TEL number automatically in my c# application
I have a CRM Desktop application (Windows Forms / c#) and i'm using a specicfic application to make calls (AirCall Application in my situation).

How can i make a button which can trigger the call  : so when i choose a number it will be called automatically with the default PC application (AirCall in my situation)?

Any help?and thanks

答:
You could also use Aircall Public API with the dedicated endpoints:

Start an outbound call

Dial a phone number in the app


问:
How to correctly implement a Map that has objects as keys?
I'm trying to implement this logic: I have a deck with several cards. Each card has a suit and a value. However, there may be repeated cards in the deck. I want to count how many of each card are in the deck. Suits are an enum and there's also a Card class:

```<code>enum Suit { Red, Green, Blue };

class Card {
  Suit suit;
  int value;

  Card(this.suit, this.value);
}
</code>```

This would be the deck:

```<code>final deck = Map<Card, int>();

final addCardToDeck = (Card c) {
  if (deck[c] != null) deck[c]++;
  else deck[c] = 1;
};
</code>```

So let's say I put 2 equal cards in the deck.

```<code>final cardA = Card(Suit.red, 7);
final cardB = Card(Suit.red, 7);

addCardToDeck(cardA);
addCardToDeck(cardB);
</code>```

Since the two cards are equal, I would expect deck[cardA] and deck[cardB] to return 2, right? Wrong! Both returned 1. So I thought, ok, must be an object reference problem, I'll overload the == operator.

```<code>bool operator ==(otherCard) {
    return otherCard is Card
      && suit == otherCard.suit
      && value == otherCard.value;
}
</code>```

And it still doesn't work as expected. So, how would I correctly implement this? I know I could just make a Map of Maps, so I would access it like deck[suit][value], but I find this approach neater. Is this feasible?

Whole code below.

```<code>enum Suit { Red, Blue, Green }

class Card {
  Suit suit;
  int value;

  Card(this.suit, this.value);

  bool operator ==(otherCard) {
    return otherCard is Card && suit == otherCard.suit && value == otherCard.value;
  }
}

void main() {
  final deck = Map<Card, int>();

  final addCardToDeck = (Card c) {
    if (deck[c] != null) deck[c]++;
    else deck[c] = 1;
  };

  final cardA = Card(Suit.Red, 7);
  final cardB = Card(Suit.Red, 7);

  addCardToDeck(cardA);
  addCardToDeck(cardB);

  print(deck[cardA]); // Expected 2, got 1
  print(deck[cardB]); // Expected 2, got 1
}
</code>```

答:
hashCode will be used to determine equality in a Map. If you override == you should also override hashCode

https://dart.dev/guides/language/effective-dart/design#equality

Here is the updated code:

```<code>enum Suit { Red, Blue, Green }

class Card {
  Suit suit;
  int value;

  Card(this.suit, this.value);

  @override
  bool operator ==(otherCard) {
    return otherCard is Card &&
        suit == otherCard.suit &&
        value == otherCard.value;
  }

  @override
  int get hashCode => suit.hashCode^value.hashCode;
}

void main() {
  final deck = <Card, int>{};

  final addCardToDeck = (Card c) {
    if (deck[c] != null) {
      deck[c]++;
    } else {
      deck[c] = 1;
    }
  };

  final cardA = Card(Suit.Red, 7);
  final cardB = Card(Suit.Red, 7);
  final cardC = Card(Suit.Green, 4);

  addCardToDeck(cardA);
  addCardToDeck(cardB);
  addCardToDeck(cardC);

  print(deck[cardA]); // Expected 2, got 2
  print(deck[cardB]); // Expected 2, got 2
  print(deck[cardC]); // Expected 1, got 1
}
</code>```

Body:
I'm trying to implement this logic: I have a deck with several cards. Each card has a suit and a value. However, there may be repeated cards in the deck. I want to count how many of each card are in the deck. Suits are an enum and there's also a Card class:

enum Suit { Red, Green, Blue };

class Card {
  Suit suit;
  int value;

  Card(this.suit, this.value);
}

This would be the deck:

final deck = Map<Card, int>();

final addCardToDeck = (Card c) {
  if (deck[c] != null) deck[c]++;
  else deck[c] = 1;
};

So let's say I put 2 equal cards in the deck.

final cardA = Card(Suit.red, 7);
final cardB = Card(Suit.red, 7);

addCardToDeck(cardA);
addCardToDeck(cardB);

Since the two cards are equal, I would expect deck[cardA] and deck[cardB] to return 2, right? Wrong! Both returned 1. So I thought, ok, must be an object reference problem, I'll overload the == operator.

bool operator ==(otherCard) {
    return otherCard is Card
      && suit == otherCard.suit
      && value == otherCard.value;
}

And it still doesn't work as expected. So, how would I correctly implement this? I know I could just make a Map of Maps, so I would access it like deck[suit][value], but I find this approach neater. Is this feasible?

Whole code below.

enum Suit { Red, Blue, Green }

class Card {
  Suit suit;
  int value;

  Card(this.suit, this.value);

  bool operator ==(otherCard) {
    return otherCard is Card && suit == otherCard.suit && value == otherCard.value;
  }
}

void main() {
  final deck = Map<Card, int>();

  final addCardToDeck = (Card c) {
    if (deck[c] != null) deck[c]++;
    else deck[c] = 1;
  };

  final cardA = Card(Suit.Red, 7);
  final cardB = Card(Suit.Red, 7);

  addCardToDeck(cardA);
  addCardToDeck(cardB);

  print(deck[cardA]); // Expected 2, got 1
  print(deck[cardB]); // Expected 2, got 1
}

Body:
hashCode will be used to determine equality in a Map. If you override == you should also override hashCode

https://dart.dev/guides/language/effective-dart/design#equality

Here is the updated code:

enum Suit { Red, Blue, Green }

class Card {
  Suit suit;
  int value;

  Card(this.suit, this.value);

  @override
  bool operator ==(otherCard) {
    return otherCard is Card &&
        suit == otherCard.suit &&
        value == otherCard.value;
  }

  @override
  int get hashCode => suit.hashCode^value.hashCode;
}

void main() {
  final deck = <Card, int>{};

  final addCardToDeck = (Card c) {
    if (deck[c] != null) {
      deck[c]++;
    } else {
      deck[c] = 1;
    }
  };

  final cardA = Card(Suit.Red, 7);
  final cardB = Card(Suit.Red, 7);
  final cardC = Card(Suit.Green, 4);

  addCardToDeck(cardA);
  addCardToDeck(cardB);
  addCardToDeck(cardC);

  print(deck[cardA]); // Expected 2, got 2
  print(deck[cardB]); // Expected 2, got 2
  print(deck[cardC]); // Expected 1, got 1
}


问:
python: minimum value within specified bounds for an array
Say I have an array  a = [-1.2, 1, 0.5, 4, 5, 3]

Is there a way to find a min element which is within a=0.2 to b=2

In this particular example the answer will be 0.5.

I want to perform this computation in python. .

答:
```<code>a = [-1.2, 1, 0.5, 4, 5, 3]
r1=0.2
r2=2
l=[]
for i in a:
    if i>r1 and i<r2:
        l.append(i)
print(min(l))
</code>```

I have considered strictly inside two given value,  use >= and <= if both are to be included .Hope this helps

Body:
a = [-1.2, 1, 0.5, 4, 5, 3]
r1=0.2
r2=2
l=[]
for i in a:
    if i>r1 and i<r2:
        l.append(i)
print(min(l))

I have considered strictly inside two given value,  use >= and <= if both are to be included .Hope this helps


问:
Can only use .str accessor with string values, which use np.object_ dtype in pandas
Trying to create year to use in date from a number of columns, getting number with trailing zeros.
I use the calculation below to calculate year,

```<code>f2.loc[:,'frt_elig_year'] = (f2['FrstElAge']-f2['iss_age']) + f2['eff_date'].dt.year
</code>```

Get the year but with 4 0's after i.e. 2021.0000

checked the

```<code>type('first_elig_year')
str
</code>```

however when I try to remove using:

```<code>f2.loc[:,'frt_elig_year']= f2['frt_elig_year'].str[:4]
</code>```

I get message:

```<code>Can only use .str accessor with string values, which use np.object_ dtype in pandas
</code>```

答:
Maybe try

```<code>f2['frt_elig_year']=f2['frt_elig_year'].astype('str')
</code>```

before making the substring .str[:4]

you can check the types of the variables of the dataframe by using

```<code>f2.dtypes
</code>```

Body:
Trying to create year to use in date from a number of columns, getting number with trailing zeros.
I use the calculation below to calculate year,

f2.loc[:,'frt_elig_year'] = (f2['FrstElAge']-f2['iss_age']) + f2['eff_date'].dt.year

Get the year but with 4 0's after i.e. 2021.0000

checked the

type('first_elig_year')
str

however when I try to remove using:

f2.loc[:,'frt_elig_year']= f2['frt_elig_year'].str[:4]

I get message:

Can only use .str accessor with string values, which use np.object_ dtype in pandas

Body:
Maybe try

f2['frt_elig_year']=f2['frt_elig_year'].astype('str')

before making the substring .str[:4]

you can check the types of the variables of the dataframe by using

f2.dtypes


问:
Trying to make an HP bar for a game using HTML/JavaScript
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}</code>```

      100hp

    Health
    Damage

```

Also, if anyone has any ideas to improve the design I'm all ears!

答:
You can try this</p>

```<code>    let width = 100;

function add() {
let addHealth = document.getElementById('health')
    width =width+ 1
    width=width>100?width=100:width
    if(addHealth){
        addHealth.style.width = width + '%';
        addHealth.innerHTML = width  + 'hp';
    }
}

function remove() {
    let damage = document.getElementById('health')
    width =width- 1
    width=width<0?width=0:width

    if(damage) {
        damage.style.width = width + '%';
        damage.innerHTML = width  + 'hp';
    }
}
</code>```

Body:
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}

.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

      100hp

    Health
    Damage

Also, if anyone has any ideas to improve the design I'm all ears!

Body:
You can try this

    let width = 100;

function add() {
let addHealth = document.getElementById('health')
    width =width+ 1
    width=width>100?width=100:width
    if(addHealth){
        addHealth.style.width = width + '%';
        addHealth.innerHTML = width  + 'hp';
    }
}

function remove() {
    let damage = document.getElementById('health')
    width =width- 1
    width=width<0?width=0:width

    if(damage) {
        damage.style.width = width + '%';
        damage.innerHTML = width  + 'hp';
    }
}


问:
Using python in postgres and this error pops up
Getting this error:</p>

```<code>Connection successful
Database Created Successfully
Connected to babynames database.
Traceback (most recent call last):
  File "C:/Users/Joseph/Desktop/INFO153 Final/Info153PartII.py", line 44, in <module>
    cur.execute('insert into boys values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))
TypeError: can only concatenate str (not "float") to str
</code>```

```<code>import pandas as pd

df_boys = pd.read_csv('babynames.txt', delimiter=' ',header=None, usecols=(0,1,2,3) )

df_boys.columns = ["Rank", "Name", "Total Babies", "Total Percentage"]

df_girls = pd.read_csv('babynames.txt', delimiter=' ',header=None, usecols=(0,4,5,6) )
df_girls.columns = ["Rank", "Name", "Total Babies", "Total Percentage"]

#check the imported data
df_boys.head()
df_girls.head()

#psycopg2 library for connecting to PostgreSQL database

import psycopg2

conn = psycopg2.connect(database="postgres", user="postgres", password="postgres", host="127.0.0.1", port="5432")
conn.autocommit = True
print ("Connection successful")

#Create babynames database

cur = conn.cursor()
cur.execute('CREATE DATABASE babynames;')
print ("Database Created Successfully")

#connect to babynames database

conn_babynames = psycopg2.connect(database="babynames", user="postgres", password="postgres", host="127.0.0.1", port="5432")
conn_babynames.autocommit = True
print ("Connected to babynames database.")
cur = conn_babynames.cursor()

#create tables for boys and girls

cur.execute('CREATE TABLE Boys (Rank integer, Name varchar(25), Total_Babies float, Total_Percentage float);')
cur.execute('CREATE TABLE Girls (Rank integer, Name varchar(25), Total_Babies float, Total_Percentage float);')

#import data from dataframe to table using insert into statement

for i, row in df_boys.iterrows():
    cur.execute('insert into boys values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))

for i, row in df_girls.iterrows():
    cur.execute('insert into girls values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))

#execute sql queries and display result of analysis

cur.execute("select sum(total) as t_children from ( select sum(Total_Babies) as total from boys union select sum(Total_Babies) as total from girls) as t")
total_babies=cur.fetchone()
print("Total babies born that year = ",total_babies[0])

cur.execute("select total from ( select sum(Total_Babies) as total from boys union select sum(Total_Babies) as total from girls) as t")
babies=cur.fetchall()
if (babies[0]>babies[1]):
    print("More boys were born in that year")
else:
    print("More girls were born in that year")

cur.execute("select name from boys where Total_Babies> {}".format(total_babies[0]/2))
babies=cur.fetchall()
print(babies)

cur.execute("select name from girls where Total_Babies> {}".format(total_babies[0]/2))
babies=cur.fetchall()
print(babies)```

</code>```

答:
I believe the error is in "'"+row.tolist()[1]+"'" in your insert. As the error states, there's an issue trying to concatenate a float to a string. You should just be able to wrap the float in a str(), so all the concatenations (+) will be strings:

"'"+str(row.tolist()[1])+"'"

As some have pointed out, it is considered poor / dangerous practice to take strings from somewhere and concatenate them into your SQL queries. Malicious strings can wreck your database. My answer was for your question about why you got the error, but you would do well to look up parameterized SQL and how to implement using it with psycopg2

Body:
Getting this error:

Connection successful
Database Created Successfully
Connected to babynames database.
Traceback (most recent call last):
  File "C:/Users/Joseph/Desktop/INFO153 Final/Info153PartII.py", line 44, in <module>
    cur.execute('insert into boys values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))
TypeError: can only concatenate str (not "float") to str

import pandas as pd

df_boys = pd.read_csv('babynames.txt', delimiter=' ',header=None, usecols=(0,1,2,3) )

df_boys.columns = ["Rank", "Name", "Total Babies", "Total Percentage"]

df_girls = pd.read_csv('babynames.txt', delimiter=' ',header=None, usecols=(0,4,5,6) )
df_girls.columns = ["Rank", "Name", "Total Babies", "Total Percentage"]

#check the imported data
df_boys.head()
df_girls.head()

#psycopg2 library for connecting to PostgreSQL database

import psycopg2

conn = psycopg2.connect(database="postgres", user="postgres", password="postgres", host="127.0.0.1", port="5432")
conn.autocommit = True
print ("Connection successful")

#Create babynames database

cur = conn.cursor()
cur.execute('CREATE DATABASE babynames;')
print ("Database Created Successfully")

#connect to babynames database

conn_babynames = psycopg2.connect(database="babynames", user="postgres", password="postgres", host="127.0.0.1", port="5432")
conn_babynames.autocommit = True
print ("Connected to babynames database.")
cur = conn_babynames.cursor()

#create tables for boys and girls

cur.execute('CREATE TABLE Boys (Rank integer, Name varchar(25), Total_Babies float, Total_Percentage float);')
cur.execute('CREATE TABLE Girls (Rank integer, Name varchar(25), Total_Babies float, Total_Percentage float);')

#import data from dataframe to table using insert into statement

for i, row in df_boys.iterrows():
    cur.execute('insert into boys values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))

for i, row in df_girls.iterrows():
    cur.execute('insert into girls values ({},{},{},{});'.format(row.tolist()[0],"'"+row.tolist()[1]+"'",row.tolist()[2],row.tolist()[3]))

#execute sql queries and display result of analysis

cur.execute("select sum(total) as t_children from ( select sum(Total_Babies) as total from boys union select sum(Total_Babies) as total from girls) as t")
total_babies=cur.fetchone()
print("Total babies born that year = ",total_babies[0])

cur.execute("select total from ( select sum(Total_Babies) as total from boys union select sum(Total_Babies) as total from girls) as t")
babies=cur.fetchall()
if (babies[0]>babies[1]):
    print("More boys were born in that year")
else:
    print("More girls were born in that year")

cur.execute("select name from boys where Total_Babies> {}".format(total_babies[0]/2))
babies=cur.fetchall()
print(babies)

cur.execute("select name from girls where Total_Babies> {}".format(total_babies[0]/2))
babies=cur.fetchall()
print(babies)```


答:
If you extend the list with your bounds (Min=0.2 and Max=2), you can get the elements between by indexing after sorting the extended list:

a =  [-1.2, 1, 0.5, 4, 5, 3]
# Define bounds
Min = 0.2
Max = 2
# Extend and sort list with integrated bounds
a = sorted(a + [Min, Max])
# Slicing and get all the elements between bounds
print(min(a[a.index(Min)+1:a.index(Max)]))
# 0.5
```

Title: python: minimum value within specified bounds for an array

Body:
Say I have an array  a = [-1.2, 1, 0.5, 4, 5, 3]

Is there a way to find a min element which is within a=0.2 to b=2

In this particular example the answer will be 0.5.

I want to perform this computation in python. .


问:
Simple Magento question
I have a website in Magento, it's still very simple and unfinished.

Since I'm a beginner in this field, I'd like someone to point me to a solution:
How do I change the Checkout link text?
Is it done inside the phtml/XML structure or inside admin panel?
this is my website: [notice the Checkout link]
http://gale.dev4.webenabled.net/

答:
you can find locale files under app/locale/language_CODE and change the translation from there . To find the translations either use file search or grep for the string you are looking for

```<code>grep '"Checkout"' app/locale/en_US/ -rsn
</code>```

this will show you filename, line number and the searched string:

```<code>app/locale/en_US/Mage_Checkout.csv:40:"Checkout","Checkout"
</code>```

remember that locale files are utf-8 encoded and cache must be cleared after changing localizations

Title: Simple Magento question

Body:
you can find locale files under app/locale/language_CODE and change the translation from there . To find the translations either use file search or grep for the string you are looking for

grep '"Checkout"' app/locale/en_US/ -rsn

this will show you filename, line number and the searched string:

app/locale/en_US/Mage_Checkout.csv:40:"Checkout","Checkout"

remember that locale files are utf-8 encoded and cache must be cleared after changing localizations


问:
Printing Right Triangles w/ Nested For-Loop
Here's my loop:

int height = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Printing a " + height + " by " + height + " right triangle...");

for (int i = 1; i <= height; i++)
{
    Console.WriteLine("*");
    for (int j = 1; j <= i; j++)
    {
        Console.Write("*");
    }
```

<p>And here is the resulting print (program takes a user input for the height, this example has a height of 5:</p>

<pre class="lang-none prettyprint-override"><code>*
**
***
****
****
</code>```

As you can see, I can't get the last star to print on the last row. This makes absolutely no sense to me, as I've compared it to many other similar constructs and there appears to be no discrepancies between the one I've constructed and the ones others have made. I just started coding about a month ago so I'm still a greenhorn.

答:
WriteLine implicitly adds a newline to the end of the string. Write will not. Follow each step in each iteration of the two loops to find the bug. For the first iteration, when i is 1, you get:

```<code>*       <-- WriteLine (i == 1), adds a newline
*       <-- Write (i == 1, j == 1), does not add a newline! Next character will be printed after this * on the same line!
</code>```

Now follow what happens when i is 2:

```<code>*       <-- WriteLine (i == 1)
**      <-- Write (i == 1, j == 1), followed by WriteLine (i == 2) on the same line
**      <-- Write (i == 2, j == 1), followed by Write (i == 2, j == 2)
</code>```

Do you see where the bug is? You're printing the newline character in the middle of the current row; you should be printing it at the end of the row instead.

Body:
Here's my loop:

int height = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Printing a " + height + " by " + height + " right triangle...");

for (int i = 1; i <= height; i++)
{
    Console.WriteLine("*");
    for (int j = 1; j <= i; j++)
    {
        Console.Write("*");
    }

And here is the resulting print (program takes a user input for the height, this example has a height of 5:

*
**
***
****
****

As you can see, I can't get the last star to print on the last row. This makes absolutely no sense to me, as I've compared it to many other similar constructs and there appears to be no discrepancies between the one I've constructed and the ones others have made. I just started coding about a month ago so I'm still a greenhorn.

Body:
WriteLine implicitly adds a newline to the end of the string. Write will not. Follow each step in each iteration of the two loops to find the bug. For the first iteration, when i is 1, you get:

*       <-- WriteLine (i == 1), adds a newline
*       <-- Write (i == 1, j == 1), does not add a newline! Next character will be printed after this * on the same line!

Now follow what happens when i is 2:

*       <-- WriteLine (i == 1)
**      <-- Write (i == 1, j == 1), followed by WriteLine (i == 2) on the same line
**      <-- Write (i == 2, j == 1), followed by Write (i == 2, j == 2)

Do you see where the bug is? You're printing the newline character in the middle of the current row; you should be printing it at the end of the row instead.


问:
Read specific parts of File in java
I need to read a file with the following structure Structure of File

In the file I have firstly to separate the deps content and the outs content.

After that separation I need to separate the blocks that start with -md5 until I find another one.

For example, in the picture I have 2 blocks for the deps part and for the outs part I have 3 blocks.

Currently I am using LineNumberReader to firstly separate deps and outs and then I create an ArrayList of the deps content and the outs content, but I think this is not very good since I need to separate next the blocks that are started by -md5 in case I have more than one.

This is What I pretend

How can I do this in a better way?
Thanks for any help.

答:
The syntax of the file type you are trying to read is YAML, so if you need to parse the file and map it to an already defined class, you can use Jackson.

Then the mapping process is as simple as:

```<code>ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
        YourCustomClass obj = mapper.readValue(new File("YourFilePath.yaml"), YourCustomClass.class);
        System.out.println(obj.getProperty());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
</code>```

BTW, you can install Jackson using maven if you are using so.

Title: Read specific parts of File in java

Body:
The syntax of the file type you are trying to read is YAML, so if you need to parse the file and map it to an already defined class, you can use Jackson.

Then the mapping process is as simple as:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
try {
        YourCustomClass obj = mapper.readValue(new File("YourFilePath.yaml"), YourCustomClass.class);
        System.out.println(obj.getProperty());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

BTW, you can install Jackson using maven if you are using so.


问:
Crashes not showing in Crashlytics after migrating from Fabric
Until now, I've had a link between Fabric and Firebase Crashlytics, so prior to today, I had all of my app's crashes show up in Firebase Crashlytics.

Today, I decided to completely migrate from Fabric to Firebase by following Google's migration guide:

https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=android

I've followed it exactly, and have gone through it half a dozen times to make sure everything is correct. Yet, when I force a crash and check my Firebase Crashlytics, none of my dozen+ crashes are showing up:

https://i.stack.imgur.com/cNcv8.png

It's showing I have 77.78% crash-free users, but none of the crashes are actually showing up.

What am I missing? Why aren't the crashes showing up?

Edit:

I discovered that it shows crashes when using the debug build type, but it's not working for release. Any ideas?

Edit:

It looks like an issue with Proguard/R8. Tried a dozen different things but nothing seems to be helping. Possibly a dependency is affecting this?

答: Turns out that one of my other dependencies, https://github.com/ACRA/acra, was the culprit. Removing that dependency fixed my issues.</p>


问:
Unable to resolve “Error: Git server extension is unavailable.” for Pytorch jupyter notebook
After creating a new notebook instance(VM type: Pytorch 1.4), there is an internal error relating to the Git server extension when opened:

```<code>Internal Error:

Fail to get the server root path. Error: Git server extension is unavailable. Please ensure you have installed the JupyterLab Git server extension by running: pip install --upgrade jupyterlab-git. To confirm that the server extension is installed, run: jupyter serverextension list.
</code>```

This means I can't use the Git clone button which returns:

```<code>Clone failed:

JSON.parse: unexpected character at line 1 column 1 of the JSON data
</code>```

When i tried the command, jupyter serverextension list, i found that git extension is disabled.

```<code> jupyterlab_git disabled
    - Validating...
      jupyterlab_git 0.10.1 OK
</code>```

I tried both 'jupyter serverextension enable --py jupyterlab_git --sys-prefix' and 'pip install --upgrade jupyterlab-git' as suggested but that didn't seem to fix anything. Below is my notebook instance setup (if not specified it is the default):

```<code>Region: us-west1 (Oregon)

Zone: us-west1-a

Environment: PyTorch 1.4 (with Intel® MKL-DNN/MKL and CUDA 10.1)

Machine type: n1-standard-4 (4vCPUs, 15 GB RAM)

GPU type: NVIDIA Tesla T4

Number of GPUs: 1

✓ Install NVIDA GPU driver automatically for me
</code>```

Has this been occurring for others? I saw a similar post for TensorFlow VM(Unable to resolve "Error: Git server extension is unavailable." (Google Notebooks)) and wondering if it is the same scenario?

答:
As the link [1], this is a known issue and is solved in the newly released images (m47) [2]:

[1] Unable to resolve "Error: Git server extension is unavailable." (Google Notebooks)

[2] https://cloud.google.com/ai-platform/deep-learning-vm/docs/release-notes

Body:
After creating a new notebook instance(VM type: Pytorch 1.4), there is an internal error relating to the Git server extension when opened:

Internal Error:

Fail to get the server root path. Error: Git server extension is unavailable. Please ensure you have installed the JupyterLab Git server extension by running: pip install --upgrade jupyterlab-git. To confirm that the server extension is installed, run: jupyter serverextension list.

This means I can't use the Git clone button which returns:

Clone failed:

JSON.parse: unexpected character at line 1 column 1 of the JSON data

When i tried the command, jupyter serverextension list, i found that git extension is disabled.

 jupyterlab_git disabled
    - Validating...
      jupyterlab_git 0.10.1 OK

I tried both 'jupyter serverextension enable --py jupyterlab_git --sys-prefix' and 'pip install --upgrade jupyterlab-git' as suggested but that didn't seem to fix anything. Below is my notebook instance setup (if not specified it is the default):

Region: us-west1 (Oregon)

Zone: us-west1-a

Environment: PyTorch 1.4 (with Intel® MKL-DNN/MKL and CUDA 10.1)

Machine type: n1-standard-4 (4vCPUs, 15 GB RAM)

GPU type: NVIDIA Tesla T4

Number of GPUs: 1

✓ Install NVIDA GPU driver automatically for me

Has this been occurring for others? I saw a similar post for TensorFlow VM(Unable to resolve "Error: Git server extension is unavailable." (Google Notebooks)) and wondering if it is the same scenario?


问:
RXJS How do I use the result of one observable in another (and then process those two results together)
A very common problem when using RxJs seems to be to want the result of one or more observables to then use them in subsequent ones.

e.g. in pseudo-code (This is not rx or valid js syntax deliberately)

```<code>var someResult = $observable-A; // wait to complete
var finalResult = $observable-B(someResult.aValueINeed);
</code>```

This can be done in an ugly way where you could subscribe to both and call one inside the other.. however, this is very messy and doesn't afford you much flexibility.

e.g. (real syntax)

```<code>$observable-A.subscribe(resultA => {
    $observable-B(resultA.aValueINeed)
        .subscribe(resultB => {
            console.log('After everything completes: ', resultB);
        }
}
</code>```

This also means that nothing else can easily consume this stream as you're completing both of the observables.

My specific use case requires the following:

An initial call to get $observable-A as it doesn't require anything else (it's a basic http GET call)

An http GET call to another service that requires data from $observable-A, which returns $observable-B

Using both observable results (A + B) to create an object for my service (In my case, an Angular service) to return a single list.

I also need to be able to subscribe to this function inside my service, this is why going with the subscribe method above, won't work for me.

答:
Snorre Danielsen nailed this problem and full credit for this solution goes to him. I'd recommend having a look at this.

The great thing about rxjs operators is their interoperability. You can mix and match almost everything to get your desired outcome.

In short. The code answer to this question is below, and i'll explain it further.

```<code>$observable-A.pipe(
    mergeMap(resultA => {
        return combineLatest(
            of(resultA),
            $observable-B(resultA)
        )
    }),
    map(([resultA, resultB]) => {
        // you can do anything with both results here
        // we can also subscribe to this any number of times because we are doing all the processing with
        // pipes and not completing the observable
    }
)
</code>```

mergeMap (or flatMap which is an alias) takes an observable as an input and projects it (just like a regular map function). This means we can use its result as the input for $observable-B. Now this is great for when you actually want to only return the second observable result. e.g.

```<code>$observable-A.pipe(
    mergeMap(resultA => $observable-B(resultA)),
    map((resultB) => {
        // resultA doesn't exist here and we can only manipulate resultB
    }
)

</code>```

Now, back to the main solution. combineLatest is the key here. It allows the mergeMap to essentially "wait" for the internal observable ($observable-B) to complete.
Without it, you're just going to return an observable to your next rxjs operator in the pipe, which is not what we want (as you're expecting to deal with regular operator functions inside a pipe).

Because of this, we can take these new merged observables into the next part of the chain and use them together. We use the of() function to re-create resultA, as combineLatest only takes observables as inputs and resultA is a completed observable in this state.

A hint:
  Take a look at the map(([resultA, resultB]). The reason we use this notation to refer to our variables instead of the standard map(results). Is so we can directly reference them without using results[0] for resultA or results[1] for resultB. Its just a lot easier to read this way.

I hope this helps people out as I have yet to find a complete SO answer which covers this case. Edits are very welcome as its complicated and I'm sure its not a perfect answer.

Body:
A very common problem when using RxJs seems to be to want the result of one or more observables to then use them in subsequent ones.

e.g. in pseudo-code (This is not rx or valid js syntax deliberately)

var someResult = $observable-A; // wait to complete
var finalResult = $observable-B(someResult.aValueINeed);

This can be done in an ugly way where you could subscribe to both and call one inside the other.. however, this is very messy and doesn't afford you much flexibility.

e.g. (real syntax)

$observable-A.subscribe(resultA => {
    $observable-B(resultA.aValueINeed)
        .subscribe(resultB => {
            console.log('After everything completes: ', resultB);
        }
}

This also means that nothing else can easily consume this stream as you're completing both of the observables.

My specific use case requires the following:

An initial call to get $observable-A as it doesn't require anything else (it's a basic http GET call)

An http GET call to another service that requires data from $observable-A, which returns $observable-B

Using both observable results (A + B) to create an object for my service (In my case, an Angular service) to return a single list.

I also need to be able to subscribe to this function inside my service, this is why going with the subscribe method above, won't work for me.

Body:
Snorre Danielsen nailed this problem and full credit for this solution goes to him. I'd recommend having a look at this.

The great thing about rxjs operators is their interoperability. You can mix and match almost everything to get your desired outcome.

In short. The code answer to this question is below, and i'll explain it further.

$observable-A.pipe(
    mergeMap(resultA => {
        return combineLatest(
            of(resultA),
            $observable-B(resultA)
        )
    }),
    map(([resultA, resultB]) => {
        // you can do anything with both results here
        // we can also subscribe to this any number of times because we are doing all the processing with
        // pipes and not completing the observable
    }
)

mergeMap (or flatMap which is an alias) takes an observable as an input and projects it (just like a regular map function). This means we can use its result as the input for $observable-B. Now this is great for when you actually want to only return the second observable result. e.g.

$observable-A.pipe(
    mergeMap(resultA => $observable-B(resultA)),
    map((resultB) => {
        // resultA doesn't exist here and we can only manipulate resultB
    }
)

Now, back to the main solution. combineLatest is the key here. It allows the mergeMap to essentially "wait" for the internal observable ($observable-B) to complete.
Without it, you're just going to return an observable to your next rxjs operator in the pipe, which is not what we want (as you're expecting to deal with regular operator functions inside a pipe).

Because of this, we can take these new merged observables into the next part of the chain and use them together. We use the of() function to re-create resultA, as combineLatest only takes observables as inputs and resultA is a completed observable in this state.

A hint:
  Take a look at the map(([resultA, resultB]). The reason we use this notation to refer to our variables instead of the standard map(results). Is so we can directly reference them without using results[0] for resultA or results[1] for resultB. Its just a lot easier to read this way.

I hope this helps people out as I have yet to find a complete SO answer which covers this case. Edits are very welcome as its complicated and I'm sure its not a perfect answer.


问:
How to divide each column with a different number
I used the "table" function of R to summarize data and got the following result:

Summarized Data

Now, I want to divide all the numbers in the first column with 32, all the numbers in the second column with 51, and all the numbers in the third column with 54. Then these numbers will form a new 3*5 matrix, and I'll use the new matrix to continue to draw a barplot.

Does anyone here know how I can write the command in R?

答:
We can use col to replicate the vector of values to make the lengths same and then do the division

```<code>out/c(32, 51, 54)[col(out)]
</code>```

Or just transpose the output, do the division and transpose

```<code>t(t(out)/c(32, 51, 54))
</code>```

If we take a reproducible example

```<code>df1 <- mtcars[1:3, 1:3]

col(df1) # gives the column index
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    1    2    3
#[3,]    1    2    3
</code>```

In R, the indexing starts from 1. As these index are repeated, when we pass a vector of values equal to the total number of columns, each of the value gets replicated

```<code>v1 <- c(32, 51, 54)
v1[col(df1)]
#[1] 32 32 32 51 51 51 54 54 54
</code>```

The lengths are now the same

```<code>df1/v1[col(df1)]
#                  mpg        cyl     disp
#Mazda RX4     0.65625 0.11764706 2.962963
#Mazda RX4 Wag 0.65625 0.11764706 2.962963
#Datsun 710    0.71250 0.07843137 2.000000
</code>```

checking the output by individually dividing

```<code>df1[,1]/32
#[1] 0.65625 0.65625 0.71250
</code>```

For the second solution, by doing the transpose, we make use of the recycling

```<code>t(df1)/v1
#     Mazda RX4 Mazda RX4 Wag Datsun 710
#mpg  0.6562500     0.6562500 0.71250000
#cyl  0.1176471     0.1176471 0.07843137
#disp 2.9629630     2.9629630 2.00000000
</code>```

As the output is transposed, we do a second transpose to get the original data structure

Body:
We can use col to replicate the vector of values to make the lengths same and then do the division

out/c(32, 51, 54)[col(out)]

Or just transpose the output, do the division and transpose

t(t(out)/c(32, 51, 54))

If we take a reproducible example

df1 <- mtcars[1:3, 1:3]

col(df1) # gives the column index
#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]    1    2    3
#[3,]    1    2    3

In R, the indexing starts from 1. As these index are repeated, when we pass a vector of values equal to the total number of columns, each of the value gets replicated

v1 <- c(32, 51, 54)
v1[col(df1)]
#[1] 32 32 32 51 51 51 54 54 54

The lengths are now the same

df1/v1[col(df1)]
#                  mpg        cyl     disp
#Mazda RX4     0.65625 0.11764706 2.962963
#Mazda RX4 Wag 0.65625 0.11764706 2.962963
#Datsun 710    0.71250 0.07843137 2.000000

checking the output by individually dividing

df1[,1]/32
#[1] 0.65625 0.65625 0.71250

For the second solution, by doing the transpose, we make use of the recycling

t(df1)/v1
#     Mazda RX4 Mazda RX4 Wag Datsun 710
#mpg  0.6562500     0.6562500 0.71250000
#cyl  0.1176471     0.1176471 0.07843137
#disp 2.9629630     2.9629630 2.00000000

As the output is transposed, we do a second transpose to get the original data structure


问:
CountVectorizer takes too long to fit_transform
```<code>def tokenize(text):
    text = re.sub('[^a-zA-Z0-9]', ' ', text)
    words = word_tokenize(text)
    lemmatizer = WordNetLemmatizer()
    words = [lemmatizer.lemmatize(w.lower().strip()) for w in words if w not in stopwords.words()]
    return words

pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
#     ('tfidf', TfidfTransformer()),
#     ('clf', MultiOutputClassifier(RandomForestClassifier()))
])
</code>```

Given above code, CountVectorizer takes too long (ran for 60 minutes but it did not finished) to fit but if I remove line if w not in stopwords.words() it just take 5 minutes to fit, what could be problem and possible solution with this code. I am using stop words from nltk.corpus.

Note: tokenize function works fine, using separately for any text input.

Thank you

答:
My first guess is that the function stopwords.words() does some heavy job on each call.
Maybe, you could try caching it. The same is true for lemmatizer: calling the constructor only once can speed up the code significantly.

```<code>stop_set = set(stopwords.words())
lemmatizer = WordNetLemmatizer()

def tokenize(text):
    text = re.sub('[^a-zA-Z0-9]', ' ', text)
    words = word_tokenize(text)
    words = [lemmatizer.lemmatize(w.lower().strip()) for w in words if w not in stop_set]
    return words
</code>```

in my experience, it can help to cache even the lemmatization function, like

```<code>from functools import lru_cache

stop_set = set(stopwords.words())
lemmatizer = WordNetLemmatizer()

@lru_cache(maxsize=10000)
def lemmatize(word):
    return lemmatizer.lemmatize(w.lower().strip())

def tokenize(text):
    text = re.sub('[^a-zA-Z0-9]+', ' ', text)
    words = [lemmatize(w) for w in word_tokenize(text)]
    return [w for w in words if w not in stop_set]
</code>```

Body:
def tokenize(text):
    text = re.sub('[^a-zA-Z0-9]', ' ', text)
    words = word_tokenize(text)
    lemmatizer = WordNetLemmatizer()
    words = [lemmatizer.lemmatize(w.lower().strip()) for w in words if w not in stopwords.words()]
    return words

pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
#     ('tfidf', TfidfTransformer()),
#     ('clf', MultiOutputClassifier(RandomForestClassifier()))
])

Given above code, CountVectorizer takes too long (ran for 60 minutes but it did not finished) to fit but if I remove line if w not in stopwords.words() it just take 5 minutes to fit, what could be problem and possible solution with this code. I am using stop words from nltk.corpus.

Note: tokenize function works fine, using separately for any text input.

Thank you

Body:
My first guess is that the function stopwords.words() does some heavy job on each call.
Maybe, you could try caching it. The same is true for lemmatizer: calling the constructor only once can speed up the code significantly.

stop_set = set(stopwords.words())
lemmatizer = WordNetLemmatizer()

def tokenize(text):
    text = re.sub('[^a-zA-Z0-9]', ' ', text)
    words = word_tokenize(text)
    words = [lemmatizer.lemmatize(w.lower().strip()) for w in words if w not in stop_set]
    return words

in my experience, it can help to cache even the lemmatization function, like

from functools import lru_cache

stop_set = set(stopwords.words())
lemmatizer = WordNetLemmatizer()

@lru_cache(maxsize=10000)
def lemmatize(word):
    return lemmatizer.lemmatize(w.lower().strip())

def tokenize(text):
    text = re.sub('[^a-zA-Z0-9]+', ' ', text)
    words = [lemmatize(w) for w in word_tokenize(text)]
    return [w for w in words if w not in stop_set]