问:
How to style the UL list to a single line
I want to render this list in a single line.

List item1

List item2

Should be shown as

*List item2 *List item2

What CSS style to use?

答:
in bootstrap use .list-inline css class

```<code><ul class="list-inline">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>
</code>```

Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h

Body:
in bootstrap use .list-inline css class

<ul class="list-inline">
    <li>Coffee</li>
    <li>Tea</li>
    <li>Milk</li>
</ul>

Ref: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_txt_list-inline&stacked=h


来源: stackexchange

问:
Spring JDBC - Configure Build Path warning error showing
I am new for Spring JDBC Template.
I am using Eclipse Kepler IDE and Mysql DB.
I trying to insert the data in DB using Spring JDBCTemplate, but its showing error as "Configure build path".(refer the screen shot)
I have added all the related JARS in my project build path.
Kindly advise me how to resolve this issue .

答:
Same error I faced once and by changing or downgrading the version of spring framework helped me to resolve this error.

Old maven dependency ---

and changed to -----

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Write a program that takes in a line of text as input, and outputs that line of text in reverse
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text.

Ex: If the input is:

Hello there

Hey

quit

then the output is:

ereht olleH

yeH

I tried like this but it instead of break loop continues. Anyone please tell me what I am missing

```<code>user_input = input()

while True:

       values = user_input

       if values == 'quit' or values == 'Quit' or values == 'q':

            break

       print(values[::-1])
</code>```

My output comes as

ereht olleH

ereht olleH

ereht olleH

ereht olleH

ereht olleH

ereht olleH

...and continues

答:
You need to reset the user_input with the next input

For example (in java):

```<code>String userInput = kb.nextLine();

while (true)
{
   String check = userInput;
   if (check.equals("quit") || check.equals("Quit") || check.equals("q")) {
      break;
   }

   String reverse = "";
   for (int i = userInput.length() - 1; i >= 0; i--) {
       reverse = reverse + userInput.charAt(i);
   }

   System.out.println(reverse);
   userInput = kb.nextLine();
}
</code>```

Body:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Quit", "quit", or "q" for the line of text.

Ex: If the input is:

Hello there

Hey

quit

then the output is:

ereht olleH

yeH

I tried like this but it instead of break loop continues. Anyone please tell me what I am missing

user_input = input()

while True:

       values = user_input

       if values == 'quit' or values == 'Quit' or values == 'q':

            break

       print(values[::-1])

My output comes as

ereht olleH

ereht olleH

ereht olleH

ereht olleH

ereht olleH

ereht olleH

...and continues

Body:
You need to reset the user_input with the next input

For example (in java):

String userInput = kb.nextLine();

while (true)
{
   String check = userInput;
   if (check.equals("quit") || check.equals("Quit") || check.equals("q")) {
      break;
   }

   String reverse = "";
   for (int i = userInput.length() - 1; i >= 0; i--) {
       reverse = reverse + userInput.charAt(i);
   }

   System.out.println(reverse);
   userInput = kb.nextLine();
}


问:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index
Trying out TypeScript for a React project and I'm stuck on this error:

```<code>Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'
</code>```

Which appears when I try to filter the array in my component

```<code>.filter(({ name }) => plotOptions[name]);
</code>```

So far I looked at the article "Indexing objects in TypeScript" (https://dev.to/kingdaro/indexing-objects-in-typescript-1cgi) since it had a similar error, but I tried to add the index signature to type plotTypes and I still get the same error.

My component code:

```<code>import React, { Component } from "react";
import createPlotlyComponent from "react-plotly.js/factory";
import Plotly from "plotly.js-basic-dist";
const Plot = createPlotlyComponent(Plotly);

interface IProps {
  data: any;
}

interface IState {
  [key: string]: plotTypes;
  plotOptions: plotTypes;
}

type plotTypes = {
  [key: string]: boolean;
  train_1: boolean;
  train_2: boolean;
  train_3: boolean;
  train_4: boolean;
};

interface trainInfo {
  name: string;
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

class FiltrationPlots extends Component<IProps, IState> {
  readonly state = {
    plotOptions: {
      train_1: true,
      train_2: true,
      train_3: true,
      train_4: true
    }
  };
  render() {
    const { data } = this.props;
    const { plotOptions } = this.state;

    if (data.filtrationData) {
      const plotData: Array<trainInfo> = [
        {
          name: "train_1",
          x: data.filtrationData.map((i: any) => i["1-CumVol"]),
          y: data.filtrationData.map((i: any) => i["1-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_2",
          x: data.filtrationData.map((i: any) => i["2-CumVol"]),
          y: data.filtrationData.map((i: any) => i["2-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_3",
          x: data.filtrationData.map((i: any) => i["3-CumVol"]),
          y: data.filtrationData.map((i: any) => i["3-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_4",
          x: data.filtrationData.map((i: any) => i["4-CumVol"]),
          y: data.filtrationData.map((i: any) => i["4-PressureA"]),
          type: "scatter",
          mode: "lines"
        }
      ].filter(({ name }) => plotOptions[name]);
      return (
        <Plot
          data={plotData}
          layout={{ width: 1000, height: 1000, title: "A Fancy Plot" }}
        />
      );
    } else {
      return <h1>No Data Loaded</h1>;
    }
  }
}

export default FiltrationPlots;

</code>```

答:
```<code>// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];

// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];

// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
  obj[key];
</code>```

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

Here is a full example:

I have switched the order of the generics (U extends keyof T now comes before T extends object) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.

const getKeyValue = (key: U) => (obj: T) =>
  obj[key];

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

const getUserName = getKeyValue<keyof User, User>("name")(user);

// => 'John Smith'
```
<h2>Alternative Syntax</h2>
<pre class="lang-js prettyprint-override"><code>const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];
</code>```

Body:
Trying out TypeScript for a React project and I'm stuck on this error:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'

Which appears when I try to filter the array in my component

.filter(({ name }) => plotOptions[name]);

So far I looked at the article "Indexing objects in TypeScript" (https://dev.to/kingdaro/indexing-objects-in-typescript-1cgi) since it had a similar error, but I tried to add the index signature to type plotTypes and I still get the same error.

My component code:

import React, { Component } from "react";
import createPlotlyComponent from "react-plotly.js/factory";
import Plotly from "plotly.js-basic-dist";
const Plot = createPlotlyComponent(Plotly);

interface IProps {
  data: any;
}

interface IState {
  [key: string]: plotTypes;
  plotOptions: plotTypes;
}

type plotTypes = {
  [key: string]: boolean;
  train_1: boolean;
  train_2: boolean;
  train_3: boolean;
  train_4: boolean;
};

interface trainInfo {
  name: string;
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

class FiltrationPlots extends Component<IProps, IState> {
  readonly state = {
    plotOptions: {
      train_1: true,
      train_2: true,
      train_3: true,
      train_4: true
    }
  };
  render() {
    const { data } = this.props;
    const { plotOptions } = this.state;

    if (data.filtrationData) {
      const plotData: Array<trainInfo> = [
        {
          name: "train_1",
          x: data.filtrationData.map((i: any) => i["1-CumVol"]),
          y: data.filtrationData.map((i: any) => i["1-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_2",
          x: data.filtrationData.map((i: any) => i["2-CumVol"]),
          y: data.filtrationData.map((i: any) => i["2-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_3",
          x: data.filtrationData.map((i: any) => i["3-CumVol"]),
          y: data.filtrationData.map((i: any) => i["3-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_4",
          x: data.filtrationData.map((i: any) => i["4-CumVol"]),
          y: data.filtrationData.map((i: any) => i["4-PressureA"]),
          type: "scatter",
          mode: "lines"
        }
      ].filter(({ name }) => plotOptions[name]);
      return (
        <Plot
          data={plotData}
          layout={{ width: 1000, height: 1000, title: "A Fancy Plot" }}
        />
      );
    } else {
      return
No Data Loaded
;
    }
  }
}

export default FiltrationPlots;

Body:
// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];

// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];

// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
  obj[key];

Bad - the reason for the error is the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.

Better - the reason the error disappears is because now we are telling the compiler the obj argument will be a collection of string/value (string/any) pairs. However, we are using the any type, so we can do better.

Best - T extends empty object. U extends the keys of T. Therefore U will always exist on T, therefore it can be used as a look up value.

Here is a full example:

I have switched the order of the generics (U extends keyof T now comes before T extends object) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.

const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
  obj[key];

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

const getUserName = getKeyValue<keyof User, User>("name")(user);

// => 'John Smith'

Alternative Syntax

const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];


问:
How to get the checkbox value in php html
I have a table showing database values as shown here:

```<code><?php
       while ($single = $output->fetch_assoc()):?>
  <tr>
    <td> <?php echo $single['Dptname']; ?></td>
    <td> <?php echo $single['firstname']; ?> </td>
    <td> <?php echo $single['lastname']; ?> </td>
    <td> <?php echo $single['email']; ?> </td>
    <td> <?php echo $single['phnumber']; ?> </td>
    <td> <?php echo $single['provider']; ?> </td>
     <td style="display: none"> <?php echo $single['id']; ?></td>
    <td><input type="checkbox" class="Dptadmin" id="Dptadmin" value="1"></td>
    <td><input type="checkbox" class="superuser" id="superuser" value="1"></td>
    <td><button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal"> <i class="fa fa-pencil-square-o">  </i> </button>
        <a href="process.php?delete=<?php echo $single['id'];?>" class="b2"><i class="fa fa-trash-o"></i> </a>
    </td>
  </tr>
    <?php endwhile;?>
</code>```

jQuery:

```<code><script>
 $(document).ready(function (){
    $('.editbtn').on('click', function(){
        $('#editmodal').modal('show');
        $tr = $(this).closest('tr');
        var data = $tr.children('td').map(function(){
          return $(this).text();
        }).get();
        console.log(data);
        $('#Dptname').val(data[0]);
        $('#firstname').val(data[1]);
        $('#lastname').val(data[2]);
        $('#email').val(data[3]);
        $('#phnumber').val(data[4]);
        $('#provider').val(data[5]);
        $('#userid').val(data[6]);
        $('#userid').val(data[6]);
        $('#Dptadmin').val(data[7]);
    });
 });
</code>```

Tried:-

```<code> $('.Dptadmin').on('click', function(){
     $tr = $(this).closest('tr');
        var data = $tr.children('td').map(function(){
          return $(this).text();
        }).get();
        console.log(data);
        $('#userid').val(data[6]);
        var val = $(this).find(":checkbox['<?php echo $single['Dadmin']; ?>']").val();
        console.log(val);
</code>```

As above jQuery, from console.log(data) I'm getting the value of selected TD, but not getting checkbox value. Thank you in advance.

答:
if you only want to get the value of your checkbox when it is clicked  then use the below code </p>

```<code>  $('.Dptadmin').on('click', function(){
    console.log($(this).val());
  });
</code>```

Body:
I have a table showing database values as shown here:

<?php
       while ($single = $output->fetch_assoc()):?>

     <?php echo $single['Dptname']; ?>
     <?php echo $single['firstname']; ?>
     <?php echo $single['lastname']; ?>
     <?php echo $single['email']; ?>
     <?php echo $single['phnumber']; ?>
     <?php echo $single['provider']; ?>
      <?php echo $single['id']; ?>
    <input type="checkbox" class="Dptadmin" id="Dptadmin" value="1">
    <input type="checkbox" class="superuser" id="superuser" value="1">
    <button type="button" class="btn b1 editbtn" data-toggle="modal" value="" data-target="#myModal">    </button>
        <a href="process.php?delete=<?php echo $single['id'];?>" class="b2">

    <?php endwhile;?>

jQuery:

Body:
if you only want to get the value of your checkbox when it is clicked  then use the below code

  $('.Dptadmin').on('click', function(){
    console.log($(this).val());
  });


问:
How to split a dataframe into two based on data from another dataframe (before and after some action) in pandas?
I need to split a dataframe with posts using data of date and time of registration into two dataframes, where I will have data of posts before and after registration.

A dataframe with posts:

```<code>posts = {'Login':['User1', 'User1', 'User2', 'User3', 'User3'], 'Posted':['13.12.2018 07:12', '13.05.2019 00:00', '13.05.2019 12:32', '13.06.2019 00:06', '01.07.2019 14:43']}
df_posts = pd.DataFrame(posts)
</code>```

A dataframe with dates of registration:

```<code>registr_date = {'Login':['User1', 'User2', 'User3'], 'Registered':['14.12.2018 12:07', '17.05.2019 14:01', '20.06.2019 15:00']}
df_registr = pd.DataFrame(registr_date)
</code>```

I changed the format of columns with time and date:

```<code>df_posts['Posted']= pd.to_datetime(df_posts['Posted'])
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Date_of_registration'])
</code>```

I need to get the following output.
Posts before registration:

```<code>    Login   Posted_before
0   User1   13.12.2018 07:12
1   User2   13.05.2019 12:32
2   User3   13.06.2019 00:06
</code>```

Posts after registration:

```<code>    Login   Posted_after
0   User1   13.05.2019 00:00
1   User3   01.07.2019 14:43
</code>```

How I should split the dataframe with posts?

答:
As LaChatonnn mentioned, please use the format option when converting to DateTime

I usually prefer using .map over .merge if possible as it results in better performance

```<code># Convert to datetime
df_posts['Posted']= pd.to_datetime(df_posts['Posted'], format = '%d-%m-%Y %H:%M')
df_registr['Registered']= pd.to_datetime(df_registr['Registered'], format = '%d-%m-%Y %H:%M')

# Set index in register df to allow mapping
df_registr = df_registr.set_index('Login')

# create the split dfs
df_before = df_posts[(df_posts['Posted'] < df_posts['Login'].map(df_registr['Registered']))]
df_after = df_posts[(df_posts['Posted'] > df_posts['Login'].map(df_registr['Registered']))]
</code>```

Output:

df_before:

```<code>    Login   Posted
0   User1   2018-12-13 07:12:00
2   User2   2019-05-13 12:32:00
3   User3   2019-06-13 00:06:00
</code>```

df_after:

```<code>    Login   Posted
1   User1   2019-05-13 00:00:00
4   User3   2019-07-01 14:43:00
</code>```

Body:
I need to split a dataframe with posts using data of date and time of registration into two dataframes, where I will have data of posts before and after registration.

A dataframe with posts:

posts = {'Login':['User1', 'User1', 'User2', 'User3', 'User3'], 'Posted':['13.12.2018 07:12', '13.05.2019 00:00', '13.05.2019 12:32', '13.06.2019 00:06', '01.07.2019 14:43']}
df_posts = pd.DataFrame(posts)

A dataframe with dates of registration:

registr_date = {'Login':['User1', 'User2', 'User3'], 'Registered':['14.12.2018 12:07', '17.05.2019 14:01', '20.06.2019 15:00']}
df_registr = pd.DataFrame(registr_date)

I changed the format of columns with time and date:

df_posts['Posted']= pd.to_datetime(df_posts['Posted'])
df_registr['Date_of_registration']= pd.to_datetime(df_registr['Date_of_registration'])

I need to get the following output.
Posts before registration:

    Login   Posted_before
0   User1   13.12.2018 07:12
1   User2   13.05.2019 12:32
2   User3   13.06.2019 00:06

Posts after registration:

    Login   Posted_after
0   User1   13.05.2019 00:00
1   User3   01.07.2019 14:43

How I should split the dataframe with posts?

Body:
As LaChatonnn mentioned, please use the format option when converting to DateTime

I usually prefer using .map over .merge if possible as it results in better performance

# Convert to datetime
df_posts['Posted']= pd.to_datetime(df_posts['Posted'], format = '%d-%m-%Y %H:%M')
df_registr['Registered']= pd.to_datetime(df_registr['Registered'], format = '%d-%m-%Y %H:%M')

# Set index in register df to allow mapping
df_registr = df_registr.set_index('Login')

# create the split dfs
df_before = df_posts[(df_posts['Posted'] < df_posts['Login'].map(df_registr['Registered']))]
df_after = df_posts[(df_posts['Posted'] > df_posts['Login'].map(df_registr['Registered']))]

Output:

df_before:

    Login   Posted
0   User1   2018-12-13 07:12:00
2   User2   2019-05-13 12:32:00
3   User3   2019-06-13 00:06:00

df_after:

    Login   Posted
1   User1   2019-05-13 00:00:00
4   User3   2019-07-01 14:43:00


问:
DRF - Checking for a concrete unique constraint violation when creating and/or validating an object
I have a table where composite unique index is set on both DB and Django level. The first question is, how do I catch in DRF that IntegrityError has risen exactly because of this given unique constraint violation?

I have come across a code snippet like this:

```<code>class TestModel(models.Model):
    class Meta:
        managed = False
        db_table = 'test_table'
        unique_together = ('fieldA','fieldB',)

class TestSerializer(serializers.ModelSerializer):

    def create(self, request, *args, **kwargs):
        try:
            return super().create(request, *args, **kwargs)
        except IntegrityError as err:
            if err.__cause__.pgcode == errorcodes.UNIQUE_VIOLATION:
                # Do something special

</code>```

...but this yields, and besides that, I am feeling like this is not the most appropriate way to achieve the goal. Any ideas?

And the second question is, how do I validate against this same constraint? How should the if-condition look like in the validate method? And should it be done in the validate method or elsewhere?

答:
Every type of validation should be done in DRF validation methods i.e. validate and is_valid. For your case, you should check in your validate method if any object already exists against provided data like this

```<code>def is_valid(self, raise_exception=True):
    data = self.initial_data
    if TestModel.objects.filter(fieldA=data.get('fieldA'), fieldB=data.get('fieldB').exists():
        raise serializers.ValidationError("Object already exist with {fieldA} and {fieldB}".format(**data)
    return super().is_valid(raise_exception)
</code>```

Body:
I have a table where composite unique index is set on both DB and Django level. The first question is, how do I catch in DRF that IntegrityError has risen exactly because of this given unique constraint violation?

I have come across a code snippet like this:

class TestModel(models.Model):
    class Meta:
        managed = False
        db_table = 'test_table'
        unique_together = ('fieldA','fieldB',)

class TestSerializer(serializers.ModelSerializer):

    def create(self, request, *args, **kwargs):
        try:
            return super().create(request, *args, **kwargs)
        except IntegrityError as err:
            if err.__cause__.pgcode == errorcodes.UNIQUE_VIOLATION:
                # Do something special

...but this yields, and besides that, I am feeling like this is not the most appropriate way to achieve the goal. Any ideas?

And the second question is, how do I validate against this same constraint? How should the if-condition look like in the validate method? And should it be done in the validate method or elsewhere?

Body:
Every type of validation should be done in DRF validation methods i.e. validate and is_valid. For your case, you should check in your validate method if any object already exists against provided data like this

def is_valid(self, raise_exception=True):
    data = self.initial_data
    if TestModel.objects.filter(fieldA=data.get('fieldA'), fieldB=data.get('fieldB').exists():
        raise serializers.ValidationError("Object already exist with {fieldA} and {fieldB}".format(**data)
    return super().is_valid(raise_exception)


问:
Getting Expected an assignment or function call and instead saw an expression no-unused-expressions error when trying to render a component in React
I am trying to render Card component based on the number of items in the items object but I am getting the error on line 6.

```<code>import React from "react";
    export class Cards extends React.Component {
      render() {
        let elements = [];
        elements = this.props.items.map(item => {
          <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        })
        return (
          {elements}
        );
      }
    }
</code>```

And this is the Card component :

```<code>import React from 'react'
export default ({titles, imgsrc, urls, discr}) => {
  return (
    <div className="cards">
        <div className="card">
          <div className="cardHead">
            <h4>{titles}</h4>
          </div>
          <div className="cardBody">
            <img src={imgsrc} alt="pst-img" />
          </div>
          <div className="cardFooter">
            <p>{discr}</p>
            <a className="buttn" href={urls}>
              <button>Read More</button>
            </a>
          </div>
        </div>
      </div>
    )
 }
</code>```

答:
As the first answer, you need to return the JSX in map()

Or using ( ) instead of {} inside the map()

like this

```<code>import React from "react";
    export class Cards extends React.Component {
      render() {
        return (
         {this.props.items.map(item => (
         return <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        ))}
        );
      }
    }
</code>```

Body:
I am trying to render Card component based on the number of items in the items object but I am getting the error on line 6.

import React from "react";
    export class Cards extends React.Component {
      render() {
        let elements = [];
        elements = this.props.items.map(item => {
          <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        })
        return (
          {elements}
        );
      }
    }

And this is the Card component :

import React from 'react'
export default ({titles, imgsrc, urls, discr}) => {
  return (

{titles}

{discr}

              <button>Read More</button>

    )
 }

Body:
As the first answer, you need to return the JSX in map()

Or using ( ) instead of {} inside the map()

like this

import React from "react";
    export class Cards extends React.Component {
      render() {
        return (
         {this.props.items.map(item => (
         return <Card titles = {item.title} imgsrc = {item.urlToImage}
          discr = {item.description} urls = {item.url}
          />
        ))}
        );
      }
    }


问:
How would you programmatically test a file for viruses?
I want to programmatically test a file for viruses.

I'm aware of this thread, which didn't get a satisfactory answer in my opinion, but I'm not looking for an API here. Any kind of workaround to make it possible to test a file would be fine.

Of course, an API would probably be the best solution (I'm using .net on a Windows platform), but maybe it's possible to drop the file in the folder, and to then check whether I can still open it or if it's been quarantined by the antivirus software.

Has someone run into the same sort of situation?

答: Windows? No problem. Check out ClamWin. It is based on ClamAV.</p>

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: TwistedAphid

LastEditorDisplayName: TwistedAphid


问:
Run script in ajax
can i run a java script in ajax? I've tried to embed some java script on the php that was triggered by an ajax command, the script is intended to change html attribute in the parent page. it doesn't work, when i look at the console  in firebug it only print the script and doesn't even make an alert.

tnx so much for the rplies.

答:
Doing such thing is considered very bad practice, you really better avoid it.

Instead of having the PHP send raw JS code, have it send "command" or "data" then parse this in the AJAX callback.

For example if you want to show alert have the PHP send only the text to appear in the alert, then in the AJAX callback take this value and do:

```<code>alert(ajaxResponse);
</code>```

Title: Run script in ajax

Body:
Doing such thing is considered very bad practice, you really better avoid it.

Instead of having the PHP send raw JS code, have it send "command" or "data" then parse this in the AJAX callback.

For example if you want to show alert have the PHP send only the text to appear in the alert, then in the AJAX callback take this value and do:

alert(ajaxResponse);


问:
Assigning to variables inside Run Keyword If
```<code>\   Run Keyword If    ${i} == 7    log to console     Testing Variant 1
\   ${is visible}=    Run Keyword And Return Status    Element Should Be Visible   (//li[@class='_8HqL0'])[${i}]
\   Run Keyword If    ${is visible}  Run keywords
\   ...  Scroll Element Into View    (//li[@class='_8HqL0'])[${i}]
\   ...   AND     Click Element     (//li[@class='_8HqL0'])[${i}]
\   ...   AND     sleep  2s
\   ...    set variable   ${Ad_Path}  Get Text  //*[@class='rui-3blDo _1Uh38 _27AdP']
\   ...   AND     log to console    ${Ad_Path}
</code>```

Hi i want to use the GET TEXT activity inside a IF block in FOR but its giving an error stating keyword name cannot be empty help

答:
You can't have a construct ${variable}=     Returned Value From Keyword inside a Run Keyword/Run Keyword If because the latter expects everything passed to it to be a keyword - and it considers ${variable} also to be one.

There is one "workaround" - Run Keyword If propagates back up the last returned value in its keyword, and that can be set to a variable. E.g. you can do this:

```<code>${variable}=     Run Keyword If    ${condition}    Returned Value From Keyword    ELSE    Set Variable    other value
</code>```

Mind the ELSE in this construct - without it, if the condition is false the variable will be undefined - will be left with a value None (the data type).

Naturally, if the Run Keyword If has more than one steps (like your console logs) you'll have to break it up - a block that "does things", and another (or others) that "assigns values".

I've typed "workaround" in quotes because it isn't really such - it's the way the keyword is designed to be used.

Body:
\   Run Keyword If    ${i} == 7    log to console     Testing Variant 1
\   ${is visible}=    Run Keyword And Return Status    Element Should Be Visible   (//li[@class='_8HqL0'])[${i}]
\   Run Keyword If    ${is visible}  Run keywords
\   ...  Scroll Element Into View    (//li[@class='_8HqL0'])[${i}]
\   ...   AND     Click Element     (//li[@class='_8HqL0'])[${i}]
\   ...   AND     sleep  2s
\   ...    set variable   ${Ad_Path}  Get Text  //*[@class='rui-3blDo _1Uh38 _27AdP']
\   ...   AND     log to console    ${Ad_Path}

Hi i want to use the GET TEXT activity inside a IF block in FOR but its giving an error stating keyword name cannot be empty help

Body:
You can't have a construct ${variable}=     Returned Value From Keyword inside a Run Keyword/Run Keyword If because the latter expects everything passed to it to be a keyword - and it considers ${variable} also to be one.

There is one "workaround" - Run Keyword If propagates back up the last returned value in its keyword, and that can be set to a variable. E.g. you can do this:

${variable}=     Run Keyword If    ${condition}    Returned Value From Keyword    ELSE    Set Variable    other value

Mind the ELSE in this construct - without it, if the condition is false the variable will be undefined - will be left with a value None (the data type).

Naturally, if the Run Keyword If has more than one steps (like your console logs) you'll have to break it up - a block that "does things", and another (or others) that "assigns values".

I've typed "workaround" in quotes because it isn't really such - it's the way the keyword is designed to be used.


问:
spring cloud stream SOURCE with key,value type of message
I was trying to send a message with key, value pair using spring cloud stream. I am not able to find any API for that. org.springframework.messaging.MessageChannel only has payload as part of send function.Using Kafka Template this can be achieved although. Is that the only way to produce key,value kind of message.As KafkaTemplate is part of spring for apache kafka, i was hoping there is a abstraction available for the same in spring cloud stream. Please suggest.

Thanks,

答:
For the purpose of your question you can look at spring-cloud-stream as higher level abstraction over more low level APIs such as spring-kafka (if kafka binder is used), spring-integration etc. In other words you don't need to either send or receive anything explicitly within the scope of the framework. It will do the sending and receiving for you; That's the core feature of the framework - to bind execution of your code to input and output destinations managed by your broker.
All you need to do for your case is produce a Message. For example, here is a fully functioning application

```<code>@SpringBootApplication
public static class SupplierConfiguration {

    @Bean
    public Supplier<String> stringSupplier() {
        return () -> "Hello from Supplier";
    }
}
</code>```

While all you did is produced a String the framework will wrap it into Message and will send it to Kafka (providing you're using Kafka binder).
If you need to control explicitly the value of the key, you can return an actual instance of the Message with kafka_messageKey set. For example;

```<code>@SpringBootApplication
public static class SupplierConfiguration {

    @Bean
    public Supplier<Message<?>> stringSupplier() {
        return () -> MessageBuilder.withPayload("Hello from Supplier")
                   .setHeader(KafkaHeaders.MESSAGE_KEY, "blah")
                   .build();
    }
}
</code>```

You can read more about it here

Also, notice we're moving away from annotation-based programming model and into a much simpler functional model.

Body:
For the purpose of your question you can look at spring-cloud-stream as higher level abstraction over more low level APIs such as spring-kafka (if kafka binder is used), spring-integration etc. In other words you don't need to either send or receive anything explicitly within the scope of the framework. It will do the sending and receiving for you; That's the core feature of the framework - to bind execution of your code to input and output destinations managed by your broker.
All you need to do for your case is produce a Message. For example, here is a fully functioning application

@SpringBootApplication
public static class SupplierConfiguration {

    @Bean
    public Supplier<String> stringSupplier() {
        return () -> "Hello from Supplier";
    }
}

While all you did is produced a String the framework will wrap it into Message and will send it to Kafka (providing you're using Kafka binder).
If you need to control explicitly the value of the key, you can return an actual instance of the Message with kafka_messageKey set. For example;

@SpringBootApplication
public static class SupplierConfiguration {

    @Bean
    public Supplier<Message<?>> stringSupplier() {
        return () -> MessageBuilder.withPayload("Hello from Supplier")
                   .setHeader(KafkaHeaders.MESSAGE_KEY, "blah")
                   .build();
    }
}

You can read more about it here

Also, notice we're moving away from annotation-based programming model and into a much simpler functional model.


问:
how to print request and response from rest assured to extentreport html
I am using extent report with testng and rest assured. default print stream for RestAssured is System.out, but System.out statements are not showed in extent html report.
How to show system.out.print statement in extent reports ??
if not how to show response and request in extentreports- i need to change the LogConfig, but i am not sure how to change.</p>

答:
public static ExtentTest test;
test.log(Status.INFO, response.prettyPrint()); use these two lines in your @Test you will get the response in your extent report.
Note: The test variable should be present in the extent report class.


问:
Should I process a JSON in the frontend or Backend, which is faster?
I am getting a response from an API as a json response.
I am coding in python for backend.

The frontend team needs information from the raw json response for populating a UI so we have to order the json and make it more easier for them to fetch information.

Now I can order the json in a specific format and push to the frontend team or I can pass the raw json response*to the frontend team and let them handle ordering the json and further use for their UI.

Remember my json file size is 15MB.

Which is faster and a better design principle?

Process in the backend then push to frontend or process in the frontend?

答: It's always better to process the data in backend itself.</p>


问:
error while npm start getting error of sass-loader
Error:

```<code>ERROR in ./src/assets/scss/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/dist/cjs.js??ref--14-3!./src/assets/scss/styles.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):

      @for $i from 1 through $grid-row-columns {
                            ^
      Undefined variable: "$grid-row-columns".
      in C:\Users\node_modules\bootstrap\scss\mixins\_grid-framework.scss (line 37, column 30)
</code>```

package.json

{
    "name": "r",
    "version": "1.2.91-SNAPSHOT",
    "license": "MIT",
    "scripts": {
        "ng": "ng",
        "start": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --base-href=/abc/  --disableHostCheck=true",
        "start:dev": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --aot --base-href=/abc/ --disableHostCheck=true",
        "build": "webpack",
        "test": "karma start ./karma.conf.js",
        "test:dev": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng test  --code-coverage",
        "lint": "ng lint",
        "deploy:dev": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --configuration=dev --base-href=/abc/  --disableHostCheck=true",
        "start:webpack": "webpack-dev-server --inline --progress --host 0.0.0.0 --port 4200 --environment prod",
        "e2e": "protractor ./protractor.conf.js",
        "pree2e": "webdriver-manager update --standalone false --gecko false --quiet",
        "bundle-report": "webpack-bundle-analyzer dist/stats.json"
    },
    "private": false,
    "dependencies": {
        "@angular/animations": "^7.2.8",
        "@angular/cdk": "^7.3.4",
        "@angular/common": "^7.2.8",
        "@angular/compiler": "^7.2.8",
        "@angular/core": "^7.2.8",
        "@angular/forms": "^7.2.8",
        "@angular/http": "^7.2.8",
        "@angular/material": "^7.3.4",
        "@angular/platform-browser": "^7.2.8",
        "@angular/platform-browser-dynamic": "^7.2.8",
        "@angular/router": "^7.2.8",
        "@babel/polyfill": "^7.2.3",
        "@ng-bootstrap/ng-bootstrap": "^4.1.0",
        "@ng-idle/core": "^7.0.0-beta.1",
        "@ng-idle/keepalive": "^7.0.0-beta.1",
        "@ngrx/entity": "7.0.0",
        "@ngrx/store": "7.0.0",
        "@ngrx/store-devtools": "7.0.0",
        "@ngx-translate/core": "^11.0.1",
        "@ngx-translate/http-loader": "^4.0.0",
        "@swimlane/ngx-datatable": "14.0.0",
        "angular-font-awesome": "^3.1.2",
        "angular-particle": "^1.0.4",
        "angular2-hotkeys": "^2.1.4",
        "angular2-jwt": "^0.2.3",
        "angular2-moment": "^1.8.0",
        "apollo-angular": "1.5.0",
        "apollo-angular-link-http": "^1.4.0",
        "apollo-cache-inmemory": "^1.5.1",
        "apollo-client": "^2.5.1",
        "apollo-link": "^1.2.9",
        "apollo-link-error": "^1.1.8",
        "bootstrap": "^4.4.1",
        "classlist.js": "^1.1.20150312",
        "core-js": "^2.6.5",
        "electron-to-chromium": "^1.3.134",
        "font-awesome": "^4.7.0",
        "graphql": "^14.1.1",
        "graphql-tag": "^2.10.1",
        "igniteui-angular": "5.2.0-beta.0",
        "jwt-decode": "^2.2.0",
        "ng2-cookies": "1.0.12",
        "ng2-trim-directive": "^2.1.2",
        "ng2-validation": "^4.2.0",
        "ngx-pagination": "^3.2.1",
        "ngx-perfect-scrollbar": "^7.1.0",
        "ngx-slick-carousel": "^0.4.4",
        "ngx-snackbar": "^2.0.1",
        "particles.js": "^2.0.0",
        "primeng": "^7.0.5",
        "rxjs": "^6.5.1",
        "serve": "^10.1.2",
        "slick-carousel": "^1.8.1",
        "stickyfill": "^1.1.1",
        "sweetalert2": "^7.22.2",
        "tslib": "^1.9.0",
        "unsubscribe-all": "1.4.0",
        "web-animations-js": "^2.1.5",
        "zone.js": "^0.8.29"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^0.13.9",
        "@angular-devkit/core": "^7.3.5",
        "@angular/cli": "^7.3.5",
        "@angular/compiler-cli": "^7.2.8",
        "@angular/language-service": "^7.2.8",
        "@types/jasmine": "^3.3.8",
        "@types/jasminewd2": "^2.0.2",
        "@types/lodash": "^4.14.122",
        "@types/node": "^10.12.30",
        "@types/uuid": "^3.4.4",
        "autoprefixer": "^9.4.10",
        "circular-dependency-plugin": "^5.0.2",
        "codelyzer": "^4.0.1",
        "copy-webpack-plugin": "^4.6.0",
        "extract-text-webpack-plugin": "^3.0.2",
        "file-loader": "^3.0.1",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "istanbul-instrumenter-loader": "^3.0.0",
        "jasmine-core": "^3.3.0",
        "jasmine-spec-reporter": "^4.2.1",
        "jquery": "^3.4.1",
        "karma": "^4.0.0",
        "karma-chrome-launcher": "^2.2.0",
        "karma-coverage-istanbul-reporter": "^2.0.5",
        "karma-firefox-launcher": "^1.1.0",
        "karma-jasmine": "^2.0.1",
        "karma-jasmine-html-reporter": "^1.4.0",
        "karma-parallel": "^0.3.1",
        "karma-phantomjs-launcher": "^1.0.4",
        "less-loader": "^4.0.5",
        "ngx-bootstrap": "^4.1.0",
        "postcss-import": "^12.0.1",
        "postcss-url": "^8.0.0",
        "protractor": "^5.4.1",
        "raw-loader": "^1.0.0",
        "sonarqube-scanner": "^2.4.0",
        "specgen": "^1.3.1",
        "style-loader": "^0.23.1",
        "stylus-loader": "^3.0.1",
        "ts-node": "^7.0.1",
        "tslint": "^5.13.1",
        "typescript": "3.2.2",
        "uglifyjs-webpack-plugin": "^2.1.2",
        "url-loader": "^1.1.2",
        "webpack-bundle-analyzer": "^3.3.2",
        "webpack-dev-server": "^3.2.1",
        "webpack-merge": "^4.1.5"
    }
}
```

答:
You need to downgrade your bootstrap to 4.3.1
Steps:
1. Remove bootstrap - npm uninstall bootstrap
2. Install Bootstrap 4.3.1 - npm install bootstrap@4.3.1

Body:
Error:

ERROR in ./src/assets/scss/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/dist/cjs.js??ref--14-3!./src/assets/scss/styles.scss)
Module build failed (from ./node_modules/sass-loader/dist/cjs.js):

      @for $i from 1 through $grid-row-columns {
                            ^
      Undefined variable: "$grid-row-columns".
      in C:\Users\node_modules\bootstrap\scss\mixins\_grid-framework.scss (line 37, column 30)

package.json

{
    "name": "r",
    "version": "1.2.91-SNAPSHOT",
    "license": "MIT",
    "scripts": {
        "ng": "ng",
        "start": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --base-href=/abc/  --disableHostCheck=true",
        "start:dev": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --aot --base-href=/abc/ --disableHostCheck=true",
        "build": "webpack",
        "test": "karma start ./karma.conf.js",
        "test:dev": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng test  --code-coverage",
        "lint": "ng lint",
        "deploy:dev": "node --max-old-space-size=8192 node_modules/@angular/cli/bin/ng serve --configuration=dev --base-href=/abc/  --disableHostCheck=true",
        "start:webpack": "webpack-dev-server --inline --progress --host 0.0.0.0 --port 4200 --environment prod",
        "e2e": "protractor ./protractor.conf.js",
        "pree2e": "webdriver-manager update --standalone false --gecko false --quiet",
        "bundle-report": "webpack-bundle-analyzer dist/stats.json"
    },
    "private": false,
    "dependencies": {
        "@angular/animations": "^7.2.8",
        "@angular/cdk": "^7.3.4",
        "@angular/common": "^7.2.8",
        "@angular/compiler": "^7.2.8",
        "@angular/core": "^7.2.8",
        "@angular/forms": "^7.2.8",
        "@angular/http": "^7.2.8",
        "@angular/material": "^7.3.4",
        "@angular/platform-browser": "^7.2.8",
        "@angular/platform-browser-dynamic": "^7.2.8",
        "@angular/router": "^7.2.8",
        "@babel/polyfill": "^7.2.3",
        "@ng-bootstrap/ng-bootstrap": "^4.1.0",
        "@ng-idle/core": "^7.0.0-beta.1",
        "@ng-idle/keepalive": "^7.0.0-beta.1",
        "@ngrx/entity": "7.0.0",
        "@ngrx/store": "7.0.0",
        "@ngrx/store-devtools": "7.0.0",
        "@ngx-translate/core": "^11.0.1",
        "@ngx-translate/http-loader": "^4.0.0",
        "@swimlane/ngx-datatable": "14.0.0",
        "angular-font-awesome": "^3.1.2",
        "angular-particle": "^1.0.4",
        "angular2-hotkeys": "^2.1.4",
        "angular2-jwt": "^0.2.3",
        "angular2-moment": "^1.8.0",
        "apollo-angular": "1.5.0",
        "apollo-angular-link-http": "^1.4.0",
        "apollo-cache-inmemory": "^1.5.1",
        "apollo-client": "^2.5.1",
        "apollo-link": "^1.2.9",
        "apollo-link-error": "^1.1.8",
        "bootstrap": "^4.4.1",
        "classlist.js": "^1.1.20150312",
        "core-js": "^2.6.5",
        "electron-to-chromium": "^1.3.134",
        "font-awesome": "^4.7.0",
        "graphql": "^14.1.1",
        "graphql-tag": "^2.10.1",
        "igniteui-angular": "5.2.0-beta.0",
        "jwt-decode": "^2.2.0",
        "ng2-cookies": "1.0.12",
        "ng2-trim-directive": "^2.1.2",
        "ng2-validation": "^4.2.0",
        "ngx-pagination": "^3.2.1",
        "ngx-perfect-scrollbar": "^7.1.0",
        "ngx-slick-carousel": "^0.4.4",
        "ngx-snackbar": "^2.0.1",
        "particles.js": "^2.0.0",
        "primeng": "^7.0.5",
        "rxjs": "^6.5.1",
        "serve": "^10.1.2",
        "slick-carousel": "^1.8.1",
        "stickyfill": "^1.1.1",
        "sweetalert2": "^7.22.2",
        "tslib": "^1.9.0",
        "unsubscribe-all": "1.4.0",
        "web-animations-js": "^2.1.5",
        "zone.js": "^0.8.29"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^0.13.9",
        "@angular-devkit/core": "^7.3.5",
        "@angular/cli": "^7.3.5",
        "@angular/compiler-cli": "^7.2.8",
        "@angular/language-service": "^7.2.8",
        "@types/jasmine": "^3.3.8",
        "@types/jasminewd2": "^2.0.2",
        "@types/lodash": "^4.14.122",
        "@types/node": "^10.12.30",
        "@types/uuid": "^3.4.4",
        "autoprefixer": "^9.4.10",
        "circular-dependency-plugin": "^5.0.2",
        "codelyzer": "^4.0.1",
        "copy-webpack-plugin": "^4.6.0",
        "extract-text-webpack-plugin": "^3.0.2",
        "file-loader": "^3.0.1",
        "html-loader": "^0.5.5",
        "html-webpack-plugin": "^3.2.0",
        "istanbul-instrumenter-loader": "^3.0.0",
        "jasmine-core": "^3.3.0",
        "jasmine-spec-reporter": "^4.2.1",
        "jquery": "^3.4.1",
        "karma": "^4.0.0",
        "karma-chrome-launcher": "^2.2.0",
        "karma-coverage-istanbul-reporter": "^2.0.5",
        "karma-firefox-launcher": "^1.1.0",
        "karma-jasmine": "^2.0.1",
        "karma-jasmine-html-reporter": "^1.4.0",
        "karma-parallel": "^0.3.1",
        "karma-phantomjs-launcher": "^1.0.4",
        "less-loader": "^4.0.5",
        "ngx-bootstrap": "^4.1.0",
        "postcss-import": "^12.0.1",
        "postcss-url": "^8.0.0",
        "protractor": "^5.4.1",
        "raw-loader": "^1.0.0",
        "sonarqube-scanner": "^2.4.0",
        "specgen": "^1.3.1",
        "style-loader": "^0.23.1",
        "stylus-loader": "^3.0.1",
        "ts-node": "^7.0.1",
        "tslint": "^5.13.1",
        "typescript": "3.2.2",
        "uglifyjs-webpack-plugin": "^2.1.2",
        "url-loader": "^1.1.2",
        "webpack-bundle-analyzer": "^3.3.2",
        "webpack-dev-server": "^3.2.1",
        "webpack-merge": "^4.1.5"
    }
}


问:
Angular 5 and jQuery: (click) not calling function
I am currently working with Angular 5 and jQuery. I created a dynamic div through jQuery which I appended to a div.

```<code>var push_div = '<div class="col-md-6">
                <span style="color: green;">' +
                droppedItemID + '</span>
                <a href="javascript:void(0)"
                (click)="removeContent()">X</a>
                </div>'
$(push_div).hide().appendTo("#" + dropZoneID).fadeIn(1000);
</code>```

When I click on the link, the removeContent function is not calling.

```<code>removeContent() {
    console.log("function called");
}
</code>```

答: Remove this -> href="javascript:void(0)" from  tag.

Body:
I am currently working with Angular 5 and jQuery. I created a dynamic div through jQuery which I appended to a div.

var push_div = '

                ' +
                droppedItemID + '
                X

'
$(push_div).hide().appendTo("#" + dropZoneID).fadeIn(1000);

When I click on the link, the removeContent function is not calling.

removeContent() {
    console.log("function called");
}

Body: Remove this -> href="javascript:void(0)" from <a> tag.


问:
Angular 8 @output EventEmitter not letting an Object to be emitted
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

```<code>export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}
</code>```

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string

答:
That's because Typescript is complaining of incompatible types.
Either use

```<code>@Output() childEventEmitter = new EventEmitter<{currenty: string, total: string}>();
</code>```

or

```<code>@Output() childEventEmitter = new EventEmitter<any>();
</code>```

Body:
How would I emit an Object instead of primitive data types?

I have a object const amount = { currenty: 'USD', total: '10.25' };
which I wanted to emmit to the parent component.

export class MyChildComponent implements OnInit {
     @Output() childEventEmitter: EventEmitter = new EventEmitter();
....
}

in the emitter function

this.childEventEmitter.emit(amount); // not working

error: Argument of type { currenty: 'USD', total: '10.25' } not assignable to paraments of type string

Body:
That's because Typescript is complaining of incompatible types.
Either use

@Output() childEventEmitter = new EventEmitter<{currenty: string, total: string}>();

or

@Output() childEventEmitter = new EventEmitter<any>();


问:
Can you sort positive integers in O(N) (linear) time using an object in JavaScript?
I need to sort an array of positive integers.
It's easy enough to do via JavaScript's sort method in O(N * log(N)):

```<code>let a = [4, 1, 3, 9, 7, 19, 11];
a.sort((a,b) => a - b);
return a;

// returns [1, 3, 4, 7, 9, 11, 19]
</code>```

But, it seems like it can be done in O(N) using a JavaScript object?
Looping through the array to add an integer into an object is O(N), then grabbing the values from that object is also O(N). (Alternatively, grab the keys and convert back to numbers).

```<code>let o = {};
let a = [4, 1, 3, 9, 7, 19, 11];

a.forEach(integer => { o[integer] = integer });

return Object.values(o);

// returns [1, 3, 4, 7, 9, 11, 19]
</code>```

Drop the constant and we're looking at sorting positive integers in O(N) (sacrificing additional O(N) space).
From everything I've read, this shouldn't be possible. What am I missing here?

答:
The internal code used for setting and retrieving keys is implementation-dependent. The output (and order) is guaranteed (for all property enumeration methods, as of ES2020), but the mechanism is up to the implementer. You'd have to look at the engine source code for that.

I don't know the code that the different Javascript engines are running under the hood, but if you know of an upper bound on the number in the array, this is possible in O(n) (or, more precisely, O(n + k) where k is a constant - the upper bound) by using counting sort: create a map of the keys (similar to you're doing, but including the number of times each item appears), then iterate from 0 to the upper bound, checking to see if the number being iterated over is included in the keys. If so, push to the array:

let o = {};
let a = [4, 1, 3, 9, 7, 19, 11];

// O(n)
for (const num of a) {
  if (!o[num]) {
    o[num] = [];
  }
  o[num].push(num);
}

// O(n). This part isn't strictly necessary, but the alternative makes the code uglier
const max = Math.max(...a);
const result = [];
// O(k)
for (let i = 0; i <= max; i++) {
  if (o[i]) {
    // total of O(n) items pushed over the whole loop
    result.push(...o[i]);
  }
}

console.log(result);```
</div>
</div>
</p>

<p>If, like in your example, there are no repeated numbers, the code is significantly easier:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let o = {};
let a = [4, 1, 3, 9, 7, 19, 11];

for (const num of a) {
  o[num] = true;
}

// O(n)
const max = Math.max(...a);
const result = [];
// O(k)
for (let i = 0; i <= max; i++) {
  if (o[i]) {
    // total of O(n) items pushed over the whole loop
    result.push(i);
  }
}

console.log(result);</code>```

Body:
I need to sort an array of positive integers.
It's easy enough to do via JavaScript's sort method in O(N * log(N)):

let a = [4, 1, 3, 9, 7, 19, 11];
a.sort((a,b) => a - b);
return a;

// returns [1, 3, 4, 7, 9, 11, 19]

But, it seems like it can be done in O(N) using a JavaScript object?
Looping through the array to add an integer into an object is O(N), then grabbing the values from that object is also O(N). (Alternatively, grab the keys and convert back to numbers).

let o = {};
let a = [4, 1, 3, 9, 7, 19, 11];

a.forEach(integer => { o[integer] = integer });

return Object.values(o);

// returns [1, 3, 4, 7, 9, 11, 19]

Drop the constant and we're looking at sorting positive integers in O(N) (sacrificing additional O(N) space).
From everything I've read, this shouldn't be possible. What am I missing here?

Body:
The internal code used for setting and retrieving keys is implementation-dependent. The output (and order) is guaranteed (for all property enumeration methods, as of ES2020), but the mechanism is up to the implementer. You'd have to look at the engine source code for that.

I don't know the code that the different Javascript engines are running under the hood, but if you know of an upper bound on the number in the array, this is possible in O(n) (or, more precisely, O(n + k) where k is a constant - the upper bound) by using counting sort: create a map of the keys (similar to you're doing, but including the number of times each item appears), then iterate from 0 to the upper bound, checking to see if the number being iterated over is included in the keys. If so, push to the array:

let o = {};
let a = [4, 1, 3, 9, 7, 19, 11];

// O(n)
for (const num of a) {
  if (!o[num]) {
    o[num] = [];
  }
  o[num].push(num);
}

// O(n). This part isn't strictly necessary, but the alternative makes the code uglier
const max = Math.max(...a);
const result = [];
// O(k)
for (let i = 0; i <= max; i++) {
  if (o[i]) {
    // total of O(n) items pushed over the whole loop
    result.push(...o[i]);
  }
}

console.log(result);

If, like in your example, there are no repeated numbers, the code is significantly easier:

let o = {};
let a = [4, 1, 3, 9, 7, 19, 11];

for (const num of a) {
  o[num] = true;
}

// O(n)
const max = Math.max(...a);
const result = [];
// O(k)
for (let i = 0; i <= max; i++) {
  if (o[i]) {
    // total of O(n) items pushed over the whole loop
    result.push(i);
  }
}

console.log(result);


问:
How to create a list in Python that will yield the following result []
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)
</code>```

My output:

```<code>[['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

But here is the expected output:

```<code>['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

Please why am I not getting the expected output?

答:
If you do a simple output of the 9th through 12th items of the list

```<code>item_count = 0
for item in new_lst:
    item_count += 1
    if 9<=item_count<=12:
        print(str(item_count)+" "+str(item))
</code>```

you get the output

```<code>9 sun
10 ['water', 'air', 'fire', 'earth']
11 games
12 2.7
</code>```

which is not an empty list.

To get the sub-list of the 9th through 12th items use a slice that starts at 8 based on a zero-based index and ends at 12 because the last item is not included in the output slice.

```<code>sub_lst = new_lst[8:12]
</code>```

which prints as

```<code>print(sub_lst)
['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]
</code>```

Body:
This a question on coursera practices excess.

Create a new list using the 9th through 12th elements (four items in all) of new_lst and assign it to the variable sub_lst.

link to the question: https://runestone.academy/runestone/books/published/fopp/Sequences/TheSliceOperator.html
The last question on the list.

How is my code

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun",
["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817,
"party", "cake", 5], "rain", "thunderstorm", "top down"]
new_lst = new_lst[9:12]
sub_lst = new_lst
print(sub_lst)

My output:

[['water', 'air', 'fire', 'earth'], 'games', 2.7]

But here is the expected output:

['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]

Please why am I not getting the expected output?

Body:
If you do a simple output of the 9th through 12th items of the list

item_count = 0
for item in new_lst:
    item_count += 1
    if 9<=item_count<=12:
        print(str(item_count)+" "+str(item))

you get the output

9 sun
10 ['water', 'air', 'fire', 'earth']
11 games
12 2.7

which is not an empty list.

To get the sub-list of the 9th through 12th items use a slice that starts at 8 based on a zero-based index and ends at 12 because the last item is not included in the output slice.

sub_lst = new_lst[8:12]

which prints as

print(sub_lst)
['sun', ['water', 'air', 'fire', 'earth'], 'games', 2.7]


问:
Problem with SqlConnection, ASP.net C#
I have the following C# code:

```<code>public string TargetDate()
{
    SqlConnection con =
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open();

    DataSet ds = new DataSet(cmd,con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.Fill(ds);
    con.Close();
}
</code>```

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded
  method match for

```<code>'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,
</code>```

System.Runtime.Serialization.StreamingContext)'
  has some invalid arguments

What is could be the problem?

答:
Try this:

```<code>SqlConnection con = new SqlConnection
    ("Server=localhost;Database=Timer;Trusted_Connection=True");

SqlCommand cmd = new SqlCommand("select * from Timer", con);

con.Open();

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

con.Close();
</code>```

This is even better:

```<code>DataTable dataTable = new DataTable();
using(SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
using(SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "select * from Timer";
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    dataTable.Load(reader);
}
</code>```

Title: Problem with SqlConnection, ASP.net C#

Body:
I have the following C# code:

public string TargetDate()
{
    SqlConnection con =
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open();

    DataSet ds = new DataSet(cmd,con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.Fill(ds);
    con.Close();
}

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded
  method match for

'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,

System.Runtime.Serialization.StreamingContext)'
  has some invalid arguments

What is could be the problem?

Body:
Try this:

SqlConnection con = new SqlConnection
    ("Server=localhost;Database=Timer;Trusted_Connection=True");

SqlCommand cmd = new SqlCommand("select * from Timer", con);

con.Open();

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

con.Close();

This is even better:

DataTable dataTable = new DataTable();
using(SqlConnection connection = new SqlConnection("Server=localhost;Database=Timer;Trusted_Connection=True"))
using(SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "select * from Timer";
    connection.Open();
    SqlDataReader reader = command.ExecuteReader();
    dataTable.Load(reader);
}


问:
Get last day of the month in Ruby
I made new object Date.new with args (year, month). After create ruby added 01 number of day to this object by default. Is there any way to add not first day, but last day of month that i  passed as arg(e.g. 28 if it will be 02month or 31 if it will be 01month) ?</p>

答:
You can do something like that:</p>

```<code>def last_day_of_month?
   (Time.zone.now.month + 1.day) > Time.zone.now.month
end

Time.zone.now.day if last_day-of_month?
</code>```

Title: Get last day of the month in Ruby

Body:
You can do something like that:

def last_day_of_month?
   (Time.zone.now.month + 1.day) > Time.zone.now.month
end

Time.zone.now.day if last_day-of_month?


问:
How to remove all extra spaces while keeping the lines
I need to remove white-spaces while keeping the lines

Before:

```<code>I brought           a            Banana
I sold                a Banana
I           brought a Apple
</code>```

After: NO WHITE SPACES or big space at the begining of the line

```<code>I brought a Banana
I sold a Banana
I brought a Apple
</code>```

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.

答:
You can split the string with \n to map them:

var str = `I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;
str = str.split('\n').map(l => l.replace(/\s+/g,' ')).join('\n');
console.log(str);```
</div>
</div>
</p>

<p>OR: Simply <code>str.replace(/[ \t]{1,}/g, ' ')</code></p>

<p>Where </p>

<p><code>\t</code> matches a tab character (ASCII 9)</p>

<p><code>{1,}</code> Quantifier — Matches between 1 and unlimited times, as many times as possible, giving back as needed</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>var str = `I    brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;
str = str.replace(/[ \t]{1,}/g, ' ');
console.log(str);</code>```

Body:
I need to remove white-spaces while keeping the lines

Before:

I brought           a            Banana
I sold                a Banana
I           brought a Apple

After: NO WHITE SPACES or big space at the begining of the line

I brought a Banana
I sold a Banana
I brought a Apple

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.

Body:
You can split the string with \n to map them:

var str = `I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;
str = str.split('\n').map(l => l.replace(/\s+/g,' ')).join('\n');
console.log(str);

OR: Simply str.replace(/[ \t]{1,}/g, ' ')

Where

\t matches a tab character (ASCII 9)

{1,} Quantifier — Matches between 1 and unlimited times, as many times as possible, giving back as needed

var str = `I    brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;
str = str.replace(/[ \t]{1,}/g, ' ');
console.log(str);


问:
Is there any easy and efficient way to write this code block which I am using to convert the Date and time to Timestamp in Groovy
```<code>String date = parameters.sendDate;
String time = parameters.sendTime;
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a");
SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");
String convertedTime = date24Format.format(date12Format.parse(time));
String convertedDate = UtilDateTime.toTimestamp(date , convertedTime);
</code>```

<p>//Currently this one is working but is there any much compact and easy way?</p>

答:
You should be able to do it with much less code. I used 11PM to illustrate getting it to 24 hour format:</p>

```<code>String sometime = '11:55 PM'
assert Date.parse('hh:mm a', sometime).format("HH.mm") == '23.55'
</code>```

Body:
String date = parameters.sendDate;
String time = parameters.sendTime;
SimpleDateFormat date12Format = new SimpleDateFormat("hh:mm a");
SimpleDateFormat date24Format = new SimpleDateFormat("HH:mm");
String convertedTime = date24Format.format(date12Format.parse(time));
String convertedDate = UtilDateTime.toTimestamp(date , convertedTime);

//Currently this one is working but is there any much compact and easy way?

Body:
You should be able to do it with much less code. I used 11PM to illustrate getting it to 24 hour format:

String sometime = '11:55 PM'
assert Date.parse('hh:mm a', sometime).format("HH.mm") == '23.55'


问:
How to update in one to one relation in laravel?
In my user model, I have the following code

```<code>public function profile()
{
    return $this->hasOne(UserProfile::class);
}
</code>```

In profile model,

```<code>public function user()
{
   return $this->belongsTo(User::class);
}
</code>```

The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.

```<code>$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';

$user = User::find($userId);
$res = $user->profile()->save($profile);
</code>```

What is the correct method to update in One to One Relationship ?

答:
You're doing right, however i could suggest a little improvement

You may use the following

```<code>$user = User::with('profile')->findOrFail($userId);

if ($user->profile === null)
{
    $profile = new UserProfile(['attr' => 'value', ....]);
    $user->profile()->save($profile);
}
else
{
    $user->profile()->update(['attr' => 'value', ....]);
}
</code>```

Body:
In my user model, I have the following code

public function profile()
{
    return $this->hasOne(UserProfile::class);
}

In profile model,

public function user()
{
   return $this->belongsTo(User::class);
}

The create method is working, But when I try to update the profile with following code, It is creating a new profile and doesn’t update the profile information.

$profile = new UserProfile();
$profile->dob = '1999-03-20';
$profile->bio = 'A professional programmer.';
$profile->facebook = 'http://facebook.com/test/1';
$profile->github = 'http://github.com/test/1';
$profile->twitter = 'http://twitter.com/test/1';

$user = User::find($userId);
$res = $user->profile()->save($profile);

What is the correct method to update in One to One Relationship ?

Body:
You're doing right, however i could suggest a little improvement

You may use the following

$user = User::with('profile')->findOrFail($userId);

if ($user->profile === null)
{
    $profile = new UserProfile(['attr' => 'value', ....]);
    $user->profile()->save($profile);
}
else
{
    $user->profile()->update(['attr' => 'value', ....]);
}


答:
Here is the code I executed in the link you have provided:

```<code>new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]
sub_lst = new_lst[8:12]
print(sub_lst)
</code>```

This line in the code you have written, you have updated the value of new_lst to only 4 elements.

```<code>new_lst = new_lst[9:12]
</code>```

So, it is showing the expected value as [].

Title: How to create a list in Python that will yield the following result []

Body:
Here is the code I executed in the link you have provided:

new_lst = ["computer", "luxurious", "basket", "crime", 0, 2.49, "institution", "slice", "sun", ["water", "air", "fire", "earth"], "games", 2.7, "code", "java", ["birthday", "celebration", 1817, "party", "cake", 5], "rain", "thunderstorm", "top down"]
sub_lst = new_lst[8:12]
print(sub_lst)

This line in the code you have written, you have updated the value of new_lst to only 4 elements.

new_lst = new_lst[9:12]

So, it is showing the expected value as [].


问:
C++ including a ".h" file, function duplication confusion
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).

Basically, my program was structured as follows:

The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).

Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc).  CalledByCurrent.h contains a class definition.

There was a non-class function defined in CalledByCurrent.cc called thisFunction().  thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function).  In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc.  However, when I did this, I got an error saying that the function was duplicated.  Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?

Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc.  However, when I did this, I found that Current.cc did not know what function I was talking about.  What the heck?  I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem.  Could you help me understand this behavior?  Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?

p.s - I apologize for how confusing this post is.  Please let me know if there's anything I can clear up.

答:
That's because whenever you simply declare a function it's considered in extern (global) scope (whether you declare it in a header file or not). Linker will have multiple implementation for the same function signature.

If those functions are truely helper functions then, declare them as;

```<code>static void thisFunction();
</code>```

Other way, if you are using the same function as helper then, simply declare it in a common header file, say:

```<code>//CalledByCurrent.h  (is included in both .cc files)
void thisFunction();
</code>```

And implement thisFunction() in either of the .cc files. This should solve the problem properly.

Body:
That's because whenever you simply declare a function it's considered in extern (global) scope (whether you declare it in a header file or not). Linker will have multiple implementation for the same function signature.

If those functions are truely helper functions then, declare them as;

static void thisFunction();

Other way, if you are using the same function as helper then, simply declare it in a common header file, say:

//CalledByCurrent.h  (is included in both .cc files)
void thisFunction();

And implement thisFunction() in either of the .cc files. This should solve the problem properly.


问:
Compare and Count Variable Dates?
Using the given statement below I am Receiving the Value of Course end date which is in varchar and coming from MySQL I tried to convert this to date format in $ced & $newformat...all goes fine but when I am trying to compare course end date with the current date it's not comparing... it's only comparing the date and not comparing with year and month

```<code> $enddate = $get_students_row['course_end_date'];
 $ced = strtotime("$enddate");
 $newformat = date('d/m/Y',$ced);
 $currentdate = date('d/m/Y');
</code>```

The function is if $newformat is less than and eqals to current date then field become red

```<code><tr <?php if(($newformat <= $currentdate)): ?> style="color:red;" <?php endif; ?>>
</code>```

But its not working as excepted its make row red but its only comapring with current date not with month and year....Also i was looking for to get Total count of $newformat.

My Code

```<code>                <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>

                   <td><?php  echo $students_rollno_class;?></td>
                   <td><?php  echo $students_admission_no;?> </td>
                   <td><?php  echo $students_firstname;?></td>
                   <td><?php  echo $students_contact;?></td>
                   <td><?php  echo $students_reference_no;?></td>
                   <td><?php  echo date('d/m/Y', strtotime($students_date));?></td>
                   <td><?php  echo $newformat;?></td>

               </tr><?php
                    }
                   ?>
</code>```

答:
You can see the comparison in this national format

```<code>$format = "d_m_y";
$date1  = \DateTime::createFromFormat($format, "03_01_12");
$date2  = \DateTime::createFromFormat($format, "31_12_11");

var_dump($date1 > $date2);
</code>```

Using DateTime::createFromFormat:

Title: Compare and Count Variable Dates?

Body:
Using the given statement below I am Receiving the Value of Course end date which is in varchar and coming from MySQL I tried to convert this to date format in $ced & $newformat...all goes fine but when I am trying to compare course end date with the current date it's not comparing... it's only comparing the date and not comparing with year and month

 $enddate = $get_students_row['course_end_date'];
 $ced = strtotime("$enddate");
 $newformat = date('d/m/Y',$ced);
 $currentdate = date('d/m/Y');

The function is if $newformat is less than and eqals to current date then field become red

<tr <?php if(($newformat <= $currentdate)): ?> style="color:red;" <?php endif; ?>>

But its not working as excepted its make row red but its only comapring with current date not with month and year....Also i was looking for to get Total count of $newformat.

My Code

                <tr <?php if(($ced <= time())): ?> style="color:red;" <?php endif; ?>>

                   <?php  echo $students_rollno_class;?>
                   <?php  echo $students_admission_no;?>
                   <?php  echo $students_firstname;?>
                   <?php  echo $students_contact;?>
                   <?php  echo $students_reference_no;?>
                   <?php  echo date('d/m/Y', strtotime($students_date));?>
                   <?php  echo $newformat;?>

<?php
                    }
                   ?>

Body:
You can see the comparison in this national format

$format = "d_m_y";
$date1  = \DateTime::createFromFormat($format, "03_01_12");
$date2  = \DateTime::createFromFormat($format, "31_12_11");

var_dump($date1 > $date2);

Using DateTime::createFromFormat:


答:
It's by design. Angular does not handle bindings defined in strings such as innetHTML bindings. (click) binding will not be processed in your situation.

You can do it like:

var dropZoneID = 'dropZone'
var droppedItemID = 'droppedItemID'

function removeContent() {
  console.log('removeContent');
}

var push_div = '
' + droppedItemID + ' X
'
$(push_div).hide().appendTo("#" + dropZoneID).fadeIn(1000);

// Using $(document).on(...) to bind events to dynamically created elements
$(document).on('click', $(push_div).find('a').eq(0), function() {
  removeContent()
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div id="dropZone"></div></code>```

For further details:

https://stackoverflow.com/a/37676847/1331040

https://stackoverflow.com/a/50809586/1331040

Title: Angular 5 and jQuery: (click) not calling function

Body:
I am currently working with Angular 5 and jQuery. I created a dynamic div through jQuery which I appended to a div.

var push_div = '

                ' +
                droppedItemID + '
                X

'
$(push_div).hide().appendTo("#" + dropZoneID).fadeIn(1000);

When I click on the link, the removeContent function is not calling.

removeContent() {
    console.log("function called");
}

Body:
It's by design. Angular does not handle bindings defined in strings such as innetHTML bindings. (click) binding will not be processed in your situation.

You can do it like:

var dropZoneID = 'dropZone'
var droppedItemID = 'droppedItemID'

function removeContent() {
  console.log('removeContent');
}

var push_div = '<div class="col-md-6"><span style="color: green;">' + droppedItemID + '</span>&nbsp;<a href="javascript:void(0)">X</a></div>'
$(push_div).hide().appendTo("#" + dropZoneID).fadeIn(1000);

// Using $(document).on(...) to bind events to dynamically created elements
$(document).on('click', $(push_div).find('a').eq(0), function() {
  removeContent()
});

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<div id="dropZone"></div>

For further details:

https://stackoverflow.com/a/37676847/1331040

https://stackoverflow.com/a/50809586/1331040


问:
Custom font-color Field Odoo
The model has attribute status

```<code>status = fields.Selection([
    ('Progreso', 'En progreso'),
    ('Completa', 'Completa'),
    ('Anulada', 'Anulada'),
    ('En espera', 'En espera')
], 'Estado')
</code>```

The view

```<code><div class="card-text">
     <field name="status" />
 </div>
</code>```

I would like each status have a particular font-color:

Progreso: Blue

Completo:Green

Thanks

答:
You can try this but you are limited to list of color.

```<code><field name = 'status' widget="selection" decoration-danger="status=='Progreso'" decoration-info="status=='Completa'" decoration-muted="status=='Anulada'" decoration-success="status=='En espera'"/>
</code>```

decoration-bf - BOLD

decoration-it - ITALICS

decoration-danger - LIGHT RED

decoration-info - LIGHT BLUE

decoration-muted - LIGHT GRAY

decoration-primary - LIGHT PURPLE

decoration-success - LIGHT GREEN

decoration-warning - LIGHT BROWN

You can try this too...

```<code><field name = 'status' widget="selection" t-att-style="'color: #f00;' if status == 'Progreso' else ('color: #00f;' if status ==
     'Completa' else 'color: #696969;')" />
</code>```

Title: Custom font-color Field Odoo

Body:
The model has attribute status

status = fields.Selection([
    ('Progreso', 'En progreso'),
    ('Completa', 'Completa'),
    ('Anulada', 'Anulada'),
    ('En espera', 'En espera')
], 'Estado')

The view

     <field name="status" />

I would like each status have a particular font-color:

Progreso: Blue

Completo:Green

Thanks

Body:
You can try this but you are limited to list of color.

<field name = 'status' widget="selection" decoration-danger="status=='Progreso'" decoration-info="status=='Completa'" decoration-muted="status=='Anulada'" decoration-success="status=='En espera'"/>

decoration-bf - BOLD

decoration-it - ITALICS

decoration-danger - LIGHT RED

decoration-info - LIGHT BLUE

decoration-muted - LIGHT GRAY

decoration-primary - LIGHT PURPLE

decoration-success - LIGHT GREEN

decoration-warning - LIGHT BROWN

You can try this too...

<field name = 'status' widget="selection" t-att-style="'color: #f00;' if status == 'Progreso' else ('color: #00f;' if status ==
     'Completa' else 'color: #696969;')" />


问:
Use/reference container name in a different service with docker compose
My docker-compose.yml file looks like this:

```<code>version: '3.7'

networks:
  myNetwork:

volumes:
  mongo_data:

services:

  db:
    image: mongo
    restart: always
    networks:
      - myNetwork
    volumes:
      - mongo_data:/data/db
    ports:
        - "27017:27017"

  mongoExpress:
    image: mongo-express
    networks:
      - myNetwork
    ports:
      - "8081:8081"
    environment:
      - ME_CONFIG_MONGODB_SERVER=<db-container-name>
    depends_on:
      - db
</code>```

For mongo-express to work, I need to be able to pass it the db/mongo container name. Is there a way to achieve this with compose?

答:
The service name is the host name on the network (myNetwork)  created by compose.

You may use db as the host name and value for <db-container-name>

i.e.

```<code>ME_CONFIG_MONGODB_SERVER=db
</code>```

Body:
My docker-compose.yml file looks like this:

version: '3.7'

networks:
  myNetwork:

volumes:
  mongo_data:

services:

  db:
    image: mongo
    restart: always
    networks:
      - myNetwork
    volumes:
      - mongo_data:/data/db
    ports:
        - "27017:27017"

  mongoExpress:
    image: mongo-express
    networks:
      - myNetwork
    ports:
      - "8081:8081"
    environment:
      - ME_CONFIG_MONGODB_SERVER=<db-container-name>
    depends_on:
      - db

For mongo-express to work, I need to be able to pass it the db/mongo container name. Is there a way to achieve this with compose?

Body:
The service name is the host name on the network (myNetwork)  created by compose.

You may use db as the host name and value for <db-container-name>

i.e.

ME_CONFIG_MONGODB_SERVER=db


问:
Markers show after hot reload but not when I press the button. (Flutter - Google Maps)
When I try to place a marker in my google map, it doesn't show until I click hot reload. Am I missing a setState() somewhere?

My issue is that I don't know where. The documentation for this package is really confusing because the google maps controller has been updated and changed dramatically since it's inception. A lot of guides simply don't help because the code has changed.

```<code>import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
import 'package:mobile_app_dev/UI/base_widget.dart';
import 'package:mobile_app_dev/UI/widgets.dart';

import '../main.dart';

class myMapScreen extends StatefulWidget {
  @override
  myMapState createState() => myMapState();

}

class myMapState extends State<myMapScreen> {

  PageController _pageController;
  GoogleMapController mapController;
  LatLng center = const LatLng(37.352727, -122.034227);
//  Location location = new Location();
  Position currentLocation;

  final Set<Marker> _markers = {};

  void _getLocation() async {
    var currentLocation = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best);

    setState(() {
      _markers.clear();
      final marker = Marker(
        markerId: MarkerId("curr_loc"),
        position: LatLng(currentLocation.latitude, currentLocation.longitude),
        infoWindow: InfoWindow(title: 'Your Location'),
        icon: BitmapDescriptor.defaultMarker
      );
      _markers.add(marker);
    });

    currentLocation = currentLocation;
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  void initState() {
    _markers.clear();
    super.initState();
    _pageController = PageController();
    _getLocation();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseWidget(builder: (context, sizingInformation) {
      return Scaffold(
        backgroundColor: MyApp.backgroundColor,
        appBar: AppBar(
          automaticallyImplyLeading: true,
          backgroundColor: MyApp.appBarColor,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              Text(
                'Map View',
                style: TextStyle(
                    color: MyApp.whiteNoChangeColor,
                    fontSize: 25.0,
                    fontWeight: FontWeight.bold
                ),
              ),
            ],
          ),
          centerTitle: true,
          actions: <Widget>[
            Padding(
                padding: EdgeInsets.only(right: 20.0),
                child: GestureDetector(
                  onTap: () async {
                    _getLocation();

                  },
                  child: Icon(
                    Icons.search,
                    size: 26.0,
                  ),
                )
            )
          ],
        ),
        body: Container(
          height: sizingInformation.myScreenSize.height,
          width: sizingInformation.myScreenSize.width,
          child: Stack(
            children: <Widget>[
              GoogleMap(
                onMapCreated: _onMapCreated,
                initialCameraPosition: CameraPosition(
                  target: center,
                  zoom: 15.0,
                ),
                myLocationEnabled: true,
                mapType: MapType.hybrid,
                compassEnabled: true,
                markers: _markers,
          ),
              Positioned(
                child: FlatButton(
                  color: Colors.green,
                  child: Text("button"),
                  onPressed: (){
                    final marker = Marker(
                      markerId: MarkerId("curr_loc"),
                      position: center,
                      infoWindow: InfoWindow(title: 'Your Location'),
                      icon: BitmapDescriptor.defaultMarker
                    );
                    _markers.add(marker);
//                    _getLocation();
                  },
                ),
              )

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

答:
**Just add a setState method inside onPressed please check the example below **</p>

```<code>     onPressed: (){
                final marker = Marker(
                  markerId: MarkerId("curr_loc"),
                  position: center,
                  infoWindow: InfoWindow(title: 'Your Location'),
                  icon: BitmapDescriptor.defaultMarker
                );
             setState((){
                        _markers.add(marker);
                       });
              },
</code>```

Body:
When I try to place a marker in my google map, it doesn't show until I click hot reload. Am I missing a setState() somewhere?

My issue is that I don't know where. The documentation for this package is really confusing because the google maps controller has been updated and changed dramatically since it's inception. A lot of guides simply don't help because the code has changed.

import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
import 'package:mobile_app_dev/UI/base_widget.dart';
import 'package:mobile_app_dev/UI/widgets.dart';

import '../main.dart';

class myMapScreen extends StatefulWidget {
  @override
  myMapState createState() => myMapState();

}

class myMapState extends State<myMapScreen> {

  PageController _pageController;
  GoogleMapController mapController;
  LatLng center = const LatLng(37.352727, -122.034227);
//  Location location = new Location();
  Position currentLocation;

  final Set<Marker> _markers = {};

  void _getLocation() async {
    var currentLocation = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best);

    setState(() {
      _markers.clear();
      final marker = Marker(
        markerId: MarkerId("curr_loc"),
        position: LatLng(currentLocation.latitude, currentLocation.longitude),
        infoWindow: InfoWindow(title: 'Your Location'),
        icon: BitmapDescriptor.defaultMarker
      );
      _markers.add(marker);
    });

    currentLocation = currentLocation;
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  void initState() {
    _markers.clear();
    super.initState();
    _pageController = PageController();
    _getLocation();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BaseWidget(builder: (context, sizingInformation) {
      return Scaffold(
        backgroundColor: MyApp.backgroundColor,
        appBar: AppBar(
          automaticallyImplyLeading: true,
          backgroundColor: MyApp.appBarColor,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[

              Text(
                'Map View',
                style: TextStyle(
                    color: MyApp.whiteNoChangeColor,
                    fontSize: 25.0,
                    fontWeight: FontWeight.bold
                ),
              ),
            ],
          ),
          centerTitle: true,
          actions: <Widget>[
            Padding(
                padding: EdgeInsets.only(right: 20.0),
                child: GestureDetector(
                  onTap: () async {
                    _getLocation();

                  },
                  child: Icon(
                    Icons.search,
                    size: 26.0,
                  ),
                )
            )
          ],
        ),
        body: Container(
          height: sizingInformation.myScreenSize.height,
          width: sizingInformation.myScreenSize.width,
          child: Stack(
            children: <Widget>[
              GoogleMap(
                onMapCreated: _onMapCreated,
                initialCameraPosition: CameraPosition(
                  target: center,
                  zoom: 15.0,
                ),
                myLocationEnabled: true,
                mapType: MapType.hybrid,
                compassEnabled: true,
                markers: _markers,
          ),
              Positioned(
                child: FlatButton(
                  color: Colors.green,
                  child: Text("button"),
                  onPressed: (){
                    final marker = Marker(
                      markerId: MarkerId("curr_loc"),
                      position: center,
                      infoWindow: InfoWindow(title: 'Your Location'),
                      icon: BitmapDescriptor.defaultMarker
                    );
                    _markers.add(marker);
//                    _getLocation();
                  },
                ),
              )

            ],
          ),
        ),
      );
    },
    );
  }
}

Body:
**Just add a setState method inside onPressed please check the example below **

     onPressed: (){
                final marker = Marker(
                  markerId: MarkerId("curr_loc"),
                  position: center,
                  infoWindow: InfoWindow(title: 'Your Location'),
                  icon: BitmapDescriptor.defaultMarker
                );
             setState((){
                        _markers.add(marker);
                       });
              },


问:
generate a sql query for the following output
I have a table account(ID,TransDate,amount,isDebit,balance). Obviously  this is a trimmed down version of my table for sake of clarity. TransDate is the date for which the entry will be made, isDebit is a boolean which tells if this transaction is a DEBIT or CREDIT.

A when a new entry is made it could have a transDate older then the last entry made, so i have to position it in right place and change the balances of all the rows which will be below that position. There I sort the rows by transDate ASC , ID ASC , which gives me the correct order of entries.

Balance will be generated by adding current amount to previous last balance id DEBIT and deducted if current entry is CREDIT.

It has the following last 5 entries sorted by transDate ASC , ID ASC:

account(ID,TransDate,amount,isDebit,balance) as an example

```<code>41 | 2011-04-10 | 1000 | 1 | 1000      // as this is the first entry  but not always

37 | 2011-05-14 | 7500 | 1 | 8500

39 | 2011-05-14 | 6500 | 0 | 2000

46 | 2011-05-15 | 1000 | 1 | 3000
</code>```

Can anyone generate a query(s):

To make a new entry with following details : <ID auto> | 2011-05-9 | 1000 | 1 | <balance>

the query should find that the new entry position is after row with ID 41 and before row ID 37. and also fetches me rows from Id 41 (as this row's balance will be used to calculate the balance for the new row) and below on which i set the new corrected balances.

Or suggest a new method to implement this kind of "ledger accounting".

答: Unfortunately, MySQL has no support for window functions, but you might be able to derive a solution from this previous answer involving stored procedures, as SQL Server's window function support is too limited for this kind of query as well: Calculate a Running Total in SQL Server</p>

Body:
I have a table account(ID,TransDate,amount,isDebit,balance). Obviously  this is a trimmed down version of my table for sake of clarity. TransDate is the date for which the entry will be made, isDebit is a boolean which tells if this transaction is a DEBIT or CREDIT.

A when a new entry is made it could have a transDate older then the last entry made, so i have to position it in right place and change the balances of all the rows which will be below that position. There I sort the rows by transDate ASC , ID ASC , which gives me the correct order of entries.

Balance will be generated by adding current amount to previous last balance id DEBIT and deducted if current entry is CREDIT.

It has the following last 5 entries sorted by transDate ASC , ID ASC:

account(ID,TransDate,amount,isDebit,balance) as an example

41 | 2011-04-10 | 1000 | 1 | 1000      // as this is the first entry  but not always

37 | 2011-05-14 | 7500 | 1 | 8500

39 | 2011-05-14 | 6500 | 0 | 2000

46 | 2011-05-15 | 1000 | 1 | 3000

Can anyone generate a query(s):

To make a new entry with following details : <ID auto> | 2011-05-9 | 1000 | 1 | <balance>

the query should find that the new entry position is after row with ID 41 and before row ID 37. and also fetches me rows from Id 41 (as this row's balance will be used to calculate the balance for the new row) and below on which i set the new corrected balances.

Or suggest a new method to implement this kind of "ledger accounting".