问:
How to delete multiple elements if checkbox is checked using javascript?
So I got this code, I figured out how to delete one element with the checkbox checked but if I try to delete the second div it won't let me?
Does anyone have a solution to it?

HTML

```<code><div id="product-space">
            <div id="product"> <input type="checkbox" id="delete-checkbox">
                <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
            </div>
            <div id="product"> <input type="checkbox" id="delete-checkbox">
                <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
            </div>
        </div>
<button type="submit" name="button" value="enter" id="button" onclick="removeCheckedCheckboxes()">MASS DELETE</button>
</code>```

JavaScript

```<code>function removeCheckedCheckboxes() {
    var checkBox = document.getElementById("delete-checkbox");
    var box = document.getElementById("product");
    if (checkBox.checked == true) {
        box.style.display = "none";
    }
}
</code>```

答:
the first thing is, both of your items have the same ID, and you must never use the same ID for multiple divs's. When you use document.getElementById, you return only the first object, and you are not exactly deleting the code by clicking in your button. Try get your element by a class or a tagName like those input fields of yours.

function removeCheckedCheckboxes() {
  var list = document.getElementsByTagName('input')
  for (var i = 0; i < list.length; ++i) {
    var product = list[i]
    if (product.checked)
      product.parentElement.hidden = true
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="product-space">
  <div class="product">
    <input type="checkbox">
    <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
  <div class="product">
    <input type="checkbox">
    <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
</div>
<button
  type="submit"
  name="button"
  value="enter"
  id="button"
  onclick="removeCheckedCheckboxes()">
  MASS DELETE
</button></code>```

https://www.quora.com/Is-it-ever-ok-to-use-the-same-ID-for-multiple-elements-in-HTML-Doesnt-CSS-specificity-make-IDs-more-granular-than-classes-Doesnt-this-violate-the-rules-of-HTML-Is-there-ever-a-reason-to-do-this

Body:
So I got this code, I figured out how to delete one element with the checkbox checked but if I try to delete the second div it won't let me?
Does anyone have a solution to it?

HTML

 <input type="checkbox" id="delete-checkbox">

 JVC200123
 Acme DISC
 1.00 $
 Size: 700 MB

 <input type="checkbox" id="delete-checkbox">

 KRK201929
 Acme DISC
 1.00 $
 Size: 700 MB

<button type="submit" name="button" value="enter" id="button" onclick="removeCheckedCheckboxes()">MASS DELETE</button>

JavaScript

function removeCheckedCheckboxes() {
    var checkBox = document.getElementById("delete-checkbox");
    var box = document.getElementById("product");
    if (checkBox.checked == true) {
        box.style.display = "none";
    }
}

Body:
the first thing is, both of your items have the same ID, and you must never use the same ID for multiple divs's. When you use document.getElementById, you return only the first object, and you are not exactly deleting the code by clicking in your button. Try get your element by a class or a tagName like those input fields of yours.

function removeCheckedCheckboxes() {
  var list = document.getElementsByTagName('input')
  for (var i = 0; i < list.length; ++i) {
    var product = list[i]
    if (product.checked)
      product.parentElement.hidden = true
  }
}

<div id="product-space">
  <div class="product">
    <input type="checkbox">
    <p> JVC200123 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
  <div class="product">
    <input type="checkbox">
    <p> KRK201929 <br> Acme DISC <br> 1.00 $ <br> Size: 700 MB</p>
  </div>
</div>
<button
  type="submit"
  name="button"
  value="enter"
  id="button"
  onclick="removeCheckedCheckboxes()">
  MASS DELETE
</button>

https://www.quora.com/Is-it-ever-ok-to-use-the-same-ID-for-multiple-elements-in-HTML-Doesnt-CSS-specificity-make-IDs-more-granular-than-classes-Doesnt-this-violate-the-rules-of-HTML-Is-there-ever-a-reason-to-do-this


来源: stackexchange

问:
Cannot construct an Explanation object
Trying to construct an Explanation object for a unit test, but can't seem to get it to work. Here's what I'm trying:

```<code>from google.cloud import aiplatform

aiplatform.compat.types.explanation_v1.Explanation(
    attributions=aiplatform.compat.types.explanation_v1.Attribution(
        {
            "approximation_error": 0.010399332817679649,
            "baseline_output_value": 0.9280818700790405,
            "feature_attributions": {
                "feature_1": -0.0410824716091156,
                "feature_2": 0.01155053575833639,
            },
            "instance_output_value": 0.6717480421066284,
            "output_display_name": "true",
            "output_index": [0],
            "output_name": "scores",
        }
    )
)
</code>```

which gives:

```<code>".venv/lib/python3.7/site-packages/proto/message.py", line 521, in __init__
    super().__setattr__("_pb", self._meta.pb(**params))
TypeError: Value must be iterable
</code>```

I found this on github, but I'm not sure how to apply that workaround here.

答:
As the error mentioned value to be passed at attributions should be iterable. See Explanation attributes documentation.

I tried your code and placed the Attribution object in a list and the error is gone. I assigned your objects in variables just so the code is readable.

See code and testing below:

```<code>from google.cloud import aiplatform

test = {
            "approximation_error": 0.010399332817679649,
            "baseline_output_value": 0.9280818700790405,
            "feature_attributions": {
                "feature_1": -0.0410824716091156,
                "feature_2": 0.01155053575833639,
            },
            "instance_output_value": 0.6717480421066284,
            "output_display_name": "true",
            "output_index": [0],
            "output_name": "scores",
        }

attributions=aiplatform.compat.types.explanation_v1.Attribution(test)
x  = aiplatform.compat.types.explanation_v1.Explanation(
    attributions=[attributions]
)
print(x)
</code>```

Output:

```<code>attributions {
  baseline_output_value: 0.9280818700790405
  instance_output_value: 0.6717480421066284
  feature_attributions {
    struct_value {
      fields {
        key: "feature_1"
        value {
          number_value: -0.0410824716091156
        }
      }
      fields {
        key: "feature_2"
        value {
          number_value: 0.01155053575833639
        }
      }
    }
  }
  output_index: 0
  output_display_name: "true"
  approximation_error: 0.010399332817679649
  output_name: "scores"
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cannot construct an Explanation object

Body:
Trying to construct an Explanation object for a unit test, but can't seem to get it to work. Here's what I'm trying:

from google.cloud import aiplatform

aiplatform.compat.types.explanation_v1.Explanation(
    attributions=aiplatform.compat.types.explanation_v1.Attribution(
        {
            "approximation_error": 0.010399332817679649,
            "baseline_output_value": 0.9280818700790405,
            "feature_attributions": {
                "feature_1": -0.0410824716091156,
                "feature_2": 0.01155053575833639,
            },
            "instance_output_value": 0.6717480421066284,
            "output_display_name": "true",
            "output_index": [0],
            "output_name": "scores",
        }
    )
)

which gives:

".venv/lib/python3.7/site-packages/proto/message.py", line 521, in __init__
    super().__setattr__("_pb", self._meta.pb(**params))
TypeError: Value must be iterable

I found this on github, but I'm not sure how to apply that workaround here.

Body:
As the error mentioned value to be passed at attributions should be iterable. See Explanation attributes documentation.

I tried your code and placed the Attribution object in a list and the error is gone. I assigned your objects in variables just so the code is readable.

See code and testing below:

from google.cloud import aiplatform

test = {
            "approximation_error": 0.010399332817679649,
            "baseline_output_value": 0.9280818700790405,
            "feature_attributions": {
                "feature_1": -0.0410824716091156,
                "feature_2": 0.01155053575833639,
            },
            "instance_output_value": 0.6717480421066284,
            "output_display_name": "true",
            "output_index": [0],
            "output_name": "scores",
        }

attributions=aiplatform.compat.types.explanation_v1.Attribution(test)
x  = aiplatform.compat.types.explanation_v1.Explanation(
    attributions=[attributions]
)
print(x)

Output:

attributions {
  baseline_output_value: 0.9280818700790405
  instance_output_value: 0.6717480421066284
  feature_attributions {
    struct_value {
      fields {
        key: "feature_1"
        value {
          number_value: -0.0410824716091156
        }
      }
      fields {
        key: "feature_2"
        value {
          number_value: 0.01155053575833639
        }
      }
    }
  }
  output_index: 0
  output_display_name: "true"
  approximation_error: 0.010399332817679649
  output_name: "scores"
}


问:
How can I mock an ES6 module import using Jest?
I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy --

The application code:

```<code>// myModule.js
import dependency from './dependency';

export default (x) => {
  dependency.doSomething(x * 2);
}
</code>```

And the test code:

```<code>//myModule-test.js
import myModule from '../myModule';
import dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    spyOn(dependency, 'doSomething');

    myModule(2);

    expect(dependency.doSomething).toHaveBeenCalledWith(4);
  });
});
</code>```

What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.

The closest I've come is by replacing the imports with requires, and moving them inside the tests/functions. Neither of which are things I want to do.

```<code>// myModule.js
export default (x) => {
  const dependency = require('./dependency'); // Yuck
  dependency.doSomething(x * 2);
}

//myModule-test.js
describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    jest.mock('../dependency');

    myModule(2);

    const dependency = require('../dependency'); // Also yuck
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});
</code>```

For bonus points, I'd love to make the whole thing work when the function inside dependency.js is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.

答:
None of the answers here seemed to work for me (the original function was always being imported rather than the mock), and it seems that ESM support in Jest is still work in progress.

After discovering this comment, I found out that jest.mock() does not actually work with regular imports, because the imports are always run before the mock (this is now also officially documented). Because of this, I am importing my dependencies using await import(). This even works with a top-level await, so I just have to adapt my imports:

import { describe, expect, it, jest } from '@jest/globals';

jest.unstable_mockModule('../dependency', () => ({
  doSomething: jest.fn()
}));

const myModule = await import('../myModule');
const dependency = await import('../dependency');

describe('myModule', async () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});
```

Body:
I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy --

The application code:

// myModule.js
import dependency from './dependency';

export default (x) => {
  dependency.doSomething(x * 2);
}

And the test code:

//myModule-test.js
import myModule from '../myModule';
import dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    spyOn(dependency, 'doSomething');

    myModule(2);

    expect(dependency.doSomething).toHaveBeenCalledWith(4);
  });
});

What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.

The closest I've come is by replacing the imports with requires, and moving them inside the tests/functions. Neither of which are things I want to do.

// myModule.js
export default (x) => {
  const dependency = require('./dependency'); // Yuck
  dependency.doSomething(x * 2);
}

//myModule-test.js
describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    jest.mock('../dependency');

    myModule(2);

    const dependency = require('../dependency'); // Also yuck
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

For bonus points, I'd love to make the whole thing work when the function inside dependency.js is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.


问:
Dynamic Filtering of Array with Multiple Confitions
I have an array which is constructed using user input values and can have any length:

```<code>var products = [
 {key1: string1,
  key2: 1,
  key3: 30,
  key4: 1},

 {key1: string2,
  key2: 2,
  key3: 35,
  key4: 2}
]

</code>```

And I have some filters

```<code>var filters = {
  key2: 1,
  key3: {min: 20, max: 40},
  key4: 1,
}
</code>```

I'm currently using the below function to filter products using my filters

```<code>        function multiFilter(array, filters) {
            const filterKeys = Object.keys(filters);
            return array.filter((item) => {
                // flipped around, and item[key] forced to a string
                return filterKeys.every(key => !!~String(item[key]).indexOf(filters[key]));
            });
        }

        var filtered = multiFilter(products, filters);
        console.log(filtered);
</code>```

Everything works as expected when key3 in filters has an exact number, but I'm running into issues when trying to incorporate a range. How would I amend the function to allow for a range in key3 (filters)?

答:
Maybe this approach would be useful

const products = [
 {key1: 'string0',key2: 0,key3: 10,key4: 1},
 {key1: 'string1',key2: 1,key3: 15,key4: 1},
 {key1: 'string2',key2: 2,key3: 20,key4: 1},
 {key1: 'string3',key2: 3,key3: 25,key4: 2},
 {key1: 'string4',key2: 4,key3: 30,key4: 2},
 {key1: 'string5',key2: 5,key3: 35,key4: 2},
 {key1: 'string6',key2: 6,key3: 40,key4: 4},
 {key1: 'string7',key2: 7,key3: 45,key4: 4},
 {key1: 'string8',key2: 8,key3: 50,key4: 4},
 {key1: 'string9',key2: 9,key3: 55,key4: 4}];

const filters = {
  key2: {max: 7},
  key3: {min: 20, max: 60},
  key4: 4,
};

const filterProdacts = (products, filters) => {
// First, we create an object where the property values (min, max, eq)
// are predicate functions.
  const fns = {
    eq: (key, value) => (obj) => obj[key] === value,
    min: (key, value) => (obj) => obj[key] >= value,
    max: (key, value) => (obj) => obj[key] <= value,
  };

// Generates a predicate based on the conditions
  makePredicat = (filterKey, filterValue) => {

// For consistency мake the numeric values as an object like { eq: 5 }
    const filterObj = (typeof filterValue === 'object')
      ? filterValue
      : { eq: filterValue };

// Pick a function from fns and initialize it with the condition parameters
    return Object.entries(filterObj)
      .map(([condKey, condValue]) => fns[condKey](filterKey, condValue));
  };

// Fill in the array with predicate functions for each condition.
// In this example there will be 4 functions, one for each condition
// key2 - max: 7; key3 - min: 20; key3 - max: 60; key4 - eq: 4;
const predicats = Object.entries(filters).flatMap(([key, value]) => makePredicat(key, value));

// Initializing reduce by source array
// then filtering it with all predicate functions
return predicats.reduce((acc, fn) => acc.filter(fn), products);
};

console.log(filterProdacts(products, filters));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{min-height: 100%!important; top: 0}</code>```

Body:
I have an array which is constructed using user input values and can have any length:

var products = [
 {key1: string1,
  key2: 1,
  key3: 30,
  key4: 1},

 {key1: string2,
  key2: 2,
  key3: 35,
  key4: 2}
]

And I have some filters

var filters = {
  key2: 1,
  key3: {min: 20, max: 40},
  key4: 1,
}

I'm currently using the below function to filter products using my filters

        function multiFilter(array, filters) {
            const filterKeys = Object.keys(filters);
            return array.filter((item) => {
                // flipped around, and item[key] forced to a string
                return filterKeys.every(key => !!~String(item[key]).indexOf(filters[key]));
            });
        }

        var filtered = multiFilter(products, filters);
        console.log(filtered);

Everything works as expected when key3 in filters has an exact number, but I'm running into issues when trying to incorporate a range. How would I amend the function to allow for a range in key3 (filters)?

Body:
Maybe this approach would be useful

const products = [
 {key1: 'string0',key2: 0,key3: 10,key4: 1},
 {key1: 'string1',key2: 1,key3: 15,key4: 1},
 {key1: 'string2',key2: 2,key3: 20,key4: 1},
 {key1: 'string3',key2: 3,key3: 25,key4: 2},
 {key1: 'string4',key2: 4,key3: 30,key4: 2},
 {key1: 'string5',key2: 5,key3: 35,key4: 2},
 {key1: 'string6',key2: 6,key3: 40,key4: 4},
 {key1: 'string7',key2: 7,key3: 45,key4: 4},
 {key1: 'string8',key2: 8,key3: 50,key4: 4},
 {key1: 'string9',key2: 9,key3: 55,key4: 4}];

const filters = {
  key2: {max: 7},
  key3: {min: 20, max: 60},
  key4: 4,
};

const filterProdacts = (products, filters) => {
// First, we create an object where the property values (min, max, eq)
// are predicate functions.
  const fns = {
    eq: (key, value) => (obj) => obj[key] === value,
    min: (key, value) => (obj) => obj[key] >= value,
    max: (key, value) => (obj) => obj[key] <= value,
  };

// Generates a predicate based on the conditions
  makePredicat = (filterKey, filterValue) => {

// For consistency мake the numeric values as an object like { eq: 5 }
    const filterObj = (typeof filterValue === 'object')
      ? filterValue
      : { eq: filterValue };

// Pick a function from fns and initialize it with the condition parameters
    return Object.entries(filterObj)
      .map(([condKey, condValue]) => fns[condKey](filterKey, condValue));
  };

// Fill in the array with predicate functions for each condition.
// In this example there will be 4 functions, one for each condition
// key2 - max: 7; key3 - min: 20; key3 - max: 60; key4 - eq: 4;
const predicats = Object.entries(filters).flatMap(([key, value]) => makePredicat(key, value));

// Initializing reduce by source array
// then filtering it with all predicate functions
return predicats.reduce((acc, fn) => acc.filter(fn), products);
};

console.log(filterProdacts(products, filters));

.as-console-wrapper{min-height: 100%!important; top: 0}


问:
Assosiation help in ruby on rails
I have fully linked everything together so a contact belongs_to :company and a company has_many :contacts everything works. The only question i have is in the contacts#new form you have to enter a companies ID is it possible to input the name of the company somehow and for it too translate to an ID in the back end? at the moment my form looks like this. You may notice company_id at the bottom of the form this is the field which i want to change. So that it is more user friendly instead of inserting an ID you insert a name or some kind of list of companies that you select. Please help?

```<code><%= form_for(@contact) do |f| %>
  <% if @contact.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:</h2>

      <ul>
      <% @contact.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :position %><br />
    <%= f.text_field :position %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :telephone %><br />
    <%= f.text_field :telephone %>
  </div>
  <div class="field">
    <%= f.label :source %><br />
    <%= f.text_field :source %>
  </div>
  <div class="field">
    <%= f.label :company_id %><br />
    <%= f.text_field :company_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
You can use a drop down list :

Take a look at this thread of how to do it in rails Drop down box in Rails

then as @David Burrows has suggested

```<code><select name="company[name]">
  <option value="">Please select</option>
  <option value="company_id[1]" selected="selected">company[name]</option>
  <option value="company_id[2]">company[name]</option>
  <option value="company_id[3]">company[name]</option>
</select>
</code>```

This should do .

ContentLicense: CC BY-SA 3.0

Title: Assosiation help in ruby on rails

Body:
I have fully linked everything together so a contact belongs_to :company and a company has_many :contacts everything works. The only question i have is in the contacts#new form you have to enter a companies ID is it possible to input the name of the company somehow and for it too translate to an ID in the back end? at the moment my form looks like this. You may notice company_id at the bottom of the form this is the field which i want to change. So that it is more user friendly instead of inserting an ID you insert a name or some kind of list of companies that you select. Please help?

<%= form_for(@contact) do |f| %>
  <% if @contact.errors.any? %>

<%= pluralize(@contact.errors.count, "error") %> prohibited this contact from being saved:

      <% @contact.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :position %>

    <%= f.text_field :position %>

    <%= f.label :email %>

    <%= f.text_field :email %>

    <%= f.label :telephone %>

    <%= f.text_field :telephone %>

    <%= f.label :source %>

    <%= f.text_field :source %>

    <%= f.label :company_id %>

    <%= f.text_field :company_id %>

    <%= f.submit %>

<% end %>

Body:
You can use a drop down list :

Take a look at this thread of how to do it in rails Drop down box in Rails

then as @David Burrows has suggested

<select name="company[name]">
  <option value="">Please select</option>
  <option value="company_id[1]" selected="selected">company[name]</option>
  <option value="company_id[2]">company[name]</option>
  <option value="company_id[3]">company[name]</option>
</select>

This should do .


问:
SwiftUI: how to get rid of top and bottom separators on lists
I'm working with Lists in SwiftUI, and noticed that when I have only one row, the separators still appear on the top and bottom:

Similarly, for Lists with multiple rows, these separators still appear on the top and bottom. How can I remove the separator at the very top and very bottom of a List, while keeping separators between middle rows?

答:
You can just hide separators using modifier (iOS 15+)</p>
```<code>List {
    ForEach(garage.cars) { car in
        Text(car.model)
            .listRowSeparator(.hidden)    // << this !!
    }
}
</code>```

Body:
You can just hide separators using modifier (iOS 15+)

List {
    ForEach(garage.cars) { car in
        Text(car.model)
            .listRowSeparator(.hidden)    // << this !!
    }
}


问:
Is UIView's opaque property with a value of YES in conflict with its backgroundColor property with a value of [UIColor clearColor]?
such as the code:

```<code>view.opaque = YES;
</code>```

and

```<code>view.backgroundColor = [UIColor clearColor];
</code>```

any one who can explain something about this?

EDIT:

as the document shows:

Declare Views as Opaque Whenever Possible

UIKit uses the opaque property of each view to determine whether the view can optimize compositing operations. Setting the value of this property to YES for a custom view tells UIKit that it does not need to render any content behind your view. Less rendering can lead to increased performance for your drawing code and is generally encouraged. Of course, if you set the opaque property to YES, your view must fills its bounds rectangle completely with fully opaque content.

opaque property is used for determining whether the view can optimize compositing operations.

so the question is:

if i set view.opaque = YES and view.backgroundColor = [UIColor clearColor]，the former increased performance，how about the latter?

答:
The opaque flag is used as an optimization for rendering. If you set it to YES when the view shouldn't be opaque you can get unexpected rendering if you actually want things to be visible through the view.

My understanding is that the opaque flag is sometimes checked to see if alpha value should even be checked.

Body:
such as the code:

view.opaque = YES;

and

view.backgroundColor = [UIColor clearColor];

any one who can explain something about this?

EDIT:

as the document shows:

Declare Views as Opaque Whenever Possible

UIKit uses the opaque property of each view to determine whether the view can optimize compositing operations. Setting the value of this property to YES for a custom view tells UIKit that it does not need to render any content behind your view. Less rendering can lead to increased performance for your drawing code and is generally encouraged. Of course, if you set the opaque property to YES, your view must fills its bounds rectangle completely with fully opaque content.

opaque property is used for determining whether the view can optimize compositing operations.

so the question is:

if i set view.opaque = YES and view.backgroundColor = [UIColor clearColor]，the former increased performance，how about the latter?


问:
Using Django-Taggit in Django Rest Framework 3.13.1 with Django 4.0.2 with Error "Invalid json list" in Serializing Tags Model Attribute
Older solutions uses django-taggit-serializer which is now been deprecated and doesn't work with the version I have.

I have already done what the documentation says regarding the integration with DRF.

However, I am getting this error:

b'{"tags":["Invalid json list. A tag list submitted in string form must be valid json."]}'

image error in drf browsable api

Here is my code

viewset.py

```<code>class AnnouncementViewSet(viewsets.ModelViewSet):
    """Announcement ViewSet."""

    queryset = Announcement.objects.all()
    serializer_class = AnnouncementSerializer
    lookup_field = "slug"
    permission_classes = [IsAdminUser, IsAuthorOrReadOnly]

    def get_permissions(self):
        """Return permissions."""
        if self.action in ["create", "update", "partial_update", "destroy"]:
            self.permission_classes = [IsAdminUser]
        else:
            self.permission_classes = [IsAuthorOrReadOnly]
        return super().get_permissions()
</code>```

models.py

```<code>class Announcement(models.Model):
    """Announcement model."""

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    title = models.CharField(_("title"), max_length=255, unique=True)
    content = models.TextField(_("content"))
    is_featured = models.BooleanField(default=False)
    thumbnail = models.ImageField(
        upload_to="announcement/thumbnail", default="announcement/thumbnail/default.jpg"
    )
    tags = TaggableManager(_("tags"))
    slug = models.SlugField(_("Slug"), max_length=255, unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)
</code>```

serializers.py

```<code>class AnnouncementSerializer(TaggitSerializer, serializers.ModelSerializer):
    tags = TagListSerializerField()

    class Meta:
        model = Announcement
        exclude = ["slug"]

        extra_kwargs = {
            "url": {"view_name": "api:announcement-detail", "lookup_field": "slug"}
        }
</code>```

What I have tried so far:

```<code>tags = "my-tag"

tags = ["tag1", "tag2"]
</code>```

I even wrote a test:

tests.py

```<code>def test_announcement_create_url(
    self, api_client: Client, admin_user
):
    api_client.force_login(admin_user)
    response = api_client.post(
        reverse("api:announcement-list"),
        {
            "title": "This is a new announcement",
            "content": "This is the content of the new announcement",
            "is_featured": "True",
            "tags": ["tag1", "tag2"],
        },
    )
    print(response.content)
    assert response.status_code == status.HTTP_201_CREATED
</code>```

But it produces the same error.

I also found this GitHub issue but again, django-taggit-serializer is deprecated and is not being maintained anymore.

答:
Found my own answer. The cause of the error is my tags Model Attribute.

If your Model Attribute is named tags then you need to do this in order to submit or tests your API query:

Browsable API

```<code>{
    "tags": ["tag1", "tag2"]
}
</code>```

Python Code

```<code>{
    "tags": '["tag1", "tag2"]'
}
</code>```

Some fields are omitted for brevity. Make sure to include the required fields needed by your serializer.

Body:
Older solutions uses django-taggit-serializer which is now been deprecated and doesn't work with the version I have.

I have already done what the documentation says regarding the integration with DRF.

However, I am getting this error:

b'{"tags":["Invalid json list. A tag list submitted in string form must be valid json."]}'

image error in drf browsable api

Here is my code

viewset.py

class AnnouncementViewSet(viewsets.ModelViewSet):
    """Announcement ViewSet."""

    queryset = Announcement.objects.all()
    serializer_class = AnnouncementSerializer
    lookup_field = "slug"
    permission_classes = [IsAdminUser, IsAuthorOrReadOnly]

    def get_permissions(self):
        """Return permissions."""
        if self.action in ["create", "update", "partial_update", "destroy"]:
            self.permission_classes = [IsAdminUser]
        else:
            self.permission_classes = [IsAuthorOrReadOnly]
        return super().get_permissions()

models.py

class Announcement(models.Model):
    """Announcement model."""

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    title = models.CharField(_("title"), max_length=255, unique=True)
    content = models.TextField(_("content"))
    is_featured = models.BooleanField(default=False)
    thumbnail = models.ImageField(
        upload_to="announcement/thumbnail", default="announcement/thumbnail/default.jpg"
    )
    tags = TaggableManager(_("tags"))
    slug = models.SlugField(_("Slug"), max_length=255, unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

serializers.py

class AnnouncementSerializer(TaggitSerializer, serializers.ModelSerializer):
    tags = TagListSerializerField()

    class Meta:
        model = Announcement
        exclude = ["slug"]

        extra_kwargs = {
            "url": {"view_name": "api:announcement-detail", "lookup_field": "slug"}
        }

What I have tried so far:

tags = "my-tag"

tags = ["tag1", "tag2"]

I even wrote a test:

tests.py

def test_announcement_create_url(
    self, api_client: Client, admin_user
):
    api_client.force_login(admin_user)
    response = api_client.post(
        reverse("api:announcement-list"),
        {
            "title": "This is a new announcement",
            "content": "This is the content of the new announcement",
            "is_featured": "True",
            "tags": ["tag1", "tag2"],
        },
    )
    print(response.content)
    assert response.status_code == status.HTTP_201_CREATED

But it produces the same error.

I also found this GitHub issue but again, django-taggit-serializer is deprecated and is not being maintained anymore.

Body:
Found my own answer. The cause of the error is my tags Model Attribute.

If your Model Attribute is named tags then you need to do this in order to submit or tests your API query:

Browsable API

{
    "tags": ["tag1", "tag2"]
}

Python Code

{
    "tags": '["tag1", "tag2"]'
}

Some fields are omitted for brevity. Make sure to include the required fields needed by your serializer.


问:
Difference between the following code C/C++ code
The first one is :

```<code>if(n--)
{
 //do something
}
</code>```

The second is :

```<code>if(n)
{
//do something
n--;
}
</code>```

I'm not able to understand the difference between these two pieces of code.
Both are giving different outputs.

答:
let say, n=1. For the first if, it is true and it will decrement 1 to 0 immediately. so if you print at the beginning of  if you will see n=0. For the 2nd if, you will see n=1, then n-- will decrement it.

Run the below code, you will get it.

The first one is :

```<code>if(n--)
{
  printf("%d\n",n);
 //do something
}
</code>```

The second is :

```<code>if(n)
{
 printf("%d\n",n);
//do something
n--;
}
</code>```

Body:
The first one is :

if(n--)
{
 //do something
}

The second is :

if(n)
{
//do something
n--;
}

I'm not able to understand the difference between these two pieces of code.
Both are giving different outputs.

Body:
let say, n=1. For the first if, it is true and it will decrement 1 to 0 immediately. so if you print at the beginning of  if you will see n=0. For the 2nd if, you will see n=1, then n-- will decrement it.

Run the below code, you will get it.

The first one is :

if(n--)
{
  printf("%d\n",n);
 //do something
}

The second is :

if(n)
{
 printf("%d\n",n);
//do something
n--;
}


问:
Store authentication token in iPhone application
I want to store authentication token, that i received from log-in response.

It is right to use for this NSUserDefaults? Or I must use KeyChainWrapper?

What is the best way store authentication token?

答:
Checkout SFHFKeychainUtils on GitHub:

```<code>[SFHFKeychainUtils storeUsername:aUsername andPassword:aPassword forServiceName:@"MyService"  updateExisting:TRUE error:&anError];
</code>```

there is also getPasswordForUsername and deleteItemForUsername

edit- and cortez has provided link in his answer

Body:
Checkout SFHFKeychainUtils on GitHub:

[SFHFKeychainUtils storeUsername:aUsername andPassword:aPassword forServiceName:@"MyService"  updateExisting:TRUE error:&anError];

there is also getPasswordForUsername and deleteItemForUsername

edit- and cortez has provided link in his answer


问:
Why does my program stop working instead of checking the input and outputing the menu and continue working?
I did a project called ATM and watched YouTube to do the basics of it.

Then I upgraded it and it worked (first version), but because it had a few bugs, I upgraded it again and fixed the errors.

But now it's not working anymore. It's supposed to ask for the account number and see if it is valid or not. If not then redo, but if yes then it should show a menu and let me do different stuff. But now, when it asks me for my account number, and when I type my account number in, the program just stops instead of showing the menu and continue working.

After a week, I still can't find out what went wrong.

Can anyone please check what’s wrong with the code?

Here is my ATM Project

I am not even sure what function is related to this problem, but I think it's the inputcheck() function, which I think is at line 33. It might have something to do with cin.clear() and cin.ignore(). I am not sure. So the input will be the account, and the function should check if it's valid.

I used some trick to return 2 variables, and it will return the account and whether it is  valid. I tried to do some changes, but I don't think it’s any better. I tried a lot of things that I don't even remember. Please help me with this.

答:
well you call inputcheck(option)

This is declared as returning an int, but it returns nothing, plus you ignore the return value even if there was one. I suspect this doesnt help

same with inputcheck(amount)

I assume you mean to pass option as a refernce so that inputchekc can update it

ie change it to

```<code>inputcheck(T &input){...}
</code>```

the compiler is warning you about the lack of a return value - or should be.

and I have no idea why those are templates but thats a different question.

Body:
well you call inputcheck(option)

This is declared as returning an int, but it returns nothing, plus you ignore the return value even if there was one. I suspect this doesnt help

same with inputcheck(amount)

I assume you mean to pass option as a refernce so that inputchekc can update it

ie change it to

inputcheck(T &input){...}

the compiler is warning you about the lack of a return value - or should be.

and I have no idea why those are templates but thats a different question.


问:
Cannot display emojis in Windows Powershell or WSL Linux Terminal using Python
I am trying to print emojis in both Windows Powershell and WSL Linux Terminal using Python3.

I have tried using unicode, CLDR names and also installed the emoji library.

```<code>print("\U0001F44D")
print(emoji.emojize(':thumbs_up:'))
</code>```

But in the terminal it is showing only a question mark within a box. No emoji is showing.

What is the issue here?

But if I copy the output here it is showing properly.
Like this

答:
Summary: Solved by using WSL terminal of Visual Code .

Details:

For me, I had the same issue.

It does not work with the default WSL terminal program:

But It does work with WSL terminal opened from Visual Code.

This is how you could open that terminal in Visual Code:

Body:
I am trying to print emojis in both Windows Powershell and WSL Linux Terminal using Python3.

I have tried using unicode, CLDR names and also installed the emoji library.

print("\U0001F44D")
print(emoji.emojize(':thumbs_up:'))

But in the terminal it is showing only a question mark within a box. No emoji is showing.

What is the issue here?

But if I copy the output here it is showing properly.
Like this


问:
Space between components in React Native styling

I have 6 View components (shown in the picture) , I want to have space between all 6 View components.

My code:

```<code><View style={{flexDirection:'column',flex:6}}>
            <View style={{flex:2,flexDirection:"row",justifyContent:'space-between'}}>
                <View style={{backgroundColor:'red',flex:1}}>
                </View>
                <View style={{backgroundColor:'blue',flex:1}}>
                </View>
            </View>

            <View style={{flex:2,flexDirection:"row",justifyContent:'space-between'}}>
                <View style={{backgroundColor:'white',flex:1}}>
                </View>
                <View style={{backgroundColor:'black',flex:1}}>
                </View>

            </View>

            <View style={{flex:2,flexDirection:"row",justifyContent:'space-between'}}>
                <View style={{backgroundColor:'gray',flex:1}}>
                </View>
                <View style={{backgroundColor:'yellow',flex:1}}>
                </View>

            </View>

 </View>
</code>```

答:
```<code><View style={{ flexDirection: "row", flexWrap: "wrap" }}>
          {Array(30)
            .fill({ name: "product name" })
            .map((item, key, arr) => (
              <View
                key={key}
                style={{
                  height: 200,
                  paddingTop: 15,
                  backgroundColor: "skyblue",
                  ...(key % 2 !== 0
                    ? { paddingRight: 15, paddingLeft: 15 }
                    : { paddingLeft: 15 }),
                  flexBasis: "50%",
                }}
              >
                <View
                  style={{
                    flex: 1,
                    backgroundColor: variables?.BackgroundLight,
                  }}
                >
                  <Text style={styles && { ...styles?.text }}>{item.name}</Text>
                </View>
              </View>
            ))}
        </View>
</code>```

Try this out. You can better control it using array map

Body:
I have 6 View components (shown in the picture) , I want to have space between all 6 View components.

My code:

<View style={{flexDirection:'column',flex:6}}>
            <View style={{flex:2,flexDirection:"row",justifyContent:'space-between'}}>
                <View style={{backgroundColor:'red',flex:1}}>
                </View>
                <View style={{backgroundColor:'blue',flex:1}}>
                </View>
            </View>

            <View style={{flex:2,flexDirection:"row",justifyContent:'space-between'}}>
                <View style={{backgroundColor:'white',flex:1}}>
                </View>
                <View style={{backgroundColor:'black',flex:1}}>
                </View>

            </View>

            <View style={{flex:2,flexDirection:"row",justifyContent:'space-between'}}>
                <View style={{backgroundColor:'gray',flex:1}}>
                </View>
                <View style={{backgroundColor:'yellow',flex:1}}>
                </View>

            </View>

 </View>

Body:
<View style={{ flexDirection: "row", flexWrap: "wrap" }}>
          {Array(30)
            .fill({ name: "product name" })
            .map((item, key, arr) => (
              <View
                key={key}
                style={{
                  height: 200,
                  paddingTop: 15,
                  backgroundColor: "skyblue",
                  ...(key % 2 !== 0
                    ? { paddingRight: 15, paddingLeft: 15 }
                    : { paddingLeft: 15 }),
                  flexBasis: "50%",
                }}
              >
                <View
                  style={{
                    flex: 1,
                    backgroundColor: variables?.BackgroundLight,
                  }}
                >
                  <Text style={styles && { ...styles?.text }}>{item.name}</Text>
                </View>
              </View>
            ))}
        </View>

Try this out. You can better control it using array map


问:
DATAFRAME join and divide
I have a data frame dF with 3 COLUMN A B C

```<code>dF =

               A                                      B                  C
        navigate to "www.xyz.com"               to "www.xyz.com"        NA
     enters valid username "JOHN"                enters                "JOHN"
    enters password "1234567"                    enters                "1234567"
    enters  RIGHT destination"YUL"                enters               "YUL"
    clicks Customer Service                      clicks                 NA
    clicks Booking Information from Booking      clicks                 NA
</code>```

i want to find the difference between of A ,B+C, and rest values will be in D column. i want my data frame to look like this

```<code>dF =

               A                                      B                     C                 D
        navigate to "www.xyz.com"               to "www.xyz.com"        NA              navigate
     enters valid username "JOHN"                enters                "JOHN"           valid username
    enters valid password "1234567"               enters              "1234567"         valid password
    enters  RIGHT destination"YUL"                enters               "YUL"            RIGHT destination
    clicks Customer Service                      clicks                 NA              Customer Service
    clicks Booking Information from Booking      clicks                 NA              Booking Information from Booking
</code>```

i am using:

```<code>df['D'] = Final_df[['B', 'C']].agg(' '.join, axis=1).str.split(' ')

df['D'] = df.apply(lambda x: ''.join(set(x['A'].split(' ')) - set(x['D'])), axis=1)
</code>```

but i am not getting in sequence order in D column.

答:
```<code>df = {'A': ['navigate to "www.xyz.com"',
  'enters valid username "JOHN"',
  'enters password "1234567"',
  'enters  RIGHT destination"YUL"',
  'clicks Customer Service',
  'clicks Booking Information from Booking'],
 'B': ['to "www.xyz.com"', 'enters', 'enters', 'enters', 'clicks', 'clicks'],
 'C': ['NA', '"JOHN"', '"1234567"', '"YUL"', 'NA', 'NA']}
</code>```

If you are sure that all words are space-separated (which is not true in row #4), then you can use split, but don't convert 'A' to a set to preserve the ordering.

```<code>a = df['A'].str.split()
b = df['B'].str.split().apply(set)
c = df['C'].str.split().apply(set)

df['D'] = [' '.join([a2 for a2 in a1 if a2 not in (b1 | c1)]) for a1, b1, c1 in zip(a,b,c)]
</code>```

Otherwise, you may consider replace

```<code>df['D'] = df.apply(lambda r: r['A'].replace(r['B'], '').replace(r['C'], '').strip(), axis=1)
</code>```

Title: DATAFRAME join and divide

Body:
I have a data frame dF with 3 COLUMN A B C

dF =

               A                                      B                  C
        navigate to "www.xyz.com"               to "www.xyz.com"        NA
     enters valid username "JOHN"                enters                "JOHN"
    enters password "1234567"                    enters                "1234567"
    enters  RIGHT destination"YUL"                enters               "YUL"
    clicks Customer Service                      clicks                 NA
    clicks Booking Information from Booking      clicks                 NA

i want to find the difference between of A ,B+C, and rest values will be in D column. i want my data frame to look like this

dF =

               A                                      B                     C                 D
        navigate to "www.xyz.com"               to "www.xyz.com"        NA              navigate
     enters valid username "JOHN"                enters                "JOHN"           valid username
    enters valid password "1234567"               enters              "1234567"         valid password
    enters  RIGHT destination"YUL"                enters               "YUL"            RIGHT destination
    clicks Customer Service                      clicks                 NA              Customer Service
    clicks Booking Information from Booking      clicks                 NA              Booking Information from Booking

i am using:

df['D'] = Final_df[['B', 'C']].agg(' '.join, axis=1).str.split(' ')

df['D'] = df.apply(lambda x: ''.join(set(x['A'].split(' ')) - set(x['D'])), axis=1)

but i am not getting in sequence order in D column.

Body:
df = {'A': ['navigate to "www.xyz.com"',
  'enters valid username "JOHN"',
  'enters password "1234567"',
  'enters  RIGHT destination"YUL"',
  'clicks Customer Service',
  'clicks Booking Information from Booking'],
 'B': ['to "www.xyz.com"', 'enters', 'enters', 'enters', 'clicks', 'clicks'],
 'C': ['NA', '"JOHN"', '"1234567"', '"YUL"', 'NA', 'NA']}

If you are sure that all words are space-separated (which is not true in row #4), then you can use split, but don't convert 'A' to a set to preserve the ordering.

a = df['A'].str.split()
b = df['B'].str.split().apply(set)
c = df['C'].str.split().apply(set)

df['D'] = [' '.join([a2 for a2 in a1 if a2 not in (b1 | c1)]) for a1, b1, c1 in zip(a,b,c)]

Otherwise, you may consider replace

df['D'] = df.apply(lambda r: r['A'].replace(r['B'], '').replace(r['C'], '').strip(), axis=1)


问:
Double quotes in Json String replaced in freemarker file
In an action class, I get a list of beans in conventional manner. Then I use Gson to convert this object list in a json string.
This works well (as you can see as follow):

```<code>"{ "employees" : [{ "firstName":"John" , "lastName":"Doe" }, {"firstName":"Anna" , "lastName":"Smith" } , { "firstName":"Peter" , "lastName":"Jones" } ]}";
</code>```

Finally, in my freemarker file I get this variable (String JSon) but, in it, all double quotes have been replaced with '& quote;'.

```<code><@sjg.grid id="gridtable"
 caption="My title"
 dataType="json"
 href="${remoteurl}"
 pager="true"
 gridModel="${employeesInJsonString?js_string}"
 rowList="10,15,20"
 rowNum="15"
 rownumbers="true">

<sjg:gridColumn name="firstName" index="firstName" title="FirstName" sortable="false"/>
<sjg:gridColumn name="lastName" index="lastName" title="LastName" sortable="false"/>
</code>```

The resulting String is the following:

```<code>"{ & quote;employees& quote; : [{ & quote;firstName& quote;:& quote;John& quote; , & quote;lastName& quote;:& quote;Doe& quote; }, {& quote;firstName& quote;:& quote;Anna& quote; , & quote;lastName& quote;:& quote;Smith& quote; } , { & quote;firstName& quote;:& quote;Peter" , & quote;lastName& quote;:& quote;Jones& quote; } ]}";
</code>```

How to keep out this transformation?

PS: I already tried to prefix all double quotes by a backslash to escape the character but the result is the same (resultJsonString = jsonString.replaceAll("\"", "\\"")).

Thank you in advance for your help

答: i think what you are looking for is simply ${yourvar?no_esc}

Body:
In an action class, I get a list of beans in conventional manner. Then I use Gson to convert this object list in a json string.
This works well (as you can see as follow):

"{ "employees" : [{ "firstName":"John" , "lastName":"Doe" }, {"firstName":"Anna" , "lastName":"Smith" } , { "firstName":"Peter" , "lastName":"Jones" } ]}";

Finally, in my freemarker file I get this variable (String JSon) but, in it, all double quotes have been replaced with '& quote;'.

<@sjg.grid id="gridtable"
 caption="My title"
 dataType="json"
 href="${remoteurl}"
 pager="true"
 gridModel="${employeesInJsonString?js_string}"
 rowList="10,15,20"
 rowNum="15"
 rownumbers="true">

<sjg:gridColumn name="firstName" index="firstName" title="FirstName" sortable="false"/>
<sjg:gridColumn name="lastName" index="lastName" title="LastName" sortable="false"/>

The resulting String is the following:

"{ & quote;employees& quote; : [{ & quote;firstName& quote;:& quote;John& quote; , & quote;lastName& quote;:& quote;Doe& quote; }, {& quote;firstName& quote;:& quote;Anna& quote; , & quote;lastName& quote;:& quote;Smith& quote; } , { & quote;firstName& quote;:& quote;Peter" , & quote;lastName& quote;:& quote;Jones& quote; } ]}";

How to keep out this transformation?

PS: I already tried to prefix all double quotes by a backslash to escape the character but the result is the same (resultJsonString = jsonString.replaceAll("\"", "\\"")).

Thank you in advance for your help


问:
Flutter Plug In
Dart SDK Screen PrintFlutter Plugin Screen Print ImageHi I uninstalled the flutter plug in from the android studio by mistake how do I reinstall it again? As the result I cannot run any dart files nor start a new flutter project. I also keep getting and error that dart sdk files not configure. So in short flutter is not running from the android studios. I tried to uninstall android studios but that didn't work</p>

答:
Windows : Android Studio > Settings > Plugins > {search flutter and install}

Mac : Android Studio > Preferences > Plugin > {search flutter and install}

Title: Flutter Plug In


问:
ElasticSearch Kubernetes Setup with Skaffold
I love elastic search so on my new project I have been trying to make it work on Kubernetes and skaffold

this is the yaml file I wrote:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: eks-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: eks
  template:
    metadata:
      labels:
        app: eks
    spec:
      containers:
        - name: eks
          image: elasticsearch:7.17.0
---
apiVersion: v1
kind: Service
metadata:
  name: eks-srv
spec:
  selector:
    app: eks
  ports:
    - name: db
      protocol: TCP
      port: 9200
      targetPort: 9200
    - name: monitoring
      protocol: TCP
      port: 9300
      targetPort: 9300
</code>```

After I run skaffold dev it shows to be working by Kubernetes but after a few seconds it crashes and goes down.

I can't understand what I am doing wrong.

After I have updated my config files as Mr. Harsh Manvar it worked like a charm but currently I am facing another issue. The client side says the following....

Btw I am using ElasticSearch version 7.11.1 and Client side module "@elastic/elasticsearch^7.11.1"

答:
Here is example YAML file you should consider running if you are planning to run the single Node elasticsearch cluster on the Kubernetes

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  labels:
    app: elasticsearch
    component: elasticsearch
    release: elasticsearch
  name: elasticsearch
  namespace: default
spec:
  podManagementPolicy: OrderedReady
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: elasticsearch
      component: elasticsearch
      release: elasticsearch
  serviceName: elasticsearch
  template:
    metadata:
      labels:
        app: elasticsearch
        component: elasticsearch
        release: elasticsearch
    spec:
      containers:
      - env:
        - name: cluster.name
          value: es_cluster
        - name: ELASTIC_PASSWORD
          value: xyz-xyz
        - name: discovery.type
          value: single-node
        - name: path.repo
          value: backup/es-backup
        - name: ES_JAVA_OPTS
          value: -Xms512m -Xmx512m
        - name: bootstrap.memory_lock
          value: "false"
        - name: xpack.security.enabled
          value: "true"
        image: elasticsearch:7.3.2
        imagePullPolicy: IfNotPresent
        name: elasticsearch
        ports:
        - containerPort: 9200
          name: http
          protocol: TCP
        - containerPort: 9300
          name: transport
          protocol: TCP
        resources:
          limits:
            cpu: 451m
            memory: 1250Mi
          requests:
            cpu: 250m
            memory: 1000Mi
        securityContext:
          privileged: true
          runAsUser: 1000
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: elasticsearch-data
      dnsPolicy: ClusterFirst
      initContainers:
      - command:
        - sh
        - -c
        - chown -R 1000:1000 /usr/share/elasticsearch/data
        - sysctl -w vm.max_map_count=262144
        - chmod 777 /usr/share/elasticsearch/data
        - chomod 777 /usr/share/elasticsearch/data/node
        - chmod g+rwx /usr/share/elasticsearch/data
        - chgrp 1000 /usr/share/elasticsearch/data
        image: busybox:1.29.2
        imagePullPolicy: IfNotPresent
        name: set-dir-owner
        resources: {}
        securityContext:
          privileged: true
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: elasticsearch-data
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 10
  updateStrategy:
    type: OnDelete
  volumeClaimTemplates:
  - metadata:
      creationTimestamp: null
      name: elasticsearch-data
    spec:
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 10Gi
      volumeMode: Filesystem
</code>```

i would also recommand checking out the helm charts of the elasticsearch :

```<code>1 . https://github.com/elastic/helm-charts/tree/master/elasticsearch

2. https://github.com/helm/charts/tree/master/stable/elasticsearch
</code>```

you can expose the above stateful set using the service and use the further with the application.

Body:
I love elastic search so on my new project I have been trying to make it work on Kubernetes and skaffold

this is the yaml file I wrote:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: eks-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: eks
  template:
    metadata:
      labels:
        app: eks
    spec:
      containers:
        - name: eks
          image: elasticsearch:7.17.0
---
apiVersion: v1
kind: Service
metadata:
  name: eks-srv
spec:
  selector:
    app: eks
  ports:
    - name: db
      protocol: TCP
      port: 9200
      targetPort: 9200
    - name: monitoring
      protocol: TCP
      port: 9300
      targetPort: 9300

After I run skaffold dev it shows to be working by Kubernetes but after a few seconds it crashes and goes down.

I can't understand what I am doing wrong.

After I have updated my config files as Mr. Harsh Manvar it worked like a charm but currently I am facing another issue. The client side says the following....

Btw I am using ElasticSearch version 7.11.1 and Client side module "@elastic/elasticsearch^7.11.1"

Body:
Here is example YAML file you should consider running if you are planning to run the single Node elasticsearch cluster on the Kubernetes

apiVersion: apps/v1
kind: StatefulSet
metadata:
  labels:
    app: elasticsearch
    component: elasticsearch
    release: elasticsearch
  name: elasticsearch
  namespace: default
spec:
  podManagementPolicy: OrderedReady
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: elasticsearch
      component: elasticsearch
      release: elasticsearch
  serviceName: elasticsearch
  template:
    metadata:
      labels:
        app: elasticsearch
        component: elasticsearch
        release: elasticsearch
    spec:
      containers:
      - env:
        - name: cluster.name
          value: es_cluster
        - name: ELASTIC_PASSWORD
          value: xyz-xyz
        - name: discovery.type
          value: single-node
        - name: path.repo
          value: backup/es-backup
        - name: ES_JAVA_OPTS
          value: -Xms512m -Xmx512m
        - name: bootstrap.memory_lock
          value: "false"
        - name: xpack.security.enabled
          value: "true"
        image: elasticsearch:7.3.2
        imagePullPolicy: IfNotPresent
        name: elasticsearch
        ports:
        - containerPort: 9200
          name: http
          protocol: TCP
        - containerPort: 9300
          name: transport
          protocol: TCP
        resources:
          limits:
            cpu: 451m
            memory: 1250Mi
          requests:
            cpu: 250m
            memory: 1000Mi
        securityContext:
          privileged: true
          runAsUser: 1000
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: elasticsearch-data
      dnsPolicy: ClusterFirst
      initContainers:
      - command:
        - sh
        - -c
        - chown -R 1000:1000 /usr/share/elasticsearch/data
        - sysctl -w vm.max_map_count=262144
        - chmod 777 /usr/share/elasticsearch/data
        - chomod 777 /usr/share/elasticsearch/data/node
        - chmod g+rwx /usr/share/elasticsearch/data
        - chgrp 1000 /usr/share/elasticsearch/data
        image: busybox:1.29.2
        imagePullPolicy: IfNotPresent
        name: set-dir-owner
        resources: {}
        securityContext:
          privileged: true
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /usr/share/elasticsearch/data
          name: elasticsearch-data
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 10
  updateStrategy:
    type: OnDelete
  volumeClaimTemplates:
  - metadata:
      creationTimestamp: null
      name: elasticsearch-data
    spec:
      accessModes:
      - ReadWriteOnce
      resources:
        requests:
          storage: 10Gi
      volumeMode: Filesystem

i would also recommand checking out the helm charts of the elasticsearch :

1 . https://github.com/elastic/helm-charts/tree/master/elasticsearch

2. https://github.com/helm/charts/tree/master/stable/elasticsearch

you can expose the above stateful set using the service and use the further with the application.


问:
No such file or directory - Boto3
I am running the following with Amazon Sagemaker

```<code>s3 = boto3.client('s3', region_name='us-east-1',
                        # Set up AWS credentials
                        aws_access_key_id=key_id,
                         aws_secret_access_key=secret_key)

s3.create_bucket(Bucket = 'gid-datacamp')

s3.upload_file(Filename = r'C:\Users\Filippo\Desktop\WineQT.csv' , Bucket = 'gid-datacamp', Key = 'WineQT.csv')
</code>```

but despite the directory being the correct one I get the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Filippo\Desktop\WineQT.csv'

I also tried to directly import the file using pd.read_csv() and I got the same error.

Is there something I don't know about how boto3 and my local machine interact?

thanks!

答:
The python script should run on your local machine, not SageMaker (SM).

SM does not have access to your local computer, unless you setup some kind of connection between SM and your home/work computer. Once you have that you can access the files through server (ssh or ftp) running on your local computer.

Title: No such file or directory - Boto3

Body:
I am running the following with Amazon Sagemaker

s3 = boto3.client('s3', region_name='us-east-1',
                        # Set up AWS credentials
                        aws_access_key_id=key_id,
                         aws_secret_access_key=secret_key)

s3.create_bucket(Bucket = 'gid-datacamp')

s3.upload_file(Filename = r'C:\Users\Filippo\Desktop\WineQT.csv' , Bucket = 'gid-datacamp', Key = 'WineQT.csv')

but despite the directory being the correct one I get the following error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\Filippo\Desktop\WineQT.csv'

I also tried to directly import the file using pd.read_csv() and I got the same error.

Is there something I don't know about how boto3 and my local machine interact?

thanks!


问:
How save a entire text file to a array and display in textbox
```<code>string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
     textBox1.Text = string.Join(",",s);
}
</code>```

This is what is in the text file:

10,

1,2,3,4,5,

6,76,81,9

in the text box in visual studio it only displays the last line, i am trying to make it display everything

答:
You have to append to the text box, not just assign it. Note the plus.

```<code>  textBox1.Text += string.Join(",",s);
</code>```

When your text file has lots of rows, the above method will not be good, since it will do lot of memory re-allocations, instead you can use the StringBuilder as in other answer.

Alternately, since you already got all the lines present in your text file into the array named readText, you just need to do this, without need for a foreach loop.

```<code>   textBox1.Text = string.Join(Environment.NewLine, readText);
</code>```

Body:
string[] readText = File.ReadAllLines(path);
foreach (string s in readText)
{
     textBox1.Text = string.Join(",",s);
}

This is what is in the text file:

10,

1,2,3,4,5,

6,76,81,9

in the text box in visual studio it only displays the last line, i am trying to make it display everything

Body:
You have to append to the text box, not just assign it. Note the plus.

  textBox1.Text += string.Join(",",s);

When your text file has lots of rows, the above method will not be good, since it will do lot of memory re-allocations, instead you can use the StringBuilder as in other answer.

Alternately, since you already got all the lines present in your text file into the array named readText, you just need to do this, without need for a foreach loop.

   textBox1.Text = string.Join(Environment.NewLine, readText);


问:
CircleCI failing to access private repository
We have a Flutter app which uses a private repository as a dependency.

The SSH key has been added to CircleCI, and the remote access to the repository works just fine locally using this same key.

The config has been added to the .circleci/config.yml:

```<code>- add_ssh_keys:
  fingerprints:
    - "84:1a:so:me:ke:y:14:31:0f"
</code>```

But CircleCI keeps failing to access the private dependency repo , giving the following error:

" Running "flutter pub get" in project... Git error. Command: git clone --mirror git@bitbucket.org:our_account/priv_repo.git /home/circleci/development/flutter/.pub-cache/git/cache/priv_repo-3456accd54b38ec5b3820944f77e90ce2ddc9887
stdout: stderr: Cloning into bare repository
'/home/circleci/development/flutter/.pub-cache/git/cache/priv_repo-3456accd54b38ec5b3820944f77e90ce2ddc9887'...
Warning: Permanently added the RSA host key for IP address
'18.205.93.1' to the list of known hosts. Unauthorized fatal: Could
not read from remote repository.

Please make sure you have the correct access rights and the repository
exists. exit code: 128 "

Has anyone successfully created a CircleCI deployment which includes a private repo dependency?

What might possibly be missing to cause this issue?

答:
I want to clarify some things first.

The main one was that I had the add_ssh_keys line in the wrong place.
It really needs to be the first step, or at least be before the flutter/install_sdk_and_pub step.

Yes, it's because each step runs in a different session, so they don't share the configs from each other. Your ssh-key only works because the environment variables defined on the Project Settings, are used across all the steps.

eg. This works (but if the add_ssh_keys step was at the bottom of the list of 4 steps here then it fails):

Yes, and if you want to use this fingerprint in another step, you need to paste it there too.

There are some things that you can do to fix your problem, you can leave the main ssh-key on the Project Settings and you can create an environment variable with the public key content (from another ssh-key).

After that, before using that second key, you need to run some commands like:

```<code>  - run:
      name: Step I'm using the second key
      command: |
        echo -e $MY_ENV_VAR | base64 -d > key
        chmod 400 key
        eval $(ssh-agent -s)
        ssh-add key
        git clone...
        docker build...
</code>```

Doing that, you will be able to clone the second repo.

Body:
We have a Flutter app which uses a private repository as a dependency.

The SSH key has been added to CircleCI, and the remote access to the repository works just fine locally using this same key.

The config has been added to the .circleci/config.yml:

- add_ssh_keys:
  fingerprints:
    - "84:1a:so:me:ke:y:14:31:0f"

But CircleCI keeps failing to access the private dependency repo , giving the following error:

" Running "flutter pub get" in project... Git error. Command: git clone --mirror git@bitbucket.org:our_account/priv_repo.git /home/circleci/development/flutter/.pub-cache/git/cache/priv_repo-3456accd54b38ec5b3820944f77e90ce2ddc9887
stdout: stderr: Cloning into bare repository
'/home/circleci/development/flutter/.pub-cache/git/cache/priv_repo-3456accd54b38ec5b3820944f77e90ce2ddc9887'...
Warning: Permanently added the RSA host key for IP address
'18.205.93.1' to the list of known hosts. Unauthorized fatal: Could
not read from remote repository.

Please make sure you have the correct access rights and the repository
exists. exit code: 128 "

Has anyone successfully created a CircleCI deployment which includes a private repo dependency?

What might possibly be missing to cause this issue?

Body:
I want to clarify some things first.

The main one was that I had the add_ssh_keys line in the wrong place.
It really needs to be the first step, or at least be before the flutter/install_sdk_and_pub step.

Yes, it's because each step runs in a different session, so they don't share the configs from each other. Your ssh-key only works because the environment variables defined on the Project Settings, are used across all the steps.

eg. This works (but if the add_ssh_keys step was at the bottom of the list of 4 steps here then it fails):

Yes, and if you want to use this fingerprint in another step, you need to paste it there too.

There are some things that you can do to fix your problem, you can leave the main ssh-key on the Project Settings and you can create an environment variable with the public key content (from another ssh-key).

After that, before using that second key, you need to run some commands like:

  - run:
      name: Step I'm using the second key
      command: |
        echo -e $MY_ENV_VAR | base64 -d > key
        chmod 400 key
        eval $(ssh-agent -s)
        ssh-add key
        git clone...
        docker build...

Doing that, you will be able to clone the second repo.


问:
Disable Cloud logging GCP
why i cannot disable the cloud logging

i tried using console and command but still not working

```<code>    gcloud beta resource-manager org-policies enable-enforce \
  constraints/gcp.disableCloudLogging --project x4-stag
</code>```

and got this error

```<code>C:\Users\aji> gcloud beta resource-manager org-policies enable-enforce constraints/gcp.disableCloudLogging --project x4-stag
ERROR: (gcloud.beta.resource-manager.org-policies.enable-enforce) User [aji.fa@xxx.com] does not have permission to access project [x4-stag:setOrgPolicy] (or it may not exist): The caller does not have permission
</code>```

for IAM role is using owner

答:
Your identity is lacking permission to enforce a policy. Add the IAM role Organization Policy Administrator (roles/orgpolicy.policyAdmin) at the Organization level. This role cannot be granted at the Folder or Project level.

Organization Policy roles

Title: Disable Cloud logging GCP

Body:
why i cannot disable the cloud logging

i tried using console and command but still not working

    gcloud beta resource-manager org-policies enable-enforce \
  constraints/gcp.disableCloudLogging --project x4-stag

and got this error

C:\Users\aji> gcloud beta resource-manager org-policies enable-enforce constraints/gcp.disableCloudLogging --project x4-stag
ERROR: (gcloud.beta.resource-manager.org-policies.enable-enforce) User [aji.fa@xxx.com] does not have permission to access project [x4-stag:setOrgPolicy] (or it may not exist): The caller does not have permission

for IAM role is using owner


问:
net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_name
I want to create CSV with Jasper Reports. There are many related questions, but nothing is working for me. Below is my bean class:

```<code>public class DataBean {

    public String First_name;
    public String Last_name;
    public String Designation;
    public String Department;

    public void setfirstName(String First_name) {
        this.First_name = First_name;
    }

    public String getfirstName() {
        return First_name;
    }

    public void setLastName(String Last_name) {
        this.Last_name = Last_name;
    }
    public String getlastName() {
        return Last_name;
   }
    public void setdesignation(String Designation) {
        this.Designation = Designation;
    }
    public String getdesignation() {
       return Designation;
    }
    public void setDepartment(String Department) {
        this.Department = Department;
    }
    public String getDepartment() {
        return Department;
    }
}
</code>```

Below is class which get data from database and generate CSV with Jasper Report:

```<code>import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.mysql.jdbc.PreparedStatement;

public class GetResult
{
    PreparedStatement pst=null;
    DBConnection dbcon=null;
    String First_name;
    String Last_name;
    String Designation;
    String Department;
    net.sf.jasperreports.engine.JasperReport report = null;
    JasperDesign design = null;
    JasperPrint print = null;
    InputStream input = null;
    public void result(){
        try{
            dbcon=new DBConnection();
            input = new FileInputStream(new File("C:/Users/adiuser1/report2.jrxml"));//report2.jasper
           design = JRXmlLoader.load(input);
            ArrayList<DataBean> al2=new ArrayList<DataBean>();
            Map<String, Object> parameters = new HashMap<String, Object>();
            pst = (PreparedStatement) dbcon.conn.prepareStatement("SELECT First_name, Last_name,     Designation, Department FROM emp_data");
            java.sql.ResultSet rs=pst.executeQuery();
            parameters.put("First_name","First_name");
            parameters.put("Last_name","Last_name");
           parameters.put("Designation","Designation");
           parameters.put("Department","Department");
           while(rs.next())
           {
                DataBean db=new DataBean();
                First_name = rs.getString("First_name");
                db.setfirstName(First_name);
                Last_name = rs.getString("Last_name");
                db.setLastName(Last_name);
                Designation = rs.getString("Designation");
                db.setdesignation(Designation);
                Department = rs.getString("Department");
                db.setDepartment(Department);
                al2.add(db);
            }
            System.out.println("size: "+parameters.size());
            System.out.println("size: "+al2.size());
            report = JasperCompileManager.compileReport(design);
            JRBeanCollectionDataSource masterDS = null;
            masterDS = new JRBeanCollectionDataSource(al2,false);
            print = JasperFillManager.fillReport(report, parameters, masterDS);
            JRCsvExporter csvExporter = new JRCsvExporter();
            csvExporter.setParameter(JRCsvExporterParameter.JASPER_PRINT, print);
            csvExporter.setParameter(JRCsvExporterParameter.OUTPUT_FILE_NAME, "X:/abc.csv");
            csvExporter.setParameter(JRCsvExporterParameter.CHARACTER_ENCODING, "ISO-8859-1");
            csvExporter.exportReport();
       }
        catch(JRException jrException)
        {
            System.out.print(jrException);
            jrException.printStackTrace();
        }
       catch(Exception e)
       {
           System.out.println(e);
      }
      }
   public static void main(String ...s)
   {
        GetResult gr=new GetResult();
       gr.result();
  }
}
</code>```

Below is my jrxml :

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isIgnorePagination="true" uuid="204c18b7-de66-4171-b8b8-82a20b837f28">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<subDataset name="sum" uuid="73ad5db5-041e-4e27-aed3-acaf6deec1b8">
    <queryString language="SQL">
        <![CDATA[]]>
    </queryString>
    <field name="First_name" class="java.lang.String"/>
    <field name="Last_name" class="java.lang.String"/>
    <field name="Designation" class="java.lang.String"/>
    <field name="Department" class="java.lang.String"/>
</subDataset>
<field name="First_name" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Last_name" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Designation" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Department" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
    <band splitType="Stretch"/>
</background>
<columnHeader>
    <band height="35" splitType="Stretch">
        <staticText>
            <reportElement uuid="2322e160-4c43-4027-af14-3c69a4d236ed" x="8" y="4" width="100" height="20" backcolor="#003333"/>
            <textElement/>
            <text><![CDATA[First_name]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="a5f84e13-ffee-491f-aa52-602b7b4e9c99" x="149" y="4" width="100" height="20" forecolor="#9999FF" backcolor="#00FFFF"/>
            <textElement/>
            <text><![CDATA[Last_name]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="cd216988-6061-4ef2-8f4d-18e31cabd9e1" x="299" y="4" width="100" height="20"/>
            <textElement/>
            <text><![CDATA[Designation]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="22587697-d3b8-4a55-b81d-d380a4e19a7a" x="433" y="4" width="100" height="20"/>
            <textElement/>
            <text><![CDATA[Department]]></text>
        </staticText>
    </band>
</columnHeader>
<detail>
    <band height="26" splitType="Stretch">
        <textField>
            <reportElement uuid="3f6821a6-3aa1-418f-aa68-25b844256276" key="First_name" x="8" y="0" width="100" height="21"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{First_name}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="e453bc45-a734-4db6-bba5-19a24252d3ba" x="149" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Last_name}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="5c604a9d-5dba-4b47-9e8c-41de0a29323c" x="299" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Designation}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="fa2e53f2-ff71-485d-b9ef-0259ace3eabb" x="433" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Department}]]></textFieldExpression>
        </textField>
    </band>
</detail>
<columnFooter>
    <band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
    <band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
    <band height="42" splitType="Stretch"/>
</summary>
</jasperReport>
</code>```

While i run GetResult.java it gives following error:

```<code>net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_namenet.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_name
at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:123)
at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getFieldValue(JRAbstractBeanDataSource.java:96)
at net.sf.jasperreports.engine.data.JRBeanCollectionDataSource.getFieldValue(JRBeanCollectionDataSource.java:100)
at net.sf.jasperreports.engine.fill.JRFillDataset.setOldValues(JRFillDataset.java:1331)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1232)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1208)
at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1577)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:149)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:932)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:864)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:88)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:653)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:969)
at GetResult.result(GetResult.java:78)
at GetResult.main(GetResult.java:99)
Caused by: java.lang.NoSuchMethodException: Unknown property 'First_name'
at org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(PropertyUtils.java:1175)
at org.apache.commons.beanutils.PropertyUtils.getNestedProperty(PropertyUtils.java:772)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:801)
at     net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:111)
... 14 more
</code>```

Please help me to resolve this problem.

答:
There are three things needs to be addressed:

Rename your fields to start with lowercase letters, and your getter and setter methods to correspond.

You should update the java build path to jdk 11 in Jasper property setting (Jasper studio -> Project -> Properties -> Java Build Path).

Make sure your implementation 'net.sf.jasperreports:jasperreports:6.2.0' version match the compilation version in Jasper property setting (Jasper studio -> Project -> Properties -> Jasper Studio -> Compatibility).

Body:
I want to create CSV with Jasper Reports. There are many related questions, but nothing is working for me. Below is my bean class:

public class DataBean {

    public String First_name;
    public String Last_name;
    public String Designation;
    public String Department;

    public void setfirstName(String First_name) {
        this.First_name = First_name;
    }

    public String getfirstName() {
        return First_name;
    }

    public void setLastName(String Last_name) {
        this.Last_name = Last_name;
    }
    public String getlastName() {
        return Last_name;
   }
    public void setdesignation(String Designation) {
        this.Designation = Designation;
    }
    public String getdesignation() {
       return Designation;
    }
    public void setDepartment(String Department) {
        this.Department = Department;
    }
    public String getDepartment() {
        return Department;
    }
}

Below is class which get data from database and generate CSV with Jasper Report:

import java.util.HashMap;
import java.util.Map;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.mysql.jdbc.PreparedStatement;

public class GetResult
{
    PreparedStatement pst=null;
    DBConnection dbcon=null;
    String First_name;
    String Last_name;
    String Designation;
    String Department;
    net.sf.jasperreports.engine.JasperReport report = null;
    JasperDesign design = null;
    JasperPrint print = null;
    InputStream input = null;
    public void result(){
        try{
            dbcon=new DBConnection();
            input = new FileInputStream(new File("C:/Users/adiuser1/report2.jrxml"));//report2.jasper
           design = JRXmlLoader.load(input);
            ArrayList<DataBean> al2=new ArrayList<DataBean>();
            Map<String, Object> parameters = new HashMap<String, Object>();
            pst = (PreparedStatement) dbcon.conn.prepareStatement("SELECT First_name, Last_name,     Designation, Department FROM emp_data");
            java.sql.ResultSet rs=pst.executeQuery();
            parameters.put("First_name","First_name");
            parameters.put("Last_name","Last_name");
           parameters.put("Designation","Designation");
           parameters.put("Department","Department");
           while(rs.next())
           {
                DataBean db=new DataBean();
                First_name = rs.getString("First_name");
                db.setfirstName(First_name);
                Last_name = rs.getString("Last_name");
                db.setLastName(Last_name);
                Designation = rs.getString("Designation");
                db.setdesignation(Designation);
                Department = rs.getString("Department");
                db.setDepartment(Department);
                al2.add(db);
            }
            System.out.println("size: "+parameters.size());
            System.out.println("size: "+al2.size());
            report = JasperCompileManager.compileReport(design);
            JRBeanCollectionDataSource masterDS = null;
            masterDS = new JRBeanCollectionDataSource(al2,false);
            print = JasperFillManager.fillReport(report, parameters, masterDS);
            JRCsvExporter csvExporter = new JRCsvExporter();
            csvExporter.setParameter(JRCsvExporterParameter.JASPER_PRINT, print);
            csvExporter.setParameter(JRCsvExporterParameter.OUTPUT_FILE_NAME, "X:/abc.csv");
            csvExporter.setParameter(JRCsvExporterParameter.CHARACTER_ENCODING, "ISO-8859-1");
            csvExporter.exportReport();
       }
        catch(JRException jrException)
        {
            System.out.print(jrException);
            jrException.printStackTrace();
        }
       catch(Exception e)
       {
           System.out.println(e);
      }
      }
   public static void main(String ...s)
   {
        GetResult gr=new GetResult();
       gr.result();
  }
}

Below is my jrxml :

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isIgnorePagination="true" uuid="204c18b7-de66-4171-b8b8-82a20b837f28">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<subDataset name="sum" uuid="73ad5db5-041e-4e27-aed3-acaf6deec1b8">
    <queryString language="SQL">
        <![CDATA[]]>
    </queryString>
    <field name="First_name" class="java.lang.String"/>
    <field name="Last_name" class="java.lang.String"/>
    <field name="Designation" class="java.lang.String"/>
    <field name="Department" class="java.lang.String"/>
</subDataset>
<field name="First_name" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Last_name" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Designation" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="Department" class="java.lang.String">
    <fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
    <band splitType="Stretch"/>
</background>
<columnHeader>
    <band height="35" splitType="Stretch">
        <staticText>
            <reportElement uuid="2322e160-4c43-4027-af14-3c69a4d236ed" x="8" y="4" width="100" height="20" backcolor="#003333"/>
            <textElement/>
            <text><![CDATA[First_name]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="a5f84e13-ffee-491f-aa52-602b7b4e9c99" x="149" y="4" width="100" height="20" forecolor="#9999FF" backcolor="#00FFFF"/>
            <textElement/>
            <text><![CDATA[Last_name]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="cd216988-6061-4ef2-8f4d-18e31cabd9e1" x="299" y="4" width="100" height="20"/>
            <textElement/>
            <text><![CDATA[Designation]]></text>
        </staticText>
        <staticText>
            <reportElement uuid="22587697-d3b8-4a55-b81d-d380a4e19a7a" x="433" y="4" width="100" height="20"/>
            <textElement/>
            <text><![CDATA[Department]]></text>
        </staticText>
    </band>
</columnHeader>
<detail>
    <band height="26" splitType="Stretch">
        <textField>
            <reportElement uuid="3f6821a6-3aa1-418f-aa68-25b844256276" key="First_name" x="8" y="0" width="100" height="21"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{First_name}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="e453bc45-a734-4db6-bba5-19a24252d3ba" x="149" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Last_name}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="5c604a9d-5dba-4b47-9e8c-41de0a29323c" x="299" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Designation}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement uuid="fa2e53f2-ff71-485d-b9ef-0259ace3eabb" x="433" y="0" width="100" height="20"/>
            <textElement/>
            <textFieldExpression><![CDATA[$F{Department}]]></textFieldExpression>
        </textField>
    </band>
</detail>
<columnFooter>
    <band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
    <band height="54" splitType="Stretch"/>
</pageFooter>

    <band height="42" splitType="Stretch"/>

</jasperReport>

While i run GetResult.java it gives following error:

net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_namenet.sf.jasperreports.engine.JRException: Error retrieving field value from bean : First_name
at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:123)
at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getFieldValue(JRAbstractBeanDataSource.java:96)
at net.sf.jasperreports.engine.data.JRBeanCollectionDataSource.getFieldValue(JRBeanCollectionDataSource.java:100)
at net.sf.jasperreports.engine.fill.JRFillDataset.setOldValues(JRFillDataset.java:1331)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1232)
at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:1208)
at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1577)
at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:149)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:932)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:864)
at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:88)
at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:653)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:969)
at GetResult.result(GetResult.java:78)
at GetResult.main(GetResult.java:99)
Caused by: java.lang.NoSuchMethodException: Unknown property 'First_name'
at org.apache.commons.beanutils.PropertyUtils.getSimpleProperty(PropertyUtils.java:1175)
at org.apache.commons.beanutils.PropertyUtils.getNestedProperty(PropertyUtils.java:772)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:801)
at     net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:111)
... 14 more

Please help me to resolve this problem.


问:
Creating BigQuery table column with BIGNUMERIC data type using Java
When creating BigQuery tables using the Java com.google.cloud:google-cloud-bigquery library, I don't see the BIGNUMERIC column data-type in the StandardSQLTypeName enumerations. I see NUMERIC but not BIGNUMERIC. How would I create a table with a BIGNUMERIC column programmatically? Thanks!

```<code>  Field f1 = Field.newBuilder("first_name", StandardSQLTypeName.STRING).build();
  Field f2 = Field.newBuilder("score", StandardSQLTypeName.NUMERIC).build();
  Schema schema = Schema.of(Arrays.asList(f1,f2));

  TableId tableId = TableId.of("my_data_set", "tbl_people"));
  TableDefinition tableDefinition = StandardTableDefinition.of(schema);
  TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

  bigQuery.create(tableInfo);
</code>```

答:
If you're using versions 1.124.7 and below, the enum for StandardSQLTypeName.BIGNUMERIC is not yet present. I suggest you use the latest version (1.125.0 and up).

You can refer to this doc for a detailed guide on how to create and use BigQuery table.

Body:
When creating BigQuery tables using the Java com.google.cloud:google-cloud-bigquery library, I don't see the BIGNUMERIC column data-type in the StandardSQLTypeName enumerations. I see NUMERIC but not BIGNUMERIC. How would I create a table with a BIGNUMERIC column programmatically? Thanks!

  Field f1 = Field.newBuilder("first_name", StandardSQLTypeName.STRING).build();
  Field f2 = Field.newBuilder("score", StandardSQLTypeName.NUMERIC).build();
  Schema schema = Schema.of(Arrays.asList(f1,f2));

  TableId tableId = TableId.of("my_data_set", "tbl_people"));
  TableDefinition tableDefinition = StandardTableDefinition.of(schema);
  TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();

  bigQuery.create(tableInfo);


问:
Calculate Percentage Increase from Array - MongoDB
My db looks like this: (Sanitized Version)

```<code>[{
    "_id": 1,
    "Type": "Car",
    "Total": 82.03,
    "DateTime": "20210713T0834"
}, {
    "_id": 2,
    "Type": "Car",
    "Total": 20.26,
    "DateTime": "20210827T0834"
}, {
    "_id": 3,
    "Type": "Air",
    "Total": 50.43,
    "DateTime": "20210913T0834"
}, {
    "_id": 4,
    "Type": "Car",
    "Total": 42.03,
    "DateTime": "20210813T0834"
}]
</code>```

I need to get the percentage increase each Type per month.

I tried to do it as follows:

Filter data in db for 2 consecutive months

Group the data by month

Group the data by type and outputs it to an array

Tries to compute the percentage increase from the array. This is the part I am stuck.

I feel that there is another proper way to do it and that I am doing too much work for it to work. Can anyone guide me?

Thank you.

The code for the above steps (Step 1 - 3) can be found here:

```<code>{"$match": {"DateTime": {"$gte": "20210701", "$lte": "20210901"}}},
{"$addFields": {"month": {"$substr": ["$DateTime", 4, 2]}}},
#Split by month
{"$group": {"_id":  {"month" : "$month", "type" : "$Type"}, "amount": {"$sum": "$Total"}}},
#Split further by types and create array
{"$group":{"_id": "$_id.type", "totalUSDPerTypePerMonth" : { "$push" : {"month":"$_id.month","type" : "$_id.type", "total" : "$amount"}}}},
</code>```

I am getting this output so far:

How to proceed any further?

Thank you.

答:
$setWindowFields

```<code>db.collection.aggregate([
  {
    $match: {}
  },
  {
    $setWindowFields: {
      partitionBy: "$Type",
      sortBy: { DateTime: 1 },
      output: {
        sumOfThePreviousTotal: {
          $sum: "$Total",
          window: { documents: [ -1, 0 ] }
        },
        previousDateTime: {
          $push: "$DateTime",
          window: { documents: [ -1, 0 ] }
        }
      }
    }
  },
  {
    $set: {
      "previousDateTime": { "$toDate": { "$first": "$previousDateTime" } },
      "DateTime": { "$toDate": "$DateTime" },
      "perviousTotal": { "$subtract": [ "$sumOfThePreviousTotal", "$Total" ] }
    }
  },
  {
    $set: {
      "dateDiff": {
        "$dateDiff": {
          startDate: "$previousDateTime",
          endDate: "$DateTime",
          unit: "day"
        }
      }
    }
  },
  {
    $set: {
      "percentageIncreasePerDay": {
        "$cond": {
          "if": { "$eq": [ "$dateDiff", 0 ] },
          "then": 0,
          "else": { "$divide": [ { "$subtract": [ "$Total", "$perviousTotal" ] }, "$dateDiff" ] }
        }
      }
    }
  }
])
</code>```

mongoplayground

Body:
My db looks like this: (Sanitized Version)

[{
    "_id": 1,
    "Type": "Car",
    "Total": 82.03,
    "DateTime": "20210713T0834"
}, {
    "_id": 2,
    "Type": "Car",
    "Total": 20.26,
    "DateTime": "20210827T0834"
}, {
    "_id": 3,
    "Type": "Air",
    "Total": 50.43,
    "DateTime": "20210913T0834"
}, {
    "_id": 4,
    "Type": "Car",
    "Total": 42.03,
    "DateTime": "20210813T0834"
}]

I need to get the percentage increase each Type per month.

I tried to do it as follows:

Filter data in db for 2 consecutive months

Group the data by month

Group the data by type and outputs it to an array

Tries to compute the percentage increase from the array. This is the part I am stuck.

I feel that there is another proper way to do it and that I am doing too much work for it to work. Can anyone guide me?

Thank you.

The code for the above steps (Step 1 - 3) can be found here:

{"$match": {"DateTime": {"$gte": "20210701", "$lte": "20210901"}}},
{"$addFields": {"month": {"$substr": ["$DateTime", 4, 2]}}},
#Split by month
{"$group": {"_id":  {"month" : "$month", "type" : "$Type"}, "amount": {"$sum": "$Total"}}},
#Split further by types and create array
{"$group":{"_id": "$_id.type", "totalUSDPerTypePerMonth" : { "$push" : {"month":"$_id.month","type" : "$_id.type", "total" : "$amount"}}}},

I am getting this output so far:

How to proceed any further?

Thank you.

Body:
$setWindowFields

db.collection.aggregate([
  {
    $match: {}
  },
  {
    $setWindowFields: {
      partitionBy: "$Type",
      sortBy: { DateTime: 1 },
      output: {
        sumOfThePreviousTotal: {
          $sum: "$Total",
          window: { documents: [ -1, 0 ] }
        },
        previousDateTime: {
          $push: "$DateTime",
          window: { documents: [ -1, 0 ] }
        }
      }
    }
  },
  {
    $set: {
      "previousDateTime": { "$toDate": { "$first": "$previousDateTime" } },
      "DateTime": { "$toDate": "$DateTime" },
      "perviousTotal": { "$subtract": [ "$sumOfThePreviousTotal", "$Total" ] }
    }
  },
  {
    $set: {
      "dateDiff": {
        "$dateDiff": {
          startDate: "$previousDateTime",
          endDate: "$DateTime",
          unit: "day"
        }
      }
    }
  },
  {
    $set: {
      "percentageIncreasePerDay": {
        "$cond": {
          "if": { "$eq": [ "$dateDiff", 0 ] },
          "then": 0,
          "else": { "$divide": [ { "$subtract": [ "$Total", "$perviousTotal" ] }, "$dateDiff" ] }
        }
      }
    }
  }
])

mongoplayground