问:
Specific field in filterset_class
I have Student Model and I need to filter students who don't have personal trainers using filterset_class

```<code>models.py

class Student(models.Model):
    personal_trainer = models.ForeignKey(PersonalTrainer, on_delete=models.CASCADE, blank=True, null=True)

views.py

class StudentsView(ReadOnlyModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = StudentsSerializer
    lookup_field = "pk"
    pagination_class = None
</code>```

and here is the views.py

```<code>class StudentFilter(rest_framework.FilterSet):
    has_personal_trainer = rest_framework.BooleanFilter(field_name="personal_trainer", lookup_expr="isnull")

    class Meta:
        model = Student
        fields = ("has_personal_trainer")

class StudentsView(ReadOnlyModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = StudentsSerializer
    lookup_field = "pk"
    pagination_class = None
    filter_backends = (rest_framework.DjangoFilterBackend,)
    filterset_class = StudentFilter
</code>```

when I use the request with api/students?care_navigator=false it gives me the following error massege

```<code>`django.core.exceptions.FieldError: Cannot resolve keyword 'has_personal_trainer' into field. Choices are: personal_trainer, personal_trainer_id`
</code>```

etc...

答:
You can use FilterSet class.

from django_filters import rest_framework

class StudentFilter(rest_framework.FilterSet):
    has_personal_trainer = rest_framework.BooleanFilter(field_name="personal_trainer", lookup_expr="isnull")

    class Meta:
        model = Student
        fields = ("has_personal_trainer",)

```
<p>In views.py</p>
<pre class="lang-py prettyprint-override"><code>from django_filters import rest_framework

class StudentsView(ReadOnlyModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = StudentsSerializer
    lookup_field = "pk"
    pagination_class = None
    filter_backends = (rest_framework.DjangoFilterBackend,)
    filterset_class = StudentFilter

</code>```

Usage
api/students?has_personal_trainer=true or api/students?has_personal_trainer=false

Title: Specific field in filterset_class

Body:
I have Student Model and I need to filter students who don't have personal trainers using filterset_class

models.py

class Student(models.Model):
    personal_trainer = models.ForeignKey(PersonalTrainer, on_delete=models.CASCADE, blank=True, null=True)

views.py

class StudentsView(ReadOnlyModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = StudentsSerializer
    lookup_field = "pk"
    pagination_class = None

and here is the views.py

class StudentFilter(rest_framework.FilterSet):
    has_personal_trainer = rest_framework.BooleanFilter(field_name="personal_trainer", lookup_expr="isnull")

    class Meta:
        model = Student
        fields = ("has_personal_trainer")

class StudentsView(ReadOnlyModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = StudentsSerializer
    lookup_field = "pk"
    pagination_class = None
    filter_backends = (rest_framework.DjangoFilterBackend,)
    filterset_class = StudentFilter

when I use the request with api/students?care_navigator=false it gives me the following error massege

`django.core.exceptions.FieldError: Cannot resolve keyword 'has_personal_trainer' into field. Choices are: personal_trainer, personal_trainer_id`

etc...

Body:
You can use FilterSet class.

from django_filters import rest_framework

class StudentFilter(rest_framework.FilterSet):
    has_personal_trainer = rest_framework.BooleanFilter(field_name="personal_trainer", lookup_expr="isnull")

    class Meta:
        model = Student
        fields = ("has_personal_trainer",)

In views.py

from django_filters import rest_framework

class StudentsView(ReadOnlyModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = StudentsSerializer
    lookup_field = "pk"
    pagination_class = None
    filter_backends = (rest_framework.DjangoFilterBackend,)
    filterset_class = StudentFilter

Usage
api/students?has_personal_trainer=true or api/students?has_personal_trainer=false


来源: stackexchange

问:
Why doesn't toolstriplabel's backcolor property change during design time or run time?
I need to have a toolstrip label and its back color changed during runtime, but no matter what I do. It just won't change its backcolor, even though they give option to change its backcolor. Why is that and how do you get its backcolor property to change during runtime or design time?

Thanks in advance,

答:
Good idea, @Plater. Thanks.
I tried to make your code even simpler and it works for me :-)</p>
```<code>ToolStripLabel.BackgroundImageLayout = ImageLayout.Stretch
ToolStripLabel.BackgroundImage = New Bitmap(1, 1)
Dim g As Graphics = Graphics.FromImage(ToolStripLabel.BackgroundImage)
g.Clear(Color.PaleGreen)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Good idea, @Plater. Thanks.
I tried to make your code even simpler and it works for me :-)

ToolStripLabel.BackgroundImageLayout = ImageLayout.Stretch
ToolStripLabel.BackgroundImage = New Bitmap(1, 1)
Dim g As Graphics = Graphics.FromImage(ToolStripLabel.BackgroundImage)
g.Clear(Color.PaleGreen)

ContentLicense: CC BY-SA 4.0


问:
Get Laravel collection's item using collection value
Suppose we got a collection from the database like this:

```<code>$projects = Projects::all();
</code>```

Now, for example, I want to get the specific project using the specified column's value. For example, suppose any project has a unique pr_code, Now I want to get an item of collection that pr_code is 1234.

Note = I Know using Projects::where('pr_code', 1234)->first() But I didn't want this. I want use inside collection

How I could do that?

答: Collections also have where and first (and whereFirst ) functions. So you just need to change the order of functions in your chain: Projects::all()->firstWhere('pr_code', 1234)

Body:
Suppose we got a collection from the database like this:

$projects = Projects::all();

Now, for example, I want to get the specific project using the specified column's value. For example, suppose any project has a unique pr_code, Now I want to get an item of collection that pr_code is 1234.

Note = I Know using Projects::where('pr_code', 1234)->first() But I didn't want this. I want use inside collection

How I could do that?


问:
How to change selected react-select input color?
Using react-select (React.js) I notice that when the select field is clicked on it shows a blue-ish color.

I say blue-ish because it seems to let through some of the yellow border I gave to it too, so it may look green.

How do change this color?

I am assuming that I need the right css selector, and that I need the 'control' style key. Is that correct?

I have already managed to style the general border color, and the border color on hover:

```<code>const SelectStyle = {
  control: styles => ({
    ...styles,
    border: `1px solid ${Colors.sec6}`,
    "&:hover": {
      borderColor: "red"
    }
  }),
  ...
};
</code>```

And I thought I could use :focus, or maybe :active to change the color when the color, but that doesn't seem to work. I have tried the following, to no avail:

```<code>"&:focus": {
  borderColor: "pink"
},
"&:active": {
  borderColor: "orange"
}
</code>```

I have checked the list of css selectors at W3schools, but I don't see which of those could be the one that I need.

答:
The answer by @Rik Schoonbeek is correct on how to remove the blue border.

To further change the color, we have to set boxShadow: "none" first for the control divisor.

Then, add border color to focus-within subclass:

```<code>    boxShadow: "none",
    "&:focus-within": {
      borderColor: "#f7c6b9",
      boxShadow: "0 0 0.2rem rgba(233, 105, 71, 0.25)",
    }
</code>```

This way, the behavior will match that of react-bootstrap text input.

We can add either using the customStyle in js or add a wrapper divisor with a specific className and add it in scss using class_end_with_selector:

```<code>.myReactSelectClass {
   [class$='-control'] {
      ...
   }
}
</code>```

Update: There is a react-select open bug when building prod DoM such that the style is not applied in prod:  https://github.com/JedWatson/react-select/issues/3309

So to avoid it, add a classNamePrefix="react-select" (could be any preferred string) to enforce the classNames in prod DoM
And the using the following classNames (use react-select Prefix as an example)

```<code>  .react-select__value-container {...}
  .react-select__indicators {...}
  .react-select__input {...}
  .react-select__control {...}
</code>```

Body:
Using react-select (React.js) I notice that when the select field is clicked on it shows a blue-ish color.

I say blue-ish because it seems to let through some of the yellow border I gave to it too, so it may look green.

How do change this color?

I am assuming that I need the right css selector, and that I need the 'control' style key. Is that correct?

I have already managed to style the general border color, and the border color on hover:

const SelectStyle = {
  control: styles => ({
    ...styles,
    border: `1px solid ${Colors.sec6}`,
    "&:hover": {
      borderColor: "red"
    }
  }),
  ...
};

And I thought I could use :focus, or maybe :active to change the color when the color, but that doesn't seem to work. I have tried the following, to no avail:

"&:focus": {
  borderColor: "pink"
},
"&:active": {
  borderColor: "orange"
}

I have checked the list of css selectors at W3schools, but I don't see which of those could be the one that I need.

Body:
The answer by @Rik Schoonbeek is correct on how to remove the blue border.

To further change the color, we have to set boxShadow: "none" first for the control divisor.

Then, add border color to focus-within subclass:

    boxShadow: "none",
    "&:focus-within": {
      borderColor: "#f7c6b9",
      boxShadow: "0 0 0.2rem rgba(233, 105, 71, 0.25)",
    }

This way, the behavior will match that of react-bootstrap text input.

We can add either using the customStyle in js or add a wrapper divisor with a specific className and add it in scss using class_end_with_selector:

.myReactSelectClass {
   [class$='-control'] {
      ...
   }
}

Update: There is a react-select open bug when building prod DoM such that the style is not applied in prod:  https://github.com/JedWatson/react-select/issues/3309

So to avoid it, add a classNamePrefix="react-select" (could be any preferred string) to enforce the classNames in prod DoM
And the using the following classNames (use react-select Prefix as an example)

  .react-select__value-container {...}
  .react-select__indicators {...}
  .react-select__input {...}
  .react-select__control {...}


问:
How to add `overflow` to SelectableText in Flutter?
There is SelectableText widget that allows you to make text selectable. But it misses the overflow parameter, which is required...

Is there any workaround, which can make it work? Or a similar solution?
Thanks!

答:
Just experienced this.
The problem is overflow hasn't been made the top level parameter in case of SelectableText as with Text in Flutter which suggests that it must be there, just not as the top level parameter which is true as it is in TextStyle.

Hence, to use overflow in SelectableText, change

```<code>SelectableText(
  text,
  overflow: TextOverflow.ellipsis
)
</code>```

to

```<code>SelectableText(
  text,
  style: TextStyle(
    overflow: TextOverflow.ellipsis,
  ),
)
</code>```

Body:
Just experienced this.
The problem is overflow hasn't been made the top level parameter in case of SelectableText as with Text in Flutter which suggests that it must be there, just not as the top level parameter which is true as it is in TextStyle.

Hence, to use overflow in SelectableText, change

SelectableText(
  text,
  overflow: TextOverflow.ellipsis
)

to

SelectableText(
  text,
  style: TextStyle(
    overflow: TextOverflow.ellipsis,
  ),
)


问:
How to create responsive Text widget in Flutter?
I'm facing a problem with responsive texts. In my app are different text font sizes and I need to do them responsive for different screen sizes (only phones and device orientation portrait). I also added textScaleFactor: 1.0 to my MaterialApp like this:

```<code>    builder: (context, widget) {
      return MediaQuery(
        child: widget,
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      );
    },
</code>```

but it does not help much.
I tried to also calculate the font size with MediaQuery.of(context).size.width, but I think it dangerous and wrong. I want it to be as close as possible to the design that was given to me, but I started to lose it on these steps.

How can I solve this?

答:
1. First Solution

You can use auto_size_text package.

2. Second Solution

A work around without the package and if you prefer using a custom theme:

get the width

```<code>    @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
     return Container(...
</code>```

create your custom ThemeData i.e for light and dark in you theme_provider class

```<code>static ThemeData dark() {
return ThemeData(
  textTheme: const TextTheme(
   bodyText2:
        TextStyle(color: Colors.white70, fontWeight: FontWeight.w300)...
</code>```

Finally, edit your Text widget with different font sizes for different screens. You can use screen height as well...

```<code>Text(
    widget.featuredModel.eventTitle,
    style: Theme.of(context).textTheme.bodyText2!
   .copyWith(  fontSize: width >= 1201
                          ? 22
                          : width >= 601
                              ? 20
                              : width >= 400
                                  ? 16
                                  : 14),
                ),
</code>```

Body:
I'm facing a problem with responsive texts. In my app are different text font sizes and I need to do them responsive for different screen sizes (only phones and device orientation portrait). I also added textScaleFactor: 1.0 to my MaterialApp like this:

    builder: (context, widget) {
      return MediaQuery(
        child: widget,
        data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      );
    },

but it does not help much.
I tried to also calculate the font size with MediaQuery.of(context).size.width, but I think it dangerous and wrong. I want it to be as close as possible to the design that was given to me, but I started to lose it on these steps.

How can I solve this?

Body:
1. First Solution

You can use auto_size_text package.

2. Second Solution

A work around without the package and if you prefer using a custom theme:

get the width

    @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
     return Container(...

create your custom ThemeData i.e for light and dark in you theme_provider class

static ThemeData dark() {
return ThemeData(
  textTheme: const TextTheme(
   bodyText2:
        TextStyle(color: Colors.white70, fontWeight: FontWeight.w300)...

Finally, edit your Text widget with different font sizes for different screens. You can use screen height as well...

Text(
    widget.featuredModel.eventTitle,
    style: Theme.of(context).textTheme.bodyText2!
   .copyWith(  fontSize: width >= 1201
                          ? 22
                          : width >= 601
                              ? 20
                              : width >= 400
                                  ? 16
                                  : 14),
                ),


问:
Is it possible to manually refresh the contents of a .per file?
I have custom .per files used to provide the user a way to interact with an application from Lauterbach. However, once in a while the values of some variables do not update and the only way to get it back to regular functioning is to close the per file and re-open it.

Is there a command that can be called to "self-refresh" the .per file?

答:
Unless you have limited the updating of windows showing memory (e.g. with command MAP.UpdateOnce) all values should be updated periodically (according to SETUP.UpdateRATE).

So I think, there should be no need for a refresh command. Maybe you should contact Lauterbach support and they can help you to find the source, why some values are not updated..

Anyway, the command to force an update of all windows showing memory is Data.UPDATE

If Data.UPDATE is not doing the trick, you could also add a button to your   PER window, which allows you to easily re-open the window. To do that, use the following PRACTICE script (cmm-script):

```<code>MENU.ReProgram
(
    ADD
    BUTTONS "per.-W"
    (
        MENUITEM "[:refresh]refresh"
        (
            PRIVATE &cmd &left &up
            &cmd=WINdow.COMMAND(WinTOP)
            &left=WINdow.POSition(WinTOP,LEFT)
            &up=WINdow.POSition(WinTOP,UP)
            WinCLEAR WinTOP
            WinPOS &left &up
            &cmd
        )
    )
)
</code>```

You need to execute this code before opening the PER window. (I suggest to add this code to the file C:\t32\system-settings.cmm to get it executed on every start of PowerView.)

When opening a new PER window after executing the script, your PER window will have this button:

When clicking the button it will re-open your PER window.

You can add a button for Data.UPDATE to your PER windows in the same way.

Body:
Unless you have limited the updating of windows showing memory (e.g. with command MAP.UpdateOnce) all values should be updated periodically (according to SETUP.UpdateRATE).

So I think, there should be no need for a refresh command. Maybe you should contact Lauterbach support and they can help you to find the source, why some values are not updated..

Anyway, the command to force an update of all windows showing memory is Data.UPDATE

If Data.UPDATE is not doing the trick, you could also add a button to your   PER window, which allows you to easily re-open the window. To do that, use the following PRACTICE script (cmm-script):

MENU.ReProgram
(
    ADD
    BUTTONS "per.-W"
    (
        MENUITEM "[:refresh]refresh"
        (
            PRIVATE &cmd &left &up
            &cmd=WINdow.COMMAND(WinTOP)
            &left=WINdow.POSition(WinTOP,LEFT)
            &up=WINdow.POSition(WinTOP,UP)
            WinCLEAR WinTOP
            WinPOS &left &up
            &cmd
        )
    )
)

You need to execute this code before opening the PER window. (I suggest to add this code to the file C:\t32\system-settings.cmm to get it executed on every start of PowerView.)

When opening a new PER window after executing the script, your PER window will have this button:

When clicking the button it will re-open your PER window.

You can add a button for Data.UPDATE to your PER windows in the same way.


问:
Divide timespan in JavaScript
I have to recreate some logic from Kusto query language in JS and I'm struggling with duration division. How can I get quotient from two durations, like this :

One can divide two timespan values to get their quotient. For example, 1d / 5h gives 4.8. This gives one the ability to express any timespan value as a multiple of another timespan value. For example, to express an hour in seconds, simply divide 1h by 1s: 1h / 1s (with the obvious result, 3600).

(taken from https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/datetime-timespan-arithmetic)

I'm using date-fns, but I'm flexible  with libraries.

答:
You can simply define constants. For example, if the smallest unit you are going to use is 1 seconds, then you can put:

```<code>const
  S = 1,
  M = 60,
  H = M * 60,
  D = H * 24,
  W = D * 7;
</code>```

Now terms like 1s cannot magically become a valid syntax in JavaScript, but expressions like (2 * D) / (10 * H) can work just fine.

(edited the answer to use uppercase for constants as it's a common convention)

Title: Divide timespan in JavaScript

Body:
You can simply define constants. For example, if the smallest unit you are going to use is 1 seconds, then you can put:

const
  S = 1,
  M = 60,
  H = M * 60,
  D = H * 24,
  W = D * 7;

Now terms like 1s cannot magically become a valid syntax in JavaScript, but expressions like (2 * D) / (10 * H) can work just fine.

(edited the answer to use uppercase for constants as it's a common convention)


问:
read specific files names in adf pipeline
I have got requirement saying, blob storage has multiple files with names file_1.csv,file_2.csv,file_3.csv,file_4.csv,file_5.csv,file_6.csv,file_7.csv. From these i have to read only filenames from 5 to 7.

how we can achieve this in ADF/Synapse pipeline.

答:
I have repro’d in my lab, please see the below repro steps.

ADF:

Using the Get Metadata activity, get a list of all files.

(Parameterize the source file name in the source dataset to pass ‘*’ in the dataset parameters to get all files.)

Get Metadata output:

Pass the Get Metadata output child items to ForEach activity.

@activity('Get Metadata1').output.childItems

Add If Condition activity inside ForEach and add the true case expression to copy only required files to sink.

@and(greater(int(substring(item().name,4,1)),4),lessOrEquals(int(substring(item().name,4,1)),7))

When the If Condition is True, add copy data activity to copy the current item (file) to sink.

Source:

Sink:

Output:


问:
parent & child with position fixed, parent overflow:hidden bug
I don't know if there is an issue, but I was wondering why the overflow:hidden does not function on fixed parent/children element.

Here's an example:

CSS and HTML:

.parent{
  position:fixed;
  overflow:hidden;
  width:300px;
  height:300px;
  background:#555;
}
.children{
  position:fixed;
  top:200px;
  left:200px;
  width:150px;
  height:150px;
  background:#333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="children">
  </div>
</div></code>```

Live demo: jsFiddle

答:
This isn't the exact answer but a handy trick to work around the issue if your use case makes sense. The accepted answer is correct.

A simple hack is to use z-index on the parent relative container in conjunction with another hiding element below and/or above.

example

body {
  margin: 0px;
  padding: 0px;
}

.parent {
  background-color: blue;
  height: 500px;
  padding: 30px;
  position: relative;
  text-align: center;
  z-index: 1;
}

.child {
  padding: 10px;
  position: fixed;
  top: 100px;
}

.sibling {
  background: white;
  min-height: 500px;
  padding: 30px;
  position: relative;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <button class="child">
    Click Me
  </button>
</div>

<div class="sibling">
  <h1>Some Header</h1>

  <p>
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
    sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
    incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate
    velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
  </p>
</div></code>```

Body:
I don't know if there is an issue, but I was wondering why the overflow:hidden does not function on fixed parent/children element.

Here's an example:

CSS and HTML:

.parent{
  position:fixed;
  overflow:hidden;
  width:300px;
  height:300px;
  background:#555;
}
.children{
  position:fixed;
  top:200px;
  left:200px;
  width:150px;
  height:150px;
  background:#333;
}

Live demo: jsFiddle

Body:
This isn't the exact answer but a handy trick to work around the issue if your use case makes sense. The accepted answer is correct.

A simple hack is to use z-index on the parent relative container in conjunction with another hiding element below and/or above.

example

body {
  margin: 0px;
  padding: 0px;
}

.parent {
  background-color: blue;
  height: 500px;
  padding: 30px;
  position: relative;
  text-align: center;
  z-index: 1;
}

.child {
  padding: 10px;
  position: fixed;
  top: 100px;
}

.sibling {
  background: white;
  min-height: 500px;
  padding: 30px;
  position: relative;
  z-index: 2;
}

<div class="parent">
  <button class="child">
    Click Me
  </button>
</div>

<div class="sibling">
  <h1>Some Header</h1>

  <p>
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas
    sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora
    incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate
    velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
  </p>
</div>


问:
Null pointer exeception in ListAdapter
I want to display Data in List View but I got Error Null Pointer Exception run time in line

```<code>fList.setAdapter(la);
</code>```

My code is here List is complete printing in Log
Thanks

```<code>public class Forfattere extends Activity {
/** Called when the activity is first created. */
ArrayList<String> aList = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.forfattere);
    ListView fList = (ListView)findViewById(R.id.Author_list);
    ArrayList<String> a = DBlistbookfestival.getAuthorName();
    for(int i=0;i<a.size();i++){
        aList.add(a.get(i));
        Log.v("all_data",a.get(i));
    }
    ListAdapter1 la = new ListAdapter1(this, R.id.Author_list, aList);
    fList.setAdapter(la);
 }

private class ListAdapter1 extends ArrayAdapter<String> {  // --CloneChangeRequired
    private ArrayList<String> mList;  // --CloneChangeRequired
    public ListAdapter1(Context context, int textViewResourceId,ArrayList<String> list) { // --CloneChangeRequired
        super(context, textViewResourceId, list);
        this.mList = list;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        View view = convertView;
        try{
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.custom_radio, null);     // --CloneChangeRequired(list_item)
        }
        final String listItem = mList.get(position);    // --CloneChangeRequired
        if (listItem != null) {
            ( (TextView) view.findViewById(R.id.textView111) ).setText(listItem);
        }}catch(Exception e){

        }
        return view;
    }
}
</code>```

}

答:
Your problem come from this line :

```<code>ListView fList = (ListView)findViewById(R.id.Author_list);
</code>```

The findviewbyid return null, this means that there is no element in your layout R.layout.forfattere with the id R.id.Author_list.
Look in your layout to see if the listview has this Id.

Title: Null pointer exeception in ListAdapter

Body:
I want to display Data in List View but I got Error Null Pointer Exception run time in line

fList.setAdapter(la);

My code is here List is complete printing in Log
Thanks

public class Forfattere extends Activity {
/** Called when the activity is first created. */
ArrayList<String> aList = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.forfattere);
    ListView fList = (ListView)findViewById(R.id.Author_list);
    ArrayList<String> a = DBlistbookfestival.getAuthorName();
    for(int i=0;i<a.size();i++){
        aList.add(a.get(i));
        Log.v("all_data",a.get(i));
    }
    ListAdapter1 la = new ListAdapter1(this, R.id.Author_list, aList);
    fList.setAdapter(la);
 }

private class ListAdapter1 extends ArrayAdapter<String> {  // --CloneChangeRequired
    private ArrayList<String> mList;  // --CloneChangeRequired
    public ListAdapter1(Context context, int textViewResourceId,ArrayList<String> list) { // --CloneChangeRequired
        super(context, textViewResourceId, list);
        this.mList = list;
    }

    public View getView(int position, View convertView, ViewGroup parent){
        View view = convertView;
        try{
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R.layout.custom_radio, null);     // --CloneChangeRequired(list_item)
        }
        final String listItem = mList.get(position);    // --CloneChangeRequired
        if (listItem != null) {
            ( (TextView) view.findViewById(R.id.textView111) ).setText(listItem);
        }}catch(Exception e){

        }
        return view;
    }
}

}

Body:
Your problem come from this line :

ListView fList = (ListView)findViewById(R.id.Author_list);

The findviewbyid return null, this means that there is no element in your layout R.layout.forfattere with the id R.id.Author_list.
Look in your layout to see if the listview has this Id.


问:
List categories of a Blog with Angular ngFor directive
I just want to list the categories of a Blog in Angular. When I use ngFor, It shows a list of the categories but is bringing in some repeated ones, like if it were bringing all the blogs and not just the categories that some of them share. Hope I was clear on this question.

This is my html:

```<code><aside class="categories">
     <h2 class="aside-title">Categorias</h2>

     <ul *ngFor="let data of datas; index as i">
        <li class="nav-elipse-blue"><a [routerLink]="['/pagina',datas.category]" title="Blog CSS
        articles">{{ data.category.name }}</a></li>
     </ul>

</aside>

</code>```

答:
It looks like you need to remove duplicates from your array.

Based on this answer, you can do this:

```<code>const uniqueCategorias = datas.filter((value, index) => {
  const _value = JSON.stringify(value);
  return index === obj.arr.findIndex(obj => {
    return JSON.stringify(obj) === _value;
  });
});
</code>```

and use it:

```<code> <ul *ngFor="let data of uniqueCategorias; index as i">
    <li class="nav-elipse-blue"><a [routerLink]="['/pagina',datas.category]" title="Blog CSS
    articles">{{ data.category.name }}</a></li>
 </ul>
</code>```

and in TypeScript file:

```<code>uniqueCategorias;

getUniqueCategorias(){
    uniqueCategorias = datas.filter((value, index) => {
        const _value = JSON.stringify(value);
        return index === obj.arr.findIndex(obj => {
            return JSON.stringify(obj) === _value;
        });
    });
}
</code>```

Body:
I just want to list the categories of a Blog in Angular. When I use ngFor, It shows a list of the categories but is bringing in some repeated ones, like if it were bringing all the blogs and not just the categories that some of them share. Hope I was clear on this question.

This is my html:

Categorias

{{ data.category.name }}

Body:
It looks like you need to remove duplicates from your array.

Based on this answer, you can do this:

const uniqueCategorias = datas.filter((value, index) => {
  const _value = JSON.stringify(value);
  return index === obj.arr.findIndex(obj => {
    return JSON.stringify(obj) === _value;
  });
});

and use it:

 <ul *ngFor="let data of uniqueCategorias; index as i">
    <li class="nav-elipse-blue"><a [routerLink]="['/pagina',datas.category]" title="Blog CSS
    articles">{{ data.category.name }}</a></li>
 </ul>

and in TypeScript file:

uniqueCategorias;

getUniqueCategorias(){
    uniqueCategorias = datas.filter((value, index) => {
        const _value = JSON.stringify(value);
        return index === obj.arr.findIndex(obj => {
            return JSON.stringify(obj) === _value;
        });
    });
}


问:
DDD: Aggregate Root encapsulation with JavaScript
I can not find any clear example of how to implement Aggregate Root (DDD) with properly encapsulated its internal state with help of JavaScript/TypeScript. Below I suggest an idea on how to implement it. Maybe someone has ideas on how to improve this solution:</p>
```<code>import cloneDeep from 'clone-deep';
import { deepFreeze } from '../utils'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

export class AggregateRoot<TEntityProps> {
  // TODO EntityId

  protected readonly props: TEntityProps

  constructor(props: TEntityProps) {
    /** Encapsulate aggregate's state from the outside world */
    this.props = cloneDeep<TEntityProps>(props)
  }

  /** Extract the state from an aggregate.
   *
   * Aggregate becomes unchangeable (read-only) after calling the flush method.
   * */
  public flush(): TEntityProps {
    return deepFreeze(this.props)
  }
}

// Usage
export class User extends AggregateRoot<UserProps> {
  constructor(props: UserProps) {
    super(props)

    // props validation here

  }

  get firstName() {
    return this.props.firstName
  }

  get lastName() {
    return this.props.lastName
  }

  get updatedAt() {
    return this.props.updatedAt
  }
}

</code>```

答:
Another variant is to rewrite this method:

```<code>  public flush(): TEntityProps {
    return deepFreeze(this.props)
  }
</code>```

with

```<code>  public snapshot(): TEntityProps {
    return cloneDeep(this.props)
  }
</code>```

But we need to know that in this case, we increase memory consumption twice. So probably, it is suitable for small aggregates, I think.

Body:
I can not find any clear example of how to implement Aggregate Root (DDD) with properly encapsulated its internal state with help of JavaScript/TypeScript. Below I suggest an idea on how to implement it. Maybe someone has ideas on how to improve this solution:

import cloneDeep from 'clone-deep';
import { deepFreeze } from '../utils'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

export class AggregateRoot<TEntityProps> {
  // TODO EntityId

  protected readonly props: TEntityProps

  constructor(props: TEntityProps) {
    /** Encapsulate aggregate's state from the outside world */
    this.props = cloneDeep<TEntityProps>(props)
  }

  /** Extract the state from an aggregate.
   *
   * Aggregate becomes unchangeable (read-only) after calling the flush method.
   * */
  public flush(): TEntityProps {
    return deepFreeze(this.props)
  }
}

// Usage
export class User extends AggregateRoot<UserProps> {
  constructor(props: UserProps) {
    super(props)

    // props validation here

  }

  get firstName() {
    return this.props.firstName
  }

  get lastName() {
    return this.props.lastName
  }

  get updatedAt() {
    return this.props.updatedAt
  }
}

Body:
Another variant is to rewrite this method:

  public flush(): TEntityProps {
    return deepFreeze(this.props)
  }

with

  public snapshot(): TEntityProps {
    return cloneDeep(this.props)
  }

But we need to know that in this case, we increase memory consumption twice. So probably, it is suitable for small aggregates, I think.


问:
How to merge different columns into a new one made with the merged columns' name
I'm trying to clean my dataset. The dataset comes from a survey that had a randomizer. It displayed different scenarios to each participant.
My dataset now has a column for each different scenario with the name I chose for it (e.g.: A_SM_GIL or D_DF_GIL etc.). The underscore "" separates the different scenarios variables that are combined together to form a new scenario. A, D_, B_, N_ are the timing for a disclosure message during the advertising, respectively AFTER, DURING, BEFORE,and NONEF. SM_, and DF_, stand for the type of terminology used. Respectively SYNTHETIC MEDIA, and DEEPFAKE. The last bit, LOR_, GIL_, describes the brand's ad. Respectively L'Oreal, Gillette.

What I am left now is a bunch of columns that show with a "1" the scenario each observation was exposed to before answering a 7point likert scale to measure their attitudes towards the ad shown. The scale used is called ADTEST (AD_) and has different items (BORING_1, IRRITATING_1, etc).

Only 1 scenario for observation is possible. So one observation will have a column with 1 and all the others with NAs.

My goal is to compare the different scenarios' attitudes. For example, studying if positioning the disclosure before the ad makes a difference than positioning it after the ad. I would like to plot the different answers (using a 7 point likert scale i.e.: AD_BORING_1 etc) people gave but divided into the different scenarios to compare them.

```<code>structure(list(D_DF_GIL = c(NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA,
1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA), A_SM_GIL = c(NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA), A_DF_GIL = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), N_DF_GILL = c(1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
1, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA), AD_BORING_1 = c("7",
"6", "5", "3", "4", "3", "5", "2", "4", "5", "3", "2", "5", "3",
"4", "4", "5", "5", "1", "1", "4", "7", "4", "4", "3", "6", "1",
"5", "2", "5", "3", "2", "2", "7", "6", "6", "6", "5", "4", "4",
"6", "7", "3", "2", "1", "5", "5", "5", "5", "5", "6", "4", "5",
"3", "5", "2", "7", "5", "2", "2", "3", "1", "5", "5", "4", "5",
"1", "3", "2", "6", "5", "1", "3", "3", "5", "6", "5", "6", "2",
"3", "5", "6", "5", "4", "6", "5", "4", "3", "5", "5", "4", "6",
"2", "4", "6", "3", "4", "5", "3", "2", "6", "6", "5", "6", "3",
"2", "6", "5", "4", "2", "3", "6", "4", "7", "3", "1", "4", "4",
"5", "4", "2", "5", "6", "3", "5", "6", "4", "2", "5", "5", "3",
"2", "3", "1", "6", "2", "1", "5", "5", "2", "6", "1", "6", "5",
"2", "5", "2", "2", "4", "2", "2", "4", "4", "6", "3", "5", "5",
"3", "2", "4", "7", "4", "4", "2", "5", "3", "2", "3", "3", "4",
"2", "5", "6", "4", "4", "7", "4", "6", "3", "4", "2", "4", "3",
"2", "6", "5", "5", "5", "4", "2", "3", "3", "5", "5", "6", "6",
"7", "4", "2", "6", "3", "6", "4", "2", "7", "6", "4", "3", "2",
"5", "5", "6", "5", "2", "7", "2", "3", "5", "2", "3", "5", "5",
"5", "2", "4", "3", "5", "2", "3", "3", "2", "5", "5", "3", "3",
"5", "3", "2", "5", "3", "7", "5", "5", "5", "4", "2", "4", "2",
"3", "4", "5", "2", "5", "7", "6", "4", "5", "6", "3", "5", "3",
"2", "4", "5", "5", "3", "1", "4", "7", "5", "6", "3", "3", "4",
"5", "6", "5", "4", "1", "5", "2", "3", "7", "3", "4", "5", "3",
"3", "5", "5", "2", "5", "4", "5", "2", "6", "2", "6", "4", "2",
"3", "4", "6", "3", "2", "5", "2", "6", "2", "1", "3", "4", "1",
"2", "5", "4", "3", "7", "5", "6", "6", "3", "4", "2", "4", "5",
"2", "4", "3", "3", "2", "2", "3", "5", "3", "1", "3", "2", "2",
"4", "2", "2", "3", "1", "4", "2", "5", "2", "5", "5", "5", "2",
"5", "5", "4", "2", "7", "5", "5", "3", "4", "5", "3", "4", "3",
"2", "5"), AD_IRRITATING_1 = c("4", "7", "3", "5", "4", "3",
"4", "4", "4", "3", "4", "2", "2", "4", "1", "2", "1", "4", "1",
"1", "4", "7", "5", "4", "2", "2", "6", "4", "2", "5", "1", "2",
"2", "4", "2", "5", "4", "6", "4", "4", "7", "6", "3", "2", "1",
"4", "2", "2", "4", "2", "7", "5", "2", "5", "2", "2", "6", "2",
"5", "2", "2", "4", "6", "5", "4", "3", "2", "5", "1", "4", "2",
"2", "2", "2", "2", "4", "5", "3", "5", "5", "1", "4", "4", "5",
"4", "4", "4", "4", "4", "2", "2", "4", "2", "5", "7", "4", "5",
"3", "2", "1", "4", "6", "3", "6", "3", "2", "6", "2", "3", "2",
"2", "4", "2", "7", "3", "1", "4", "5", "2", "4", "1", "5", "5",
"5", "5", "6", "2", "3", "5", "5", "2", "2", "3", "2", "6", "2",
"1", "4", "2", "2", "5", "2", "2", "3", "2", "4", "2", "2", "2",
"2", "2", "4", "5", "5", "1", "5", "2", "5", "1", "2", "2", "4",
"5", "2", "4", "3", "2", "5", "2", "4", "2", "2", "4", "3", "5",
"5", "3", "3", "1", "5", "2", "5", "6", "3", "4", "2", "6", "4",
"4", "2", "2", "2", "2", "2", "4", "1", "6", "3", "2", "5", "1",
"4", "5", "2", "2", "2", "6", "1", "1", "2", "3", "5", "7", "5",
"7", "2", "3", "2", "3", "2", "1", "2", "5", "2", "4", "4", "6",
"2", "3", "3", "1", "5", "4", "4", "3", "4", "4", "2", "4", "4",
"5", "4", "6", "4", "4", "2", "5", "2", "2", "2", "7", "2", "3",
"6", "5", "3", "3", "6", "1", "6", "2", "2", "5", "4", "2", "4",
"1", "2", "4", "6", "4", "1", "2", "4", "2", "2", "4", "3", "1",
"2", "2", "4", "4", "3", "5", "2", "4", "4", "5", "5", "3", "5",
"4", "2", "2", "4", "5", "4", "2", "5", "2", "4", "3", "2", "1",
"2", "2", "6", "5", "2", "1", "2", "1", "3", "6", "4", "4", "6",
"3", "4", "4", "2", "2", "1", "4", "1", "2", "3", "2", "2", "5",
"2", "3", "7", "7", "3", "2", "2", "3", "3", "1", "5", "2", "1",
"4", "2", "5", "2", "5", "4", "4", "2", "5", "6", "2", "1", "2",
"4", "4", "2", "5", "2", "4", "2", "5", "2", "7")), row.names = c(NA,
-367L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

I was thinking I could create a new column made of the other columns' name if a condition is met (in this case the fact that a column has a 1 and not NA).

Something like this

Another problem is all around the dataset there are other columns, so I need to specify exactly the columns to analyze.

Thank you so much for your time.

答:
What you want to do is transform many dummy variables to one factor variable (with levels corresponding to dummy variable names).

I give a small reproducible example similar to your data:

library(tidyverse)

df <- structure(list(dummy1 = c(NA, 1, NA, NA),
                      dummy2 = c(1, NA, 1, NA), dummy3 = c(NA, NA, NA, 1)),
                 .Names = c("dummy1", "dummy2", "dummy3"), class = "data.frame", row.names = c(NA, -4L))

df
#>   dummy1 dummy2 dummy3
#> 1     NA      1     NA
#> 2      1     NA     NA
#> 3     NA      1     NA
#> 4     NA     NA      1

df %>%
  tidyr::pivot_longer(cols = dummy1:dummy3, names_to = "dummy", values_to = "value", values_drop_na = TRUE) %>%
  dplyr::mutate(dummy = as.factor(dummy)) %>%
  dplyr::select(-value)
#> # A tibble: 4 x 1
#>   dummy
#>   <fct>
#> 1 dummy2
#> 2 dummy1
#> 3 dummy2
#> 4 dummy3
```
<p><sup>Created on 2022-02-08 by the reprex package (v2.0.1)</sup></p>
<p>UPDATE: After posting your data, I simplified to only the <code>pivot_longer</code> (the <code>mutate</code> transformed <code>dummy</code> to factor, the <code>select</code> just dropped the <code>value</code> column that you don't need).</p>
```df %>%
    tidyr::pivot_longer(cols = D_DF_GIL:N_DF_GILL, names_to = "dummy", values_to = "value", values_drop_na = TRUE)
# A tibble: 75 x 4
   AD_BORING_1 AD_IRRITATING_1 dummy     value
   <chr>       <chr>           <chr>     <dbl>
 1 7           4               N_DF_GILL     1
 2 4           4               A_SM_GIL      1
 3 2           4               D_DF_GIL      1
 4 4           4               N_DF_GILL     1
 5 3           4               D_DF_GIL      1
 6 3           1               N_DF_GILL     1
 7 2           2               A_DF_GIL      1
 8 6           5               A_SM_GIL      1
 9 4           4               A_SM_GIL      1
10 1           1               N_DF_GILL     1
# ... with 65 more rows
```

Body:
I'm trying to clean my dataset. The dataset comes from a survey that had a randomizer. It displayed different scenarios to each participant.
My dataset now has a column for each different scenario with the name I chose for it (e.g.: A_SM_GIL or D_DF_GIL etc.). The underscore "" separates the different scenarios variables that are combined together to form a new scenario. A, D_, B_, N_ are the timing for a disclosure message during the advertising, respectively AFTER, DURING, BEFORE,and NONEF. SM_, and DF_, stand for the type of terminology used. Respectively SYNTHETIC MEDIA, and DEEPFAKE. The last bit, LOR_, GIL_, describes the brand's ad. Respectively L'Oreal, Gillette.

What I am left now is a bunch of columns that show with a "1" the scenario each observation was exposed to before answering a 7point likert scale to measure their attitudes towards the ad shown. The scale used is called ADTEST (AD_) and has different items (BORING_1, IRRITATING_1, etc).

Only 1 scenario for observation is possible. So one observation will have a column with 1 and all the others with NAs.

My goal is to compare the different scenarios' attitudes. For example, studying if positioning the disclosure before the ad makes a difference than positioning it after the ad. I would like to plot the different answers (using a 7 point likert scale i.e.: AD_BORING_1 etc) people gave but divided into the different scenarios to compare them.

structure(list(D_DF_GIL = c(NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA,
1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA), A_SM_GIL = c(NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA), A_DF_GIL = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, 1, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 1, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
NA, NA, 1, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), N_DF_GILL = c(1,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA,
NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA,
NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, 1, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
1, NA, 1, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, 1, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA), AD_BORING_1 = c("7",
"6", "5", "3", "4", "3", "5", "2", "4", "5", "3", "2", "5", "3",
"4", "4", "5", "5", "1", "1", "4", "7", "4", "4", "3", "6", "1",
"5", "2", "5", "3", "2", "2", "7", "6", "6", "6", "5", "4", "4",
"6", "7", "3", "2", "1", "5", "5", "5", "5", "5", "6", "4", "5",
"3", "5", "2", "7", "5", "2", "2", "3", "1", "5", "5", "4", "5",
"1", "3", "2", "6", "5", "1", "3", "3", "5", "6", "5", "6", "2",
"3", "5", "6", "5", "4", "6", "5", "4", "3", "5", "5", "4", "6",
"2", "4", "6", "3", "4", "5", "3", "2", "6", "6", "5", "6", "3",
"2", "6", "5", "4", "2", "3", "6", "4", "7", "3", "1", "4", "4",
"5", "4", "2", "5", "6", "3", "5", "6", "4", "2", "5", "5", "3",
"2", "3", "1", "6", "2", "1", "5", "5", "2", "6", "1", "6", "5",
"2", "5", "2", "2", "4", "2", "2", "4", "4", "6", "3", "5", "5",
"3", "2", "4", "7", "4", "4", "2", "5", "3", "2", "3", "3", "4",
"2", "5", "6", "4", "4", "7", "4", "6", "3", "4", "2", "4", "3",
"2", "6", "5", "5", "5", "4", "2", "3", "3", "5", "5", "6", "6",
"7", "4", "2", "6", "3", "6", "4", "2", "7", "6", "4", "3", "2",
"5", "5", "6", "5", "2", "7", "2", "3", "5", "2", "3", "5", "5",
"5", "2", "4", "3", "5", "2", "3", "3", "2", "5", "5", "3", "3",
"5", "3", "2", "5", "3", "7", "5", "5", "5", "4", "2", "4", "2",
"3", "4", "5", "2", "5", "7", "6", "4", "5", "6", "3", "5", "3",
"2", "4", "5", "5", "3", "1", "4", "7", "5", "6", "3", "3", "4",
"5", "6", "5", "4", "1", "5", "2", "3", "7", "3", "4", "5", "3",
"3", "5", "5", "2", "5", "4", "5", "2", "6", "2", "6", "4", "2",
"3", "4", "6", "3", "2", "5", "2", "6", "2", "1", "3", "4", "1",
"2", "5", "4", "3", "7", "5", "6", "6", "3", "4", "2", "4", "5",
"2", "4", "3", "3", "2", "2", "3", "5", "3", "1", "3", "2", "2",
"4", "2", "2", "3", "1", "4", "2", "5", "2", "5", "5", "5", "2",
"5", "5", "4", "2", "7", "5", "5", "3", "4", "5", "3", "4", "3",
"2", "5"), AD_IRRITATING_1 = c("4", "7", "3", "5", "4", "3",
"4", "4", "4", "3", "4", "2", "2", "4", "1", "2", "1", "4", "1",
"1", "4", "7", "5", "4", "2", "2", "6", "4", "2", "5", "1", "2",
"2", "4", "2", "5", "4", "6", "4", "4", "7", "6", "3", "2", "1",
"4", "2", "2", "4", "2", "7", "5", "2", "5", "2", "2", "6", "2",
"5", "2", "2", "4", "6", "5", "4", "3", "2", "5", "1", "4", "2",
"2", "2", "2", "2", "4", "5", "3", "5", "5", "1", "4", "4", "5",
"4", "4", "4", "4", "4", "2", "2", "4", "2", "5", "7", "4", "5",
"3", "2", "1", "4", "6", "3", "6", "3", "2", "6", "2", "3", "2",
"2", "4", "2", "7", "3", "1", "4", "5", "2", "4", "1", "5", "5",
"5", "5", "6", "2", "3", "5", "5", "2", "2", "3", "2", "6", "2",
"1", "4", "2", "2", "5", "2", "2", "3", "2", "4", "2", "2", "2",
"2", "2", "4", "5", "5", "1", "5", "2", "5", "1", "2", "2", "4",
"5", "2", "4", "3", "2", "5", "2", "4", "2", "2", "4", "3", "5",
"5", "3", "3", "1", "5", "2", "5", "6", "3", "4", "2", "6", "4",
"4", "2", "2", "2", "2", "2", "4", "1", "6", "3", "2", "5", "1",
"4", "5", "2", "2", "2", "6", "1", "1", "2", "3", "5", "7", "5",
"7", "2", "3", "2", "3", "2", "1", "2", "5", "2", "4", "4", "6",
"2", "3", "3", "1", "5", "4", "4", "3", "4", "4", "2", "4", "4",
"5", "4", "6", "4", "4", "2", "5", "2", "2", "2", "7", "2", "3",
"6", "5", "3", "3", "6", "1", "6", "2", "2", "5", "4", "2", "4",
"1", "2", "4", "6", "4", "1", "2", "4", "2", "2", "4", "3", "1",
"2", "2", "4", "4", "3", "5", "2", "4", "4", "5", "5", "3", "5",
"4", "2", "2", "4", "5", "4", "2", "5", "2", "4", "3", "2", "1",
"2", "2", "6", "5", "2", "1", "2", "1", "3", "6", "4", "4", "6",
"3", "4", "4", "2", "2", "1", "4", "1", "2", "3", "2", "2", "5",
"2", "3", "7", "7", "3", "2", "2", "3", "3", "1", "5", "2", "1",
"4", "2", "5", "2", "5", "4", "4", "2", "5", "6", "2", "1", "2",
"4", "4", "2", "5", "2", "4", "2", "5", "2", "7")), row.names = c(NA,
-367L), class = c("tbl_df", "tbl", "data.frame"))

I was thinking I could create a new column made of the other columns' name if a condition is met (in this case the fact that a column has a 1 and not NA).

Something like this

Another problem is all around the dataset there are other columns, so I need to specify exactly the columns to analyze.

Thank you so much for your time.

Body:
What you want to do is transform many dummy variables to one factor variable (with levels corresponding to dummy variable names).

I give a small reproducible example similar to your data:

library(tidyverse)

df <- structure(list(dummy1 = c(NA, 1, NA, NA),
                      dummy2 = c(1, NA, 1, NA), dummy3 = c(NA, NA, NA, 1)),
                 .Names = c("dummy1", "dummy2", "dummy3"), class = "data.frame", row.names = c(NA, -4L))

df
#>   dummy1 dummy2 dummy3
#> 1     NA      1     NA
#> 2      1     NA     NA
#> 3     NA      1     NA
#> 4     NA     NA      1

df %>%
  tidyr::pivot_longer(cols = dummy1:dummy3, names_to = "dummy", values_to = "value", values_drop_na = TRUE) %>%
  dplyr::mutate(dummy = as.factor(dummy)) %>%
  dplyr::select(-value)
#> # A tibble: 4 x 1
#>   dummy
#>   <fct>
#> 1 dummy2
#> 2 dummy1
#> 3 dummy2
#> 4 dummy3

Created on 2022-02-08 by the reprex package (v2.0.1)

UPDATE: After posting your data, I simplified to only the pivot_longer (the mutate transformed dummy to factor, the select just dropped the value column that you don't need).

df %>%
    tidyr::pivot_longer(cols = D_DF_GIL:N_DF_GILL, names_to = "dummy", values_to = "value", values_drop_na = TRUE)
# A tibble: 75 x 4
   AD_BORING_1 AD_IRRITATING_1 dummy     value
   <chr>       <chr>           <chr>     <dbl>
 1 7           4               N_DF_GILL     1
 2 4           4               A_SM_GIL      1
 3 2           4               D_DF_GIL      1
 4 4           4               N_DF_GILL     1
 5 3           4               D_DF_GIL      1
 6 3           1               N_DF_GILL     1
 7 2           2               A_DF_GIL      1
 8 6           5               A_SM_GIL      1
 9 4           4               A_SM_GIL      1
10 1           1               N_DF_GILL     1
# ... with 65 more rows


问:
AWS storage: S3 object go to Glacier if never accessed in the last month
i am storing objects to S3, i would like that object never accessed in the last month go to glacier.

After some research i don't think i can achieve this, but i hope to be wrong.

When creating lifecycle for an s3 bucket the rule is based on object creation date (not last access date)

Setting the storage class for the object will not help according to http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html

"You cannot associate an object with the Glacier storage class as you upload it. You transition existing Amazon S3 objects to the Glacier storage class by using lifecycle management. For more information, see Object Lifecycle Management."

Does anyone know how can achieve this?

Thanks

答:
It is not provided out of the box feature from S3 lifecycle rules. However, there is good AWS blog which explains the possible architecture to achieve the same.

Here is the URL -> expiring-amazon-s3-objects-based-on-last-accessed-date-to-decrease-costs

There are several other services are used apart from S3. These are Event bridge, Athena, Lambda.
Here is the description from AWS blog:

The S3 server access logs capture S3 object requests. These are generated and stored in the target S3 bucket.

An S3 inventory report is generated for the source bucket daily. It is written to the S3 inventory target bucket.

An Amazon EventBridge rule is configured that will initiate an AWS Lambda function once a day, or as desired.

The Lambda function initiates an S3 Batch Operation job to tag objects in the source bucket. These must be expired using the following logic:

Capture the number of days (x) configuration from the S3 Lifecycle configuration.

Run an Amazon Athena query that will get the list of objects from the S3 inventory report and server access logs. Create a delta list with objects that were created earlier than 'x' days, but not accessed during that time.

Write a manifest file with the list of these objects to an S3 bucket.

Create an S3 Batch operation job that will tag all objects in the manifest file with a tag of "delete=True".

The Lifecycle rule on the source S3 bucket will expire all objects that were created prior to 'x' days. They will have the tag given via the S3 batch operation of "delete=True".


问:
Symfony 3.4 session time
In my Symfony 3.4 application, the user is automatically logged out after a certain period of time. I want to change this behaviour and make my application never log out automatically. It should log out the session only when the user clicks on the logout link.

I have read the documentation and tried by setting the cookie_lifetime but it is not working for me. If anybody worked on this area please suggest how to proceed.

Updates:

I'm using this documentation page http://symfony.com/doc/master/components/http_foundation/session_configuration.html#session-lifetime

I'm using Symfony 3.4 flex based project.

I'm setting the configurations in config/packages/framework.yml. The configurations are as follows:

```<code>framework:
    session:
        handler_id: ~
        cookie_lifetime: 31536000
        gc_maxlifetime: 31536000
</code>```

答:
Just in case there's RedisSessionHandler configured for session storage, one should also consider increasing the ttl parameter passed into the service:

```<code># config/services.yaml
services:
    # ...
    Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler:
        arguments:
            - '@Redis'
            # you can optionally pass an array of options. The only options are 'prefix' and 'ttl',
            # which define the prefix to use for the keys to avoid collision on the Redis server
            # and the expiration time for any given entry (in seconds), defaults are 'sf_s' and null:
            - { 'prefix': 'my_prefix', 'ttl': 600 } # also set equal 31536000
</code>```

Title: Symfony 3.4 session time

Body:
In my Symfony 3.4 application, the user is automatically logged out after a certain period of time. I want to change this behaviour and make my application never log out automatically. It should log out the session only when the user clicks on the logout link.

I have read the documentation and tried by setting the cookie_lifetime but it is not working for me. If anybody worked on this area please suggest how to proceed.

Updates:

I'm using this documentation page http://symfony.com/doc/master/components/http_foundation/session_configuration.html#session-lifetime

I'm using Symfony 3.4 flex based project.

I'm setting the configurations in config/packages/framework.yml. The configurations are as follows:

framework:
    session:
        handler_id: ~
        cookie_lifetime: 31536000
        gc_maxlifetime: 31536000

Body:
Just in case there's RedisSessionHandler configured for session storage, one should also consider increasing the ttl parameter passed into the service:

# config/services.yaml
services:
    # ...
    Symfony\Component\HttpFoundation\Session\Storage\Handler\RedisSessionHandler:
        arguments:
            - '@Redis'
            # you can optionally pass an array of options. The only options are 'prefix' and 'ttl',
            # which define the prefix to use for the keys to avoid collision on the Redis server
            # and the expiration time for any given entry (in seconds), defaults are 'sf_s' and null:
            - { 'prefix': 'my_prefix', 'ttl': 600 } # also set equal 31536000


问:
How to return ActiveRecord WhereChain as a standard relation?
I have this scope that is performing a product search. The problem is it returns ActiveRecord::QueryMethods::WhereChain when I need just a standard relation array of the Product objects.

I don't think I can use the standard .where() to achieve what I'm trying to do here. This works, but, it returns the wherechain that I don't want.

scope :product_search, -> (query) {
    I18n.transliterate(query)
        .downcase
        .gsub(/\s+/, ' ')
        .gsub(/[^\w\s]/, '')
        .split(' ')
        .map{ |w| "%#{w}%" }
        .reduce(self) do |dataset, word|
        binding.pry
      dataset.where{ product_search_format(full_title).like word }
    end
  }
```
<p>For reference, product_search_format is an index in the db:</p>
<pre class="lang-rb prettyprint-override"><code>      t.index "product_search_format((full_title)::text) gin_trgm_ops", name: "app_products_full_title_search_idx", using: :gin

</code>```

答:
As I understand you need something like this

```<code>scope :product_search, ->(query) do
  pattern =
    I18n.transliterate(query)
      .downcase
      .gsub(/\s+/, ' ')
      .gsub(/[^\w\s]/, '')
      .split
      .join("|")

  where('product_search_format(full_title) ~ :pattern', pattern: pattern)
end
</code>```

BTW split without args could be used as tokenizer (split string to words)

~ operator is match operator in PostgreSQL, instead of this you can use LIKE and %-matchers

Body:
I have this scope that is performing a product search. The problem is it returns ActiveRecord::QueryMethods::WhereChain when I need just a standard relation array of the Product objects.

I don't think I can use the standard .where() to achieve what I'm trying to do here. This works, but, it returns the wherechain that I don't want.

scope :product_search, -> (query) {
    I18n.transliterate(query)
        .downcase
        .gsub(/\s+/, ' ')
        .gsub(/[^\w\s]/, '')
        .split(' ')
        .map{ |w| "%#{w}%" }
        .reduce(self) do |dataset, word|
        binding.pry
      dataset.where{ product_search_format(full_title).like word }
    end
  }

For reference, product_search_format is an index in the db:

      t.index "product_search_format((full_title)::text) gin_trgm_ops", name: "app_products_full_title_search_idx", using: :gin

Body:
As I understand you need something like this

scope :product_search, ->(query) do
  pattern =
    I18n.transliterate(query)
      .downcase
      .gsub(/\s+/, ' ')
      .gsub(/[^\w\s]/, '')
      .split
      .join("|")

  where('product_search_format(full_title) ~ :pattern', pattern: pattern)
end

BTW split without args could be used as tokenizer (split string to words)

~ operator is match operator in PostgreSQL, instead of this you can use LIKE and %-matchers


问:
Running cells with Python 3.10 requires ipykernel installed
I just installed Python 3.10 on my laptop (Ubuntu 20.04).

Running a Jupyter Notebook inside of VS Code works with Python 3.9 but not with Python 3.10. I get the error message: Running cells with 'Python 3.10.0 64 bit' requires ipykernel installed or requires an update.

Update February 2022

Jalil Nourmohammadi Khiarak gave a more complete answere, it is now the new accepted answer.

Update January 2022

It was a dumb error, I solved my problem (see accepted answer).

Things I tried:

Clicking on reinstall, which runs:

```<code>/usr/bin/python3.10 /home/joris/.vscode/extensions/ms-python.python-2021.10.1365161279/pythonFiles/shell_exec.py /usr/bin/python3.10 -m pip install -U --force-reinstall ipykernel /tmp/tmp-12568krFMIDJVy4jp.log
</code>```

Running pip3 install --upgrade ipykernel jupyter notebook pyzmq (from this thread).

Edits

As asked in the comments, here is the output when I click the "reinstall" button:

/usr/bin/python3.10 /home/joris/.vscode/extensions/ms-python.python-2021.10.1365161279/pythonFiles/shell_exec.py /usr/bin/python3.10 -m pip install -U --force-reinstall ipykernel /tmp/tmp-10997AnLZP3B079oV.log
Executing command in shell >> /usr/bin/python3.10 -m pip install -U --force-reinstall ipykernel
Traceback (most recent call last):
  File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/pip/__main__.py", line 19, in <module>
    sys.exit(_main())
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 73, in main
    command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/__init__.py", line 96, in create_command
    module = importlib.import_module(module_path)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/install.py", line 24, in <module>
    from pip._internal.cli.req_command import RequirementCommand
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/req_command.py", line 15, in <module>
    from pip._internal.index.package_finder import PackageFinder
  File "/usr/lib/python3/dist-packages/pip/_internal/index/package_finder.py", line 21, in <module>
    from pip._internal.index.collector import parse_links
  File "/usr/lib/python3/dist-packages/pip/_internal/index/collector.py", line 12, in <module>
    from pip._vendor import html5lib, requests
ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/__init__.py)
Traceback (most recent call last):
  File "/home/joris/.vscode/extensions/ms-python.python-2021.10.1365161279/pythonFiles/shell_exec.py", line 26, in <module>
    subprocess.check_call(shell_args, stdout=sys.stdout, stderr=sys.stderr)
  File "/usr/lib/python3.10/subprocess.py", line 369, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python3.10', '-m', 'pip', 'install', '-U', '--force-reinstall', 'ipykernel']' returned non-zero exit status 1.
```
<ul>
<li>Here is what my <code>_vendor</code> folder contains:</li>
</ul>
<pre class="lang-sh prettyprint-override"><code>joris@joris-N751JK:~$ ls /usr/lib/python3/dist-packages/pip/_vendor/
__init__.py  __pycache__
</code>```

Here is the output of reinstalling pip and checking the _vendor file:

joris@joris-N751JK:~$ python3 -m pip install --upgrade --force-reinstall pip
Defaulting to user installation because normal site-packages is not writeable
Collecting pip
  Using cached pip-21.3.1-py3-none-any.whl (1.7 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 21.3.1
    Uninstalling pip-21.3.1:
      Successfully uninstalled pip-21.3.1
Successfully installed pip-21.3.1
joris@joris-N751JK:~$ ls /usr/lib/python3/dist-packages/pip/_vendor
__init__.py  __pycache__
```

答:
I would like to add a comment for that:

Your solution is correct but it didn't work for me when I have used it on my new Linux. I did the following job to solve the problem.

Probably people after using the following comment:

```<code>python3.10 -m pip install ipykernel
</code>```

Will get error for 'distutils.util'. So you should install first:

```<code>sudo apt-get install python3.10-distutils
</code>```

Then again if you try to install you will get the other error:

ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/

To solve it you should use:

```<code>  curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10
</code>```

Finally, it would be best if you run:

```<code> /bin/python3.10 ~/.vscode/extensions/ms-python.python-2022.0.1786462952/pythonFiles/shell_exec.py /bin/python3.10 -m pip install -U notebook /tmp/tmp-5290PWIe78U4HgLu.log
</code>```

Body:
I just installed Python 3.10 on my laptop (Ubuntu 20.04).

Running a Jupyter Notebook inside of VS Code works with Python 3.9 but not with Python 3.10. I get the error message: Running cells with 'Python 3.10.0 64 bit' requires ipykernel installed or requires an update.

Update February 2022

Jalil Nourmohammadi Khiarak gave a more complete answere, it is now the new accepted answer.

Update January 2022

It was a dumb error, I solved my problem (see accepted answer).

Things I tried:

Clicking on reinstall, which runs:

/usr/bin/python3.10 /home/joris/.vscode/extensions/ms-python.python-2021.10.1365161279/pythonFiles/shell_exec.py /usr/bin/python3.10 -m pip install -U --force-reinstall ipykernel /tmp/tmp-12568krFMIDJVy4jp.log

Running pip3 install --upgrade ipykernel jupyter notebook pyzmq (from this thread).

Edits

As asked in the comments, here is the output when I click the "reinstall" button:

/usr/bin/python3.10 /home/joris/.vscode/extensions/ms-python.python-2021.10.1365161279/pythonFiles/shell_exec.py /usr/bin/python3.10 -m pip install -U --force-reinstall ipykernel /tmp/tmp-10997AnLZP3B079oV.log
Executing command in shell >> /usr/bin/python3.10 -m pip install -U --force-reinstall ipykernel
Traceback (most recent call last):
  File "/usr/lib/python3.10/runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.10/runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "/usr/lib/python3/dist-packages/pip/__main__.py", line 19, in <module>
    sys.exit(_main())
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 73, in main
    command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/__init__.py", line 96, in create_command
    module = importlib.import_module(module_path)
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/usr/lib/python3/dist-packages/pip/_internal/commands/install.py", line 24, in <module>
    from pip._internal.cli.req_command import RequirementCommand
  File "/usr/lib/python3/dist-packages/pip/_internal/cli/req_command.py", line 15, in <module>
    from pip._internal.index.package_finder import PackageFinder
  File "/usr/lib/python3/dist-packages/pip/_internal/index/package_finder.py", line 21, in <module>
    from pip._internal.index.collector import parse_links
  File "/usr/lib/python3/dist-packages/pip/_internal/index/collector.py", line 12, in <module>
    from pip._vendor import html5lib, requests
ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/__init__.py)
Traceback (most recent call last):
  File "/home/joris/.vscode/extensions/ms-python.python-2021.10.1365161279/pythonFiles/shell_exec.py", line 26, in <module>
    subprocess.check_call(shell_args, stdout=sys.stdout, stderr=sys.stderr)
  File "/usr/lib/python3.10/subprocess.py", line 369, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/usr/bin/python3.10', '-m', 'pip', 'install', '-U', '--force-reinstall', 'ipykernel']' returned non-zero exit status 1.

Here is what my _vendor folder contains:

joris@joris-N751JK:~$ ls /usr/lib/python3/dist-packages/pip/_vendor/
__init__.py  __pycache__

Here is the output of reinstalling pip and checking the _vendor file:

joris@joris-N751JK:~$ python3 -m pip install --upgrade --force-reinstall pip
Defaulting to user installation because normal site-packages is not writeable
Collecting pip
  Using cached pip-21.3.1-py3-none-any.whl (1.7 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 21.3.1
    Uninstalling pip-21.3.1:
      Successfully uninstalled pip-21.3.1
Successfully installed pip-21.3.1
joris@joris-N751JK:~$ ls /usr/lib/python3/dist-packages/pip/_vendor
__init__.py  __pycache__

Body:
I would like to add a comment for that:

Your solution is correct but it didn't work for me when I have used it on my new Linux. I did the following job to solve the problem.

Probably people after using the following comment:

python3.10 -m pip install ipykernel

Will get error for 'distutils.util'. So you should install first:

sudo apt-get install python3.10-distutils

Then again if you try to install you will get the other error:

ImportError: cannot import name 'html5lib' from 'pip._vendor' (/usr/lib/python3/dist-packages/pip/_vendor/

To solve it you should use:

  curl -sS https://bootstrap.pypa.io/get-pip.py | python3.10

Finally, it would be best if you run:

 /bin/python3.10 ~/.vscode/extensions/ms-python.python-2022.0.1786462952/pythonFiles/shell_exec.py /bin/python3.10 -m pip install -U notebook /tmp/tmp-5290PWIe78U4HgLu.log


问:
Error: Failed to start the transport 'LongPolling': Error: No Connection with that ID: Status code '404'
I have created a signalr selfhosted webapp service that connects to on prem signalr service using hybrid connection. This self hosted service then broadcast the changes to front end and back to on prem signalR.  The self hosted service is fronted by a front door.

Everything works fine locally with long polling (front door doesn't support websockets), but doesn't work when deployed in Azure. Error: Failed to start the transport 'LongPolling': Error: No Connection with that ID: Status code '404'

Anything i am missing?

答: Enabled the clientAffinity on the app service and that did the magic. Also on Azure front door removed the host header on the backend


问:
Comparing 2 arrays for at least 3 similarities
So I want to compare 2 arrays with each other to count the similarities that they have.

[ 401, 271, 259, 260, 342, 410 ]

[ 401, 12021, 923, 235, 342, 410 ]```

The above arrays should output 3. Right now I have a forEach inside a forEach just going through each one individually to check the other array individually for the same number.

答:
you can use the Array.reduce() method

const a = [ 401, 271, 259, 260, 342, 410 ]

const b = [ 401, 12021, 923, 235, 342, 410 ]

console.log(a.reduce((acc,curr, i)=>{
    if(curr==b[i]) acc+=1
    return acc
},0));```

Body:
So I want to compare 2 arrays with each other to count the similarities that they have.

[ 401, 271, 259, 260, 342, 410 ]

[ 401, 12021, 923, 235, 342, 410 ]

The above arrays should output 3. Right now I have a forEach inside a forEach just going through each one individually to check the other array individually for the same number.


问:
Can you redirect Tee-Object to standard out?
I am writing a script and I want to pass the values but also see them displayed

```<code>Get-Content data.txt | Tee-Object | data_processor.exe
</code>```

But Tee-Object always requests a file and I just want to see it on the screen.

答:
You can output to a variable instead of a file:

Get-Content data.txt | Tee-Object -Variable data | data_processor.exe
$data  # Output
```
<p>This passes content to "data_processor.exe" and stores it in variable <code>$data</code>. Data will be shown only when the .exe has finished.</p>
<p>Use <code>ForEach-Object</code> to examine output of <code>Get-Content</code> before each line is being send to the .exe:</p>
<pre class="lang-sh prettyprint-override"><code>Get-Content data.txt | ForEach-Object {
    Write-Host $_   # Output line to console
    $_              # Forward line to next command in chain
} | data_processor.exe
</code>```

This pattern could be made more succinct and reusable, by writing a small filter function:

Filter Write-HostAndForward {
    Write-Host $_   # Output line to console
    $_              # Forward line to next command in chain
}
```
<p>Now we can write:</p>
<pre class="lang-sh prettyprint-override"><code>Get-Content data.txt | Write-HostAndForward | data_processor.exe
</code>```

Remarks:

While Write-HostAndForward works for simple input, like strings received from Get-Content, for complex objects it typically doesn't produce the same output as we normally see in the console. That is because Write-Host simply converts the input to string using the .ToString() method, which skips PowerShells rich formatting system.

You might be tempted to simply replace Write-Host by Out-Host, but as mklement0 explains, it would format the input objects individually, which will produce a header for each object for table-formatted output. To avoid that, mklement0's answer shows different ways to produce the expected formatted output.

Body:
I am writing a script and I want to pass the values but also see them displayed

Get-Content data.txt | Tee-Object | data_processor.exe

But Tee-Object always requests a file and I just want to see it on the screen.

Body:
You can output to a variable instead of a file:

Get-Content data.txt | Tee-Object -Variable data | data_processor.exe
$data  # Output

This passes content to "data_processor.exe" and stores it in variable $data. Data will be shown only when the .exe has finished.

Use ForEach-Object to examine output of Get-Content before each line is being send to the .exe:

Get-Content data.txt | ForEach-Object {
    Write-Host $_   # Output line to console
    $_              # Forward line to next command in chain
} | data_processor.exe

This pattern could be made more succinct and reusable, by writing a small filter function:

Filter Write-HostAndForward {
    Write-Host $_   # Output line to console
    $_              # Forward line to next command in chain
}

Now we can write:

Get-Content data.txt | Write-HostAndForward | data_processor.exe

Remarks:

While Write-HostAndForward works for simple input, like strings received from Get-Content, for complex objects it typically doesn't produce the same output as we normally see in the console. That is because Write-Host simply converts the input to string using the .ToString() method, which skips PowerShells rich formatting system.

You might be tempted to simply replace Write-Host by Out-Host, but as mklement0 explains, it would format the input objects individually, which will produce a header for each object for table-formatted output. To avoid that, mklement0's answer shows different ways to produce the expected formatted output.


问:
Checking if multiple elements are rendering using jasmine

it('should check if all div are appearing which are dependent on a common condition', () => {
  component.someCommonCondition = true;
  fixture.detectChanges();
  // now the prob lies in line below since it only gets the first element of the mentioned class
  const contentCheck = fixture.debugElement.query(By.css('.someClass'))
  expect() // what to write here to check all 3 divs are getting rendered
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div *ngif="someCommonCondition" class="someClass"></div>
<div *ngif="someCommonCondition" class="someClass"></div>
<div *ngif="someCommonCondition" class="someClass"></div></code>```

Greetings, I am trying to write a unit test where i can test if multiple divs are getting rendered which depend on a common condition. I want to know if there is a way to do it in one test  rather than writing a test for each of them individually since they all dependent on a common condition. That is, either none of them appear or all of them should.

答:
I think you can use queryAll instead of query. queryAll will return an array.

Try the following:

```<code>it('should check if all div are appearing which are dependent on a common condition', () => {
  component.someCommonCondition = true;
  fixture.detectChanges();
  // now the prob lies in line below since it only gets the first element of the mentioned class
  const contentChecks = fixture.debugElement.queryAll(By.css('.someClass'))
  expect(contentChecks.length).toBe(3);
})
</code>```

Body:
it('should check if all div are appearing which are dependent on a common condition', () => {
  component.someCommonCondition = true;
  fixture.detectChanges();
  // now the prob lies in line below since it only gets the first element of the mentioned class
  const contentCheck = fixture.debugElement.query(By.css('.someClass'))
  expect() // what to write here to check all 3 divs are getting rendered
})

Greetings, I am trying to write a unit test where i can test if multiple divs are getting rendered which depend on a common condition. I want to know if there is a way to do it in one test  rather than writing a test for each of them individually since they all dependent on a common condition. That is, either none of them appear or all of them should.

Body:
I think you can use queryAll instead of query. queryAll will return an array.

Try the following:

it('should check if all div are appearing which are dependent on a common condition', () => {
  component.someCommonCondition = true;
  fixture.detectChanges();
  // now the prob lies in line below since it only gets the first element of the mentioned class
  const contentChecks = fixture.debugElement.queryAll(By.css('.someClass'))
  expect(contentChecks.length).toBe(3);
})


问:
Set constraint height percent with databinding
I have a bar that should have a height according to the viewmodel.heartStrengthLiveData value (0..100). I want to set height with app:layout_constraintHeight_percent="..." with databinding.
How can i do this?

```<code>            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/heart_strength_bgc"
                android:layout_width="@dimen/cardiogram_status_bar_width"
                android:layout_height="0dp"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_dark_gray"
                app:layout_constraintBottom_toBottomOf="@+id/cardiogram_background_light"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/cardiogram_background_light" >

                <androidx.constraintlayout.widget.ConstraintLayout
                    android:id="@+id/heart_strength"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    app:heartStrength="@{viewmodel.heartStrengthLiveData}"
                    android:background="@drawable/chart_widget_background_light_gray"
                    android:backgroundTint="@color/turquoise"
                    app:layout_constraintHeight_percent="0"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Update: Corrected XML.

In your ViewModel, set up something like this which include the LiveData and the BindingAdapter for the layout percent height attribute:

```<code>public MutableLiveData heartStrengthLiveData = new MutableLiveData<>(100f);

public float getHeartStrength() {
    return (float) heartStrengthLiveData.getValue() / 100f;
}

@BindingAdapter("layout_constraintHeight_percent")
public static void setLayoutConstraintHeightPercent(View view, float percentHeight) {

    ConstraintLayout layout = (ConstraintLayout) view.getParent();
    ConstraintSet cs = new ConstraintSet();
    cs.clone(layout);
    cs.constrainPercentHeight(view.getId(), percentHeight);
    cs.applyTo(layout);
}
</code>```

In the layout, specify:

```<code>app:layout_constraintHeight_percent='@{viewmodel.heartStrength}'
app:layout_constraintHeight_default="percent"
</code>```

A height percentage of 1.0 will not work if the default height is not set to "percent" which addresses the issue in your (now deleted) comment.

Body:
I have a bar that should have a height according to the viewmodel.heartStrengthLiveData value (0..100). I want to set height with app:layout_constraintHeight_percent="..." with databinding.
How can i do this?

            <androidx.constraintlayout.widget.ConstraintLayout
                android:id="@+id/heart_strength_bgc"
                android:layout_width="@dimen/cardiogram_status_bar_width"
                android:layout_height="0dp"
                android:layout_marginEnd="@dimen/default_screen_margin"
                android:background="@drawable/chart_widget_background_dark_gray"
                app:layout_constraintBottom_toBottomOf="@+id/cardiogram_background_light"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="@+id/cardiogram_background_light" >

                <androidx.constraintlayout.widget.ConstraintLayout
                    android:id="@+id/heart_strength"
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    app:heartStrength="@{viewmodel.heartStrengthLiveData}"
                    android:background="@drawable/chart_widget_background_light_gray"
                    android:backgroundTint="@color/turquoise"
                    app:layout_constraintHeight_percent="0"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>

Body:
Update: Corrected XML.

In your ViewModel, set up something like this which include the LiveData and the BindingAdapter for the layout percent height attribute:

public MutableLiveData heartStrengthLiveData = new MutableLiveData<>(100f);

public float getHeartStrength() {
    return (float) heartStrengthLiveData.getValue() / 100f;
}

@BindingAdapter("layout_constraintHeight_percent")
public static void setLayoutConstraintHeightPercent(View view, float percentHeight) {

    ConstraintLayout layout = (ConstraintLayout) view.getParent();
    ConstraintSet cs = new ConstraintSet();
    cs.clone(layout);
    cs.constrainPercentHeight(view.getId(), percentHeight);
    cs.applyTo(layout);
}

In the layout, specify:

app:layout_constraintHeight_percent='@{viewmodel.heartStrength}'
app:layout_constraintHeight_default="percent"

A height percentage of 1.0 will not work if the default height is not set to "percent" which addresses the issue in your (now deleted) comment.


问:
AttributeError at /media/.. when requesting file in media folder Django development stage
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error:

AttributeError at /media/test.png
This FileResponse instance has no content attribute. Use streaming_content instead.

Request: http://localhost:8000/media/test.png

I added below to the url patterns:

```<code>urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

And below to the settings:

```<code>STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
</code>```

Static files are working just fine.

What do I overlook?
Thanks!

答:
hello if you have debug  set to True you have to  use  this:

first go to you settings and set all you static file directories in

```<code>STATICFILES_DIRS = [
list of your static file,.......,]
</code>```

the second step you should have this in your urls.py

```<code>    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS[0])
</code>```

note:there is a difference between static_root and staticfile_dirs

static_root is only used for production

this is my mail for more explanation :nguewofoss@gmail.com

Body:
When I am reqeuesting media files (.png in this case) in the media folder in development I get this error:

AttributeError at /media/test.png
This FileResponse instance has no content attribute. Use streaming_content instead.

Request: http://localhost:8000/media/test.png

I added below to the url patterns:

urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And below to the settings:

STATIC_ROOT = BASE_DIR / 'static'
STATIC_URL = '/static/'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'

Static files are working just fine.

What do I overlook?
Thanks!

Body:
hello if you have debug  set to True you have to  use  this:

first go to you settings and set all you static file directories in

STATICFILES_DIRS = [
list of your static file,.......,]

the second step you should have this in your urls.py

    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATICFILES_DIRS[0])

note:there is a difference between static_root and staticfile_dirs

static_root is only used for production

this is my mail for more explanation :nguewofoss@gmail.com