问:
Retrieve specific data from child nodes through loop in firebase android development
I am trying to get specific value from firebase database.look at the code first.
It's data base reference

```<code>DatabaseReference databasedeposit= FirebaseDatabase.getInstance().getReference("Deposit");

totalb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            databasedeposit.addListenerForSingleValueEvent (new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    abc.clear();
                    Integer total = 0;

                    for (DataSnapshot ds : dataSnapshot.getChildren()) {
                        ADeposit bazar = ds.getValue(ADeposit.class);
                        Integer cost = Integer.valueOf(bazar.getAmount());
                        total = total + cost;
                        abc.add(bazar);

                    }

                    Query queryn=databasedeposit.orderByChild("name").equalTo("Rabbani");

                    queryn.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            Integer n_total=0;

                            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                ADeposit bazar = ds.getValue(ADeposit.class);
                                Integer c = Integer.valueOf(bazar.getAmount());
                                n_total = n_total + c;
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                    DepositList adapter = new DepositList(admininterface.this,abc);
                    deposit.setAdapter(adapter);

                    AlertDialog.Builder dialog1 = new AlertDialog.Builder(admininterface.this);
                    dialog1.setTitle("Notification");
                    dialog1.setMessage("Total Deposit  : " +total );

                    dialog1.setIcon(R.drawable.ic_done_black_24dp);
                    dialog1.setNeutralButton(
                            "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    dialog.dismiss();

                                }
                            });
                    dialog1.show();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            }); ;

        }
    });

}
</code>```

now the total cost is easily retrievable. but specific data from a user like in here "Rabbani" for retrive his total amount i create a Query but i cannot access n_total value from the portion like dialogue box.

Take a look database structure:

Now i want, to get the sum off all amount from name "Rabbani" so do same like for other name "Sobuj". is this process is right?
or  is there any other process? to retrieve separe users total amount?

答:
You don't need the nested listener to get Rabbani's spending. Since this data is already present in databasedeposit, you can just use an if in your existing loop to track that:

```<code>databasedeposit.addListenerForSingleValueEvent (new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        abc.clear();
        Integer total = 0;
        Integer n_total=0;

        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            ADeposit bazar = ds.getValue(ADeposit.class);
            Integer cost = Integer.valueOf(bazar.getAmount());
            total = total + cost;
            abc.add(bazar);

            if ("Rabbani".equals(ds.child("name").getValue(String.class)) {
                n_total = n_total + cost;
            }
        }

        System.out.println("total: "+total+", n_total: "+n_total);

        ...

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
}); ;
</code>```

Body:
I am trying to get specific value from firebase database.look at the code first.
It's data base reference

DatabaseReference databasedeposit= FirebaseDatabase.getInstance().getReference("Deposit");

totalb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            databasedeposit.addListenerForSingleValueEvent (new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    abc.clear();
                    Integer total = 0;

                    for (DataSnapshot ds : dataSnapshot.getChildren()) {
                        ADeposit bazar = ds.getValue(ADeposit.class);
                        Integer cost = Integer.valueOf(bazar.getAmount());
                        total = total + cost;
                        abc.add(bazar);

                    }

                    Query queryn=databasedeposit.orderByChild("name").equalTo("Rabbani");

                    queryn.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            Integer n_total=0;

                            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                ADeposit bazar = ds.getValue(ADeposit.class);
                                Integer c = Integer.valueOf(bazar.getAmount());
                                n_total = n_total + c;
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                    DepositList adapter = new DepositList(admininterface.this,abc);
                    deposit.setAdapter(adapter);

                    AlertDialog.Builder dialog1 = new AlertDialog.Builder(admininterface.this);
                    dialog1.setTitle("Notification");
                    dialog1.setMessage("Total Deposit  : " +total );

                    dialog1.setIcon(R.drawable.ic_done_black_24dp);
                    dialog1.setNeutralButton(
                            "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    dialog.dismiss();

                                }
                            });
                    dialog1.show();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {}
            }); ;

        }
    });

}

now the total cost is easily retrievable. but specific data from a user like in here "Rabbani" for retrive his total amount i create a Query but i cannot access n_total value from the portion like dialogue box.

Take a look database structure:

Now i want, to get the sum off all amount from name "Rabbani" so do same like for other name "Sobuj". is this process is right?
or  is there any other process? to retrieve separe users total amount?

Body:
You don't need the nested listener to get Rabbani's spending. Since this data is already present in databasedeposit, you can just use an if in your existing loop to track that:

databasedeposit.addListenerForSingleValueEvent (new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        abc.clear();
        Integer total = 0;
        Integer n_total=0;

        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            ADeposit bazar = ds.getValue(ADeposit.class);
            Integer cost = Integer.valueOf(bazar.getAmount());
            total = total + cost;
            abc.add(bazar);

            if ("Rabbani".equals(ds.child("name").getValue(String.class)) {
                n_total = n_total + cost;
            }
        }

        System.out.println("total: "+total+", n_total: "+n_total);

        ...

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
}); ;


来源: stackexchange

问:
How to write this type of data to csv
im a noobie in python. I want to get some data from csv with pandas and after write a new csv file with extra data in format
"type";"currency";"amount";"comment"
"type1";"currency1";"amount1";"comment1"
etc

```<code>import pandas as pd
import csv

  req=pd.read_csv('/Users/user/web/python/Bookcopy.csv')
  type="type"
  comment = "2week"
  i=0
  while i<3:
  Currency = req['Currency'].values[i]
  ReqAmount = req['Request'].values[i]
  r = round(ReqAmount,-1)
  i+=1
  data =[type,Currency,r,comment]
  #print(data)

csv_file = open('data2.csv', 'w')
with csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(data)

print("DONE")
</code>```

writer.writerows(data)
_csv.Error: iterable expected, not numpy.float64

答:
I have multiple things to criticize here. I hope it doesn't come across mean, but rather educational. While your code would work regardless of those points, it is good coding style to follow them.

Variables should not start with a capital letter. Currency and ReqAmount should be currency and reqAmount.

Don't use keywords for variable names. type is a python keyword.

Make sure your formatting doesn't get destroyed when posting here. Especially for python, which relies on tab formatting. Read here for more information: https://stackoverflow.com/editing-help#code

That said, let me try to go through your code and give you tips and tricks:

Don't run code in python directly. Always use the main() method. It's just better coding style.

When looping, don't use the i=0; while i<3; i+=1 construct, rather use for i in range(3). While it works, it is not very pythonic and a lot harder to read.

Never assume anything that cannot be guaranteed in your code. In this case, you assume that the csv-file has at least 3 lines, otherwise your program would crash. Instead, read the number of lines from the csv file, with len(req).

data =[type,Currency,r,comment] keeps overwriting your data variable. You could either append to data and then write everything to the output file at the end, or directly write to the output file in every iteration.

Don't use open to create a variable (except absolutely necessary). Instead, use open in a with statement. This ensures that the file will get closed properly. I have seen that you do use the with statement, nonetheless you usually use it like with open(...) as variable_name:.

CSV files usually start with the column names. Therefore you should write the column names before you write data.

I won't fix that, because it will change the appearance of the program completely, but normally, don't mix different libraries. If you use pandas for csv reading, also use it for writing. If you use the csv library for writing, also use it for reading. While it isn't wrong to mix them, it is bad style and creates more dependencies than would be necessary.

I don't really understand what your code is supposed to do, so I just guess and hope it goes in the right direction.

When fixing all those points, you might have something like that:

import pandas as pd
import csv

def main():
    req=pd.read_csv('/Users/user/web/python/Bookcopy.csv')
    transferType = "type"
    comment = "2week"

    with open('data2.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow(["type","currency","amount","comment"])

        for i in range(len(req)):
            currency = req['Currency'].values[i]
            reqAmount = req['Request'].values[i]
            r = round(reqAmount,-1)
            data = [transferType,currency,r,comment]
            #print(data)

            writer.writerow(data)

    print("DONE")

# Whenever you run a program, __name__ will be set to '__main__' in the initial
# script. This makes it easier later when you work with multiple code files.
if __name__ == '__main__':
    main()
```

ContentLicense: CC BY-SA 4.0

Title: How to write this type of data to csv

Body:
im a noobie in python. I want to get some data from csv with pandas and after write a new csv file with extra data in format
"type";"currency";"amount";"comment"
"type1";"currency1";"amount1";"comment1"
etc

import pandas as pd
import csv

  req=pd.read_csv('/Users/user/web/python/Bookcopy.csv')
  type="type"
  comment = "2week"
  i=0
  while i<3:
  Currency = req['Currency'].values[i]
  ReqAmount = req['Request'].values[i]
  r = round(ReqAmount,-1)
  i+=1
  data =[type,Currency,r,comment]
  #print(data)

csv_file = open('data2.csv', 'w')
with csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(data)

print("DONE")

writer.writerows(data)
_csv.Error: iterable expected, not numpy.float64


问:
How can we see logs just after and before particular text in Google Cloud Logging?
In Google Cloud Logging, using advanced search Can we search for a text and then see logs present after and before that particular text?

Like for example in a PDF, doc or any file when you search for a word then after searching that word you can see content just above and below of the searched text, but in google cloud logging we can only see texts where words are present, but not the content present just above and below it.

Can anyone please tell me is it possible to search just above and below logs present in Google Cloud Logging or not?

答:
You can do this by pinning the log entry: https://cloud.google.com/logging/docs/view/overview#pin

Once the entry is pinned, you can relax the filter to match whatever other entries would be helpful for context.


问:
Google Search API Missing Parameter q
Not sure what I'm doing wrong here. I have been following these instructions fully.

Anyways, I am trying to use Google custom search API. I have my API and CS key.  I enter the following, with appropriate info filled in, but it says I am missing the q parameter when I am clearly not. Any ideas what I am doing wrong?

```<code>curl https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures

{
 "error": {
  "errors": [
    {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: q",
    "locationType": "parameter",
    "location": "q"
   }
  ],
  "code": 400,
  "message": "Required parameter: q"
 }
}
</code>```

答:
The Google API states that "q" or the query is necessary to run.

Parameter name    Value   Description
  Required query parameters
  cx    string  The custom search engine ID to use for this request.
  q     string  Query

https://developers.google.com/custom-search/v1/cse/list

ContentLicense: CC BY-SA 3.0

Title: Google Search API Missing Parameter q

Body:
Not sure what I'm doing wrong here. I have been following these instructions fully.

Anyways, I am trying to use Google custom search API. I have my API and CS key.  I enter the following, with appropriate info filled in, but it says I am missing the q parameter when I am clearly not. Any ideas what I am doing wrong?

curl https://www.googleapis.com/customsearch/v1?key=INSERT_YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=lectures

{
 "error": {
  "errors": [
    {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: q",
    "locationType": "parameter",
    "location": "q"
   }
  ],
  "code": 400,
  "message": "Required parameter: q"
 }
}


问:
H2 db for SpringBoot tests
I am using Postgres database and I want to use H2 database for tests. The problem is when I'm creating new object in database, it seems that H2 is not used at all in test.

Test class:

```<code> @RunWith(SpringJUnit4ClassRunner.class)
 @SpringBootTest
 @AutoConfigureMockMvc
 @WithMockUser(roles = "ADMIN")
 @ActiveProfiles("test")
 public class CompanyTests {

@SpyBean
private CompanyService companyServiceMock;

@Autowired
private MockMvc mockMvc;

@Autowired
EntityManager entityManager;

@Test
@Transactional
public void testaaaa() {
    entityManager.persist(new Company("nnnn", new Address()));
    List<Company> all = companyServiceMock.findAll();
    all.forEach(company -> System.out.println(company.getName()));
}
</code>```

application.properties:

```<code> spring.datasource.driverClassName=org.postgresql.Driver
 spring.datasource.url=jdbc:postgresql://localhost:5432/EDI
 spring.datasource.username=postgres
 spring.datasource.password=password
 spring.datasource.platform=postgresql
 spring.datasource.initialize=true
 spring.datasource.continue-on-error=true
 spring.jackson.serialization.fail-on-empty-beans=false

 spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
 spring.jpa.generate-ddl=true
 spring.jpa.show-sql=true
 spring.jpa.hibernate.ddl-auto=create
</code>```

application-test.properties:

```<code>spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-
1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true
</code>```

And when I use findAll() in my test, it lists all companies from postgresql and new which is created by entityManager.

答:
How about adding @TestPropertySource(locations= "classpath:application-test.properties") to the annotation? you should make it explicit for the test class that you are using the test application.properties.

This is late, but I'd be happy to be of some help.

Title: H2 db for SpringBoot tests

Body:
I am using Postgres database and I want to use H2 database for tests. The problem is when I'm creating new object in database, it seems that H2 is not used at all in test.

Test class:

 @RunWith(SpringJUnit4ClassRunner.class)
 @SpringBootTest
 @AutoConfigureMockMvc
 @WithMockUser(roles = "ADMIN")
 @ActiveProfiles("test")
 public class CompanyTests {

@SpyBean
private CompanyService companyServiceMock;

@Autowired
private MockMvc mockMvc;

@Autowired
EntityManager entityManager;

@Test
@Transactional
public void testaaaa() {
    entityManager.persist(new Company("nnnn", new Address()));
    List<Company> all = companyServiceMock.findAll();
    all.forEach(company -> System.out.println(company.getName()));
}

application.properties:

 spring.datasource.driverClassName=org.postgresql.Driver
 spring.datasource.url=jdbc:postgresql://localhost:5432/EDI
 spring.datasource.username=postgres
 spring.datasource.password=password
 spring.datasource.platform=postgresql
 spring.datasource.initialize=true
 spring.datasource.continue-on-error=true
 spring.jackson.serialization.fail-on-empty-beans=false

 spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
 spring.jpa.generate-ddl=true
 spring.jpa.show-sql=true
 spring.jpa.hibernate.ddl-auto=create

application-test.properties:

spring.datasource.initialize=true
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-
1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.h2.console.enabled=true

And when I use findAll() in my test, it lists all companies from postgresql and new which is created by entityManager.


问:
GridLayoutManager item width wrap_content not working
I am laying out views using GridLayoutManager which works fine. However I each item in the grid fills the whole width of the column which makes the view having lots of empty spaces hence I want to use wrap_content for the root view of items but its not working. There's still spaces left from the right side of the grid.

答: Since no one has been able to answer this, I will just outline what I did to sort it. I use ItemDecorator to fill the space between the columns</p>


问:
Google Charts: Dynamically Add Series to Chart
There is a similar thread here but the answer isn't clear and there is no clear example to follow.

I need to dynamically add series to a Google Charts graph. Suppose each successive click of a button should add a new series from my array. Right now it just replaces it. What should I do?

// Init
google.charts.load('current', {'packages':['corechart']});

var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];

$('#addSeries').click(function() {

   if (currentclick < 3) {
       draw(nums, currentclick);
   }
   currentclick++;
});

function draw(arr, seriesnum) {
  var chartData = new google.visualization.DataTable();
 chartData.addColumn('string', 'Year');
 chartData.addColumn('number', 'Value');

  var chartRowArray = $.makeArray();
 for (var i = 0; i < 4; i++) {
  chartRowArray.push( [ titles[i], arr[seriesnum][i] ] );
 }
 chartData.addRows(chartRowArray);
  var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
  chart.draw(chartData, null);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="addSeries">Add Next Series</button>

<div id="chartarea">
</div></code>```

答:
The key thing is the final structure of the data.

The Column Array should be

```<code>0: Year
1: Value
2: Value
etc.
</code>```

The Column array is added 1-by-1 as chartData.addColumn(type, name).

The data's Row Array should be

```<code>0:
   0: Year1
   1: 44
   2: 33
1:
   0: Year2
   1: 12
   2: 11
etc.
</code>```

The Row Array is added in one shot as chartData.addRows(rowArray).

Knowing this, I made both RowArray / ColArray global variables that get modified on the fly (thanks for the idea Tainake) and for the initial conditions when the arrays are empty, I construct or initialize them for the first time.

Working example below. Thanks again for the help!

// Init
google.charts.load('current', {'packages':['corechart']});

var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];
var chartColArray = $.makeArray(); // Global var
var chartRowArray = $.makeArray(); // Global var

$('#addSeries').click(function() {

   if (currentclick < 3) {
       draw(nums, currentclick);
   }
   currentclick++;
});

function draw(arr, seriesnum) {
 var chartData = new google.visualization.DataTable();

 // For initial Column, push 'Year'; otherwise, push 'Value'
 if (chartColArray.length == 0) {
  chartColArray.push('Year');
 }
 chartColArray.push('Value');
 // addColumn() has to be 1-by-1-by-1, there is no addColumns(colarray)
 $.each(chartColArray, function(index, item) {
  (index == 0 ? chartData.addColumn('string', item) : chartData.addColumn('number', item));
 });

 for (var i = 0; i < 4; i++) {
        // For initial Row subarray, create subarray and push 'Year Series';
        // otherwise, push actual 'Series' value
  if (chartRowArray[i] == undefined) {
   chartRowArray[i] = $.makeArray();
   chartRowArray[i].push(titles[seriesnum]);
  }
  chartRowArray[i].push(nums[seriesnum][i]);
 }
 chartData.addRows(chartRowArray);

 // Instantiate and draw the chart.
 var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
 chart.draw(chartData, null);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="addSeries">Add Next Series</button>

<div id="chartarea">
</div></code>```

Body:
There is a similar thread here but the answer isn't clear and there is no clear example to follow.

I need to dynamically add series to a Google Charts graph. Suppose each successive click of a button should add a new series from my array. Right now it just replaces it. What should I do?

// Init
google.charts.load('current', {'packages':['corechart']});

var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];

$('#addSeries').click(function() {

   if (currentclick < 3) {
       draw(nums, currentclick);
   }
   currentclick++;
});

function draw(arr, seriesnum) {
  var chartData = new google.visualization.DataTable();
 chartData.addColumn('string', 'Year');
 chartData.addColumn('number', 'Value');

  var chartRowArray = $.makeArray();
 for (var i = 0; i < 4; i++) {
  chartRowArray.push( [ titles[i], arr[seriesnum][i] ] );
 }
 chartData.addRows(chartRowArray);
  var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
  chart.draw(chartData, null);
}

<button id="addSeries">Add Next Series</button>

Body:
The key thing is the final structure of the data.

The Column Array should be

0: Year
1: Value
2: Value
etc.

The Column array is added 1-by-1 as chartData.addColumn(type, name).

The data's Row Array should be

0:
   0: Year1
   1: 44
   2: 33
1:
   0: Year2
   1: 12
   2: 11
etc.

The Row Array is added in one shot as chartData.addRows(rowArray).

Knowing this, I made both RowArray / ColArray global variables that get modified on the fly (thanks for the idea Tainake) and for the initial conditions when the arrays are empty, I construct or initialize them for the first time.

Working example below. Thanks again for the help!

// Init
google.charts.load('current', {'packages':['corechart']});

var currentclick = 0;

// My Data
var titles = ['Year1','Year2','Year3','Year4'];
var nums = [ [44,12,33,22], [33,11,7,8], [2,1,65,44] ];
var chartColArray = $.makeArray(); // Global var
var chartRowArray = $.makeArray(); // Global var

$('#addSeries').click(function() {

   if (currentclick < 3) {
       draw(nums, currentclick);
   }
   currentclick++;
});

function draw(arr, seriesnum) {
 var chartData = new google.visualization.DataTable();

 // For initial Column, push 'Year'; otherwise, push 'Value'
 if (chartColArray.length == 0) {
  chartColArray.push('Year');
 }
 chartColArray.push('Value');
 // addColumn() has to be 1-by-1-by-1, there is no addColumns(colarray)
 $.each(chartColArray, function(index, item) {
  (index == 0 ? chartData.addColumn('string', item) : chartData.addColumn('number', item));
 });

 for (var i = 0; i < 4; i++) {
        // For initial Row subarray, create subarray and push 'Year Series';
        // otherwise, push actual 'Series' value
  if (chartRowArray[i] == undefined) {
   chartRowArray[i] = $.makeArray();
   chartRowArray[i].push(titles[seriesnum]);
  }
  chartRowArray[i].push(nums[seriesnum][i]);
 }
 chartData.addRows(chartRowArray);

 // Instantiate and draw the chart.
 var chart = new google.visualization.LineChart(document.getElementById('chartarea'));
 chart.draw(chartData, null);
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="addSeries">Add Next Series</button>

<div id="chartarea">
</div>


问:
Use inline keyword for small, private functions in kotlin?
I would like to know, if it is a good idea to inline small, private functions?
These functions, in my case, are only there for readability purposes and I know, that they are only called a few times, so the bigger bytecode size is insignificant.

I know, that the performance boost may also be insignificant, because I am not passing functional types (and the compiler actually warns me about that), but lets assume that it is a hot spot in our application.

Actual example:

I hava a theoretically infinite tape of symbols (like the one of a turing machine) which is modeled by tow arrays (left and right for positions < 0 and positions >= 0, respectively). Now I have read and write operations which are assumed to be called a lot.

In java I had:

/**
 * @param cell the cell
 * @return the symbol at the specified cell
 */
public char read(int cell) {
    char[] tape;
    if (cell < 0) {
        tape = left;
        cell = -cell - 1;
    } else {
        tape = right;
    }
    return cell < tape.length ? tape[cell] : blank;
}

/**
 * Writes a symbol to the specified cell.
 * @param c    the symbol
 * @param cell the cell
 */
public void write(char c, int cell) {
    char[] tape;
    if (cell < 0) {
        cell = -cell - 1;
        if (cell >= left.length) left = expandArray(left, cell, blank);
        tape = left;
    } else {
        if (cell >= right.length) right = expandArray(right, cell, blank);
        tape = right;
    }
    tape[cell] = c;
}
```

<p>Now I wanted to translate the snippet to kotlin, read about inline functions and come up with this:</p>

```fun read(cell: Int = headPosition) = when {
    cell < 0 -> read(left, -cell - 1)
    else     -> read(right, cell)
}

private inline fun read(tape: CharArray, cell: Int): Char {
    return if (cell < tape.size) tape[cell] else blank
}

fun write(c: Char, cell: Int = headPosition) = when {
    cell < 0 -> left = write(c, left, -cell - 1)
    else -> right = write(c, right, cell)
}

private inline fun write(c: Char, tape: CharArray, cell: Int): CharArray = when {
    cell >= tape.size -> expandArray(tape, cell, blank)
    else -> tape
}.also { it[cell] = c }
```

I personally think, especially the read functions, are easy to read.

So is this a good idea and can I ignore the warning of the IDE? Or am I missing something? Maybe there is a best practice or other pattern to write these functions without repeading (almost) the same lines twice (for position < 0 and position >= 0).

答:
There is no need to inline a very small repeatedly used function since the JVM JIT will likely do this for you anyway when it deems it to be appropriate.  If you inline the function you do cause a bit of bloat in the generated bytecode but otherwise, there isn't a lot of harm there either for functions that are not called from many different points in your code.  Bytecode bloat is worse for larger inline functions, functions used from many places in your code, and inline functions that call other inline functions.  Your case does not cause much at all.

Short methods benefit heavily from inlining and as you can read in When Short Methods Pay Off: JIT Inlining:

A method is eligible for inlining if:

It’s small – the bytecode size is smaller than 35 bytes (can be overridden by the -XX:MaxInlineSize=X flag).

It’s called frequently (it’s hot) and it’s smaller than 325 bytes (can be overridden by the -XX:MaxFreqInlineSize=X flag).

If you exceed these parameters or want to pre-warm up the inlining you can use the inline keyword to cause it to happen at compilation time.

You also would want to use inline on small functions when:

You want to allow a lambda passed to the function to do a non-local return

You want to use reified generic type parameters.

You are writing a function that accepts a lambda that it uses in high repetition and you want to avoid the function call overhead to the lambda.  By inlining this type of function, the Kotlin compiler also inlines the lambda.

Body:
I would like to know, if it is a good idea to inline small, private functions?
These functions, in my case, are only there for readability purposes and I know, that they are only called a few times, so the bigger bytecode size is insignificant.

I know, that the performance boost may also be insignificant, because I am not passing functional types (and the compiler actually warns me about that), but lets assume that it is a hot spot in our application.

Actual example:

I hava a theoretically infinite tape of symbols (like the one of a turing machine) which is modeled by tow arrays (left and right for positions < 0 and positions >= 0, respectively). Now I have read and write operations which are assumed to be called a lot.

In java I had:

/**
 * @param cell the cell
 * @return the symbol at the specified cell
 */
public char read(int cell) {
    char[] tape;
    if (cell < 0) {
        tape = left;
        cell = -cell - 1;
    } else {
        tape = right;
    }
    return cell < tape.length ? tape[cell] : blank;
}

/**
 * Writes a symbol to the specified cell.
 * @param c    the symbol
 * @param cell the cell
 */
public void write(char c, int cell) {
    char[] tape;
    if (cell < 0) {
        cell = -cell - 1;
        if (cell >= left.length) left = expandArray(left, cell, blank);
        tape = left;
    } else {
        if (cell >= right.length) right = expandArray(right, cell, blank);
        tape = right;
    }
    tape[cell] = c;
}

Now I wanted to translate the snippet to kotlin, read about inline functions and come up with this:

fun read(cell: Int = headPosition) = when {
    cell < 0 -> read(left, -cell - 1)
    else     -> read(right, cell)
}

private inline fun read(tape: CharArray, cell: Int): Char {
    return if (cell < tape.size) tape[cell] else blank
}

fun write(c: Char, cell: Int = headPosition) = when {
    cell < 0 -> left = write(c, left, -cell - 1)
    else -> right = write(c, right, cell)
}

private inline fun write(c: Char, tape: CharArray, cell: Int): CharArray = when {
    cell >= tape.size -> expandArray(tape, cell, blank)
    else -> tape
}.also { it[cell] = c }

I personally think, especially the read functions, are easy to read.

So is this a good idea and can I ignore the warning of the IDE? Or am I missing something? Maybe there is a best practice or other pattern to write these functions without repeading (almost) the same lines twice (for position < 0 and position >= 0).


问:
Excel: Sum duplicates values only once and only on visible cells
Given the following FILTERED table :

```<code>TYPE    NUM
A       3
A       3
A       3
B       5
B       5
</code>```

I need to find the sum of column NUM without including the duplicate values.
I currently have the following solution based on another post:

=SUMPRODUCT(B2:B6/COUNTIFS(A2:A6,A2:A6))

In this case, the result is 8, which is correct when no filters have been applied.

Now if I filter the column to show only A in TYPE, it will still show me 8. The issue I am having is I need the sum to be adjusted based on what is visible. After applying the filter to show only A, I should be getting 3 and if I filter to show B only I should get 5. I've tried AGGREGATE and SUBTOTAL and haven't gotten anywhere.

Is there a way to adjust the above formula to VISIBLE cells only?

Thanks,

答:
So it's a rather complicated formula involving both SUMPRODUCT(), SUBTOTAL() and OFFSET(). More information here

To implement this to your situation you would get:

```<code>=SUMPRODUCT((B2:B6/COUNTIFS(A2:A6,A2:A6))*(SUBTOTAL(3,OFFSET(B2,ROW(B2:B6)-MIN(ROW(B2:B6)),0))))
</code>```

Another option would be (in your case if values for each criteria is the same)

```<code>=SUMPRODUCT((A2:A6<>A3:A7)*(B2:B6)*(SUBTOTAL(3,OFFSET(B2,ROW(B2:B6)-MIN(ROW(B2:B6)),0))))
</code>```

In my example I'll filter out both A and B

A formula to be used on dynamic ranges would look like:

```<code>=SUMPRODUCT((B2:INDEX(B:B,COUNTA(B:B))/COUNTIFS(A2:INDEX(A:A,COUNTA(A:A)),A2:INDEX(A:A,COUNTA(A:A))))*(SUBTOTAL(3,OFFSET(B2,ROW(B2:INDEX(B:B,COUNTA(B:B)))-MIN(ROW(B2:INDEX(B:B,COUNTA(B:B)))),0))))
</code>```

Body:
Given the following FILTERED table :

TYPE    NUM
A       3
A       3
A       3
B       5
B       5

I need to find the sum of column NUM without including the duplicate values.
I currently have the following solution based on another post:

=SUMPRODUCT(B2:B6/COUNTIFS(A2:A6,A2:A6))

In this case, the result is 8, which is correct when no filters have been applied.

Now if I filter the column to show only A in TYPE, it will still show me 8. The issue I am having is I need the sum to be adjusted based on what is visible. After applying the filter to show only A, I should be getting 3 and if I filter to show B only I should get 5. I've tried AGGREGATE and SUBTOTAL and haven't gotten anywhere.

Is there a way to adjust the above formula to VISIBLE cells only?

Thanks,

Body:
So it's a rather complicated formula involving both SUMPRODUCT(), SUBTOTAL() and OFFSET(). More information here

To implement this to your situation you would get:

=SUMPRODUCT((B2:B6/COUNTIFS(A2:A6,A2:A6))*(SUBTOTAL(3,OFFSET(B2,ROW(B2:B6)-MIN(ROW(B2:B6)),0))))

Another option would be (in your case if values for each criteria is the same)

=SUMPRODUCT((A2:A6<>A3:A7)*(B2:B6)*(SUBTOTAL(3,OFFSET(B2,ROW(B2:B6)-MIN(ROW(B2:B6)),0))))

In my example I'll filter out both A and B

A formula to be used on dynamic ranges would look like:

=SUMPRODUCT((B2:INDEX(B:B,COUNTA(B:B))/COUNTIFS(A2:INDEX(A:A,COUNTA(A:A)),A2:INDEX(A:A,COUNTA(A:A))))*(SUBTOTAL(3,OFFSET(B2,ROW(B2:INDEX(B:B,COUNTA(B:B)))-MIN(ROW(B2:INDEX(B:B,COUNTA(B:B)))),0))))


问:
How to get info about last called func in Go?
Is it possible to get name of the last called function and args that were passed to?</p>

```<code>func main() {
    f(1)
    log.Printf("%s(%s=%d)", // how to paste here "f(arg=1)"? )
}

func f(arg int) {
    ...
}
</code>```

答:
Is it possible to get name of the last called function and args that were passed to?

No.

Body:
Is it possible to get name of the last called function and args that were passed to?

func main() {
    f(1)
    log.Printf("%s(%s=%d)", // how to paste here "f(arg=1)"? )
}

func f(arg int) {
    ...
}


问:
Error when im trying add a column to a ListCtrl in wxPython(4.0.6)
Im trying to add a column to a LisCtrl but i cannot

I tried to follow the documentation but i dont know what am i doing wrong

The documentation says : InsertColumn (self, col, heading, format=LIST_FORMAT_LEFT, width=LIST_AUTOSIZE)

(https://docs.wxpython.org/wx.ListCtrl.html#wx.ListCtrl.InsertColumn)

```
import wx</p>

<p>class View1(wx.Frame):
    def <strong>init</strong>(self,*args,**kw):
        super(View1, self).<strong>init</strong>(*args,**kw)</p>

<code>    panel = wx.Panel(self, pos=(0,0), size=(800,700))

    #TITULO
    titulo = wx.StaticText(panel,label="AGENDA DE CONTACTOS",pos=(130,1))

    #Creamos Sizer y le agregamos el titulo
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(titulo,0,wx.ALIGN_CENTER,0)
    panel.SetSizer(sizer)

    #Texto1 X,Y
    label1 = wx.StaticText(panel,label="Nombre",pos=(70,50))
    field1 = wx.TextCtrl(panel,pos=(200,50), size=(150,20))

    #Texto2 X,Y
    label2 = wx.StaticText(panel,label="Apellido Paterno",pos=(70,90))
    field2 = wx.TextCtrl(panel,pos=(200,90), size=(150,20))

    #Texto3 X,Y
    label3 = wx.StaticText(panel,label="Apellido Materno",pos=(70,130))
    field3 = wx.TextCtrl(panel,pos=(200,130), size=(150,20))

    #Texto4 X,Y
    label4 = wx.StaticText(panel,label="Teléfono ",pos=(70,170))
    field4 = wx.TextCtrl(panel,pos=(200,170), size=(150,20))

    #Texto5 X,Y
    label5 = wx.StaticText(panel,label="Correo",pos=(70,210))
    field5 = wx.TextCtrl(panel,pos=(200,210), size=(150,20))

    #Texto6 X,Y
    label6 = wx.StaticText(panel,label="Teléfono",pos=(450,50))
    field6 = wx.TextCtrl(panel,pos=(550,50), size=(150,21))

    #Boton Agregar
    botonAgregar = wx.Button(panel,label="Agregar",pos=(215,245),size=(120,22))

    #Boton eliminar
    botonEliminar = wx.Button(panel,label="Eliminar",pos=(565,90),size=(120,22))

    #Creamos el ListCtrl para desplegar la información
    tabla = wx.ListCtrl(panel,pos=(25,350),size=(750,250), style=wx.LC_LIST)
    tabla.InsertColumn (self,0, 'NOMBRE', format=wx.LIST_FORMAT_LEFT, width=wx.LIST_AUTOSIZE)
</code>```

The result in terminal is : TypeError: ListCtrl.InsertColumn(): arguments did not match any overloaded call:
  overload 1: argument 1 has unexpected type 'View1'
  overload 2: argument 1 has unexpected type 'View1'

i tried remove the self parameter leaving as tabla.InsertColumn (0, 'NOMBRE', format=wx.LIST_FORMAT_LEFT, width=wx.LIST_AUTOSIZE) , but appears other error :
 wx._core.wxAssertionError: C++ assertion "InReportView()" failed at /home/vagrant/wxPython-4.0.6/ext/wxWidgets/src/generic/listctrl.cpp(5196) in DoInsertColumn(): can't add column in non report mode

答:
As Attila Toth said, remove the self parameter. Self is automatically passed to methods in python. In this case self is the wx.ListCtrl instance, but then you pass the View1 instance as the column number parameter.  If you're still confused about the self parameter here is a pretty good explanation of it

updated to address new question

The second error is pretty self-explanatory. Create the ListCtrl with the style flag wx.LC_REPORT instead of wx.LC_LIST

Body:
Im trying to add a column to a LisCtrl but i cannot

I tried to follow the documentation but i dont know what am i doing wrong

The documentation says : InsertColumn (self, col, heading, format=LIST_FORMAT_LEFT, width=LIST_AUTOSIZE)

(https://docs.wxpython.org/wx.ListCtrl.html#wx.ListCtrl.InsertColumn)

import wx

class View1(wx.Frame):
    def init(self,*args,**kw):
        super(View1, self).init(*args,**kw)

    panel = wx.Panel(self, pos=(0,0), size=(800,700))

    #TITULO
    titulo = wx.StaticText(panel,label="AGENDA DE CONTACTOS",pos=(130,1))

    #Creamos Sizer y le agregamos el titulo
    sizer = wx.BoxSizer(wx.VERTICAL)
    sizer.Add(titulo,0,wx.ALIGN_CENTER,0)
    panel.SetSizer(sizer)

    #Texto1 X,Y
    label1 = wx.StaticText(panel,label="Nombre",pos=(70,50))
    field1 = wx.TextCtrl(panel,pos=(200,50), size=(150,20))

    #Texto2 X,Y
    label2 = wx.StaticText(panel,label="Apellido Paterno",pos=(70,90))
    field2 = wx.TextCtrl(panel,pos=(200,90), size=(150,20))

    #Texto3 X,Y
    label3 = wx.StaticText(panel,label="Apellido Materno",pos=(70,130))
    field3 = wx.TextCtrl(panel,pos=(200,130), size=(150,20))

    #Texto4 X,Y
    label4 = wx.StaticText(panel,label="Teléfono ",pos=(70,170))
    field4 = wx.TextCtrl(panel,pos=(200,170), size=(150,20))

    #Texto5 X,Y
    label5 = wx.StaticText(panel,label="Correo",pos=(70,210))
    field5 = wx.TextCtrl(panel,pos=(200,210), size=(150,20))

    #Texto6 X,Y
    label6 = wx.StaticText(panel,label="Teléfono",pos=(450,50))
    field6 = wx.TextCtrl(panel,pos=(550,50), size=(150,21))

    #Boton Agregar
    botonAgregar = wx.Button(panel,label="Agregar",pos=(215,245),size=(120,22))

    #Boton eliminar
    botonEliminar = wx.Button(panel,label="Eliminar",pos=(565,90),size=(120,22))

    #Creamos el ListCtrl para desplegar la información
    tabla = wx.ListCtrl(panel,pos=(25,350),size=(750,250), style=wx.LC_LIST)
    tabla.InsertColumn (self,0, 'NOMBRE', format=wx.LIST_FORMAT_LEFT, width=wx.LIST_AUTOSIZE)

The result in terminal is : TypeError: ListCtrl.InsertColumn(): arguments did not match any overloaded call:
  overload 1: argument 1 has unexpected type 'View1'
  overload 2: argument 1 has unexpected type 'View1'

i tried remove the self parameter leaving as tabla.InsertColumn (0, 'NOMBRE', format=wx.LIST_FORMAT_LEFT, width=wx.LIST_AUTOSIZE) , but appears other error :
 wx._core.wxAssertionError: C++ assertion "InReportView()" failed at /home/vagrant/wxPython-4.0.6/ext/wxWidgets/src/generic/listctrl.cpp(5196) in DoInsertColumn(): can't add column in non report mode


问:
Vue Cli 3 exclude typescript file from being injected in index.html
I created a project typescript project with the Vue Cli.

I want to have a separated commands.html file that should contain the javascript code from a commands.ts file.

I put the commands.html file in the public folder, so it is copied to the dist folder when building the project.

The commands.ts file is in the root folder (in the same folder in that the public, src, node_modules, etc folders are).

Webpack should do the following:

Minify the commands.html file (like it is minifying the index.html)

Compile the commands.ts file to JavaScript

Put the generated JavaScript file to the dist/js folder

Put a script tag in the commands.html file that points to the generated JavaScript file

I tried the following:

I installed html-webpack-plugin

I created a vue.config.js file with the following code:

```<code>const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  configureWebpack: {
    entry: {
      commands: './commands.ts',
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'commands.html',
        template: './public/commands.html',
        chunks: ['commands'],
        minify: {
          collapseWhitespace: true,
        },
      }),
    ],
  },
};
</code>```

That is doing everything correctly, but it also creates a script tag in the index.html file that points to the generated JavaScript file. I think the default Webpack config of Vue is compiling the commands.ts in the bundle that is injected in the index.html file. How can I stop it from doing that?

答:
Found it out:</p>

```<code>const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  configureWebpack: {
    entry: {
      functionFile: './functionFile.ts',
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'functionFile.html',
        template: './public/functionFile.html',
        chunks: ['functionFile'],
        minify: {
          collapseWhitespace: true,
        },
      }),
    ],
    devServer: {
      https: true,
    },
  },
  chainWebpack: (config) => {
    config
      .plugin('html')
      .tap((args) => {
        // eslint-disable-next-line no-param-reassign
        args[0].excludeChunks = ['functionFile'];
        return args;
      });
  },
};
</code>```

Body:
I created a project typescript project with the Vue Cli.

I want to have a separated commands.html file that should contain the javascript code from a commands.ts file.

I put the commands.html file in the public folder, so it is copied to the dist folder when building the project.

The commands.ts file is in the root folder (in the same folder in that the public, src, node_modules, etc folders are).

Webpack should do the following:

Minify the commands.html file (like it is minifying the index.html)

Compile the commands.ts file to JavaScript

Put the generated JavaScript file to the dist/js folder

Put a script tag in the commands.html file that points to the generated JavaScript file

I tried the following:

I installed html-webpack-plugin

I created a vue.config.js file with the following code:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  configureWebpack: {
    entry: {
      commands: './commands.ts',
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'commands.html',
        template: './public/commands.html',
        chunks: ['commands'],
        minify: {
          collapseWhitespace: true,
        },
      }),
    ],
  },
};

That is doing everything correctly, but it also creates a script tag in the index.html file that points to the generated JavaScript file. I think the default Webpack config of Vue is compiling the commands.ts in the bundle that is injected in the index.html file. How can I stop it from doing that?

Body:
Found it out:

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  configureWebpack: {
    entry: {
      functionFile: './functionFile.ts',
    },
    plugins: [
      new HtmlWebpackPlugin({
        filename: 'functionFile.html',
        template: './public/functionFile.html',
        chunks: ['functionFile'],
        minify: {
          collapseWhitespace: true,
        },
      }),
    ],
    devServer: {
      https: true,
    },
  },
  chainWebpack: (config) => {
    config
      .plugin('html')
      .tap((args) => {
        // eslint-disable-next-line no-param-reassign
        args[0].excludeChunks = ['functionFile'];
        return args;
      });
  },
};


问:
jQuery mobile $(document).ready equivalent
in ajax navigation pages, the classic "document ready" form for performing initialization javascript simply doesn't fire.

What's the right way to execute some code in an ajax loaded page?

(I mean, not my ajax... it's the jquery mobile page navigation system which brings me to that page)

Ok, I did suspect something like that... thanks a lot =) But... it still doesn't work, here's my code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
</code>```

```<code><head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mypage</title>

    <link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />
    <script type="text/javascript" src="jquery-1.5.min.js"></script>
    <script type="text/javascript" src="jquery.mobile-1.0a4.min.js"></script>
    <script type="text/javascript">
        $('div').live('pageshow',function(event, ui){
          alert('ciao');
        });
    </script>

</head>

<body>

    <div data-role="page">

        <div data-role="header" data-position="fixed">
            <h1>Shopping Cart</h1>
        </div>

        <div data-role="content"> asd

        </div>

    </div>

</body>
</code>```

Do I need to specify the div id?

答:
If you want the code to run on a certain page (I bet that's the case) you can use this pattern:

```<code>$('div:jqmData(url="thepageyouwanted.html")').live('pageshow',function(){
    // code to execute on that page
    //$(this) works as expected - refers the page
});
</code>```

Events you can use:

pagebeforeshow starts just before transition

pageshow starts right after transition

pagecreate starts only the first time page is loaded

Body:
in ajax navigation pages, the classic "document ready" form for performing initialization javascript simply doesn't fire.

What's the right way to execute some code in an ajax loaded page?

(I mean, not my ajax... it's the jquery mobile page navigation system which brings me to that page)

Ok, I did suspect something like that... thanks a lot =) But... it still doesn't work, here's my code:

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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>mypage</title>

    <link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />

Shopping Cart

 asd

Do I need to specify the div id?

Body:
If you want the code to run on a certain page (I bet that's the case) you can use this pattern:

$('div:jqmData(url="thepageyouwanted.html")').live('pageshow',function(){
    // code to execute on that page
    //$(this) works as expected - refers the page
});

Events you can use:

pagebeforeshow starts just before transition

pageshow starts right after transition

pagecreate starts only the first time page is loaded


问:
Printing last element in an array using if statement
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.

Edit:
Why is if statement not working in this case? It seems logic that it should work...

My main.c file:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7

int main(void)
{

    int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };

    maxValue(array1, Size);

    return 0;
}
```

<p>My functions.h file:</p>

<pre class="lang-cpp prettyprint-override"><code>#pragma once

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int maxValue(const int *, int);

#endif

</code>```

My functions.c file:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>

int maxValue(const int *array1, int Size)
{

    int max = array1[0];

    if (max < array1[Size]) {
        Size++;
        max = array1[Size];
    }

    printf("Max value: %d \n", max);
}

```

答:
Let's simulate what the CPU does when it enters the maxValue function with those arguments. 1. The variable max is assigned the value of array1[0], which is 11.
2. If max (11) is less than array1[7] (4). It is not, so the if block is not executed.
3. Print max: print 11.

Another thing: Your program causes undefined behaviour. Let's take an example where array1[0] is 3, instead of 11. The if block will be executed (3 < 4), so:
Size is incremented to 8.
max is assigned array1[8]. Since the last index in array1 is 7 (that is how you declared the array), you are accessing a memory adress which you are not supposed to access. This is undefined behaviour.

Body:
I am currently trying to learn about using pointers and functions together in C, which I don't think is easy.
I am trying to print the last element in an array, it actually does the opposite and prints the first element.
I know people normally use for loops, but I can't figure out how to do that with exactly this kind of problem and therefore I thought that I would try it out with an if statement instead.

Edit:
Why is if statement not working in this case? It seems logic that it should work...

My main.c file:

#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
#define Size 7

int main(void)
{

    int array1[] = { 11, 88, 5, 9, 447, 8, 68, 4 };

    maxValue(array1, Size);

    return 0;
}

My functions.h file:

#pragma once

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int maxValue(const int *, int);

#endif

My functions.c file:

#include "functions.h"
#include <stdio.h>
#include <stdlib.h>

int maxValue(const int *array1, int Size)
{

    int max = array1[0];

    if (max < array1[Size]) {
        Size++;
        max = array1[Size];
    }

    printf("Max value: %d \n", max);
}


问:
Foreign Key issue with migrations
Im using the package https://github.com/musonza/groups to added group system on my laravel app, but when I want to migrate I get the error:

```<code>Migration table created successfully.
Migrating: 2019_05_26_125854_create_groups_tables

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `groupsystem`.`#sql-2678_26` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `groups` add constraint `groups_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)
</code>```

This is my 2 migrations table code:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
</code>```

And also this is the migration table I get from installing the package:
That I mentioned in the link in the top of this post
This is the first time I try to use this package
And im trying tocreate a group system on my laravel application
Any other suggetions will be welcomed

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGroupsTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('short_description')->nullable();
            $table->string('image')->nullable();
            $table->string('url')->nullable();
            $table->integer('user_id')->unsigned();
            $table->boolean('private')->unsigned()->default(false);
            $table->integer('conversation_id')->unsigned()->nullable();
            $table->text('extra_info')->nullable();
            $table->text('settings')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('group_id')->unsigned();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');
        });

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->string('type');
            $table->integer('user_id')->unsigned();
            $table->text('extra_info')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('body');
            $table->integer('user_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->string('type')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts');
        });

        Schema::create('group_post', function (Blueprint $table) {
            $table->integer('group_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('cascade');
        });

        Schema::create('likes', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('likeable_id')->unsigned();
            $table->string('likeable_type');
            $table->primary(['user_id', 'likeable_id', 'likeable_type']);
            $table->timestamps();
        });

        Schema::create('reports', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('reportable_id')->unsigned();
            $table->string('reportable_type');
            $table->primary(['user_id', 'reportable_id', 'reportable_type']);
            $table->timestamps();
        });

        Schema::create('group_request', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('group_id')->unsigned()->index();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('groups');
        Schema::drop('group_user');
        Schema::drop('posts');
        Schema::drop('comments');
        Schema::drop('group_post');
        Schema::drop('likes');
        Schema::drop('reports');
        Schema::drop('group_request');
    }
}
</code>```

答: I did found the solution it's because of the new Laravel 5.8.3 it comes with unsignedBigInteger(id) instead of increments(id)</p>

Title: Foreign Key issue with migrations

Body:
Im using the package https://github.com/musonza/groups to added group system on my laravel app, but when I want to migrate I get the error:

Migration table created successfully.
Migrating: 2019_05_26_125854_create_groups_tables

   Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1005 Can't create table `groupsystem`.`#sql-2678_26` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `groups` add constraint `groups_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade)

This is my 2 migrations table code:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

And also this is the migration table I get from installing the package:
That I mentioned in the link in the top of this post
This is the first time I try to use this package
And im trying tocreate a group system on my laravel application
Any other suggetions will be welcomed

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGroupsTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description')->nullable();
            $table->string('short_description')->nullable();
            $table->string('image')->nullable();
            $table->string('url')->nullable();
            $table->integer('user_id')->unsigned();
            $table->boolean('private')->unsigned()->default(false);
            $table->integer('conversation_id')->unsigned()->nullable();
            $table->text('extra_info')->nullable();
            $table->text('settings')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('group_user', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('group_id')->unsigned();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');
        });

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('body');
            $table->string('type');
            $table->integer('user_id')->unsigned();
            $table->text('extra_info')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });

        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('body');
            $table->integer('user_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->string('type')->nullable();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts');
        });

        Schema::create('group_post', function (Blueprint $table) {
            $table->integer('group_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('post_id')
                ->references('id')
                ->on('posts')
                ->onDelete('cascade');
        });

        Schema::create('likes', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('likeable_id')->unsigned();
            $table->string('likeable_type');
            $table->primary(['user_id', 'likeable_id', 'likeable_type']);
            $table->timestamps();
        });

        Schema::create('reports', function (Blueprint $table) {
            $table->integer('user_id')->index();
            $table->integer('reportable_id')->unsigned();
            $table->string('reportable_type');
            $table->primary(['user_id', 'reportable_id', 'reportable_type']);
            $table->timestamps();
        });

        Schema::create('group_request', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->integer('group_id')->unsigned()->index();
            $table->timestamps();

            $table->foreign('group_id')
                ->references('id')
                ->on('groups')
                ->onDelete('cascade');

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('groups');
        Schema::drop('group_user');
        Schema::drop('posts');
        Schema::drop('comments');
        Schema::drop('group_post');
        Schema::drop('likes');
        Schema::drop('reports');
        Schema::drop('group_request');
    }
}


问:
Clustering Algorithm for Paper Boys
I need help selecting or creating a clustering algorithm according to certain criteria.

Imagine you are managing newspaper delivery persons.

You have a set of street addresses, each of which is geocoded.

You want to cluster the addresses so that each cluster is assigned to a delivery person.

The number of delivery persons, or clusters, is not fixed.  If needed, I can always hire more delivery persons, or lay them off.

Each cluster should have about the same number of addresses.  However, a cluster may have less addresses if a cluster's addresses are more spread out.  (Worded another way: minimum number of clusters where each cluster contains a maximum number of addresses, and any address within cluster must be separated by a maximum distance.)

For bonus points, when the data set is altered (address added or removed), and the algorithm is re-run, it would be nice if the clusters remained as unchanged as possible (ie. this rules out simple k-means clustering which is random in nature).  Otherwise the delivery persons will go crazy.

So... ideas?

UPDATE

The street network graph, as described in Arachnid's answer, is not available.

答: Perhaps a minimum spanning tree of the customers, broken into set based on locality to the paper boy. Prims or Kruskal to get the MST with the distance between houses for the weight.</p>

OwnerDisplayName: carrier

ContentLicense: CC BY-SA 2.5

Title: Clustering Algorithm for Paper Boys

LastEditorDisplayName: carrier

OwnerDisplayName: sfossen

LastEditorDisplayName: sfossen


问:
Launching Ansible playbook to communicate with Windows host fails without sudo rights
I'm setting up an Ansible server running on CentOS 7 (with AWX as User Interface) and I want to communicate with a few windows hosts to perform basic package manipulation.

As a first approach, I'm using NTLM to communicate with my hosts (Basic Auth is disabled by the sysadmin).

However, I noticed that my playbooks fail to run when I launch ansible-playbook without sudo privileges.

I've already checked the TCP stream in both case. And it seems that when it fails (ie. without sudo rights) the server doesn't event start to communicate with the host. As if it failed without even trying (despite telling otherwise)

It's not a matter of firewall, since I am able to access the wsman endpoint with curl.

I've also checked the Windows account's rights (as was suggested for a similar problem), but everything that's needed was already there.

My playbook is this very simple taskless file:

```<code>- hosts: win
  vars:
    ansible_user: ansible_admin
    ansible_connection: winrm
    ansible_winrm_server_cert_validation: ignore
    ansible_port: 5985
    ansible_winrm_transport: ntlm
</code>```

I've checked with and without tasks (like win_ping) and the ansible_winrm_server_cert_validation variable.

My /etc/ansible/hosts file is this one:

```<code>[win]
192.168.0.42

[localhost]
127.0.0.1
</code>```

Here's what I get when I run the playbook without sudo right

```<code>$ ansible-playbook helloworld.yml --ask-pass -vvvvv
ansible-playbook 2.7.9
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/var/lib/awx/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.6.7 (default, Dec 5 2018, 15:02:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
SSH password:
setting up inventory plugins
/etc/ansible/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
Set default localhost to 127.0.0.1
Parsed /etc/ansible/hosts inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3.6/site-packages/ansible/callback/default.py

PLAYBOOK: hello_world.yml ******************************************************
1 plays in hello_world.yml

PLAY [win] ******************************************************

TASK [Gathering Facts] *********************************************************
task path: /home/ansible/playbooks/hello_world.yml:1
Using module file /usr/lib/python3.6/site-packages/ansible/modules/windows/setup.ps1
<192.168.0.42> ESTABLISH WINRM CONNECTION FOR USER: ansible_admin on PORT 5985 TO 192.168.0.42
checking if winrm_host 192.168.0.42 is an IPv6 address
<192.168.0.42> WINRM CONNECT: transport=ntlm endpoint=http://192.168.0.42:5985/wsman
<192.168.0.42> WINRM CONNECTION ERROR: the specified credentials were rejected by the server
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/ansible/plugins/connection/winrm.py", line 402, in _winrm_connect
    self.shell_id = protocol.open_shell(codepage=65001)  # UTF-8
  File "/usr/lib/python3.6/site-packages/winrm/protocol.py", line 157, in open_shell
    res = self.send_message(xmltodict.unparse(req))
  File "/usr/lib/python3.6/site-packages/winrm/protocol.py", line 234, in send_message
    resp = self.transport.send_message(message)
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 243, in send_message
    self.build_session()
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 232, in build_session
    self.setup_encryption()
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 238, in setup_encryption
    self._send_message_request(prepared_request, '')
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 266, in _send_message_request
    raise InvalidCredentialError("the specified credentials were rejected by the server") winrm.exceptions.invalidCredentialError: the specified credentials were rejected by the server
fatal: [192.168.0.42]: UNREACHABLE! => {
    "changed": false,
    "msg": "ntlm: the specified credentials were rejected by the server",
    "unreachable": true
}
        to retry, use: --limit @/home/ansible/playbooks/hello_world.retry
PLAY RECAP *********************************************************************
192.168.0.42               : ok=0    changed=0    unreachable=1    failed=0
</code>```

But when I run the playbook with sudo rights, this works just fine

```<code>$ sudo ansible-playbook helloworld.yml --ask-pass -vvvvv
ansible-playbook 2.7.9
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/var/lib/awx/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.6.7 (default, Dec 5 2018, 15:02:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
SSH password:
setting up inventory plugins
/etc/ansible/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
Set default localhost to 127.0.0.1
Parsed /etc/ansible/hosts inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3.6/site-packages/ansible/callback/default.py

PLAYBOOK: hello_world.yml ******************************************************
1 plays in hello_world.yml

PLAY [win] ******************************************************

TASK [Gathering Facts] *********************************************************
task path: /home/ansible/playbooks/hello_world.yml:1
Using module file /usr/lib/python3.6/site-packages/ansible/modules/windows/setup.ps1
<192.168.0.42> ESTABLISH WINRM CONNECTION FOR USER: ansible_admin on PORT 5985 TO 192.168.0.42
checking if winrm_host 192.168.0.42 is an IPv6 address
<192.168.0.42> WINRM CONNECT: transport=ntlm endpoint=http://192.168.0.42:5985/wsman
<192.168.0.42> WINRM OPEN SHELL: E04DA2D8-15E4-4B28-A079-A5C795B612C5
EXEC (via pipeline wrapper)
<192.168.0.42> WINRM EXEC 'Powershell' ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-EncodedCommand', '<-- Very long string here -->']
<192.168.0.42> WINRM RESULT '<Response code 1, out "{"changed":false,"an", err "#< CLIXML\r\n<Objs Ver">'
<192.168.0.42> WINRM CLOSE SHELL: E04DA2D8-15E4-4B28-A079-A5C795B612C5
ok: [192.168.0.42]

PLAY RECAP *********************************************************************
192.168.0.42               : ok=1    changed=0    unreachable=0    failed=0
</code>```

Does someone have an explanation for this?

Or, as a workaround, is it possible to run a playbook on AWX with sudo privileges?

Edit: Added output with extra verbosity

答: If you're using AWX, you need to check your credentials correctly, especially on Privilege Escalation Method, if you want to specify the type of escalation privilege to assign to specific users.</p>

Body:
I'm setting up an Ansible server running on CentOS 7 (with AWX as User Interface) and I want to communicate with a few windows hosts to perform basic package manipulation.

As a first approach, I'm using NTLM to communicate with my hosts (Basic Auth is disabled by the sysadmin).

However, I noticed that my playbooks fail to run when I launch ansible-playbook without sudo privileges.

I've already checked the TCP stream in both case. And it seems that when it fails (ie. without sudo rights) the server doesn't event start to communicate with the host. As if it failed without even trying (despite telling otherwise)

It's not a matter of firewall, since I am able to access the wsman endpoint with curl.

I've also checked the Windows account's rights (as was suggested for a similar problem), but everything that's needed was already there.

My playbook is this very simple taskless file:

- hosts: win
  vars:
    ansible_user: ansible_admin
    ansible_connection: winrm
    ansible_winrm_server_cert_validation: ignore
    ansible_port: 5985
    ansible_winrm_transport: ntlm

I've checked with and without tasks (like win_ping) and the ansible_winrm_server_cert_validation variable.

My /etc/ansible/hosts file is this one:

[win]
192.168.0.42

[localhost]
127.0.0.1

Here's what I get when I run the playbook without sudo right

$ ansible-playbook helloworld.yml --ask-pass -vvvvv
ansible-playbook 2.7.9
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/var/lib/awx/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.6.7 (default, Dec 5 2018, 15:02:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
SSH password:
setting up inventory plugins
/etc/ansible/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
Set default localhost to 127.0.0.1
Parsed /etc/ansible/hosts inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3.6/site-packages/ansible/callback/default.py

PLAYBOOK: hello_world.yml ******************************************************
1 plays in hello_world.yml

PLAY [win] ******************************************************

TASK [Gathering Facts] *********************************************************
task path: /home/ansible/playbooks/hello_world.yml:1
Using module file /usr/lib/python3.6/site-packages/ansible/modules/windows/setup.ps1
<192.168.0.42> ESTABLISH WINRM CONNECTION FOR USER: ansible_admin on PORT 5985 TO 192.168.0.42
checking if winrm_host 192.168.0.42 is an IPv6 address
<192.168.0.42> WINRM CONNECT: transport=ntlm endpoint=http://192.168.0.42:5985/wsman
<192.168.0.42> WINRM CONNECTION ERROR: the specified credentials were rejected by the server
Traceback (most recent call last):
  File "/usr/lib/python3.6/site-packages/ansible/plugins/connection/winrm.py", line 402, in _winrm_connect
    self.shell_id = protocol.open_shell(codepage=65001)  # UTF-8
  File "/usr/lib/python3.6/site-packages/winrm/protocol.py", line 157, in open_shell
    res = self.send_message(xmltodict.unparse(req))
  File "/usr/lib/python3.6/site-packages/winrm/protocol.py", line 234, in send_message
    resp = self.transport.send_message(message)
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 243, in send_message
    self.build_session()
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 232, in build_session
    self.setup_encryption()
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 238, in setup_encryption
    self._send_message_request(prepared_request, '')
  File "/usr/lib/python3.6/site-packages/winrm/transport.py", line 266, in _send_message_request
    raise InvalidCredentialError("the specified credentials were rejected by the server") winrm.exceptions.invalidCredentialError: the specified credentials were rejected by the server
fatal: [192.168.0.42]: UNREACHABLE! => {
    "changed": false,
    "msg": "ntlm: the specified credentials were rejected by the server",
    "unreachable": true
}
        to retry, use: --limit @/home/ansible/playbooks/hello_world.retry
PLAY RECAP *********************************************************************
192.168.0.42               : ok=0    changed=0    unreachable=1    failed=0

But when I run the playbook with sudo rights, this works just fine

$ sudo ansible-playbook helloworld.yml --ask-pass -vvvvv
ansible-playbook 2.7.9
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/var/lib/awx/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 3.6.7 (default, Dec 5 2018, 15:02:05) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
Using /etc/ansible/ansible.cfg as config file
SSH password:
setting up inventory plugins
/etc/ansible/hosts did not meet host_list requirements, check plugin documentation if this is unexpected
Set default localhost to 127.0.0.1
Parsed /etc/ansible/hosts inventory source with ini plugin
Loading callback plugin default of type stdout, v2.0 from /usr/lib/python3.6/site-packages/ansible/callback/default.py

PLAYBOOK: hello_world.yml ******************************************************
1 plays in hello_world.yml

PLAY [win] ******************************************************

TASK [Gathering Facts] *********************************************************
task path: /home/ansible/playbooks/hello_world.yml:1
Using module file /usr/lib/python3.6/site-packages/ansible/modules/windows/setup.ps1
<192.168.0.42> ESTABLISH WINRM CONNECTION FOR USER: ansible_admin on PORT 5985 TO 192.168.0.42
checking if winrm_host 192.168.0.42 is an IPv6 address
<192.168.0.42> WINRM CONNECT: transport=ntlm endpoint=http://192.168.0.42:5985/wsman
<192.168.0.42> WINRM OPEN SHELL: E04DA2D8-15E4-4B28-A079-A5C795B612C5
EXEC (via pipeline wrapper)
<192.168.0.42> WINRM EXEC 'Powershell' ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-EncodedCommand', '<-- Very long string here -->']
<192.168.0.42> WINRM RESULT '<Response code 1, out "{"changed":false,"an", err "#< CLIXML\r\n<Objs Ver">'
<192.168.0.42> WINRM CLOSE SHELL: E04DA2D8-15E4-4B28-A079-A5C795B612C5
ok: [192.168.0.42]

PLAY RECAP *********************************************************************
192.168.0.42               : ok=1    changed=0    unreachable=0    failed=0

Does someone have an explanation for this?

Or, as a workaround, is it possible to run a playbook on AWX with sudo privileges?

Edit: Added output with extra verbosity


问:
Maven regular expression to match file is not working
I have two files test-200-12-30-2990 and test-project-200-12-30-2990 I am unziping it to corresponding folders. Second task is not working. I want to select the file 'test-200-12-30-2990'
Below is the ant build.xml. I am using maven ant plugin inside pom

```<code>                        <mkdir dir="/testdir"/>
              <unzip dest="src/main/resources/testdir">
                <fileset dir="src/main/resources">
                    <include name="**/test-project*.zip"/>
                </fileset>
             </unzip>
           </target>
</code>```

```<code>                        <mkdir dir="/test-projectdir"/>
              <unzip dest="src/main/resources/test-projectdir">
                <fileset dir="src/main/resources">
                    <include name="**/test[1-9].zip"/>
                </fileset>
             </unzip>
           </target>
</code>```

答:
I'm not quite sure how inclusion might work in Maven, but maybe we could solve this problem with a simple expression that you already have, something maybe similar to:

```<code>test-[0-9-]+
</code>```

Then, the include might look like:

```<code>test-[0-9-]+\.zip
</code>```

```<code>**/test-[0-9-]+\.zip
</code>```

If escaping . might be unnecessary, then we can just use:

```<code>**/test-[0-9-]+.zip
</code>```

DEMO

Reference

Include xml files in maven project

Body:
I have two files test-200-12-30-2990 and test-project-200-12-30-2990 I am unziping it to corresponding folders. Second task is not working. I want to select the file 'test-200-12-30-2990'
Below is the ant build.xml. I am using maven ant plugin inside pom

                        <mkdir dir="/testdir"/>
              <unzip dest="src/main/resources/testdir">
                <fileset dir="src/main/resources">
                    <include name="**/test-project*.zip"/>
                </fileset>
             </unzip>
           </target>

                        <mkdir dir="/test-projectdir"/>
              <unzip dest="src/main/resources/test-projectdir">
                <fileset dir="src/main/resources">
                    <include name="**/test[1-9].zip"/>
                </fileset>
             </unzip>
           </target>

Body:
I'm not quite sure how inclusion might work in Maven, but maybe we could solve this problem with a simple expression that you already have, something maybe similar to:

test-[0-9-]+

Then, the include might look like:

test-[0-9-]+\.zip

**/test-[0-9-]+\.zip

If escaping . might be unnecessary, then we can just use:

**/test-[0-9-]+.zip

DEMO

Reference

Include xml files in maven project


问:
How I make a trigger for add in a field of a table in MYSQL
I want to make a trigger on MYSQL that increases the value in the field of a table

```<code>DROP DATABASE IF EXISTS Lollipop;
CREATE DATABASE Lollipop;
USE Lollipop;

/* Sucursales */
DROP TABLE IF EXISTS Sucursales;
CREATE TABLE IF NOT EXISTS Sucursales (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    Direccion VARCHAR(50),
    Numero_empleados DECIMAL(10) DEFAULT '0',
 PRIMARY KEY (id)
) AUTO_INCREMENT=1;

/* Empleados */
DROP TABLE IF EXISTS Empleados;
CREATE TABLE IF NOT EXISTS Empleados (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    Nombres VARCHAR(25),
    Tipo_de_sangre VARCHAR(3),
    Seguro_social VARCHAR(11) NOT NULL,
    Fecha_nacimiento DATE NOT NULL,
    ID_Sucursal INT UNSIGNED NOT NULL,
 PRIMARY KEY (id)
) AUTO_INCREMENT=1;

CREATE TRIGGER add_empleados
BEFORE INSERT ON Empleados
UPDATE Sucursales
SET Numero_empleados = Numero_empleados + 1
WHERE id = new.ID_Sucursal;
</code>```

When I try to insert the trigger it sends me an "ERROR 1064 (42000): You have an error in your SQL syntax"

答:
Yes, FOR EACH ID not optional

CREATE TRIGGER add_empleados BEFORE INSERT ON Empleados UPDATE Sucursales SET
FOR EACH Numero_empleados = Numero_empleados + 1 WHERE id = new.ID_Sucursal;

Body:
I want to make a trigger on MYSQL that increases the value in the field of a table

DROP DATABASE IF EXISTS Lollipop;
CREATE DATABASE Lollipop;
USE Lollipop;

/* Sucursales */
DROP TABLE IF EXISTS Sucursales;
CREATE TABLE IF NOT EXISTS Sucursales (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    Direccion VARCHAR(50),
    Numero_empleados DECIMAL(10) DEFAULT '0',
 PRIMARY KEY (id)
) AUTO_INCREMENT=1;

/* Empleados */
DROP TABLE IF EXISTS Empleados;
CREATE TABLE IF NOT EXISTS Empleados (
    id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    Nombres VARCHAR(25),
    Tipo_de_sangre VARCHAR(3),
    Seguro_social VARCHAR(11) NOT NULL,
    Fecha_nacimiento DATE NOT NULL,
    ID_Sucursal INT UNSIGNED NOT NULL,
 PRIMARY KEY (id)
) AUTO_INCREMENT=1;

CREATE TRIGGER add_empleados
BEFORE INSERT ON Empleados
UPDATE Sucursales
SET Numero_empleados = Numero_empleados + 1
WHERE id = new.ID_Sucursal;

When I try to insert the trigger it sends me an "ERROR 1064 (42000): You have an error in your SQL syntax"


问:
Remove everything after a certain character
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

```<code>/Controller/Action?id=11112&value=4444
</code>```

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

```<code> $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }
</code>```

答:
```<code>var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
</code>```

This will work if it finds a '?' and if it doesn't

Body:
Is there a way to remove everything after a certain character or just choose everything up to that character?  I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.

Like this

/Controller/Action?id=11112&value=4444

I want the href to be /Controller/Action only, so I want to remove everything after the "?".

I'm using this now:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');
     var url = $(this).attr('href');

     console.log(url);
 }

Body:
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action

This will work if it finds a '?' and if it doesn't


问:
How to detect if a window is "docked" on the desktop?
When a user presses, for example, Windows-RightArrow the window gets resized to the half of monitor's width and to its full height, and then gets "docked" to the right half of the monitor (ref).

The question is if it's possible to detect either being in this state or being put into this state.

Obvioulsy, this can be deduced from WM_WINDOWPOSCHANGING and the bunch, checking against monitor area and what not, but is there a cleaner solution?

答:
To copy from my own comment above -

It appears that rcNormalPosition in WINDOWPLACEMENT saves the original (pre-docked) window position. So simply comparing it to the window's effective rectangle will show if the window is in a "special" state. Then, we just need to look at the showCommand - if it's SW_SHOWNORMAL, then we are in the docked state.

Edit

After field-testing this approach I have to amend the answer, because there exist cases on Windows 10 when the above conditions will be met for windows that are not vertically-docked.

An option that works is to additionally use MonitorFromWindow, followed by GetMonitorInfo, followed by comparing window's current top and bottom against those of rcWork from MONITORINFO.

So there was no miracle. No clean and easy way to do this.