问:
ASP.NET C# Creating checkboxes from DataTable
I am new to ASP.NET, but I need to create checkboxes from a query result.  So far here is what I have.

In my code behind...I pull the query that I need and then create a DataTable from that result like so:

```<code>DataTable dtLocations = new DataTable();
        dtLocations.Columns.Add("ID");
        dtLocations.Columns.Add("VALUE");
        // Pull locations and add to our datatable
        string strConnection = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
        using (SqlConnection dbConn = new SqlConnection(strConnection))
        {
            SqlDataAdapter dbAdapter = new SqlDataAdapter();
            SqlCommand dbCommand = new SqlCommand();
            dbConn.Open();
            dbCommand.CommandText = @"SELECT location_id, location_desc FROM admin_locations WHERE enabled = 'Y'";
            dbCommand.Connection = dbConn;
            SqlDataReader dbReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (dbReader.HasRows) {
                while (dbReader.Read()) {
                    dtLocations.Rows.Add(new object[] { dbReader["location_id"].ToString(), dbReader["location_desc"].ToString() });
                }
            }
        }
        return dtLocations;
</code>```

I then have a class level var defined as

```<code>public DataTable dtLocations = new DataTable();
</code>```

which I populate using the method above in my Page_Load

```<code>protected void Page_Load(object sender, EventArgs e)
{
    if (!(IsPostBack))
    {
        dtLocations = createLocationsDataTable();
    }
}
</code>```

Then in my aspx file (not code behind) I'm doing this to try and create the checkboxes, which needless to say, does not work.

```<code><% foreach (DataRow row in dtLocations.Rows) {%>
                                    <asp:CheckBox ID="idLocationChk" runat="server" Value="<% Response.Write(row["ID"].ToString()); %>" />
                                <% } %>
</code>```

Can someone show me how you're supposed to do this in ASP.NET c#?  I'll also need to be able to get the value of any that are checked in my code behind when a button on the page is clicked.

When I try using a CheckBoxList like this it tells me I can not use codeblocks here.

```<code><asp:CheckBoxList ID="message_locations" runat="server">
                                <% foreach (DataRow row in dtLocations.Rows) {%>
                                    <asp:ListItem>TEST</asp:ListItem>
                                <% } %>
                                </asp:CheckBoxList>
</code>```

答:
You can bind a DataTable directly to a CheckBoxList</p>

```<code>if (!IsPostBack)
{
    CheckBoxList1.DataSource = dtLocations;
    CheckBoxList1.DataTextField = "location_desc";
    CheckBoxList1.DataValueField = "location_id";
    CheckBoxList1.DataBind();
}
</code>```

Body:
I am new to ASP.NET, but I need to create checkboxes from a query result.  So far here is what I have.

In my code behind...I pull the query that I need and then create a DataTable from that result like so:

DataTable dtLocations = new DataTable();
        dtLocations.Columns.Add("ID");
        dtLocations.Columns.Add("VALUE");
        // Pull locations and add to our datatable
        string strConnection = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
        using (SqlConnection dbConn = new SqlConnection(strConnection))
        {
            SqlDataAdapter dbAdapter = new SqlDataAdapter();
            SqlCommand dbCommand = new SqlCommand();
            dbConn.Open();
            dbCommand.CommandText = @"SELECT location_id, location_desc FROM admin_locations WHERE enabled = 'Y'";
            dbCommand.Connection = dbConn;
            SqlDataReader dbReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (dbReader.HasRows) {
                while (dbReader.Read()) {
                    dtLocations.Rows.Add(new object[] { dbReader["location_id"].ToString(), dbReader["location_desc"].ToString() });
                }
            }
        }
        return dtLocations;

I then have a class level var defined as

public DataTable dtLocations = new DataTable();

which I populate using the method above in my Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (!(IsPostBack))
    {
        dtLocations = createLocationsDataTable();
    }
}

Then in my aspx file (not code behind) I'm doing this to try and create the checkboxes, which needless to say, does not work.

<% foreach (DataRow row in dtLocations.Rows) {%>
                                    <asp:CheckBox ID="idLocationChk" runat="server" Value="<% Response.Write(row["ID"].ToString()); %>" />
                                <% } %>

Can someone show me how you're supposed to do this in ASP.NET c#?  I'll also need to be able to get the value of any that are checked in my code behind when a button on the page is clicked.

When I try using a CheckBoxList like this it tells me I can not use codeblocks here.

<asp:CheckBoxList ID="message_locations" runat="server">
                                <% foreach (DataRow row in dtLocations.Rows) {%>
                                    <asp:ListItem>TEST</asp:ListItem>
                                <% } %>
                                </asp:CheckBoxList>

Body:
You can bind a DataTable directly to a CheckBoxList

if (!IsPostBack)
{
    CheckBoxList1.DataSource = dtLocations;
    CheckBoxList1.DataTextField = "location_desc";
    CheckBoxList1.DataValueField = "location_id";
    CheckBoxList1.DataBind();
}


来源: stackexchange

问:
Returning a 4D array from a function in MATLAB
I am trying to return a 4D array of image data from a function call in MATLAB. I'm not very advanced in MATLAB and I don't know what type of data I have to return from the function. Here is my function:

```<code>function classimg = loadImages(classdir,ext)
    % create array of all images in directory
    neg = dir([classdir ext]);
    % get size of array (to loop through images)
    numFileNeg = max(size(neg));
    % create a 4D array to store our images
    classimg = zeros(51,51,3,numFileNeg);
    % loop through directory
    for i=1:numFileNeg
        classimg(:,:,:,i) = imread([myDir neg(i).name]);
    end
end
</code>```

Here is the function call:

```<code>negativeImgs = loadImages("C:\Users\example\Documents\TrainingImages\negatives\","*.jpg");
</code>```

I cannot find any online documentation for the return type? Does anyone know what this would be? classimg is populated correctly so the code inner works.

答: You initialize classimg to be a 51x51x3xnumFileNeg matrix of zeros.  You use the zeros function, so the datatype is double.  To see this clearly, call your function from the command window, and then type "whos" to see both the size and datatype of classimg.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to return a 4D array of image data from a function call in MATLAB. I'm not very advanced in MATLAB and I don't know what type of data I have to return from the function. Here is my function:

function classimg = loadImages(classdir,ext)
    % create array of all images in directory
    neg = dir([classdir ext]);
    % get size of array (to loop through images)
    numFileNeg = max(size(neg));
    % create a 4D array to store our images
    classimg = zeros(51,51,3,numFileNeg);
    % loop through directory
    for i=1:numFileNeg
        classimg(:,:,:,i) = imread([myDir neg(i).name]);
    end
end

Here is the function call:

negativeImgs = loadImages("C:\Users\example\Documents\TrainingImages\negatives\","*.jpg");

I cannot find any online documentation for the return type? Does anyone know what this would be? classimg is populated correctly so the code inner works.


问:
css: inset shadow around of an arrow
I design an arrow top of an ul box menu like this picture:

You can see, I set a border around of box:

```<code>border: .1rem solid rgba(228,234,248,.5);
</code>```

but Is there a way to set a border around of arrow?

```<code>.mega-dropdown-menu:before {
    content: "";
    border-bottom: 8px solid #fbfbfb;
    border-right: 9px solid transparent;
    border-left: 9px solid transparent;
    position: absolute;
    top: -7px;
    left: 13.1rem;
    z-index: 10;
}
</code>```

答:
Well, no ways to set a border around the arrow as the triangle you made is itself a border. But there's a solution, you can overlay the triangles on each other like, this will give you a border effect around your triangle.

div {
  position: relative;
  /* make sure you use this else your elements will fly in the wild */
}

div:before {
  content: "";
  border-bottom: 10px solid #aaa;
  border-right: 11px solid transparent;
  border-left: 11px solid transparent;
  position: absolute;
  left: -2px;
  top: -2px;
}

div:after {
  content: "";
  border-bottom: 8px solid #ddd;
  border-right: 9px solid transparent;
  border-left: 9px solid transparent;
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Title: css: inset shadow around of an arrow

Body:
I design an arrow top of an ul box menu like this picture:

You can see, I set a border around of box:

border: .1rem solid rgba(228,234,248,.5);

but Is there a way to set a border around of arrow?

.mega-dropdown-menu:before {
    content: "";
    border-bottom: 8px solid #fbfbfb;
    border-right: 9px solid transparent;
    border-left: 9px solid transparent;
    position: absolute;
    top: -7px;
    left: 13.1rem;
    z-index: 10;
}

Body:
Well, no ways to set a border around the arrow as the triangle you made is itself a border. But there's a solution, you can overlay the triangles on each other like, this will give you a border effect around your triangle.

div {
  position: relative;
  /* make sure you use this else your elements will fly in the wild */
}

div:before {
  content: "";
  border-bottom: 10px solid #aaa;
  border-right: 11px solid transparent;
  border-left: 11px solid transparent;
  position: absolute;
  left: -2px;
  top: -2px;
}

div:after {
  content: "";
  border-bottom: 8px solid #ddd;
  border-right: 9px solid transparent;
  border-left: 9px solid transparent;
  position: absolute;
}

<div></div>


问:
Pushing Response From Axios Call To Firebase - Vue.js
I am doing an axios call to an api and am getting the desired response. However, I now need to take that response and push it up into my firebase firestore. I know how to push into the firestore, but I can't seem to access the data correctly from the axios call to push. Here is my code:

```<code>axios.get('https://somewhereontheweb.com/api/getgames', {
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + token,
          }
        })
          .then(response => {
            this.games = response.data;

            // push data into firestore?
          })
          .catch(function (error) {
            console.log(error);
          });
</code>```

I get a json array back from the api and can display it on my vue page (at this point it is an object) (so {{games}}). However, I am needing to take that data, iterate over it and in each iterations push the game data into firestore. Can you explain how to do that? I can write the code to push into firestore, but I can't write the code to iterate over the response from the axios call to push into firebase. I have been trying but am not getting anywhere. Any hint is great.

Thanks!

答:
As it is a JSON string you are a getting then you can use something like this to iterate over it to manipulate it into the data structure you want: </p>

```<code>for(var i in response.data){
  response.data[i].dosomething()
}
</code>```

<p>Also, might be a good idea to pass the iteration to a helper function with a promise that ends in sending it to Firestore. </p>

Body:
I am doing an axios call to an api and am getting the desired response. However, I now need to take that response and push it up into my firebase firestore. I know how to push into the firestore, but I can't seem to access the data correctly from the axios call to push. Here is my code:

axios.get('https://somewhereontheweb.com/api/getgames', {
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'Bearer ' + token,
          }
        })
          .then(response => {
            this.games = response.data;

            // push data into firestore?
          })
          .catch(function (error) {
            console.log(error);
          });

I get a json array back from the api and can display it on my vue page (at this point it is an object) (so {{games}}). However, I am needing to take that data, iterate over it and in each iterations push the game data into firestore. Can you explain how to do that? I can write the code to push into firestore, but I can't write the code to iterate over the response from the axios call to push into firebase. I have been trying but am not getting anywhere. Any hint is great.

Thanks!

Body:
As it is a JSON string you are a getting then you can use something like this to iterate over it to manipulate it into the data structure you want:

for(var i in response.data){
  response.data[i].dosomething()
}

Also, might be a good idea to pass the iteration to a helper function with a promise that ends in sending it to Firestore.


问:
HTML Button contain two names
I am trying to make the button in my form contain two names. Let me explain.

I have 2 buttons, the first one has a value of 1, and the other one has a value of 2. They are both connected to the post method "Click". But I need my "$pos = $_POST['position']" to become the value of the button. Is that possible?

What I tried was <button name="click" name="position" type="submit"> but it's not working

答:
No element can have two attributes with the same name (i.e. you cannot have two attributes named name on one element). Some attributes take a space-separated list of values, but name is not one of them.

Pick either click or position to be the name of the button, and change your server-side code so that it recognises data with that name as representing both pieces of information that you were trying to convey.

You'll probably want to add a value attribute too.

Title: HTML Button contain two names


问:
Transparent stage, solid attributes javafx
I'm trying to create a javafx application (in scenebuilder).

How to get transparent stage, with solid items (buttons etc) on it? As it is done in Windows 10 calculator. The buttons are solid but the rest of the pane is transparent.

Thanks in advance.

答:
To do that, first, you need to put the scene in a transparent Stage :

```<code>myStage.initStyle(StageStyle.TRANSPARENT);
</code>```

Be aware: if you do this, you need to use your own exit button, minimize buttons, because the titlebar will be gone.

Then, change the alpha channel of your scene to your desired, say 0.5:

```<code>scene.setFill(Color.rgb(0,26,0,0.5));
</code>```

and finally, the root node's Background needs to be empty:

```<code>root.setBackground(Background.EMPTY);
</code>```

You are done. Now you can change the translucency of your application through the alpha variable.

Body:
To do that, first, you need to put the scene in a transparent Stage :

myStage.initStyle(StageStyle.TRANSPARENT);

Be aware: if you do this, you need to use your own exit button, minimize buttons, because the titlebar will be gone.

Then, change the alpha channel of your scene to your desired, say 0.5:

scene.setFill(Color.rgb(0,26,0,0.5));

and finally, the root node's Background needs to be empty:

root.setBackground(Background.EMPTY);

You are done. Now you can change the translucency of your application through the alpha variable.


问:
Convert string of tab seperated data into list of objects in C#
I am facing hard time converting below string of input in C#. As you can see, the string of input are each in a new line seperated by \r\n. And each input data in one line is seperated by \t

I need to delete the lines which start with '!'

```<code>!710889\tF\t3400\r\n
BY\tF\t5000\r\n
G1\tC\t600\r\n
</code>```

So Valid input file would be

```<code>BY\tF\t5000\r\n
G1\tC\t600\r\n
</code>```

I need to convert this into following

```<code>Object {Info: Array[3]}
 > Info: Array[3]
 >[0]: Object
       id: 'BY'
       type: 'F'
       value: 3400
 >[1]: Object
       id: 'G1'
       type: 'C'
       value: 600
</code>```

Following thing was tried but no success

```<code> string[] values = str.Split("\t".ToCharArray());
 // ... do something with "values" ...
 xxx.aaa = values[0];
 xxx.bbb = values[1];
 xxx.ccc = values[2];
</code>```

It didnt list all the elements as i wanted. Can someone please shed some light here

答:
Take baby steps, and things get easier:

Get an enumeration of lines from the input string:

```<code>var lines = input.Split(new[] { Environment.NewLine },
                        StringSplitOptions.RemoveEmptyEntries);
</code>```

Filter out those you don't need:

```<code>var validLines = lines.Where(s => !s.StartsWith('!'));
</code>```

Split each valid line into your object fields and build a ValueTuple with the data:

```<code>foreach (var line in validLines)
{
    var fields = line.Split('\t');
    yield return ( fields[0],
                   fields[1],
                   int.Parse(fields[2]) };
}
</code>```

Note I've used C#7 native tuple support. If you are not using C#7, you'll have to change the code slightly. Anyway, putting everything together:

```<code>static IEnumerable<(string Id, string Type, int Value)>
    ParseData(string input)
{
    var lines = input.Split(new[] { Environment.NewLine },
                            StringSplitOptions.RemoveEmptyEntries);
    var validLines = lines.Where(s => !s.StartsWith('!'));

    foreach (var line in validLines)
    {
        var fields = line.Split('\t');
        yield return ( fields[0],
                       fields[1],
                       int.Parse(fields[2]));
    }
}
</code>```

I've obviously omitted any error checking or data validation. I'll leave that to you, but there are a lot of things that can go wrong in the code above: field count is not 3, parsing field[2] fails, etc.

Body:
I am facing hard time converting below string of input in C#. As you can see, the string of input are each in a new line seperated by \r\n. And each input data in one line is seperated by \t

I need to delete the lines which start with '!'

!710889\tF\t3400\r\n
BY\tF\t5000\r\n
G1\tC\t600\r\n

So Valid input file would be

BY\tF\t5000\r\n
G1\tC\t600\r\n

I need to convert this into following

Object {Info: Array[3]}
 > Info: Array[3]
 >[0]: Object
       id: 'BY'
       type: 'F'
       value: 3400
 >[1]: Object
       id: 'G1'
       type: 'C'
       value: 600

Following thing was tried but no success

 string[] values = str.Split("\t".ToCharArray());
 // ... do something with "values" ...
 xxx.aaa = values[0];
 xxx.bbb = values[1];
 xxx.ccc = values[2];

It didnt list all the elements as i wanted. Can someone please shed some light here

Body:
Take baby steps, and things get easier:

Get an enumeration of lines from the input string:

var lines = input.Split(new[] { Environment.NewLine },
                        StringSplitOptions.RemoveEmptyEntries);

Filter out those you don't need:

var validLines = lines.Where(s => !s.StartsWith('!'));

Split each valid line into your object fields and build a ValueTuple with the data:

foreach (var line in validLines)
{
    var fields = line.Split('\t');
    yield return ( fields[0],
                   fields[1],
                   int.Parse(fields[2]) };
}

Note I've used C#7 native tuple support. If you are not using C#7, you'll have to change the code slightly. Anyway, putting everything together:

static IEnumerable<(string Id, string Type, int Value)>
    ParseData(string input)
{
    var lines = input.Split(new[] { Environment.NewLine },
                            StringSplitOptions.RemoveEmptyEntries);
    var validLines = lines.Where(s => !s.StartsWith('!'));

    foreach (var line in validLines)
    {
        var fields = line.Split('\t');
        yield return ( fields[0],
                       fields[1],
                       int.Parse(fields[2]));
    }
}

I've obviously omitted any error checking or data validation. I'll leave that to you, but there are a lot of things that can go wrong in the code above: field count is not 3, parsing field[2] fails, etc.


问:
Need help creating a specific pointcut inside of a method
I started with an original question on
Need help creating a specific pointcut that utilizes a value from a method annotation

I decided I wanted to ask another question to change the approach I was taking.
I have a method (navigation), that has a call inside of that method to another method which I would like to have @Around advice.

```<code>@RequestMapping(method = RequestMethod.GET)
public String navigation(ModelMap model) {
    ...
            // Call Auto Handling
            logger.info("Call AutoHandling");
            this.processAutoHandling(callSession, FunctionalArea.PRE_MAIN_MENU);
        }
        ...

    return forward(returnView);
}
</code>```

Is this possible as I cannot seem to get this to work if the method is inside of the same class.

This work if it was not on the object itself:

```<code>@Around("execution(* *.processAutoHandling(..)) &&" +
        "args(callSession, functionalArea) && " +
        "args(functionalArea) && " +
        "target(bean)"
)
public Object processAutoHandlingCall2(ProceedingJoinPoint jp,
                                      CallSession callSession,
                                      FunctionalArea functionalArea,
                                      Object bean)
        throws Throwable {
    logger.debug("processAutoHandleCall");
    return jp.proceed();
}
</code>```

With this call in my controller:

```<code>autoHandlingComponent.processAutoHandling(callSession, FunctionalArea.PRE_MAIN_MENU);
</code>```

instead of

```<code>this.processAutoHandling(callSession, FunctionalArea.PRE_MAIN_MENU);
</code>```

答:
It seems that you are using Spring's proxy-based AOP. If so, this is a known limitation. See Understanding AOP Proxies from Spring documentation for more details. You have two ways to solve this issue:

Use the AopContext.currentProxy() approach outlined in the documentation. I will discourage this approach, since your code will now be tied to Spring AOP quite explicitly.

Use AspectJ's byte-code weaving. Since there is no proxy involved with it, you won't have the issue with 'this' pointing to original object and proxy is transparently available only to external objects.

ContentLicense: CC BY-SA 2.5

Body:
I started with an original question on
Need help creating a specific pointcut that utilizes a value from a method annotation

I decided I wanted to ask another question to change the approach I was taking.
I have a method (navigation), that has a call inside of that method to another method which I would like to have @Around advice.

@RequestMapping(method = RequestMethod.GET)
public String navigation(ModelMap model) {
    ...
            // Call Auto Handling
            logger.info("Call AutoHandling");
            this.processAutoHandling(callSession, FunctionalArea.PRE_MAIN_MENU);
        }
        ...

    return forward(returnView);
}

Is this possible as I cannot seem to get this to work if the method is inside of the same class.

This work if it was not on the object itself:

@Around("execution(* *.processAutoHandling(..)) &&" +
        "args(callSession, functionalArea) && " +
        "args(functionalArea) && " +
        "target(bean)"
)
public Object processAutoHandlingCall2(ProceedingJoinPoint jp,
                                      CallSession callSession,
                                      FunctionalArea functionalArea,
                                      Object bean)
        throws Throwable {
    logger.debug("processAutoHandleCall");
    return jp.proceed();
}

With this call in my controller:

autoHandlingComponent.processAutoHandling(callSession, FunctionalArea.PRE_MAIN_MENU);

instead of

this.processAutoHandling(callSession, FunctionalArea.PRE_MAIN_MENU);


问:
INNER JOIN in DJANGO PROJECT (SELECT-RELATED)
I would like to know how run this sql code in django project:

```<code>> SELECT * FROM COLETA INNER JOIN TRANSDUTOR ON COLETA.id_transdutor =
> TRANSDUTOR.id_transdutor INNER JOIN USER ON TRANSDUTOR.id_user =
> USER.id_user
</code>```

Note that I have 3 tables (COLETA, TRANSDUTOR, USER), and I want to relate them through your foreign keys.

The USER table has a one to many relationship with TRANSDUTOR table and the TRANSDUTOR table has a one to many relationship with COLETA table.

I saw something about SELECT-RELATED to Django, does anyone know how to use this?

models.py:

```<code>class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    is_staff = models.BooleanField(_('staff'), default=True)
    avatar = models.ImageField(upload_to='dashboard/static/avatars/', null=True, blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        '''
        Returns the first_name plus the last_name, with a space in between.
        '''
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        '''
        Returns the short name for the user.
        '''
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        '''
        Sends an email to this User.
        '''
        send_mail(subject, message, from_email, [self.email], **kwargs)

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class Concessionaria(models.Model):
    nome = models.CharField(max_length=255)
    hp_inicio = models.DateTimeField('hp inicio')
    hp_fim = models.DateTimeField('hp fim')
    def __str__(self):
        return self.nome

class Cliente_has_concessionaria(models.Model):
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)
    id_concessionaria = models.ForeignKey(Concessionaria, on_delete=models.CASCADE)

class Classificacao(models.Model):
    nome = models.CharField(max_length=255)
    id_concessionaria = models.ForeignKey(Concessionaria, on_delete=models.CASCADE)

    def __str__(self):
        return self.nome

class Transdutor(models.Model):
    data_instalacao = models.DateTimeField('Data instalacao')
    numero_serie = models.CharField(max_length=255)
    chave_api = models.CharField(max_length=25, default='', blank=False) #T TODO: precisamos verificar se KEY cadastrado existe em algum equipamento
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)
    id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE)
    parametro_a = models.FloatField(max_length=255, null=True)
    parametro_b = models.FloatField(max_length=255, null=True)
    hora_ponto_inicio = models.TimeField('Hora inicio')
    hora_ponto_fim = models.TimeField('Hora fim')
    nome_io6 = models.CharField(max_length=255)
    nome_io7 = models.CharField(max_length=255, blank=True)
    nome_io8 = models.CharField(max_length=255, blank=True)
    nome_io9 = models.CharField(max_length=255, blank=True)
    nome_io10 = models.CharField(max_length=255, blank=True)
    nome_io11 = models.CharField(max_length=255, blank=True)
    nome_io12 = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return (self.chave_api)

class Servico(models.Model):
    descricao = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)
    id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE)

    def __str__(self):
        return self.descricao

class Coleta(models.Model):
    data_leitura = models.DateTimeField(null=True)  # TODO: MUdar isso depois
    io6 = models.FloatField(max_length=255, null=True)
    calculo_io6 = models.FloatField(max_length=255, null=True)
    media_io6 = models.FloatField(max_length=255, null=True)
    io7 = models.FloatField(max_length=255, null=True)
    calculo_io7 = models.FloatField(max_length=255, null=True)
    media_io7 = models.FloatField(max_length=255, null=True)
    io8 = models.FloatField(max_length=255, null=True)
    calculo_io8 = models.FloatField(max_length=255, null=True)
    media_io8 = models.FloatField(max_length=255, null=True)
    io9 = models.FloatField(max_length=255, null=True)
    io10 = models.FloatField(max_length=255, null=True)
    io11 = models.FloatField(max_length=255, null=True)
    io12 = models.FloatField(max_length=255, null=True)
    parametro_a = models.FloatField(max_length=255, null=True)
    parametro_b = models.FloatField(max_length=255, null=True)
    id_transdutor = models.ForeignKey(Transdutor, on_delete=models.CASCADE, null=True)

class Conta_contrato(models.Model):
    conta_contrato = models.CharField(max_length=255)
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)

class Imposto(models.Model):
    nome = models.CharField(max_length=255)
    estado = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)

    def __str__(self):
        return self.nome

class Constante(models.Model):
    nome = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)

    def __str__(self):
        return self.nome
</code>```

views.py:

```<code>def my_custom_bad_request_view(request):
    return render(request, '400.html', )

def my_custom_permission_denied_view(request):
    return render(request, '403.html', )

def my_custom_page_not_found_view(request):
    return render(request, '404.html', )

def my_custom_error_view(request):
    return render(request, '500.html', )

def index(request):
    return render(request, 'dashboard/index.html')

def do_change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('change_password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'dashboard/change_password.html', {
        'form': form
    })

@login_required
def graficos(request):
    current_user = request.user
    first_name = User.objects.values_list('first_name', flat=True).filter(pk=current_user.id)
    last_name = User.objects.values_list('last_name', flat=True).filter(pk=current_user.id)
    date_joined = User.objects.values_list('date_joined', flat=True).filter(pk=current_user.id)
    context = {
        'last_name': last_name,
        'first_name': first_name,
        'date_joined': date_joined,
    }
    return render(request, 'dashboard/graficos.html', context)

def printa(request):

    coletas = Coleta.objects.all().order_by('-id')
    transdutores = Transdutor.objects.filter(id_cliente=request.user.id)
    io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(id_cliente=request.user.id)
    io7_name = Transdutor.objects.values_list('nome_io7', flat=True).filter(id_cliente=request.user.id)
    io8_name = Transdutor.objects.values_list('nome_io8', flat=True).filter(id_cliente=request.user.id)

    parametros = Transdutor.objects.all().filter(id_cliente=request.user.id).order_by('-id')
    parametro_a = Transdutor.objects.values_list('parametro_a', flat=True).filter(id_cliente=request.user.id).order_by('-id').first()
    parametro_b = Transdutor.objects.values_list('parametro_b', flat=True).filter(id_cliente=request.user.id).order_by('-id').first()

    data = Coleta.objects.values_list('data_leitura', flat=True).filter(id_transdutor=1).order_by('-id')[:10]
    context = {

        'coletas': coletas,
        'transdutores': transdutores,
        'io6_name': io6_name,
        'io7_name': io7_name,
        'io8_name': io8_name,
        'parametro_a': parametro_a,
        'parametro_b': parametro_b,
        'data': data,
    }
    return render(request, 'dashboard/print.html', context)

def do_login(request):
    if request.method == 'GET':
        if request.user.is_authenticated():
            return render(request, 'dashboard/graficos.html')

    if request.method == 'POST':
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            if request.POST.get('lembrar', None) is not None:
                request.session.set_expiry(
                    60 * 60 * 24 * 30 * 12)  # Se selecionar o "lembrar-me" ficará logado por 1 ano
            login(request, user)
            return redirect('/graficos')
    return render(request, 'dashboard/login.html')

def do_logout(request):
    # return render(request, 'dashboard/logout.html')
    logout(request)
    return redirect('/login')

def consumo_mensal(request, *args, **kargs):
    mes = request.GET['mes']  # TODO: avaliar a forma como isso ta sendo feito
    dados = []
    transdutores = Transdutor.objects.filter(id_cliente=request.user.id)
    for t in transdutores:
        coletas = Coleta.objects.filter(id_transdutor_id=t.id, data_leitura__month=mes).order_by('data_leitura')
        for c in coletas:
            # soma os valores dos canais
            valores = [float(c.io6), float(c.io7), float(c.io8), float(c.io9), float(c.io10), float(c.io11),
                       float(c.io12)]
            soma = sum(valores)
            dia = int(c.data_leitura.day)
            adicionado = False
            for dado in dados:
                if dado['Dia'] == dia:
                    novo_valor = float(dado['Consumo']) + soma
                    dado['Consumo'] = "%.4f" % novo_valor
                    adicionado = True

            if not adicionado:
                dados.append({'Dia': dia, 'Consumo': "%.4f" % soma})

    return JsonResponse(dados, safe=False)

def consumo_mensal_por_setores(request, *args, **kargs):
    #io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(chave_api="hab0001")
    data2 = [
        {'value': 2554, 'label': 'Industria'},
        {'value': 242, 'label': 'Oficina'},
        {'value': 3233, 'label': 'Suprimento'},
        {'value': 122, 'label': 'Outros Departamentos'}
    ]
    return JsonResponse(data2, safe=False)

def gasto_mensal(request, *args, **kargs):
    data3 = [
        {'Dia': '01', 'Valor': 51333},
        {'Dia': '02', 'Valor': 30222},
        {'Dia': '03', 'Valor': 20442},
        {'Dia': '04', 'Valor': 20123},
        {'Dia': '05', 'Valor': 32333},
        {'Dia': '06', 'Valor': 44963},
    ]
    return JsonResponse(data3, safe=False)

def gasto_mensal_por_setores(request, *args, **kargs):
    data = [
        {'value': 12.22, 'label': 'Industria'},
        {'value': 15.32, 'label': 'Oficina'},
        {'value': 12.12, 'label': 'Suprimento'},
        {'value': 51.30, 'label': 'Outros Departamentos'}
    ]
    return JsonResponse(data, safe=False)
</code>```

Thanks guys.

答:
This is easier than you think. in Django.
Note that to these links. please

many to many in django model

and

many to one in django model

Body:
I would like to know how run this sql code in django project:

> SELECT * FROM COLETA INNER JOIN TRANSDUTOR ON COLETA.id_transdutor =
> TRANSDUTOR.id_transdutor INNER JOIN USER ON TRANSDUTOR.id_user =
> USER.id_user

Note that I have 3 tables (COLETA, TRANSDUTOR, USER), and I want to relate them through your foreign keys.

The USER table has a one to many relationship with TRANSDUTOR table and the TRANSDUTOR table has a one to many relationship with COLETA table.

I saw something about SELECT-RELATED to Django, does anyone know how to use this?

models.py:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    is_staff = models.BooleanField(_('staff'), default=True)
    avatar = models.ImageField(upload_to='dashboard/static/avatars/', null=True, blank=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        '''
        Returns the first_name plus the last_name, with a space in between.
        '''
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        '''
        Returns the short name for the user.
        '''
        return self.first_name

    def email_user(self, subject, message, from_email=None, **kwargs):
        '''
        Sends an email to this User.
        '''
        send_mail(subject, message, from_email, [self.email], **kwargs)

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

class Concessionaria(models.Model):
    nome = models.CharField(max_length=255)
    hp_inicio = models.DateTimeField('hp inicio')
    hp_fim = models.DateTimeField('hp fim')
    def __str__(self):
        return self.nome

class Cliente_has_concessionaria(models.Model):
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)
    id_concessionaria = models.ForeignKey(Concessionaria, on_delete=models.CASCADE)

class Classificacao(models.Model):
    nome = models.CharField(max_length=255)
    id_concessionaria = models.ForeignKey(Concessionaria, on_delete=models.CASCADE)

    def __str__(self):
        return self.nome

class Transdutor(models.Model):
    data_instalacao = models.DateTimeField('Data instalacao')
    numero_serie = models.CharField(max_length=255)
    chave_api = models.CharField(max_length=25, default='', blank=False) #T TODO: precisamos verificar se KEY cadastrado existe em algum equipamento
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)
    id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE)
    parametro_a = models.FloatField(max_length=255, null=True)
    parametro_b = models.FloatField(max_length=255, null=True)
    hora_ponto_inicio = models.TimeField('Hora inicio')
    hora_ponto_fim = models.TimeField('Hora fim')
    nome_io6 = models.CharField(max_length=255)
    nome_io7 = models.CharField(max_length=255, blank=True)
    nome_io8 = models.CharField(max_length=255, blank=True)
    nome_io9 = models.CharField(max_length=255, blank=True)
    nome_io10 = models.CharField(max_length=255, blank=True)
    nome_io11 = models.CharField(max_length=255, blank=True)
    nome_io12 = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return (self.chave_api)

class Servico(models.Model):
    descricao = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)
    id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE)

    def __str__(self):
        return self.descricao

class Coleta(models.Model):
    data_leitura = models.DateTimeField(null=True)  # TODO: MUdar isso depois
    io6 = models.FloatField(max_length=255, null=True)
    calculo_io6 = models.FloatField(max_length=255, null=True)
    media_io6 = models.FloatField(max_length=255, null=True)
    io7 = models.FloatField(max_length=255, null=True)
    calculo_io7 = models.FloatField(max_length=255, null=True)
    media_io7 = models.FloatField(max_length=255, null=True)
    io8 = models.FloatField(max_length=255, null=True)
    calculo_io8 = models.FloatField(max_length=255, null=True)
    media_io8 = models.FloatField(max_length=255, null=True)
    io9 = models.FloatField(max_length=255, null=True)
    io10 = models.FloatField(max_length=255, null=True)
    io11 = models.FloatField(max_length=255, null=True)
    io12 = models.FloatField(max_length=255, null=True)
    parametro_a = models.FloatField(max_length=255, null=True)
    parametro_b = models.FloatField(max_length=255, null=True)
    id_transdutor = models.ForeignKey(Transdutor, on_delete=models.CASCADE, null=True)

class Conta_contrato(models.Model):
    conta_contrato = models.CharField(max_length=255)
    id_cliente = models.ForeignKey(User, on_delete=models.CASCADE)

class Imposto(models.Model):
    nome = models.CharField(max_length=255)
    estado = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)

    def __str__(self):
        return self.nome

class Constante(models.Model):
    nome = models.CharField(max_length=255)
    valor = models.CharField(max_length=255)

    def __str__(self):
        return self.nome

views.py:

def my_custom_bad_request_view(request):
    return render(request, '400.html', )

def my_custom_permission_denied_view(request):
    return render(request, '403.html', )

def my_custom_page_not_found_view(request):
    return render(request, '404.html', )

def my_custom_error_view(request):
    return render(request, '500.html', )

def index(request):
    return render(request, 'dashboard/index.html')

def do_change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('change_password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'dashboard/change_password.html', {
        'form': form
    })

@login_required
def graficos(request):
    current_user = request.user
    first_name = User.objects.values_list('first_name', flat=True).filter(pk=current_user.id)
    last_name = User.objects.values_list('last_name', flat=True).filter(pk=current_user.id)
    date_joined = User.objects.values_list('date_joined', flat=True).filter(pk=current_user.id)
    context = {
        'last_name': last_name,
        'first_name': first_name,
        'date_joined': date_joined,
    }
    return render(request, 'dashboard/graficos.html', context)

def printa(request):

    coletas = Coleta.objects.all().order_by('-id')
    transdutores = Transdutor.objects.filter(id_cliente=request.user.id)
    io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(id_cliente=request.user.id)
    io7_name = Transdutor.objects.values_list('nome_io7', flat=True).filter(id_cliente=request.user.id)
    io8_name = Transdutor.objects.values_list('nome_io8', flat=True).filter(id_cliente=request.user.id)

    parametros = Transdutor.objects.all().filter(id_cliente=request.user.id).order_by('-id')
    parametro_a = Transdutor.objects.values_list('parametro_a', flat=True).filter(id_cliente=request.user.id).order_by('-id').first()
    parametro_b = Transdutor.objects.values_list('parametro_b', flat=True).filter(id_cliente=request.user.id).order_by('-id').first()

    data = Coleta.objects.values_list('data_leitura', flat=True).filter(id_transdutor=1).order_by('-id')[:10]
    context = {

        'coletas': coletas,
        'transdutores': transdutores,
        'io6_name': io6_name,
        'io7_name': io7_name,
        'io8_name': io8_name,
        'parametro_a': parametro_a,
        'parametro_b': parametro_b,
        'data': data,
    }
    return render(request, 'dashboard/print.html', context)

def do_login(request):
    if request.method == 'GET':
        if request.user.is_authenticated():
            return render(request, 'dashboard/graficos.html')

    if request.method == 'POST':
        user = authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            if request.POST.get('lembrar', None) is not None:
                request.session.set_expiry(
                    60 * 60 * 24 * 30 * 12)  # Se selecionar o "lembrar-me" ficará logado por 1 ano
            login(request, user)
            return redirect('/graficos')
    return render(request, 'dashboard/login.html')

def do_logout(request):
    # return render(request, 'dashboard/logout.html')
    logout(request)
    return redirect('/login')

def consumo_mensal(request, *args, **kargs):
    mes = request.GET['mes']  # TODO: avaliar a forma como isso ta sendo feito
    dados = []
    transdutores = Transdutor.objects.filter(id_cliente=request.user.id)
    for t in transdutores:
        coletas = Coleta.objects.filter(id_transdutor_id=t.id, data_leitura__month=mes).order_by('data_leitura')
        for c in coletas:
            # soma os valores dos canais
            valores = [float(c.io6), float(c.io7), float(c.io8), float(c.io9), float(c.io10), float(c.io11),
                       float(c.io12)]
            soma = sum(valores)
            dia = int(c.data_leitura.day)
            adicionado = False
            for dado in dados:
                if dado['Dia'] == dia:
                    novo_valor = float(dado['Consumo']) + soma
                    dado['Consumo'] = "%.4f" % novo_valor
                    adicionado = True

            if not adicionado:
                dados.append({'Dia': dia, 'Consumo': "%.4f" % soma})

    return JsonResponse(dados, safe=False)

def consumo_mensal_por_setores(request, *args, **kargs):
    #io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(chave_api="hab0001")
    data2 = [
        {'value': 2554, 'label': 'Industria'},
        {'value': 242, 'label': 'Oficina'},
        {'value': 3233, 'label': 'Suprimento'},
        {'value': 122, 'label': 'Outros Departamentos'}
    ]
    return JsonResponse(data2, safe=False)

def gasto_mensal(request, *args, **kargs):
    data3 = [
        {'Dia': '01', 'Valor': 51333},
        {'Dia': '02', 'Valor': 30222},
        {'Dia': '03', 'Valor': 20442},
        {'Dia': '04', 'Valor': 20123},
        {'Dia': '05', 'Valor': 32333},
        {'Dia': '06', 'Valor': 44963},
    ]
    return JsonResponse(data3, safe=False)

def gasto_mensal_por_setores(request, *args, **kargs):
    data = [
        {'value': 12.22, 'label': 'Industria'},
        {'value': 15.32, 'label': 'Oficina'},
        {'value': 12.12, 'label': 'Suprimento'},
        {'value': 51.30, 'label': 'Outros Departamentos'}
    ]
    return JsonResponse(data, safe=False)

Thanks guys.


问:
Built-in string formatting vs string concatenation as logging parameter
I'm using SonarLint that shows me an issue in the following line.

```<code>LOGGER.debug("Comparing objects: " + object1 + " and " + object2);
</code>```

Side-note: The method that contains this line might get called quite often.

The description for this issue is

"Preconditions" and logging arguments should not require evaluation
(squid:S2629)

Passing message arguments that require further evaluation into a Guava
com.google.common.base.Preconditions check can result in a performance
penalty. That's because whether or not they're needed, each argument
must be resolved before the method is actually called.

Similarly, passing concatenated strings into a logging method can also
incur a needless performance hit because the concatenation will be
performed every time the method is called, whether or not the log
level is low enough to show the message.

Instead, you should structure your code to pass static or pre-computed
values into Preconditions conditions check and logging calls.

Specifically, the built-in string formatting should be used instead of
string concatenation, and if the message is the result of a method
call, then Preconditions should be skipped altoghether, and the
relevant exception should be conditionally thrown instead.

Noncompliant Code Example

```<code>logger.log(Level.DEBUG, "Something went wrong: " + message);  // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages

LOG.error("Unable to open file " + csvPath, e);  // Noncompliant

Preconditions.checkState(a > 0, "Arg must be positive, but got " + a); // Noncompliant. String concatenation performed even when a > 0

Preconditions.checkState(condition, formatMessage());  //Noncompliant. formatMessage() invoked regardless of condition

Preconditions.checkState(condition, "message: %s", formatMessage()); // Noncompliant
</code>```

Compliant Solution

```<code>logger.log(Level.SEVERE, "Something went wrong: %s", message);  // String formatting only applied if needed

logger.log(Level.SEVERE, () -> "Something went wrong: " + message); //since Java 8, we can use Supplier , which will be evaluated lazily

LOG.error("Unable to open file {}", csvPath, e);

if (LOG.isDebugEnabled() {   LOG.debug("Unable to open file " + csvPath, e);  // this is compliant, because it will not evaluate if log level is above debug. }

Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a);  // String formatting only applied if needed

if (!condition) {   throw new IllegalStateException(formatMessage()); // formatMessage() only invoked conditionally }

if (!condition) {   throw new IllegalStateException("message: " + formatMessage()); }
</code>```

I'm not 100% sure whether i understand this right. So why is this really an issue. Especially the part about the performance hit when using string concatenation. Because I often read that string concatenation is faster than formatting it.

EDIT: Maybe someone can explain me the difference between

```<code>LOGGER.debug("Comparing objects: " + object1 + " and " + object2);
</code>```

AND

```<code>LOGGER.debug("Comparing objects: {} and {}",object1, object2);
</code>```

is in the background. Because I think the String will get created before it is passed to the method. Right? So for me there is no difference. But obviously I'm wrong because SonarLint is complaining about it

答:
String concatenation means
LOGGER.info("The program started at " + new Date());

Built in formatting of logger means

LOGGER.info("The program started at {}", new Date());

very good article to understand the difference
http://dba-presents.com/index.php/jvm/java/120-use-the-built-in-formatting-to-construct-this-argument

ContentLicense: CC BY-SA 4.0

Body:
I'm using SonarLint that shows me an issue in the following line.

LOGGER.debug("Comparing objects: " + object1 + " and " + object2);

Side-note: The method that contains this line might get called quite often.

The description for this issue is

"Preconditions" and logging arguments should not require evaluation
(squid:S2629)

Passing message arguments that require further evaluation into a Guava
com.google.common.base.Preconditions check can result in a performance
penalty. That's because whether or not they're needed, each argument
must be resolved before the method is actually called.

Similarly, passing concatenated strings into a logging method can also
incur a needless performance hit because the concatenation will be
performed every time the method is called, whether or not the log
level is low enough to show the message.

Instead, you should structure your code to pass static or pre-computed
values into Preconditions conditions check and logging calls.

Specifically, the built-in string formatting should be used instead of
string concatenation, and if the message is the result of a method
call, then Preconditions should be skipped altoghether, and the
relevant exception should be conditionally thrown instead.

Noncompliant Code Example

logger.log(Level.DEBUG, "Something went wrong: " + message);  // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages

LOG.error("Unable to open file " + csvPath, e);  // Noncompliant

Preconditions.checkState(a > 0, "Arg must be positive, but got " + a); // Noncompliant. String concatenation performed even when a > 0

Preconditions.checkState(condition, formatMessage());  //Noncompliant. formatMessage() invoked regardless of condition

Preconditions.checkState(condition, "message: %s", formatMessage()); // Noncompliant

Compliant Solution

logger.log(Level.SEVERE, "Something went wrong: %s", message);  // String formatting only applied if needed

logger.log(Level.SEVERE, () -> "Something went wrong: " + message); //since Java 8, we can use Supplier , which will be evaluated lazily

LOG.error("Unable to open file {}", csvPath, e);

if (LOG.isDebugEnabled() {   LOG.debug("Unable to open file " + csvPath, e);  // this is compliant, because it will not evaluate if log level is above debug. }

Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a);  // String formatting only applied if needed

if (!condition) {   throw new IllegalStateException(formatMessage()); // formatMessage() only invoked conditionally }

if (!condition) {   throw new IllegalStateException("message: " + formatMessage()); }

I'm not 100% sure whether i understand this right. So why is this really an issue. Especially the part about the performance hit when using string concatenation. Because I often read that string concatenation is faster than formatting it.

EDIT: Maybe someone can explain me the difference between

LOGGER.debug("Comparing objects: " + object1 + " and " + object2);

AND

LOGGER.debug("Comparing objects: {} and {}",object1, object2);

is in the background. Because I think the String will get created before it is passed to the method. Right? So for me there is no difference. But obviously I'm wrong because SonarLint is complaining about it


问:
How to create a random decimal between 0 and 1 vb.net
I need a random decimal between 0 and 1 in VB.NET

```<code>Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))
</code>```

I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.

It should be between 0 and 1, but it's just returning 0.

答:
RND Class already generates a decimal</p>

```<code>Dim RandomOperator as new Rnd()
Dim Value as double = RandomOperator()
</code>```

Body:
I need a random decimal between 0 and 1 in VB.NET

Dim value As Decimal = CInt(Int((1 * Rnd()) + 0))

I'm trying this but it's just saving as 0. It's definitely something I'm doing wrong but I'm not sure yet.

It should be between 0 and 1, but it's just returning 0.

Body:
RND Class already generates a decimal

Dim RandomOperator as new Rnd()
Dim Value as double = RandomOperator()


问:
Large geojson to topojson
I am trying to convert a relatively large geojson file (383 MB) to topojson to use it with D3.js. I am running the following command on a mac book pro 2016:

```<code>geo2topo test.json > test.topojson
</code>```

and also the following command for simplification:

```<code>geo2topo test.json > test.topojson -q 10000
</code>```

Both of them produce the same following error:

buffer.js:503
      throw new Error('"toString()" failed');
      ^

Error: "toString()" failed
      at Buffer.toString (buffer.js:503:11)
      at JSON.parse ()
      at ReadStream. (/usr/local/lib/node_modules/topojson/node_modules/topojson-server/bin/geo2topo:107:46)
      at emitNone (events.js:91:20)
      at ReadStream.emit (events.js:188:7)
      at endReadableNT (_stream_readable.js:975:12)
      at _combinedTickCallback (internal/process/next_tick.js:80:11)
      at process._tickCallback (internal/process/next_tick.js:104:9)

I looked at various threads like this one but haven't found any solutions. Please note that the geojson itself is properly formatted and can be loaded in d3.js, but due to its size cannot be used in web applications.

答:
I hit the same problem yesterday. Specifically, the v8 engine can't read strings larger than 256Mb. Since the first step of loading the geojson is to read and parse it as a json, that doesn't work.

However, a good soul ported the node implementation to python:

https://github.com/calvinmetcalf/topojson.py

Since python doesn't have that limitation, you can use this code to create the topojson, then do whatever you want with it.

Title: Large geojson to topojson

Body:
I am trying to convert a relatively large geojson file (383 MB) to topojson to use it with D3.js. I am running the following command on a mac book pro 2016:

geo2topo test.json > test.topojson

and also the following command for simplification:

geo2topo test.json > test.topojson -q 10000

Both of them produce the same following error:

buffer.js:503
      throw new Error('"toString()" failed');
      ^

Error: "toString()" failed
      at Buffer.toString (buffer.js:503:11)
      at JSON.parse ()
      at ReadStream. (/usr/local/lib/node_modules/topojson/node_modules/topojson-server/bin/geo2topo:107:46)
      at emitNone (events.js:91:20)
      at ReadStream.emit (events.js:188:7)
      at endReadableNT (_stream_readable.js:975:12)
      at _combinedTickCallback (internal/process/next_tick.js:80:11)
      at process._tickCallback (internal/process/next_tick.js:104:9)

I looked at various threads like this one but haven't found any solutions. Please note that the geojson itself is properly formatted and can be loaded in d3.js, but due to its size cannot be used in web applications.


问:
implement part of a github repository
I'm trying to modifyt this repository which I forked https://github.com/vinnytwice/BicycleSpeed
but without the use of the tableviews because i'm interested in display the data like speed cadence and distance inside a more graphically designed InfoSpeedoViewController.
I don't manage tableviews controller yet so I can't understand how and where to modify the project.
Can anybody help to point me in the right direction?
my version will have just two ViewControllers :
MainViewController with a ScanButton and SpeedoViewController

So far I deleted the InfoTableViewController.swift, that is just drawing the tableview. but I'm stuck in modifying MainViewController according to my needs. I don't understand the override function prepare(for segue ) part of the code. it passes data to the InfoTableViewController with the first if statement so I don't need it, but with the second if statement it starts the scan function bluetoothManager.startScan() and passes data to ScanViewcontroller via it's UINAvigationController and than to the tableView in the ScanViewController. Am I right?
If so, could I just call the scan function and pass data to my SpeedoViewController instead?

```<code>@IBAction func scanButton(_ sender: UIBarButtonItem) {
    bluetoothManager.startscan()
    performSegue(withIdentifier identifier: MainToSpeedoSegue, sender: self)
}
</code>```

I don't really understand the relationship with scanViewController I guess. does data end to the infoTableView anyway?
thank

答:
Finally found the solution. it was to change the tableViewController for a normal ViewController having labels to display values. Change the references from the tableViewController to the ViewController, and link the returned values to the labels inside the function that was receiving the  continuously updated values.
Pretty easy once decoded the data flow.</p>

Title: implement part of a github repository

Body:
I'm trying to modifyt this repository which I forked https://github.com/vinnytwice/BicycleSpeed
but without the use of the tableviews because i'm interested in display the data like speed cadence and distance inside a more graphically designed InfoSpeedoViewController.
I don't manage tableviews controller yet so I can't understand how and where to modify the project.
Can anybody help to point me in the right direction?
my version will have just two ViewControllers :
MainViewController with a ScanButton and SpeedoViewController

So far I deleted the InfoTableViewController.swift, that is just drawing the tableview. but I'm stuck in modifying MainViewController according to my needs. I don't understand the override function prepare(for segue ) part of the code. it passes data to the InfoTableViewController with the first if statement so I don't need it, but with the second if statement it starts the scan function bluetoothManager.startScan() and passes data to ScanViewcontroller via it's UINAvigationController and than to the tableView in the ScanViewController. Am I right?
If so, could I just call the scan function and pass data to my SpeedoViewController instead?

@IBAction func scanButton(_ sender: UIBarButtonItem) {
    bluetoothManager.startscan()
    performSegue(withIdentifier identifier: MainToSpeedoSegue, sender: self)
}

I don't really understand the relationship with scanViewController I guess. does data end to the infoTableView anyway?
thank


问:
Including jQuery UI easing using Webpack
I am using Webpack for code bundling and want to use easing option in jQuery hide function.

```<code>$('.comment').hide('slide', { direction: 'left' }, 1000);
</code>```

I got this error message:

```<code>Uncaught TypeError: jQuery.easing[this.easing] is not a function
</code>```

package.json

```<code>...
"dependencies": {
    "@koa/cors": "^2.2.1",
    "axios": "^0.16.2",
    "bootstrap": "^3.3.7",
    "bootstrap-timepicker": "github:janzenz/bootstrap-timepicker#feature/compatibility-es6",
    "d3-ease": "^1.0.3",
    "d3-selection": "^1.1.0",
    "d3-shape": "^1.2.0",
    "d3-transition": "^1.1.0",
    "font-awesome": "^4.7.0",
    "http-server": "^0.10.0",
    "immutable": "^3.8.2",
    "jquery": "^3.2.1",
    "jquery-ui": "^1.12.1",
    "jquery.panzoom": "^3.2.2",
    "juration": "^0.1.0",
    "koa": "^2.3.0",
    "koa-body": "^2.5.0",
    "koa-bodyparser": "^4.2.0",
    "koa-logger": "^3.1.0",
    "koa-router": "^7.2.1",
    "koa-send": "^4.1.1",
    "koa-static": "^4.0.2",
    "moment": "^2.18.1",
    "oembed-auto": "0.0.3",
    "probe-image-size": "^3.1.0",
    "puppeteer": "^0.12.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-dropzone": "^4.2.1",
    "react-facebook-login": "^3.6.2",
    "react-google-login": "^3.0.2",
    "react-modal": "^3.1.2",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^4.0.8",
    "react-share": "^1.17.0",
    "react-transition-group": "^1.2.1",
    "react-twitter-widgets": "^1.7.1",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0",
    "request": "^2.83.0",
    "request-promise-native": "^1.0.5",
    "select2": "^4.0.4",
    "select2-bootstrap-theme": "0.1.0-beta.10",
    "shave": "^2.1.3",
    "sugar-date": "^2.0.4",
    "svg-url-loader": "^2.3.0",
    "twitter": "^1.7.1",
    "twitter-widgets": "^1.0.0",
    "unfluff": "^1.1.0"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.4",
    "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.7",
    "eslint": "^4.7.2",
    "eslint-config-airbnb": "^15.1.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "^5.1.1",
    "eslint-plugin-react": "^7.4.0",
    "file-loader": "^0.11.2",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "less": "^2.7.2",
    "less-loader": "^4.0.5",
    "node-sass": "^4.5.3",
    "nodemon": "^1.12.1",
    "npm-install-webpack-plugin": "^4.0.5",
    "postcss": "^6.0.11",
    "postcss-loader": "^2.0.6",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "url-loader": "^0.5.9",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.9.1",
    "webpack-merge": "^4.1.0",
    "webpack-notifier": "^1.5.0"
  }
</code>```

webpack.config.js

```<code>const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const WebpackNotifierPlugin = require('webpack-notifier');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const autoprefixer = require('autoprefixer');

const TARGET = process.env.npm_lifecycle_event;
console.log(`target event is ${TARGET}`);

let outputFileName = 'app';
outputFileName += TARGET === 'prod' ? '.min.js' : '.js';

const common = {
  entry: {
    app: './index.jsx',
  },
  module: {
    rules: [
      {
        test: /\.js[x]?$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader?presets[]=es2015&presets[]=react',
        },
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.less$/,
        loaders: ['style-loader', 'css-loader', 'less-loader'],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(eot|ttf|svg|gif|png|jpg|otf|woff|woff2)$/,
        loader: 'url-loader',
      },
    ],
  },
  externals: {
    twttr: 'twttr',
  },
  resolve: {
    alias: {
      jquery: 'jquery/src/jquery',
      'jquery-ui': 'jquery-ui/ui',
    },
  },
  plugins: [
    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          autoprefixer({
            browsers: ['last 3 versions'],
          }),
        ],
      },
    }),
    new WebpackNotifierPlugin(),
  ],
};

if (TARGET === 'dev' || !TARGET) {
  module.exports = webpackMerge(common, {
    devtool: 'eval-source-map',
    output: {
      filename: 'bundle.js',
      sourceMapFilename: '[file].map',
    },
    devServer: {
      contentBase: path.resolve(__dirname), // New
      historyApiFallback: true,
    },
    plugins: [
      new NpmInstallPlugin({
        save: true, // --save
      }),
      new FriendlyErrorsWebpackPlugin(),
    ],
  });
}
</code>```

I tried several ways how to import it:

```<code>import 'jquery-ui/ui/effect';
</code>```

```<code>const $ = require('jquery');
require('jquery-ui/ui/version');
require('../../../../node_modules/jquery-ui/ui/effect.js');
</code>```

```<code>window.jQuery.easing = require('../../../../node_modules/jquery-ui/ui/effect.js');

window.jQuery = require('../../../../node_modules/jquery-ui/ui/effect.js');
</code>```

```<code>jQuery.easing = require('../../../../node_modules/jquery-ui/ui/effect.js');

jQuery = require('../../../../node_modules/jquery-ui/ui/effect.js');
</code>```

```<code>import * as JQuery from 'jquery';
import 'jquery-ui';
</code>```

I tried to change alias in Webpack config:

```<code>alias: {
      "jquery-ui": "jquery-ui/jquery-ui.js",
      // bind to modules;
      modules: path.join(__dirname, "node_modules"),
    },
</code>```

答:
The easiest option for you would be to use the recommended approach from official docs

```<code>const $ = require("jquery");

// because you use 'slide' in
// $('.comment').hide('slide', { direction: 'left' }, 1000);
require("jquery-ui/ui/effects/effect-slide");
</code>```

But there are lots of other ways you can solve this: jquery-ui and webpack, how to manage it into module?

Body:
I am using Webpack for code bundling and want to use easing option in jQuery hide function.

$('.comment').hide('slide', { direction: 'left' }, 1000);

I got this error message:

Uncaught TypeError: jQuery.easing[this.easing] is not a function

package.json

...
"dependencies": {
    "@koa/cors": "^2.2.1",
    "axios": "^0.16.2",
    "bootstrap": "^3.3.7",
    "bootstrap-timepicker": "github:janzenz/bootstrap-timepicker#feature/compatibility-es6",
    "d3-ease": "^1.0.3",
    "d3-selection": "^1.1.0",
    "d3-shape": "^1.2.0",
    "d3-transition": "^1.1.0",
    "font-awesome": "^4.7.0",
    "http-server": "^0.10.0",
    "immutable": "^3.8.2",
    "jquery": "^3.2.1",
    "jquery-ui": "^1.12.1",
    "jquery.panzoom": "^3.2.2",
    "juration": "^0.1.0",
    "koa": "^2.3.0",
    "koa-body": "^2.5.0",
    "koa-bodyparser": "^4.2.0",
    "koa-logger": "^3.1.0",
    "koa-router": "^7.2.1",
    "koa-send": "^4.1.1",
    "koa-static": "^4.0.2",
    "moment": "^2.18.1",
    "oembed-auto": "0.0.3",
    "probe-image-size": "^3.1.0",
    "puppeteer": "^0.12.0",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-dropzone": "^4.2.1",
    "react-facebook-login": "^3.6.2",
    "react-google-login": "^3.0.2",
    "react-modal": "^3.1.2",
    "react-redux": "^5.0.6",
    "react-router": "^4.2.0",
    "react-router-dom": "^4.2.2",
    "react-router-redux": "^4.0.8",
    "react-share": "^1.17.0",
    "react-transition-group": "^1.2.1",
    "react-twitter-widgets": "^1.7.1",
    "redux": "^3.7.2",
    "redux-thunk": "^2.2.0",
    "request": "^2.83.0",
    "request-promise-native": "^1.0.5",
    "select2": "^4.0.4",
    "select2-bootstrap-theme": "0.1.0-beta.10",
    "shave": "^2.1.3",
    "sugar-date": "^2.0.4",
    "svg-url-loader": "^2.3.0",
    "twitter": "^1.7.1",
    "twitter-widgets": "^1.0.0",
    "unfluff": "^1.1.0"
  },
  "devDependencies": {
    "autoprefixer": "^7.1.4",
    "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "css-loader": "^0.28.7",
    "eslint": "^4.7.2",
    "eslint-config-airbnb": "^15.1.0",
    "eslint-plugin-import": "^2.7.0",
    "eslint-plugin-jsx-a11y": "^5.1.1",
    "eslint-plugin-react": "^7.4.0",
    "file-loader": "^0.11.2",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "less": "^2.7.2",
    "less-loader": "^4.0.5",
    "node-sass": "^4.5.3",
    "nodemon": "^1.12.1",
    "npm-install-webpack-plugin": "^4.0.5",
    "postcss": "^6.0.11",
    "postcss-loader": "^2.0.6",
    "sass-loader": "^6.0.6",
    "style-loader": "^0.18.2",
    "url-loader": "^0.5.9",
    "webpack": "^3.6.0",
    "webpack-dev-server": "^2.9.1",
    "webpack-merge": "^4.1.0",
    "webpack-notifier": "^1.5.0"
  }

webpack.config.js

const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const WebpackNotifierPlugin = require('webpack-notifier');
const NpmInstallPlugin = require('npm-install-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const autoprefixer = require('autoprefixer');

const TARGET = process.env.npm_lifecycle_event;
console.log(`target event is ${TARGET}`);

let outputFileName = 'app';
outputFileName += TARGET === 'prod' ? '.min.js' : '.js';

const common = {
  entry: {
    app: './index.jsx',
  },
  module: {
    rules: [
      {
        test: /\.js[x]?$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader?presets[]=es2015&presets[]=react',
        },
      },
      {
        test: /\.scss$/,
        loaders: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      {
        test: /\.less$/,
        loaders: ['style-loader', 'css-loader', 'less-loader'],
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(eot|ttf|svg|gif|png|jpg|otf|woff|woff2)$/,
        loader: 'url-loader',
      },
    ],
  },
  externals: {
    twttr: 'twttr',
  },
  resolve: {
    alias: {
      jquery: 'jquery/src/jquery',
      'jquery-ui': 'jquery-ui/ui',
    },
  },
  plugins: [
    new webpack.ProvidePlugin({
      jQuery: 'jquery',
      $: 'jquery',
      jquery: 'jquery',
      'window.jQuery': 'jquery',
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          autoprefixer({
            browsers: ['last 3 versions'],
          }),
        ],
      },
    }),
    new WebpackNotifierPlugin(),
  ],
};

if (TARGET === 'dev' || !TARGET) {
  module.exports = webpackMerge(common, {
    devtool: 'eval-source-map',
    output: {
      filename: 'bundle.js',
      sourceMapFilename: '[file].map',
    },
    devServer: {
      contentBase: path.resolve(__dirname), // New
      historyApiFallback: true,
    },
    plugins: [
      new NpmInstallPlugin({
        save: true, // --save
      }),
      new FriendlyErrorsWebpackPlugin(),
    ],
  });
}

I tried several ways how to import it:

import 'jquery-ui/ui/effect';

const $ = require('jquery');
require('jquery-ui/ui/version');
require('../../../../node_modules/jquery-ui/ui/effect.js');

window.jQuery.easing = require('../../../../node_modules/jquery-ui/ui/effect.js');

window.jQuery = require('../../../../node_modules/jquery-ui/ui/effect.js');

jQuery.easing = require('../../../../node_modules/jquery-ui/ui/effect.js');

jQuery = require('../../../../node_modules/jquery-ui/ui/effect.js');

import * as JQuery from 'jquery';
import 'jquery-ui';

I tried to change alias in Webpack config:

alias: {
      "jquery-ui": "jquery-ui/jquery-ui.js",
      // bind to modules;
      modules: path.join(__dirname, "node_modules"),
    },

Body:
The easiest option for you would be to use the recommended approach from official docs

const $ = require("jquery");

// because you use 'slide' in
// $('.comment').hide('slide', { direction: 'left' }, 1000);
require("jquery-ui/ui/effects/effect-slide");

But there are lots of other ways you can solve this: jquery-ui and webpack, how to manage it into module?


问:
django forms multiple form with one field same by default
I have a list of links,(A,B,C,D,) each link opens the same pop up form with fields (name , email, region, service)
all the inputs except SERVICE is user input.
I want the service field to have a default name of the links.

```<code>EXAMPLE:

LINK A

---FORM-------

NAME= .........

EMAIL=........

REGION=........

SERVICE=FORM A

===========================

LINK B

---FORM-------

NAME= .........

EMAIL=........

REGION=........

SERVICE=FORM B
</code>```

====================================

I want the service field to have that default value.
how can I achieve that in Django??????

答:
You can create base form and other forms in your forms.py file:

```<code>from django import forms
class BaseForm(forms.Form):
    name = forms.CharField(label="Name")
    email = forms.EmailField(label="Email")
    region = forms.CharField(label="Region")

class AForm(BaseForm):
    service = forms.CharField(initial="A")

class BForm(BaseForm):
    service = forms.CharField(initial="B")

class CForm(BaseForm):
    service = forms.CharField(initial="C")

class DForm(BaseForm):
    service = forms.CharField(initial="D")
</code>```

Now in your view you can add forms as below:

```<code>def example_view(request):
    context = {
        'aform':AForm(),
        'bform':BForm(),
        'cform':CForm(),
        'dform':DForm()
    }
    template = "xyz.html"
    return render(request, template, context)
</code>```

Now in your 'xyz.html' you can access these forms using context variables: aform, bform, cform, dform.

Body:
I have a list of links,(A,B,C,D,) each link opens the same pop up form with fields (name , email, region, service)
all the inputs except SERVICE is user input.
I want the service field to have a default name of the links.

EXAMPLE:

LINK A

---FORM-------

NAME= .........

EMAIL=........

REGION=........

SERVICE=FORM A

===========================

LINK B

---FORM-------

NAME= .........

EMAIL=........

REGION=........

SERVICE=FORM B

====================================

I want the service field to have that default value.
how can I achieve that in Django??????

Body:
You can create base form and other forms in your forms.py file:

from django import forms
class BaseForm(forms.Form):
    name = forms.CharField(label="Name")
    email = forms.EmailField(label="Email")
    region = forms.CharField(label="Region")

class AForm(BaseForm):
    service = forms.CharField(initial="A")

class BForm(BaseForm):
    service = forms.CharField(initial="B")

class CForm(BaseForm):
    service = forms.CharField(initial="C")

class DForm(BaseForm):
    service = forms.CharField(initial="D")

Now in your view you can add forms as below:

def example_view(request):
    context = {
        'aform':AForm(),
        'bform':BForm(),
        'cform':CForm(),
        'dform':DForm()
    }
    template = "xyz.html"
    return render(request, template, context)

Now in your 'xyz.html' you can access these forms using context variables: aform, bform, cform, dform.


问:
Perl - How to decode or replace ' from database to single quote for browser display
I have found lots of questions close to this but, nothing that helped me solve it. Prob due to my lack of expertise.

PHP has  html_entity_decode which could have helped but, Perl does not, I believe.

In my MySQL database I have ' " following lengths in a description like: 12' 6"

I would like it to display as 12' 6".

I have tried:

```<code>$string =~ s/:[']:/'/g;
$string =~ s/:["]:/"/g;
$string =~ s/'/'/g;
$string =~ s/"/"/g;
$string =~ s/\'/'/g;
$string =~ s/\"/"/g;
$string =~ s/\'/\'/g;
$string =~ s/\"/\"/g;
perl -pi -e 's:':':g' $_; #crashes.
perl -pi -e 's:":":g' $string #also crashes.
system -pi -e 's:':':g' $_; #crashes.
system -pi -e 's:":":g' $string #also crashes.
</code>```

I am at a loss. Can someone help?

答:
Have a look at HTML::Entities:</p>

```<code>use warnings;
use strict;
use HTML::Entities;

my $str = '12' 6"';
print decode_entities($str);
</code>```

Body:
I have found lots of questions close to this but, nothing that helped me solve it. Prob due to my lack of expertise.

PHP has  html_entity_decode which could have helped but, Perl does not, I believe.

In my MySQL database I have ' " following lengths in a description like: 12' 6"

I would like it to display as 12' 6".

I have tried:

$string =~ s/:[']:/'/g;
$string =~ s/:["]:/"/g;
$string =~ s/'/'/g;
$string =~ s/"/"/g;
$string =~ s/\'/'/g;
$string =~ s/\"/"/g;
$string =~ s/\'/\'/g;
$string =~ s/\"/\"/g;
perl -pi -e 's:':':g' $_; #crashes.
perl -pi -e 's:":":g' $string #also crashes.
system -pi -e 's:':':g' $_; #crashes.
system -pi -e 's:":":g' $string #also crashes.

I am at a loss. Can someone help?

Body:
Have a look at HTML::Entities:

use warnings;
use strict;
use HTML::Entities;

my $str = '12&#39; 6&#34;';
print decode_entities($str);


问:
find the first duplicate number from an array for which the second occurrence has the minimal index
i am trying to write a javascript code to  find the first duplicate number from an arrayn for which the second occurrence has the minimal index.I have already written the function and it works fine for almost all given arrays except for the test case given below.

Input:
a: [1, 1, 2, 2, 1]
Output:
2
Expected Output:
1

The javascript code is given below

```<code>function firstDuplicate(a) {

  var firstIndex = "";
  var isMatch = false;
  for (var i = 0; i <= a.length; i++) {
    for (var j = i + 1; j <= a.length; j++) {
      alert(a[i] + "," + a[j]);
      if (a[i] === a[j]) {
        firstIndex = j;
        isMatch = true;
        break;
      }
    }

  }
  if (isMatch)
    return a[firstIndex];
  else
    return -1;

}
</code>```

the program is bugged using alert statement inside the second for loop.I found that the value of a[i] and a[j] is same in the first execution of the loop itself yet the if condition right below fails. I wonder how this happens and can anyone plaese explain me why this happens?

答:
You should only set firstIndex if it is lower than its current value.

Also, your loop bounds are incorrect. They should have < instead of <=.

console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1

function firstDuplicate(a) {
  var firstIndex = Infinity;
  var isMatch = false;
  for (var i = 0; i < a.length; i++) {
    for (var j = i + 1; j < a.length; j++) {
      // ---------------vvvvvvvvvvvvvvvvv
      if (a[i] === a[j] && j < firstIndex) {
        firstIndex = j;
        isMatch = true;
        break;
      }
    }
  }
  if (isMatch)
    return a[firstIndex];
  else
    return -1;
}```
</div>
</div>
</p>

<hr>

<p>Here's another way to write it:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1

function firstDuplicate(a) {
  let idx = Infinity;
  for (const [i, n] of a.entries()) {
    const dupIdx = a.indexOf(n, i+1);
    if (dupIdx !== -1 && dupIdx < idx) {
      idx = dupIdx;
    }
  }
  return isFinite(idx) ? a[idx] : -1;
}</code>```

Body:
i am trying to write a javascript code to  find the first duplicate number from an arrayn for which the second occurrence has the minimal index.I have already written the function and it works fine for almost all given arrays except for the test case given below.

Input:
a: [1, 1, 2, 2, 1]
Output:
2
Expected Output:
1

The javascript code is given below

function firstDuplicate(a) {

  var firstIndex = "";
  var isMatch = false;
  for (var i = 0; i <= a.length; i++) {
    for (var j = i + 1; j <= a.length; j++) {
      alert(a[i] + "," + a[j]);
      if (a[i] === a[j]) {
        firstIndex = j;
        isMatch = true;
        break;
      }
    }

  }
  if (isMatch)
    return a[firstIndex];
  else
    return -1;

}

the program is bugged using alert statement inside the second for loop.I found that the value of a[i] and a[j] is same in the first execution of the loop itself yet the if condition right below fails. I wonder how this happens and can anyone plaese explain me why this happens?

Body:
You should only set firstIndex if it is lower than its current value.

Also, your loop bounds are incorrect. They should have < instead of <=.

console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1

function firstDuplicate(a) {
  var firstIndex = Infinity;
  var isMatch = false;
  for (var i = 0; i < a.length; i++) {
    for (var j = i + 1; j < a.length; j++) {
      // ---------------vvvvvvvvvvvvvvvvv
      if (a[i] === a[j] && j < firstIndex) {
        firstIndex = j;
        isMatch = true;
        break;
      }
    }
  }
  if (isMatch)
    return a[firstIndex];
  else
    return -1;
}

Here's another way to write it:

console.log(firstDuplicate([1, 1, 2, 2, 1])); // 1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); // 3
console.log(firstDuplicate([2, 4, 3, 5, 1])); // -1

function firstDuplicate(a) {
  let idx = Infinity;
  for (const [i, n] of a.entries()) {
    const dupIdx = a.indexOf(n, i+1);
    if (dupIdx !== -1 && dupIdx < idx) {
      idx = dupIdx;
    }
  }
  return isFinite(idx) ? a[idx] : -1;
}


问:
ASP .NET Core https rewrite does not seem to work
Env: ASP.NET Core 2.0. App gets deployed to IIS on Windows Server 2016.

In my startup.cs, I have the following code:

public void ConfigureServices(IServiceCollection services)
  ...
  services.Configure<MvcOptions>(options => {
      options.Filters.Add(new RequireHttpsAttribute());
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
   ...
   var options = new RewriteOptions().AddRedirectToHttps();
   app.UseRewriter(options);
}
```

However, when the app is deployed to IIS, I do not see http://xxx getting changed to https://xxx in the browser.

I can directly go to https://xxx and that seems to work. However, the idea is to automatically redirect http requests to https.

What is it that I am missing? Do I need to do something on IIS as well? Regards.

答:
From the code snippet you posted looks like app.UseRewriter(options); is the last in the Configure() method. Move app.UseMvc(); to the very bottom of the method, since sort order in the pipeline is very important. I suspect MVC processes your request before the rewrite rule is actually applied.

Also:

You might not need RequireHttpsAttribute -- run your code without the filter, the HTTPS redirect should still happen.

This might depend on your requirements, however I normally set 301 (permanent) redirect to HTTPS. There is an extension for that AddRedirectToHttpsPermanent().

Body:
Env: ASP.NET Core 2.0. App gets deployed to IIS on Windows Server 2016.

In my startup.cs, I have the following code:

public void ConfigureServices(IServiceCollection services)
  ...
  services.Configure<MvcOptions>(options => {
      options.Filters.Add(new RequireHttpsAttribute());
  });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
   ...
   var options = new RewriteOptions().AddRedirectToHttps();
   app.UseRewriter(options);
}

However, when the app is deployed to IIS, I do not see http://xxx getting changed to https://xxx in the browser.

I can directly go to https://xxx and that seems to work. However, the idea is to automatically redirect http requests to https.

What is it that I am missing? Do I need to do something on IIS as well? Regards.


问:
Need help removing functions from CASE WHEN
I have a situation where I have created script to select data in our company's environment. In doing so, I decided to use functions for some pattern matching and stripping of characters in a CASE WHEN.

However, one of our clients doesn't want to let us put their data in our local environment, so I now have the requirement of massaging the script to be able to run on their environment--essentially meaning I need to remove the functions, and I am having trouble thinking about how I need to move stuff around to do so.

An example of the function call would be:

```<code>SELECT ....
CASE WHEN Prp = 'Key Cabinet'
        AND SerialNumber IS NOT NULL
        AND dbo.fnRemoveNonNumericCharacters(SerialNumber) <> ''
     THEN dbo.fnRemoveNonNumericCharacters(SerialNumber)
....
INTO #EmpProperty
FROM ....
</code>```

Where Prp is a column that contains the property type and SerialNumber is a column that contains a serial number, but also some other random garbage because data entry was sloppy.

The function definition is:

```<code>WHILE PATINDEX('%[^0-9]%', @strText) > 0
BEGIN
    SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
END
RETURN @strText
</code>```

where @strText is the SerialNumber I am passing in.

I may be stuck in analysis paralysis because I just can't figure out a good way to do this. I don't need a full on solution per-say, perhaps just point me in a direction you know will work. Let me know if you would like some sample DDL/DML to mess around with stuff.

Example 'SerialNumber' values: CA100 (Trash bins), T110, 101B.
 There are also a bunch of other types of values such as all text or all numbers, but we are filtering those out. The current patterning matching is good enough.

答:
So I think you mean you can't use a function... so, perhaps:</p>

```<code>declare @table table (SomeCol varchar(4000))
insert into @table values
('1 ab2cdefghijk3lmnopqr4stuvwxyz5 6 !7@#$8%^&9*()-10_=11+[]{}12\|;:13></14? 15'),
('CA100 (Trash bins), T110, 101B')

;with cte as (
    select top (100)
    N=row_number() over (order by @@spid) from sys.all_columns),

Final as (
    select SomeCol, Col
    from @table
        cross apply (
            select (select X + ''
            from (select N, substring(SomeCol, N, 1) X
                  from cte
                  where N<=datalength(SomeCol)) [1]
            where X between '0' and '9'
            order by N
            for xml path(''))
        ) Z (Col)
    where Z.Col is not NULL
)

select
    SomeCol
    ,cast(Col as varchar) CleanCol  --change this to BIGINT if it isn't too large
from Final
</code>```

Body:
I have a situation where I have created script to select data in our company's environment. In doing so, I decided to use functions for some pattern matching and stripping of characters in a CASE WHEN.

However, one of our clients doesn't want to let us put their data in our local environment, so I now have the requirement of massaging the script to be able to run on their environment--essentially meaning I need to remove the functions, and I am having trouble thinking about how I need to move stuff around to do so.

An example of the function call would be:

SELECT ....
CASE WHEN Prp = 'Key Cabinet'
        AND SerialNumber IS NOT NULL
        AND dbo.fnRemoveNonNumericCharacters(SerialNumber) <> ''
     THEN dbo.fnRemoveNonNumericCharacters(SerialNumber)
....
INTO #EmpProperty
FROM ....

Where Prp is a column that contains the property type and SerialNumber is a column that contains a serial number, but also some other random garbage because data entry was sloppy.

The function definition is:

WHILE PATINDEX('%[^0-9]%', @strText) > 0
BEGIN
    SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '')
END
RETURN @strText

where @strText is the SerialNumber I am passing in.

I may be stuck in analysis paralysis because I just can't figure out a good way to do this. I don't need a full on solution per-say, perhaps just point me in a direction you know will work. Let me know if you would like some sample DDL/DML to mess around with stuff.

Example 'SerialNumber' values: CA100 (Trash bins), T110, 101B.
 There are also a bunch of other types of values such as all text or all numbers, but we are filtering those out. The current patterning matching is good enough.

Body:
So I think you mean you can't use a function... so, perhaps:

declare @table table (SomeCol varchar(4000))
insert into @table values
('1 ab2cdefghijk3lmnopqr4stuvwxyz5 6 !7@#$8%^&9*()-10_=11+[]{}12\|;:13></14? 15'),
('CA100 (Trash bins), T110, 101B')

;with cte as (
    select top (100)
    N=row_number() over (order by @@spid) from sys.all_columns),

Final as (
    select SomeCol, Col
    from @table
        cross apply (
            select (select X + ''
            from (select N, substring(SomeCol, N, 1) X
                  from cte
                  where N<=datalength(SomeCol)) [1]
            where X between '0' and '9'
            order by N
            for xml path(''))
        ) Z (Col)
    where Z.Col is not NULL
)

select
    SomeCol
    ,cast(Col as varchar) CleanCol  --change this to BIGINT if it isn't too large
from Final


问:
Return results for Ubuntu Updates in a Variable
I am trying to get the result from /usr/lib/update-notifier/apt-check on a Ubuntu 16 Server into a Array to make a XML response for a monitoring tool, but somehow the value of this apt-check just refuses to get in my Variable. For simplicity sake, I have omitted the XML creation part.

```<code>#!/bin/bash
APTCHECK="/usr/lib/update-notifier/apt-check"
APTResult="$(${APTCHECK})"
echo "Result is $APTResult"
exit 0
</code>```

if you now run this code with bash -x you will see that the result is returned to the Terminal, but not assigned to the Variable. If I substitute the "command" to something simple like "ls -lah" everything works fine.

I just don't know why this is not working ? Anybody ?

答:
apt-check prints to the stderr, so you need to capture that instead with aptresult=$(/usr/lib/update-notifier/apt-check 2>&1).

The other option is with the --human-readable switch, which'll print to the stdout. The only problem then is that you have to parse the text output (unless the text output is what you actually want).

Body:
I am trying to get the result from /usr/lib/update-notifier/apt-check on a Ubuntu 16 Server into a Array to make a XML response for a monitoring tool, but somehow the value of this apt-check just refuses to get in my Variable. For simplicity sake, I have omitted the XML creation part.

#!/bin/bash
APTCHECK="/usr/lib/update-notifier/apt-check"
APTResult="$(${APTCHECK})"
echo "Result is $APTResult"
exit 0

if you now run this code with bash -x you will see that the result is returned to the Terminal, but not assigned to the Variable. If I substitute the "command" to something simple like "ls -lah" everything works fine.

I just don't know why this is not working ? Anybody ?


问:
Ionic 3: Grey(?) horizontal bar under img
Ok so I have a horizontal bar at the bottom of my img, this is not part of the image, I tried cropping, changing from png to jpeg and changing dimensions, this is an excerpt from it's html

<ion-content padding center text-center>
  <ion-img width="200" height="200" src="assets/imgs/applogo.png"></ion-img>
  <ion-list>
    <ion-item>```

and this is how it looks(sorry drew over the logo in red for privacy reasons):

It may seem a simple issue but I found no one posting about it online, any help is appreciated.

答:
You need to set the exact image dimensions on the ion-img element as mentioned in the official docs

The grey color appears because the ion-img component by default has a grey background color. You've set 200px as the height of your image but it is actually shorter than 200px so the background color of the ion-img element appears below the image.

Body:
Ok so I have a horizontal bar at the bottom of my img, this is not part of the image, I tried cropping, changing from png to jpeg and changing dimensions, this is an excerpt from it's html

<ion-content padding center text-center>
  <ion-img width="200" height="200" src="assets/imgs/applogo.png"></ion-img>
  <ion-list>
    <ion-item>

and this is how it looks(sorry drew over the logo in red for privacy reasons):

It may seem a simple issue but I found no one posting about it online, any help is appreciated.