问:
Django localflavor field overwrite breaks form
I have the following form, which generates a Value error upon submition.

ValueError at /en/orders/create/

The view orders.views.order_create didn't return an HttpResponse object. It returned None instead.

my form:

from django import forms
from .models import Order
from localflavor.us.forms import USZipCodeField

class OrderCreateForm(forms.ModelForm):
    postal_code = USZipCodeField()

    class Meta:
        model = Order

        fields = ['first_name', 'last_name', 'email', 'address',
                  'postal_code', 'city']

```

<p>my model:</p>

<pre class="lang-py prettyprint-override"><code>class Order(models.Model):
    first_name = models.CharField(_('first name'), max_length=50)
    last_name = models.CharField(_('last name'), max_length=50)
    email = models.EmailField(_('e-mail'))
    address = models.CharField(_('address'), max_length=250)
    postal_code = models.CharField(_('postal code'), max_length=20)
    city = models.CharField(_('city'), max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)

    class Meta:
        ordering = ('-created', )

    def __str__(self):
        return f'Order {self.id}'

</code>```

my view:

def order_create(request):
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)

        if form.is_valid():
            order.save()

            request.session['order_id'] = order.id

            # redirect for payment return
            return redirect(reverse('payment:process'))

    else:
        form = OrderCreateForm()
        return render(request,
                      'orders/order/create.html',
                      {'cart': cart, 'form': form})

```

<p>Traceback:</p>

<pre class="lang-py prettyprint-override"><code>Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/en/orders/create/

Django Version: 3.0.6
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rosetta',
 'parler',
 'localflavor',
 'shop.apps.ShopConfig',
 'cart.apps.CartConfig',
 'orders.apps.OrdersConfig',
 'payment.apps.PaymentConfig',
 'coupons.apps.CouponsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/home/[user]/.virtualenvs/shop/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/[user]/.virtualenvs/shop/lib/python3.8/site-packages/django/core/handlers/base.py", line 124, in _get_response
    raise ValueError(

Exception Type: ValueError at /en/orders/create/
Exception Value: The view orders.views.order_create didn't return an HttpResponse object. It returned None instead.
</code>```

The process works fine, and redirects to a payment form, without this line in the form : postal_code = USZipCodeField()

I cant seem to understand what causes the error.

Expected behavior:

On valid form, redirect to payment.

On invalid form, validation error that is raised by USZipCodeField: "Enter a zip code in the format XXXXX or XXXXX-XXXX."

答:
I think the issue is that the code isn't rendering the form in the case that the form isn't valid. For an invalid form, the function returns None which is exactly the error message you're seeing. Maybe you're submitting an empty or invalid value? Try this modified (untested) version:

```<code>def order_create(request):
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)

        if form.is_valid():
            order = form.save()

            request.session['order_id'] = order.id

            # redirect for payment return
            return redirect(reverse('payment:process'))

    else:
        form = OrderCreateForm()

    # FIXME Where does 'cart' come from?
    return render(request,
                  'orders/order/create.html',
                  {'cart': cart, 'form': form})
</code>```

Does this work?

You might want to consider using the built-in CreateView to avoid boilerplate form processing code:
https://docs.djangoproject.com/en/3.0/ref/class-based-views/flattened-index/#CreateView

If you haven't used class-based views, it's definitely something to look into. I find I can move a little faster using them but they do take a bit of time to learn and make the flow a little harder to follow when things don't work. Here are the full docs for the class based views:
https://docs.djangoproject.com/en/3.0/topics/class-based-views/

Body:
I have the following form, which generates a Value error upon submition.

ValueError at /en/orders/create/

The view orders.views.order_create didn't return an HttpResponse object. It returned None instead.

my form:

from django import forms
from .models import Order
from localflavor.us.forms import USZipCodeField

class OrderCreateForm(forms.ModelForm):
    postal_code = USZipCodeField()

    class Meta:
        model = Order

        fields = ['first_name', 'last_name', 'email', 'address',
                  'postal_code', 'city']

my model:

class Order(models.Model):
    first_name = models.CharField(_('first name'), max_length=50)
    last_name = models.CharField(_('last name'), max_length=50)
    email = models.EmailField(_('e-mail'))
    address = models.CharField(_('address'), max_length=250)
    postal_code = models.CharField(_('postal code'), max_length=20)
    city = models.CharField(_('city'), max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    paid = models.BooleanField(default=False)

    class Meta:
        ordering = ('-created', )

    def __str__(self):
        return f'Order {self.id}'

my view:

def order_create(request):
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)

        if form.is_valid():
            order.save()

            request.session['order_id'] = order.id

            # redirect for payment return
            return redirect(reverse('payment:process'))

    else:
        form = OrderCreateForm()
        return render(request,
                      'orders/order/create.html',
                      {'cart': cart, 'form': form})

Traceback:

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/en/orders/create/

Django Version: 3.0.6
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rosetta',
 'parler',
 'localflavor',
 'shop.apps.ShopConfig',
 'cart.apps.CartConfig',
 'orders.apps.OrdersConfig',
 'payment.apps.PaymentConfig',
 'coupons.apps.CouponsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
  File "/home/[user]/.virtualenvs/shop/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/[user]/.virtualenvs/shop/lib/python3.8/site-packages/django/core/handlers/base.py", line 124, in _get_response
    raise ValueError(

Exception Type: ValueError at /en/orders/create/
Exception Value: The view orders.views.order_create didn't return an HttpResponse object. It returned None instead.

The process works fine, and redirects to a payment form, without this line in the form : postal_code = USZipCodeField()

I cant seem to understand what causes the error.

Expected behavior:

On valid form, redirect to payment.

On invalid form, validation error that is raised by USZipCodeField: "Enter a zip code in the format XXXXX or XXXXX-XXXX."

Body:
I think the issue is that the code isn't rendering the form in the case that the form isn't valid. For an invalid form, the function returns None which is exactly the error message you're seeing. Maybe you're submitting an empty or invalid value? Try this modified (untested) version:

def order_create(request):
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)

        if form.is_valid():
            order = form.save()

            request.session['order_id'] = order.id

            # redirect for payment return
            return redirect(reverse('payment:process'))

    else:
        form = OrderCreateForm()

    # FIXME Where does 'cart' come from?
    return render(request,
                  'orders/order/create.html',
                  {'cart': cart, 'form': form})

Does this work?

You might want to consider using the built-in CreateView to avoid boilerplate form processing code:
https://docs.djangoproject.com/en/3.0/ref/class-based-views/flattened-index/#CreateView

If you haven't used class-based views, it's definitely something to look into. I find I can move a little faster using them but they do take a bit of time to learn and make the flow a little harder to follow when things don't work. Here are the full docs for the class based views:
https://docs.djangoproject.com/en/3.0/topics/class-based-views/


来源: stackexchange

问:
ERROR in animate (1023: Incompatible override. AND 1021: Duplicate function definition.)
I'm new to Adobe Animate and action script so I really dont know how to fix this.

I'm creating a mcq quiz which goes like this:
if user choose answer a or b or c or d. if a is correct answer, give 1 mark, choose wrong answer 0 mark

The source of the two errors is in the function speed.

Here is the code I made so far...

```<code>import flash.events.Event;
import flash.events.EventDispatcher;
stop();
question.text="the question is"

var totalscore=3;
var currentscore=0;

function mark()
{
    currentscore = currentscore + 1;
}

/* Click to Go to Scene and Play
Clicking on the specified symbol instance plays the movie from the specified scene and frame.

Instructions:
1. Replace "Scene 3" with the name of the scene you would like play.
2. Replace 1 with the frame number you would like the movie to play from in the specified scene.
*/

ans1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 1;
}

ans2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 0;
}

ans3.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 0;
}
ans4.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 0;
}

stop();

</code>```

答:
You have 4 functions there all with the same name. That's probably the source of the error.

Also, your script is too complicated. You don't even need 4 different handlers to begin with.

```<code>// Subscribe a single handler to all 4 buttons.
ans1.addEventListener(MouseEvent.CLICK, onAnswer);
ans2.addEventListener(MouseEvent.CLICK, onAnswer);
ans3.addEventListener(MouseEvent.CLICK, onAnswer);
ans4.addEventListener(MouseEvent.CLICK, onAnswer);

function onAnswer(e:MouseEvent):void
{
    // Event.target contains the reference to the source of the event.
    // Figuring if that was a correct answer is easy.
    if (e.target == ans1)
    {
        currentscore += 1;
    }

    // In any case...
    (root as MovieClip).gotoAndPlay(1, "quiz 2");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to Adobe Animate and action script so I really dont know how to fix this.

I'm creating a mcq quiz which goes like this:
if user choose answer a or b or c or d. if a is correct answer, give 1 mark, choose wrong answer 0 mark

The source of the two errors is in the function speed.

Here is the code I made so far...

import flash.events.Event;
import flash.events.EventDispatcher;
stop();
question.text="the question is"

var totalscore=3;
var currentscore=0;

function mark()
{
    currentscore = currentscore + 1;
}

/* Click to Go to Scene and Play
Clicking on the specified symbol instance plays the movie from the specified scene and frame.

Instructions:
1. Replace "Scene 3" with the name of the scene you would like play.
2. Replace 1 with the frame number you would like the movie to play from in the specified scene.
*/

ans1.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 1;
}

ans2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 0;
}

ans3.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 0;
}
ans4.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene_24);

function fl_ClickToGoToScene_24(event:MouseEvent):void
{
    MovieClip(this.root).gotoAndPlay(1, "quiz 2");
    currentscore = currentscore + 0;
}

stop();

Body:
You have 4 functions there all with the same name. That's probably the source of the error.

Also, your script is too complicated. You don't even need 4 different handlers to begin with.

// Subscribe a single handler to all 4 buttons.
ans1.addEventListener(MouseEvent.CLICK, onAnswer);
ans2.addEventListener(MouseEvent.CLICK, onAnswer);
ans3.addEventListener(MouseEvent.CLICK, onAnswer);
ans4.addEventListener(MouseEvent.CLICK, onAnswer);

function onAnswer(e:MouseEvent):void
{
    // Event.target contains the reference to the source of the event.
    // Figuring if that was a correct answer is easy.
    if (e.target == ans1)
    {
        currentscore += 1;
    }

    // In any case...
    (root as MovieClip).gotoAndPlay(1, "quiz 2");
}


问:
Adding and removing select value in text area using jquery

i have a textarea, a select list and two buttons:- add and remove

on clicking the add button i want to add the select list value to the textarea and on
remove button click i want to remove the text selected from the textarea.
and on a single click in the text area i want the corresponding added select item to be selected(so that i can click on remove button to remove it)
Please help me with this.

```<code><table cellpadding="0" cellspacing="0">
<tr>
<td colspan="3">
    <select>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    <select>
</td>
</tr>
<tr>
<td><input type="button" value="Remove" style="width:110px" class="btn" id="remove"/></td>
<td  style="width:110px"></td>
<td><input type="button" value="Add" style="width:110px" class="btn" id="add"/></td>
</tr>
<tr>
    <td colspan="3">
        <textarea cols="45" rows="5" id="textarea"  readonly="true" ></textarea>
    </td>
</tr>
</table>
</code>```

Thanks,

Devan

答:
on add click:

$('textarea').val($('select').val());

on remove click:

$('textarea').val('');

ContentLicense: CC BY-SA 3.0

Body:
i have a textarea, a select list and two buttons:- add and remove

on clicking the add button i want to add the select list value to the textarea and on
remove button click i want to remove the text selected from the textarea.
and on a single click in the text area i want the corresponding added select item to be selected(so that i can click on remove button to remove it)
Please help me with this.

    <select>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    <select>

<input type="button" value="Remove" style="width:110px" class="btn" id="remove"/>

<input type="button" value="Add" style="width:110px" class="btn" id="add"/>

        <textarea cols="45" rows="5" id="textarea"  readonly="true" ></textarea>

Thanks,

Devan


问:
Is there a good tool for MySQL that will help me optimise my queries and index settings?
I use MySQL in a fairly complex web site (PHP driven).

Ideally, there would be a tool I could use that would help me test the SQL queries I am using and suggest better table indexes that will improve performance and avoid table scans.

Failing that, something that will tell me exactly what each query is up to, so I can perform the optimisation myself.

Edit: a simple guide to understanding the output from EXPLAIN ... would also be useful.

Thank you.

答:
EverSQL
https://www.eversql.com

It will analyse your slow queries and generate indexes and give you some tips.

OwnerDisplayName: rikh

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: rikh


问:
unable to load data in treepanel of extjs4
I am new to extjs and I am creating MVC application.

I am trying to create tree panel as following.

Following is my model file

```<code>Ext.define('rt.model.userinproject', {
extend: 'Ext.data.Model',

proxy: {
    type: 'memory'
},

fields: [
    { name: 'text', type: 'string'},
    { name: 'id',  type: 'Number'}

]
});
</code>```

Following is my store file

```<code>Ext.define('rt.store.userinproject', {
extend: 'Ext.data.TreeStore',

model: 'rt.model.userinproject',

root: {
        text: 'Project 1',
        id: 1,
        expanded: true
    },

folderSort: true,

sorters: [{
        property: 'text',
        direction: 'ASC'
    }],

data: [
        {
            text: "Project 1",
            id: 1,
            expanded: true,
            children: [
                        {
                            text: "Department 1",
                            id: 1,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 1",
                                            id: 1,
                                            leaf:true
                                        },
                                        {
                                            text: "User 2",
                                            id: 2,
                                            leaf:true
                                        },
                                        {
                                            text: "User 3",
                                            id: 3,
                                            leaf:true
                                        },
                                        {
                                            text: "User 4",
                                            id: 4,
                                            leaf:true
                                        },
                                        {
                                            text: "User 5",
                                            id: 5,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 2",
                            id: 2,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 6",
                                            id: 6,
                                            leaf:true
                                        },
                                        {
                                            text: "User 7",
                                            id: 7,
                                            leaf:true
                                        },
                                        {
                                            text: "User 8",
                                            id: 8,
                                            leaf:true
                                        },
                                        {
                                            text: "User 9",
                                            id: 9,
                                            leaf:true
                                        },
                                        {
                                            text: "User 10",
                                            id: 10,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 3",
                            id: 2,
                            cls:"folder",
                            children:[
                                        {
                                            text: "User 11",
                                            id: 11,
                                            leaf:true
                                        },
                                        {
                                            text: "User 12",
                                            id: 12,
                                            leaf:true
                                        },
                                        {
                                            text: "User 13",
                                            id: 13,
                                            leaf:true
                                        },
                                        {
                                            text: "User 14",
                                            id: 14,
                                            leaf:true
                                        },
                                        {
                                            text: "User 15",
                                            id: 15,
                                            leaf:true
                                        }
                                    ]
                        }

                    ]
        },
        {
            text: "Project 2",
            id: 1,
            expanded: true,
            children: [
                        {
                            text: "Department 1",
                            id: 1,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 1",
                                            id: 1,
                                            leaf:true
                                        },
                                        {
                                            text: "User 2",
                                            id: 2,
                                            leaf:true
                                        },
                                        {
                                            text: "User 3",
                                            id: 3,
                                            leaf:true
                                        },
                                        {
                                            text: "User 4",
                                            id: 4,
                                            leaf:true
                                        },
                                        {
                                            text: "User 5",
                                            id: 5,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 2",
                            id: 2,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 16",
                                            id: 16,
                                            leaf:true
                                        },
                                        {
                                            text: "User 17",
                                            id: 17,
                                            leaf:true
                                        },
                                        {
                                            text: "User 18",
                                            id: 18,
                                            leaf:true
                                        },
                                        {
                                            text: "User 19",
                                            id: 19,
                                            leaf:true
                                        },
                                        {
                                            text: "User 20",
                                            id: 20,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 3",
                            id: 2,
                            cls:"folder",
                            children:[
                                        {
                                            text: "User 21",
                                            id: 21,
                                            leaf:true
                                        },
                                        {
                                            text: "User 22",
                                            id: 22,
                                            leaf:true
                                        },
                                        {
                                            text: "User 23",
                                            id: 23,
                                            leaf:true
                                        },
                                        {
                                            text: "User 24",
                                            id: 24,
                                            leaf:true
                                        },
                                        {
                                            text: "User 25",
                                            id: 25,
                                            leaf:true
                                        }
                                    ]
                        }

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

Following is my view file

```<code>Ext.define('rt.view.project.projectuser', {
extend: 'Ext.tree.Panel',
alias: 'widget.projectuser',

disabled: true,
border: false,
cls: 'projectuser',
autoScroll: true,

initComponent: function() {
    Ext.apply(this, {
        store: this.store,

        items: {
        title: 'User in project',
        }
    });

    this.callParent(arguments);
},

});
</code>```

When I am running code, tree panel seems empty without tree.

What I want to do is, I want to show tree based on project id in store above

Let me know if you need any other information from me.

Can anyone help me regarding the matter.

Thanks in advance.

答:
I was able to solve above problem by replacing following line in my view file

```<code>store: this.store,
</code>```

as following,

```<code>store: Ext.data.StoreManager.lookup('userinproject'),
</code>```

Hope this will help someone.

Thanks.

Body:
I am new to extjs and I am creating MVC application.

I am trying to create tree panel as following.

Following is my model file

Ext.define('rt.model.userinproject', {
extend: 'Ext.data.Model',

proxy: {
    type: 'memory'
},

fields: [
    { name: 'text', type: 'string'},
    { name: 'id',  type: 'Number'}

]
});

Following is my store file

Ext.define('rt.store.userinproject', {
extend: 'Ext.data.TreeStore',

model: 'rt.model.userinproject',

root: {
        text: 'Project 1',
        id: 1,
        expanded: true
    },

folderSort: true,

sorters: [{
        property: 'text',
        direction: 'ASC'
    }],

data: [
        {
            text: "Project 1",
            id: 1,
            expanded: true,
            children: [
                        {
                            text: "Department 1",
                            id: 1,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 1",
                                            id: 1,
                                            leaf:true
                                        },
                                        {
                                            text: "User 2",
                                            id: 2,
                                            leaf:true
                                        },
                                        {
                                            text: "User 3",
                                            id: 3,
                                            leaf:true
                                        },
                                        {
                                            text: "User 4",
                                            id: 4,
                                            leaf:true
                                        },
                                        {
                                            text: "User 5",
                                            id: 5,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 2",
                            id: 2,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 6",
                                            id: 6,
                                            leaf:true
                                        },
                                        {
                                            text: "User 7",
                                            id: 7,
                                            leaf:true
                                        },
                                        {
                                            text: "User 8",
                                            id: 8,
                                            leaf:true
                                        },
                                        {
                                            text: "User 9",
                                            id: 9,
                                            leaf:true
                                        },
                                        {
                                            text: "User 10",
                                            id: 10,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 3",
                            id: 2,
                            cls:"folder",
                            children:[
                                        {
                                            text: "User 11",
                                            id: 11,
                                            leaf:true
                                        },
                                        {
                                            text: "User 12",
                                            id: 12,
                                            leaf:true
                                        },
                                        {
                                            text: "User 13",
                                            id: 13,
                                            leaf:true
                                        },
                                        {
                                            text: "User 14",
                                            id: 14,
                                            leaf:true
                                        },
                                        {
                                            text: "User 15",
                                            id: 15,
                                            leaf:true
                                        }
                                    ]
                        }

                    ]
        },
        {
            text: "Project 2",
            id: 1,
            expanded: true,
            children: [
                        {
                            text: "Department 1",
                            id: 1,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 1",
                                            id: 1,
                                            leaf:true
                                        },
                                        {
                                            text: "User 2",
                                            id: 2,
                                            leaf:true
                                        },
                                        {
                                            text: "User 3",
                                            id: 3,
                                            leaf:true
                                        },
                                        {
                                            text: "User 4",
                                            id: 4,
                                            leaf:true
                                        },
                                        {
                                            text: "User 5",
                                            id: 5,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 2",
                            id: 2,
                            cls: "folder",
                            children:[
                                        {
                                            text: "User 16",
                                            id: 16,
                                            leaf:true
                                        },
                                        {
                                            text: "User 17",
                                            id: 17,
                                            leaf:true
                                        },
                                        {
                                            text: "User 18",
                                            id: 18,
                                            leaf:true
                                        },
                                        {
                                            text: "User 19",
                                            id: 19,
                                            leaf:true
                                        },
                                        {
                                            text: "User 20",
                                            id: 20,
                                            leaf:true
                                        }
                                    ]

                        },
                        {
                            text: "Department 3",
                            id: 2,
                            cls:"folder",
                            children:[
                                        {
                                            text: "User 21",
                                            id: 21,
                                            leaf:true
                                        },
                                        {
                                            text: "User 22",
                                            id: 22,
                                            leaf:true
                                        },
                                        {
                                            text: "User 23",
                                            id: 23,
                                            leaf:true
                                        },
                                        {
                                            text: "User 24",
                                            id: 24,
                                            leaf:true
                                        },
                                        {
                                            text: "User 25",
                                            id: 25,
                                            leaf:true
                                        }
                                    ]
                        }

                    ]
        }
    ]
});

Following is my view file

Ext.define('rt.view.project.projectuser', {
extend: 'Ext.tree.Panel',
alias: 'widget.projectuser',

disabled: true,
border: false,
cls: 'projectuser',
autoScroll: true,

initComponent: function() {
    Ext.apply(this, {
        store: this.store,

        items: {
        title: 'User in project',
        }
    });

    this.callParent(arguments);
},

});

When I am running code, tree panel seems empty without tree.

What I want to do is, I want to show tree based on project id in store above

Let me know if you need any other information from me.

Can anyone help me regarding the matter.

Thanks in advance.

Body:
I was able to solve above problem by replacing following line in my view file

store: this.store,

as following,

store: Ext.data.StoreManager.lookup('userinproject'),

Hope this will help someone.

Thanks.


问:
Delete specific line from .txt file (C++)
I am trying to scan through the content of a .txt file in order to compare it with a user's int input and once found the matching value, line where it is written to be removed.
The file DOES NOT have only numerical values.
Ex of what the file contains:
" hello world 505 "
" hello world 506 " etc.

So far my code is able to make the comparison(the lines do not have the same length) but I do not know how to move the file pointer to the line where said value is found.Any help?

```<code>void comparisoniD2 (int a) {

    int x[ countLinesOf() ];

    ifstream readFile;
    readFile.open("ClientList.txt");
    string str;
    for (int i = 0; i< countLinesOf();i++){
        while (getline(readFile, str)) {
            reverseStr2(str);
            str.erase(3);
            reverseStr2(str);
            stringstream geek(str);
            geek >> x[i];
            if( x[i]==a ){
                cout<<a<<" is equal to "<<x[i]<<endl;
                break;
            }
        }
    }

    readFile.close();
}
</code>```

答:
If you want to do this in the same file it's slightly difficult.

For example you can open the same file twice: for reading strings and for saving strings.
Your cycle would be: read string, save string (if it doesn't contain suitable number).

Another trouble is to cut file to lower size. You can use boost::filesystem or native api.

Body:
I am trying to scan through the content of a .txt file in order to compare it with a user's int input and once found the matching value, line where it is written to be removed.
The file DOES NOT have only numerical values.
Ex of what the file contains:
" hello world 505 "
" hello world 506 " etc.

So far my code is able to make the comparison(the lines do not have the same length) but I do not know how to move the file pointer to the line where said value is found.Any help?

void comparisoniD2 (int a) {

    int x[ countLinesOf() ];

    ifstream readFile;
    readFile.open("ClientList.txt");
    string str;
    for (int i = 0; i< countLinesOf();i++){
        while (getline(readFile, str)) {
            reverseStr2(str);
            str.erase(3);
            reverseStr2(str);
            stringstream geek(str);
            geek >> x[i];
            if( x[i]==a ){
                cout<<a<<" is equal to "<<x[i]<<endl;
                break;
            }
        }
    }

    readFile.close();
}


问:
Gradle Kotlin, Cucumber, and OKHttp
I'm trying to set up a spring boot project in Kotlin with OkHttp and Cucumber and getting the following error when running the cucumber task.  How do I fix?

```<code>Execution failed for task ':cucumber'.
> Could not resolve all files for configuration ':cucumberRuntime'.
   > Could not resolve com.squareup.okio:okio:2.4.1.
     Required by:
         project : > com.squareup.okhttp3:okhttp:4.3.1
      > Cannot choose between the following variants of com.squareup.okio:okio:2.4.1:
          - jvm-api
          - jvm-runtime
          - metadata-api
        All of them match the consumer attributes:
          - Variant 'jvm-api' capability com.squareup.okio:okio:2.4.1:
              - Unmatched attributes:
                  - Found org.gradle.libraryelements 'jar' but wasn't required.
                  - Found org.gradle.status 'release' but wasn't required.
                  - Found org.gradle.usage 'java-api' but wasn't required.
                  - Found org.jetbrains.kotlin.platform.type 'jvm' but wasn't required.
          - Variant 'jvm-runtime' capability com.squareup.okio:okio:2.4.1:
              - Unmatched attributes:
                  - Found org.gradle.libraryelements 'jar' but wasn't required.
                  - Found org.gradle.status 'release' but wasn't required.
                  - Found org.gradle.usage 'java-runtime' but wasn't required.
                  - Found org.jetbrains.kotlin.platform.type 'jvm' but wasn't required.
          - Variant 'metadata-api' capability com.squareup.okio:okio:2.4.1:
              - Unmatched attributes:
                  - Found org.gradle.status 'release' but wasn't required.
                  - Found org.gradle.usage 'kotlin-api' but wasn't required.
                  - Found org.jetbrains.kotlin.platform.type 'common' but wasn't required.

</code>```

and the build gradle kts snippet

```<code>import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.2.5.RELEASE"
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    kotlin("jvm") version "1.3.61"
    kotlin("plugin.spring") version "1.3.61"
}

group = "com.foo"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

val developmentOnly by configurations.creating
configurations {
    runtimeClasspath {
        extendsFrom(developmentOnly)
    }
    compileOnly {
        extendsFrom(configurations.annotationProcessor.get())
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

    compileOnly("org.projectlombok:lombok")
    developmentOnly("org.springframework.boot:spring-boot-devtools")
    annotationProcessor("org.projectlombok:lombok")

    implementation("com.squareup.okhttp3:okhttp:4.3.1")
    implementation("com.graphql-java-kickstart:graphql-spring-boot-starter:6.0.1")
    runtimeOnly("com.graphql-java-kickstart:graphiql-spring-boot-starter:6.0.1")
    runtimeOnly("com.graphql-java-kickstart:voyager-spring-boot-starter:6.0.1")

    testImplementation("io.cucumber:cucumber-java8:5.4.0")
    testImplementation("io.cucumber:cucumber-junit:5.4.0")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "11"
    }
}

val cucumberRuntime by configurations.creating {
    extendsFrom(configurations["testImplementation"])
}

task("cucumber") {
    dependsOn("assemble")
    dependsOn("compileTestJava")
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = cucumberRuntime + sourceSets.main.get().output + sourceSets.test.get().output
            args = listOf("--plugin", "pretty", "--glue", "gradle.cucumber", "src/test/resources")
        }
    }
}

</code>```

I saw this error https://github.com/square/okio/issues/647 that seems like it could be it and a fix with this build.gradle, how would I translate this to kotlin for a build.gradle.kts?

```<code>subprojects { subProject ->
  ...

  configurations.all { configuration ->
    // Workaround for kapt bug with MPP dependencies
    // https://youtrack.jetbrains.com/issue/KT-31641
    // https://youtrack.jetbrains.com/issue/KT-33206
    if (name.contains('kapt') || name.contains("wire")) {
      attributes.attribute(Usage.USAGE_ATTRIBUTE, subProject.objects.named(Usage.class, Usage.JAVA_RUNTIME))
    }
  }
</code>```

答:
It looks like this line is the key:

``` > Could not resolve all files for configuration ':cucumberRuntime'.```

In https://github.com/square/okio/issues/647, this is:

```> Could not resolve all task dependencies for configuration ':main:kapt'.```

So they used "kapt" as the name. In MonkeyBonkey's case, he will need to use:

```<code>configurations.all {
    if (name.contains("cucumberRuntime")) {
        attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class.java, Usage.JAVA_RUNTIME))
    }
}
</code>```

This worked for me with yet another name in my case: "productionRuntimeClasspath"

Title: Gradle Kotlin, Cucumber, and OKHttp

Body:
I'm trying to set up a spring boot project in Kotlin with OkHttp and Cucumber and getting the following error when running the cucumber task.  How do I fix?

Execution failed for task ':cucumber'.
> Could not resolve all files for configuration ':cucumberRuntime'.
   > Could not resolve com.squareup.okio:okio:2.4.1.
     Required by:
         project : > com.squareup.okhttp3:okhttp:4.3.1
      > Cannot choose between the following variants of com.squareup.okio:okio:2.4.1:
          - jvm-api
          - jvm-runtime
          - metadata-api
        All of them match the consumer attributes:
          - Variant 'jvm-api' capability com.squareup.okio:okio:2.4.1:
              - Unmatched attributes:
                  - Found org.gradle.libraryelements 'jar' but wasn't required.
                  - Found org.gradle.status 'release' but wasn't required.
                  - Found org.gradle.usage 'java-api' but wasn't required.
                  - Found org.jetbrains.kotlin.platform.type 'jvm' but wasn't required.
          - Variant 'jvm-runtime' capability com.squareup.okio:okio:2.4.1:
              - Unmatched attributes:
                  - Found org.gradle.libraryelements 'jar' but wasn't required.
                  - Found org.gradle.status 'release' but wasn't required.
                  - Found org.gradle.usage 'java-runtime' but wasn't required.
                  - Found org.jetbrains.kotlin.platform.type 'jvm' but wasn't required.
          - Variant 'metadata-api' capability com.squareup.okio:okio:2.4.1:
              - Unmatched attributes:
                  - Found org.gradle.status 'release' but wasn't required.
                  - Found org.gradle.usage 'kotlin-api' but wasn't required.
                  - Found org.jetbrains.kotlin.platform.type 'common' but wasn't required.

and the build gradle kts snippet

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.2.5.RELEASE"
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    kotlin("jvm") version "1.3.61"
    kotlin("plugin.spring") version "1.3.61"
}

group = "com.foo"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

val developmentOnly by configurations.creating
configurations {
    runtimeClasspath {
        extendsFrom(developmentOnly)
    }
    compileOnly {
        extendsFrom(configurations.annotationProcessor.get())
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

    compileOnly("org.projectlombok:lombok")
    developmentOnly("org.springframework.boot:spring-boot-devtools")
    annotationProcessor("org.projectlombok:lombok")

    implementation("com.squareup.okhttp3:okhttp:4.3.1")
    implementation("com.graphql-java-kickstart:graphql-spring-boot-starter:6.0.1")
    runtimeOnly("com.graphql-java-kickstart:graphiql-spring-boot-starter:6.0.1")
    runtimeOnly("com.graphql-java-kickstart:voyager-spring-boot-starter:6.0.1")

    testImplementation("io.cucumber:cucumber-java8:5.4.0")
    testImplementation("io.cucumber:cucumber-junit:5.4.0")
    testImplementation("org.springframework.boot:spring-boot-starter-test") {
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "11"
    }
}

val cucumberRuntime by configurations.creating {
    extendsFrom(configurations["testImplementation"])
}

task("cucumber") {
    dependsOn("assemble")
    dependsOn("compileTestJava")
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = cucumberRuntime + sourceSets.main.get().output + sourceSets.test.get().output
            args = listOf("--plugin", "pretty", "--glue", "gradle.cucumber", "src/test/resources")
        }
    }
}

I saw this error https://github.com/square/okio/issues/647 that seems like it could be it and a fix with this build.gradle, how would I translate this to kotlin for a build.gradle.kts?

subprojects { subProject ->
  ...

  configurations.all { configuration ->
    // Workaround for kapt bug with MPP dependencies
    // https://youtrack.jetbrains.com/issue/KT-31641
    // https://youtrack.jetbrains.com/issue/KT-33206
    if (name.contains('kapt') || name.contains("wire")) {
      attributes.attribute(Usage.USAGE_ATTRIBUTE, subProject.objects.named(Usage.class, Usage.JAVA_RUNTIME))
    }
  }

Body:
It looks like this line is the key:

 > Could not resolve all files for configuration ':cucumberRuntime'.

In https://github.com/square/okio/issues/647, this is:

> Could not resolve all task dependencies for configuration ':main:kapt'.

So they used "kapt" as the name. In MonkeyBonkey's case, he will need to use:

configurations.all {
    if (name.contains("cucumberRuntime")) {
        attributes.attribute(Usage.USAGE_ATTRIBUTE, objects.named(Usage::class.java, Usage.JAVA_RUNTIME))
    }
}

This worked for me with yet another name in my case: "productionRuntimeClasspath"


问:
Creating a div by pressing a button
I was trying to create Divs by clicking a button but it just fill the button range with red.

```<code><div class="app">
  <button onclick="createDiv()">Make a cube</button>
</div>
<script>

  function createDiv ()
  {
  var boxEle = document.querySelector('.app');
  boxEle.style.width = 100;
  boxEle.style.height = 100;
  boxEle.style.backgroundColor = '#f00';

  }
</script>
</code>```

答:
This should do it:</p>

```<code><div class="app">
  <button onclick="createDiv()">Make a cube</button>
</div>
<script>

function createDiv () {
    var boxEle = document.querySelector('.app');
    var newDiv = document.createElement('div');
    newDiv.style.width = 100;
    newDiv.style.height = 100;
    newDiv.style.margin = 5;
    newDiv.style.backgroundColor = '#f00';
    boxEle.appendChild(newDiv);
}
</script>
</code>```

Title: Creating a div by pressing a button

Body:
I was trying to create Divs by clicking a button but it just fill the button range with red.

  <button onclick="createDiv()">Make a cube</button>

Body:
This should do it:

<div class="app">
  <button onclick="createDiv()">Make a cube</button>
</div>
<script>

function createDiv () {
    var boxEle = document.querySelector('.app');
    var newDiv = document.createElement('div');
    newDiv.style.width = 100;
    newDiv.style.height = 100;
    newDiv.style.margin = 5;
    newDiv.style.backgroundColor = '#f00';
    boxEle.appendChild(newDiv);
}
</script>


问:
Android Retrofit - Unable to add response to a List / recyclerview
When I get my response.body() it will not allow me to set it to a List.

SAMPLE GSON:

```<code> {
"cod": "200",
"message": 0,
"cnt": 5,
"list": [
    {
        "dt": 1590861600,
        "main": {
            "temp": 17.74,
            "feels_like": 14.52,
            "temp_min": 15.99,
            "temp_max": 17.74,
            "pressure": 1022,
            "sea_level": 1022,
            "grnd_level": 1021,
            "humidity": 51,
            "temp_kf": 1.75
        },
        "weather": [
            {
                "id": 803,
                "main": "Clouds",
                "description": "broken clouds",
                "icon": "04d"
            }
        ],
        "clouds": {
            "all": 82
        },
        "wind": {
            "speed": 3.75,
            "deg": 124
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2020-05-30 18:00:00"
    },
</code>```

Class

```<code>public class WeatherResponse {

@SerializedName("cod")
@Expose
private String cod;
@SerializedName("message")
@Expose
private Long message;
@SerializedName("cnt")
@Expose
private Long cnt;
@SerializedName("list")
@Expose
private List<WeatherList> results;
@SerializedName("city")
@Expose
private City city;
</code>```

CODE

```<code>  private List<WeatherResponse> mWeatherResponseList;

  public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {

            Log.d(TAG, "onResponse: server response " + response.toString());

            // response code 200 means a successful request
            // if successful store the response body in the log
            if (response.code() == 200) {

              mWeatherResponseList = response.body();   --Throws an error
</code>```

The error states incompatible types: Required Java.util.list - Found WeatherResponse

I did this:

list = new ArrayList(Collections.singleton(((response.body())))); Which appears to have worked. But the problem now is the response has nested Json. Its one object with a list of 5 items. When I try to display the 5 items in the recyclerview it only displays the one object but not the nested list of 5 items which I actually want

答:
Try this
declare this arraylist like this

```<code>private List<WeatherList> mWeatherResponseList=new ArrayList();
</code>```

now in onResponse() use this

```<code>mWeatherResponseList = response.body().getResults();
</code>```

Body:
When I get my response.body() it will not allow me to set it to a List.

SAMPLE GSON:

 {
"cod": "200",
"message": 0,
"cnt": 5,
"list": [
    {
        "dt": 1590861600,
        "main": {
            "temp": 17.74,
            "feels_like": 14.52,
            "temp_min": 15.99,
            "temp_max": 17.74,
            "pressure": 1022,
            "sea_level": 1022,
            "grnd_level": 1021,
            "humidity": 51,
            "temp_kf": 1.75
        },
        "weather": [
            {
                "id": 803,
                "main": "Clouds",
                "description": "broken clouds",
                "icon": "04d"
            }
        ],
        "clouds": {
            "all": 82
        },
        "wind": {
            "speed": 3.75,
            "deg": 124
        },
        "sys": {
            "pod": "d"
        },
        "dt_txt": "2020-05-30 18:00:00"
    },

Class

public class WeatherResponse {

@SerializedName("cod")
@Expose
private String cod;
@SerializedName("message")
@Expose
private Long message;
@SerializedName("cnt")
@Expose
private Long cnt;
@SerializedName("list")
@Expose
private List<WeatherList> results;
@SerializedName("city")
@Expose
private City city;

CODE

  private List<WeatherResponse> mWeatherResponseList;

  public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {

            Log.d(TAG, "onResponse: server response " + response.toString());

            // response code 200 means a successful request
            // if successful store the response body in the log
            if (response.code() == 200) {

              mWeatherResponseList = response.body();   --Throws an error

The error states incompatible types: Required Java.util.list - Found WeatherResponse

I did this:

list = new ArrayList(Collections.singleton(((response.body())))); Which appears to have worked. But the problem now is the response has nested Json. Its one object with a list of 5 items. When I try to display the 5 items in the recyclerview it only displays the one object but not the nested list of 5 items which I actually want

Body:
Try this
declare this arraylist like this

private List<WeatherList> mWeatherResponseList=new ArrayList();

now in onResponse() use this

mWeatherResponseList = response.body().getResults();


问:
View contents of a dll
I am looking for a tool to view contents of a C# dll, preferably a free one. .Net Reflector used to be free but not anymore. It is an awesome tool and you can easily see all code down to the line. PE Explorer is another one I looked at but the Disassembler in it does not seem to output C# code. If you know any other tools, please share.
.Net reflector is the best one I know for the job, but just curious if there are any other options.</p>

答: DotPeek is awesome and free.</p>

Title: View contents of a dll

Body: DotPeek is awesome and free.


问:
Python to retrieve Outlook email user profile
Is there a way to read the Outlook user's profile information, for example job title, Department, telephone number, and reporting manager,  by given an email address?

For example I have 5 email address (internal user in the same company)

I want to quickly find out above information of each email user (probably with win32com?)

Thank you.

答:
You can use the following sequence of actions in the Outlook object model:

```<code>Recipient.AddressEntry.GetContact()
</code>```

The ContactItem class provides all the required properties you are interested in.

To get an instance of the Recipient class you need to use the CreateRecipient method of the Namespace class. For example, a sample VBA macro which shows how to use the method:

```<code>Sub ResolveName()
 Dim myNamespace As Outlook.NameSpace
 Dim myRecipient As Outlook.Recipient
 Dim CalendarFolder As Outlook.Folder
 Set myNamespace = Application.GetNamespace("MAPI")
 Set myRecipient = myNamespace.CreateRecipient("Eugene Astafiev") ' or email address
 myRecipient.Resolve
 If myRecipient.Resolved Then
  Call ShowCalendar(myNamespace, myRecipient)
 End If
End Sub

Sub ShowCalendar(myNamespace, myRecipient)
 Dim CalendarFolder As Folder
 Set CalendarFolder = _
 myNamespace.GetSharedDefaultFolder _
 (myRecipient, olFolderCalendar)
 CalendarFolder.Display
End Sub
</code>```

Body:
You can use the following sequence of actions in the Outlook object model:

Recipient.AddressEntry.GetContact()

The ContactItem class provides all the required properties you are interested in.

To get an instance of the Recipient class you need to use the CreateRecipient method of the Namespace class. For example, a sample VBA macro which shows how to use the method:

Sub ResolveName()
 Dim myNamespace As Outlook.NameSpace
 Dim myRecipient As Outlook.Recipient
 Dim CalendarFolder As Outlook.Folder
 Set myNamespace = Application.GetNamespace("MAPI")
 Set myRecipient = myNamespace.CreateRecipient("Eugene Astafiev") ' or email address
 myRecipient.Resolve
 If myRecipient.Resolved Then
  Call ShowCalendar(myNamespace, myRecipient)
 End If
End Sub

Sub ShowCalendar(myNamespace, myRecipient)
 Dim CalendarFolder As Folder
 Set CalendarFolder = _
 myNamespace.GetSharedDefaultFolder _
 (myRecipient, olFolderCalendar)
 CalendarFolder.Display
End Sub


问:
How to create such an element in Flutter?
I want to create such an element. But I'm still new to flutter. Can there be something similar?
I need the button and the text box (I don't know what it's called) to have States depending on which it changed color and the plus button turned on and off. The text changes in the first and second text boxes so they should stretch.
*The button and text box still need to be moved to the right side

答:
here is a working code, you can further change size and colors to satisfy your requirements

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _numberCounter = 0;
  var _clickCounter = 0;
  var _changeColor = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Material(
            elevation: 6.0,
            child: Row(children: <Widget>[
              Container(
                padding: EdgeInsets.all(8),
                child: Text(
                  '$_numberCounter',
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 20.0),
                ),
              ),
              Container(
                color: _changeColor ? Colors.green : Colors.grey,
                padding: const EdgeInsets.all(8.0),
                child: GestureDetector(
                    onTap: () => setState(() {
                          _changeColor = !_changeColor;
                          _numberCounter++;
                          _clickCounter++;
                        }),
                    child: Icon(Icons.add), color: Colors.white),
              ),
              Expanded(
                child: Text(
                  '$_clickCounter per click',
                  style: TextStyle(fontSize: 20.0),
                  textAlign: TextAlign.center,
                ),
              )
            ]),
          ),
        ),
      ),
    );
  }
}
```


问:
Does authlib support refresh my access token when using client credentials?
I'm new to authlib, and while checking on the documentation it mentions that it supports "auto-refresh" for password grant_type.

I was wondering if the library is able to detect when the currently associated token expired, while using client_credentials, and then request a new access token for me. (doing the whole OAuth dance for me)

It seems ugly to check for every call that I need to do, whether I got a 401 and then trigger the action of getting a new token.

Is there a best practice to follow here? can this be added as a decorator somehow?

答:
To add some flavour to the previous answer, I was able to get the refresh_token function to work for a recent API integration.

This had some peculiarities in that I had to pass the client_id and client_secret in the refresh_token call. I also had to set the grant_type. These may not be applicable to the API you're trying to use.

```<code>from authlib.integrations.requests_client import OAuth2Session

my_token = {'refresh_token':current_refresh_token,
            'access_token': current_access_token,
            'expires_at': current_access_token_expires_at,
            'expires_in': current_access_token_expires_in}

oauth_session = OAuth2Session(CLIENT_ID,CLIENT_SECRET,
                              authorization_endpoint=AUTH_ENDPOINT,
                              token_endpoint=TOKEN_ENDPOINT,
                              token=my_token,
                              grant_type='refresh_token')

    new_token = oauth_session.refresh_token(
                    url=REFRESH_TOKEN_URL,
                    client_id=CLIENT_ID,
                    client_secret=CLIENT_SECRET)
</code>```

Body:
To add some flavour to the previous answer, I was able to get the refresh_token function to work for a recent API integration.

This had some peculiarities in that I had to pass the client_id and client_secret in the refresh_token call. I also had to set the grant_type. These may not be applicable to the API you're trying to use.

from authlib.integrations.requests_client import OAuth2Session

my_token = {'refresh_token':current_refresh_token,
            'access_token': current_access_token,
            'expires_at': current_access_token_expires_at,
            'expires_in': current_access_token_expires_in}

oauth_session = OAuth2Session(CLIENT_ID,CLIENT_SECRET,
                              authorization_endpoint=AUTH_ENDPOINT,
                              token_endpoint=TOKEN_ENDPOINT,
                              token=my_token,
                              grant_type='refresh_token')

    new_token = oauth_session.refresh_token(
                    url=REFRESH_TOKEN_URL,
                    client_id=CLIENT_ID,
                    client_secret=CLIENT_SECRET)


问:
C++ Union, garbage value
For the following code

```<code>#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}
</code>```

the output is -858993567 a (MSVC) or 4201057 a(g++ MINGW).

but for

```<code>#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.a = 0;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}
</code>```

the output is 97 a

And these values are fixed under every circumstances (tried rebooting and creating new workspace/file, hence not garbage values).

So, why did the initialization (in the second case) made a difference?

I have tried it both on visual studio (using MSVC) and visual studio code (using g++).

Update 1
I checked on online IDE which probably use Linux g++, and they give the exact expected answer i.e., 97 a, in both the cases.

答:
Union is like type who can holds any type but this types musts be writed in definition of union, like this:

```<code>union Example {

    char a;
    std::int32_t b;

};

Example ex; /// Create object of union
ex.a = 'c'; /// At this moment a member is valid and b is invalid
std::cout << ex.b; /// This cause undefined behavior
</code>```

Be aware, size of union object is size of type who need most bytes. In this case size is same as size of b property.

Title: C++ Union, garbage value

Body:
For the following code

#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}

the output is -858993567 a (MSVC) or 4201057 a(g++ MINGW).

but for

#include <iostream>

using namespace std;

union type
{
    int a;
    char b ;
};

int main()
{
    type first;
    first.a = 0;
    first.b = 'a';
    cout << first.a << " " << first.b << endl;

}

the output is 97 a

And these values are fixed under every circumstances (tried rebooting and creating new workspace/file, hence not garbage values).

So, why did the initialization (in the second case) made a difference?

I have tried it both on visual studio (using MSVC) and visual studio code (using g++).

Update 1
I checked on online IDE which probably use Linux g++, and they give the exact expected answer i.e., 97 a, in both the cases.

Body:
Union is like type who can holds any type but this types musts be writed in definition of union, like this:

union Example {

    char a;
    std::int32_t b;

};

Example ex; /// Create object of union
ex.a = 'c'; /// At this moment a member is valid and b is invalid
std::cout << ex.b; /// This cause undefined behavior

Be aware, size of union object is size of type who need most bytes. In this case size is same as size of b property.


问:
How to change the text returned by DisplayFor in Razor Pages?
In MVC, I used a DescriptionAttribute to change the text returned by DisplayFor().

But I can't figure out how to do this in Razor Pages.

I tried:

```<code>[Description("Available Spots")]
public int? AvailableSpots {get; set; }
</code>```

And I tried:

```<code>builder.Entity<Location>()
    .Property(m => m.AvailableSpots)
    .HasComment("Available Spots");
</code>```

And still my column headers display as AvailableSpots.

It's frustrating how Core has taken away so many conveniences we had before. Does anyone know how to change the text returned by DisplayFor()?

答:
<pre class="lang-cs prettyprint-override"><code>[Display(Name = "Available Spots")]
public int? AvailableSpots {get; set; }
</code>```

Body:
In MVC, I used a DescriptionAttribute to change the text returned by DisplayFor().

But I can't figure out how to do this in Razor Pages.

I tried:

[Description("Available Spots")]
public int? AvailableSpots {get; set; }

And I tried:

builder.Entity<Location>()
    .Property(m => m.AvailableSpots)
    .HasComment("Available Spots");

And still my column headers display as AvailableSpots.

It's frustrating how Core has taken away so many conveniences we had before. Does anyone know how to change the text returned by DisplayFor()?


问:
Firebase Cloud Function, triggers onWrite method and getting problem in retrieving user data
This is the cloud function that triggers when data is changed,created or deleted.
Inside this function i have marked the code, in which i want to retreive the user token that is stored in another node of real time database with same id.As you can see in the real time database. But i am unable to fetch the token from the database. Kindly help me to fix this problem.

This is Structure of my realtime database.
 i want to get the token from the database in this cloud function

答:
The once() method is asynchronous and returns a Promise, but you don't wait this Promise resolves in order to get the value of the node.

Since you declare your Cloud Function as an async function, the following should do the trick

```<code>//...
const deviceTokenSnap = await admin.database().ref(`tokens/${userId}/token`).once('value');
const token = deviceTokenSnap.val();
//...
</code>```

In addition it is recommended to avoid mixing the use of async/await an then().

You should adapt the end of the function as follows:

```<code>const response = await admin.messaging().sendToDevice(...);
console.log(response);
return null;
</code>```

You should also use a try/catch block, see https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a

Finally, please avoid adding screenshots of your IDE, but copy/paste the code to your question.

Body:
The once() method is asynchronous and returns a Promise, but you don't wait this Promise resolves in order to get the value of the node.

Since you declare your Cloud Function as an async function, the following should do the trick

//...
const deviceTokenSnap = await admin.database().ref(`tokens/${userId}/token`).once('value');
const token = deviceTokenSnap.val();
//...

In addition it is recommended to avoid mixing the use of async/await an then().

You should adapt the end of the function as follows:

const response = await admin.messaging().sendToDevice(...);
console.log(response);
return null;

You should also use a try/catch block, see https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a

Finally, please avoid adding screenshots of your IDE, but copy/paste the code to your question.


问:
HSum up rows in a dataframe that have the same property in R
I hope this question hasn't been asked two often (first time user).

I have a data frame called data2003 and for simplicity I'll say it looks something like this:

```<code>ID   Weight   North   South
1    0.5      1       0
2    0.7      0       1
3    1.0      0       1
4    1.4      0       1
5    .95      1       0
6    1.1      1       0

</code>```

I want to add up the values in weight column that correspond to North and South dummy variables--so only include weight in the count when the North value in the same row is 1.

What I've done is make subsets for North and South:

```<code>subset2003N <- subset(data2003, data2003$North == 1 )
sum2003N <-sum(subset2003N$Weight)
</code>```

The problem is that I have 6 zones, not just north and south, and datasets for two other years. Is there a way to simply do this in one line of code without cluttering up my global environment with so many subsets?

答:
If North and South are mutually exclusive it would be best to have them as a single column. You could use reshape2 and dplyr to help you here:

```<code>library(reshape2)
library(dplyr)

melt(data2003, c("ID", "Weight")) %>%
  filter(value == 1) %>%
  group_by(variable) %>%
  summarize(Weight = sum(Weight))
#> # A tibble: 2 x 2
#>   variable Weight
#>   <fct>     <dbl>
#> 1 North      2.55
#> 2 South      3.10
</code>```

This solution should also work with your multiple zones. You would need to add any other measurement variables to the melt call in your actual data.

Body:
I hope this question hasn't been asked two often (first time user).

I have a data frame called data2003 and for simplicity I'll say it looks something like this:

ID   Weight   North   South
1    0.5      1       0
2    0.7      0       1
3    1.0      0       1
4    1.4      0       1
5    .95      1       0
6    1.1      1       0

I want to add up the values in weight column that correspond to North and South dummy variables--so only include weight in the count when the North value in the same row is 1.

What I've done is make subsets for North and South:

subset2003N <- subset(data2003, data2003$North == 1 )
sum2003N <-sum(subset2003N$Weight)

The problem is that I have 6 zones, not just north and south, and datasets for two other years. Is there a way to simply do this in one line of code without cluttering up my global environment with so many subsets?

Body:
If North and South are mutually exclusive it would be best to have them as a single column. You could use reshape2 and dplyr to help you here:

library(reshape2)
library(dplyr)

melt(data2003, c("ID", "Weight")) %>%
  filter(value == 1) %>%
  group_by(variable) %>%
  summarize(Weight = sum(Weight))
#> # A tibble: 2 x 2
#>   variable Weight
#>   <fct>     <dbl>
#> 1 North      2.55
#> 2 South      3.10

This solution should also work with your multiple zones. You would need to add any other measurement variables to the melt call in your actual data.


问:
Sequentially select parts of a string similar to ngram
Here is the problem I am trying to solve.

For example there is this string

```<code>my_string = 'jan feb mar'
</code>```

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

```<code>my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']
</code>```

What I tried is below and it is not what I want.

```<code>my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)
</code>```

Please help me out here. Thanks.

答:
Mark's way is best in my opinion, but here's another take on it for good measure. This works with the normal combinations of any length algorithm with a nested loop on the results to reorganize the output according to OP's spec. I'm returning a generator but most of the work is unfortunately up front.

I also moved the string manipulation to the caller. I don't see any reason to return anything but tuples which is a more flexible format than strings for this use case. The caller can always join the tuples as shown below (or do other useful things that serialization might prevent).

```<code>import itertools

def all_combs(L):
    combinations = [list(itertools.combinations(L, i + 1)) for i in range(len(L))]

    for i in range(len(L)):
        for j in range(len(combinations) - i):
            for comb in combinations[j][i+i*j:i+j+1]:
                yield comb

if __name__ == "__main__":
    print(list(map(" ".join, all_combs("jan feb mar".split()))))
</code>```

Output:

```<code>['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb', 'feb mar', 'mar']
</code>```

Body:
Here is the problem I am trying to solve.

For example there is this string

my_string = 'jan feb mar'

And I want to have sequentially generated items like this in a list.
It is always true that the words in a string are splittable with ' '.

my_function(my_string)
output = ['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb','feb mar','mar']

What I tried is below and it is not what I want.

my_string = "jan feb mar"
words_list = my_string.split(' ')
words = [' '.join(words_list[i:i+n]) for i in range(len(words_list) - n+1)]
words.extend(input_list)

Please help me out here. Thanks.

Body:
Mark's way is best in my opinion, but here's another take on it for good measure. This works with the normal combinations of any length algorithm with a nested loop on the results to reorganize the output according to OP's spec. I'm returning a generator but most of the work is unfortunately up front.

I also moved the string manipulation to the caller. I don't see any reason to return anything but tuples which is a more flexible format than strings for this use case. The caller can always join the tuples as shown below (or do other useful things that serialization might prevent).

import itertools

def all_combs(L):
    combinations = [list(itertools.combinations(L, i + 1)) for i in range(len(L))]

    for i in range(len(L)):
        for j in range(len(combinations) - i):
            for comb in combinations[j][i+i*j:i+j+1]:
                yield comb

if __name__ == "__main__":
    print(list(map(" ".join, all_combs("jan feb mar".split()))))

Output:

['jan', 'jan feb', 'jan mar', 'jan feb mar', 'feb', 'feb mar', 'mar']


问:
Stop all Pods in a StatefulSet before scaling it up or down
My team is currently working on migrating a Discord chat bot to Kubernetes. We plan on using a StatefulSet for the main bot service, as each Shard (pod) should only have a single connection to the Gateway. Whenever a shard connects to said Gateway, it tells it its ID (in our case the pod's ordinal index) and how many shards we are running in total (the amount of replicas in the StatefulSet).

Having to tell the gateway the total number of shards means that in order to scale our StatefulSet up or down we'd have to stop all pods in that StatefulSet before starting new ones with the updated value.

How can I achieve that? Preferrably through configuration so I don't have to run a special command each time.

答:
One way of doing this is,
Firstly get the YAML configuration of StatefulSets by running the below command and save it in a file:

```<code>kubectl get statefulset NAME -o yaml > sts.yaml
</code>```

And then delete the StatefulSets by running the below command:

```<code>kubectl delete -f sts.yaml
</code>```

And Finally, again create the StatefulSets by using the same configuration file which you got in the first step.

```<code>kubectl apply -f sts.yaml
</code>```

I hope this answers your query to only delete the StatefulSets and to create the new StatefulSets as well.

Body:
One way of doing this is,
Firstly get the YAML configuration of StatefulSets by running the below command and save it in a file:

kubectl get statefulset NAME -o yaml > sts.yaml

And then delete the StatefulSets by running the below command:

kubectl delete -f sts.yaml

And Finally, again create the StatefulSets by using the same configuration file which you got in the first step.

kubectl apply -f sts.yaml

I hope this answers your query to only delete the StatefulSets and to create the new StatefulSets as well.


问:
Insert data in json file
The code inserts wrong structure json into file</p>

```<code>import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json

urls = {}
urls['Av'] = {'Áa', 'Bb'}

data = {}
for key, value in urls.items():
    for x in value:

        url = 'https://www.google.pt/search?q=' + key + '%20' + x
        driver = webdriver.Chrome()
        driver.get(url)
        html = driver.page_source

        soup = BeautifulSoup(html, 'html.parser')
        a = soup.find("body")

        for child in a.find_all("div", {'class': 'g'}):
            h2 = child.find("span", {'class': 'Q8LRLc'})
            div = child.find("a", {'class': 'Fx4vi'})

        data[key] = []
        data[key].append({'h2': h2, 'div': div})
        print(data)

        with open("data_file.json", "a") as write_file:
            json.dump(data, write_file, indent=4)

        driver.quit()
</code>```

答:
I see a bunch of issues, most are things either being inside a loop when they should be outside, or outside when they should be in.

You set your variables h2 and div inside the loop for child in a.find_all("div", {'class': 'g'}):, but you add them to data outside the loop, so only the last values will be added.

Additionally, you initialize the data for each key inside the loop, and it should be done outside, or it will be re-initialized each time.

You also open the file to append to it each time, I'd just do it once.

And, you initialize your driver in every loop.

requests and selenium.webdriver.chrome.options.Options are both unused imports

So, I'd change it like this:

```<code>urls = {}
urls['Av'] = {'Áa', 'Bb'}

data = {}
driver = webdriver.Chrome()
with open("data_file.json", "a") as write_file:
    for key, value in urls.items():
        data[key] = []. # initialize only once per key

        for x in value:
            url = 'https://www.google.pt/search?q=' + key + '%20' + x
            driver.get(url)
            html = driver.page_source
            soup = BeautifulSoup(html, 'html.parser')
            a = soup.find("body")

            for child in a.find_all("div", {'class': 'g'}):
                h2 = child.find("span", {'class': 'Q8LRLc'})
                div = child.find("a", {'class': 'Fx4vi'})
                data[key].append({'h2': h2, 'div': div})  # update data for every h2/div found

    json.dump(data, write_file, indent=4) # This write can be done once, outside all loops!

driver.quit()
</code>```

A little hard for me to test, but hope that helps! Happy Coding!

Title: Insert data in json file

Body:
The code inserts wrong structure json into file

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json

urls = {}
urls['Av'] = {'Áa', 'Bb'}

data = {}
for key, value in urls.items():
    for x in value:

        url = 'https://www.google.pt/search?q=' + key + '%20' + x
        driver = webdriver.Chrome()
        driver.get(url)
        html = driver.page_source

        soup = BeautifulSoup(html, 'html.parser')
        a = soup.find("body")

        for child in a.find_all("div", {'class': 'g'}):
            h2 = child.find("span", {'class': 'Q8LRLc'})
            div = child.find("a", {'class': 'Fx4vi'})

        data[key] = []
        data[key].append({'h2': h2, 'div': div})
        print(data)

        with open("data_file.json", "a") as write_file:
            json.dump(data, write_file, indent=4)

        driver.quit()

Body:
I see a bunch of issues, most are things either being inside a loop when they should be outside, or outside when they should be in.

You set your variables h2 and div inside the loop for child in a.find_all("div", {'class': 'g'}):, but you add them to data outside the loop, so only the last values will be added.

Additionally, you initialize the data for each key inside the loop, and it should be done outside, or it will be re-initialized each time.

You also open the file to append to it each time, I'd just do it once.

And, you initialize your driver in every loop.

requests and selenium.webdriver.chrome.options.Options are both unused imports

So, I'd change it like this:

urls = {}
urls['Av'] = {'Áa', 'Bb'}

data = {}
driver = webdriver.Chrome()
with open("data_file.json", "a") as write_file:
    for key, value in urls.items():
        data[key] = []. # initialize only once per key

        for x in value:
            url = 'https://www.google.pt/search?q=' + key + '%20' + x
            driver.get(url)
            html = driver.page_source
            soup = BeautifulSoup(html, 'html.parser')
            a = soup.find("body")

            for child in a.find_all("div", {'class': 'g'}):
                h2 = child.find("span", {'class': 'Q8LRLc'})
                div = child.find("a", {'class': 'Fx4vi'})
                data[key].append({'h2': h2, 'div': div})  # update data for every h2/div found

    json.dump(data, write_file, indent=4) # This write can be done once, outside all loops!

driver.quit()

A little hard for me to test, but hope that helps! Happy Coding!


答:
Instead of

```<code>mbrNo = '1'  OR mbrNo = '-'
</code>```

you can say

```<code>mbrNo IN ('1', '-')
</code>```

Although those two expressions are identical, the change would have coincidentally fixed your problem.

The real "problem" is

```<code>a OR b AND c   means   a OR (b AND c)
</code>```

but you wanted

```<code>                       (a OR b) AND c
</code>```

See "precedence of operators".

Title: how to fix sql query?

Body:
In this noti_card_data my DB schema

  id      | date  |        cmd  |     mbrNo
--------------------------------------------
  1        2020-04-01      success    1
  2        2020-04-29      fail       -

I Want result

  id      | date  |        cmd  |     mbrNo
--------------------------------------------
  1        2020-04-01      success    1

But, sending a query like this results.

SELECT * FROM noti_card_data WHERE mbrNo = '1'  OR mbrNo = '-'  AND cmd ='success'

 id      | date  |        cmd  |     mbrNo
--------------------------------------------
  1        2020-04-01      success    1
  2        2020-04-29      fail       -

How to fix my query?

Body:
Instead of

mbrNo = '1'  OR mbrNo = '-'

you can say

mbrNo IN ('1', '-')

Although those two expressions are identical, the change would have coincidentally fixed your problem.

The real "problem" is

a OR b AND c   means   a OR (b AND c)

but you wanted

                       (a OR b) AND c

See "precedence of operators".


问:
How can I print all the products attributes in product.html
This is my models.py

```<code>class Product(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(blank=True, null=True)
    price = models.FloatField()
    summary = models.TextField(blank=False, null=False)
    image = models.ImageField(blank=True, null=True)
</code>```

This is my Django views.py

```<code>def products_view(request,*args, **kwargs):
    print(Product.objects.values())
    myDict = list()
    for product in Product.objects.all():
        my_product = {
        "product_id": product.id,
        "product_title":product.title,
        "product_description":product.description,
        "product_price":product.price,
        "product_summary":product.summary,
        "product_image":product.image
        }
        print(my_product)
    return render(request, "products.html", my_product)
</code>```

This my products.html

```<code>{% extends 'base.html' %}

{% block content %}
<h1>Products Page</h1>

<ul>
{% for product in my_product %}
<div class="card" style="width: 18rem;">
  <img src="{{ product_image }}" class="card-img-top" alt="{{ product_id }}">
  <div class="card-body">
    <h5 class="card-title">{{ product_title }}</h5>
    <p class="card-text">{{ product_description }}</p>
    <a href="/cart" class="btn btn-primary">Add to Basket</a>
  </div>
</div>
{% endfor %}
</ul>

{% endblock %}
</code>```

My Product.html page only show the "h1" tag, do not show the Products attributes. How can I achieve this problem?
Products.objects.all() gives me QuerySet and I tried to change into dict. but I cannot print the dict elements' attributes .

答:
The reason the for loop doesn't print out correctly is because my_product is not an iterable so the template cannot loop over it.

You will need to change this to be an iterable - like a list or queryset.

```<code>def products_view(request,*args, **kwargs):
    print(Product.objects.values())

    my_product = Product.objects.all()

    print(my_product)
    return render(request, "products.html", {'my_product': my_product})
</code>```

Now, in the template, you will be able to access the product attributes using dot notation.

```<code>{% for product in my_product %}
  <div class="card" style="width: 18rem;">
    <img src="{{ product.image }}" class="card-img-top" alt="{{ product.id }}">
    <div class="card-body">
      <h5 class="card-title">{{ product.title }}</h5>
      <p class="card-text">{{ product.description }}</p>
      <a href="/cart" class="btn btn-primary">Add to Basket</a>
    </div>
  </div>
{% endfor %}
</code>```

Body:
This is my models.py

class Product(models.Model):
    title = models.CharField(max_length=50)
    description = models.TextField(blank=True, null=True)
    price = models.FloatField()
    summary = models.TextField(blank=False, null=False)
    image = models.ImageField(blank=True, null=True)

This is my Django views.py

def products_view(request,*args, **kwargs):
    print(Product.objects.values())
    myDict = list()
    for product in Product.objects.all():
        my_product = {
        "product_id": product.id,
        "product_title":product.title,
        "product_description":product.description,
        "product_price":product.price,
        "product_summary":product.summary,
        "product_image":product.image
        }
        print(my_product)
    return render(request, "products.html", my_product)

This my products.html

{% extends 'base.html' %}

{% block content %}

Products Page

{% for product in my_product %}

{{ product_title }}

{{ product_description }}

    Add to Basket

{% endfor %}

{% endblock %}

My Product.html page only show the "h1" tag, do not show the Products attributes. How can I achieve this problem?
Products.objects.all() gives me QuerySet and I tried to change into dict. but I cannot print the dict elements' attributes .

Body:
The reason the for loop doesn't print out correctly is because my_product is not an iterable so the template cannot loop over it.

You will need to change this to be an iterable - like a list or queryset.

def products_view(request,*args, **kwargs):
    print(Product.objects.values())

    my_product = Product.objects.all()

    print(my_product)
    return render(request, "products.html", {'my_product': my_product})

Now, in the template, you will be able to access the product attributes using dot notation.

{% for product in my_product %}
  <div class="card" style="width: 18rem;">
    <img src="{{ product.image }}" class="card-img-top" alt="{{ product.id }}">
    <div class="card-body">
      <h5 class="card-title">{{ product.title }}</h5>
      <p class="card-text">{{ product.description }}</p>
      <a href="/cart" class="btn btn-primary">Add to Basket</a>
    </div>
  </div>
{% endfor %}


问:
Delete part of the string to the character encountered javascript
I would need to write a js function that would do this to me:

```<code>export const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';
</code>```

Normally it will be:

```<code>console.log(LOGIN_REQUEST); // app/LoginPage/LOGIN_REQUEST
</code>```

And I would need:

```<code>app/LoginPage/LOGIN
</code>```

I would like to cut the string to the first one I encountered _. How to do it using js?

答:
In Javascript, you can use the split function.

```<code>var data = "app/LoginPage/LOGIN_REQUEST".split("_");
console.log(data[0]); // app/LoginPage/LOGIN
</code>```

Body:
I would need to write a js function that would do this to me:

export const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';

Normally it will be:

console.log(LOGIN_REQUEST); // app/LoginPage/LOGIN_REQUEST

And I would need:

app/LoginPage/LOGIN

I would like to cut the string to the first one I encountered _. How to do it using js?

Body:
In Javascript, you can use the split function.

var data = "app/LoginPage/LOGIN_REQUEST".split("_");
console.log(data[0]); // app/LoginPage/LOGIN


问:
PL/SQL Oracle_home directory contents of listener.ora
I'm trying to write the contents of listener.ora to another file without hardcoding in the directory.

Originally it worked when I specified the directory as:

```<code>'C:\app\OracleDB11g\product\11.2.0\dbhome_1\NETWORK\ADMIN'
</code>```

But I don't want to hard-code because this script will be used different machines/DBs.

```<code>CREATE OR REPLACE DIRECTORY LISTENERDIR AS '%ORACLE_HOME%/NETWORK/ADMIN/';
declare
f utl_file.file_type;
fOUT utl_file.file_type;
s varchar2(200);
begin
f := utl_file.fopen('LISTENERDIR','listener.ora','R');
loop
    utl_file.get_line(f,s);
    fOUT := utl_file.fopen('OUTPUT','oraDBoutput.txt','A');
    utl_file.put_line(fOUT,s);
    utl_file.fclose(fOUT);
end loop;
exception
when NO_DATA_FOUND then
    utl_file.fclose(f);
end;
/

drop directory LISTENERDIR;
</code>```

I have tried using the other slashes, small caps, different variations such as \NETWORK\ADMIN, and even assigning a variable from the dbms_system.get_env() but no avail.

答:
```<code>CREATE OR REPLACE DIRECTORY LISTENERDIR AS
</code>```

'%ORACLE_HOME%/NETWORK/ADMIN/';

We cannot do this. We have to specify the absolute OS path when we create a directory object.  That's why it worked when you used the full path.  It's in the documentation.  Find out more.

If you really want to create the library dynamically you can do it like this:

```<code>SQL> conn / as sysdba
Connected.

SQL> declare
  2      l_home varchar2(255);
  3  begin
  4      dbms_system.get_env('ORACLE_HOME', l_home);
  5
  6      execute immediate 'create directory listenerdir as '''
  7          ||l_home||'\NETWORK\ADMIN''';
  8  end;
  9  /

PL/SQL procedure successfully completed.

SQL>
SQL> select directory_path
  2  from all_directories
  3  where directory_name = 'LISTENERDIR'
  4  /

DIRECTORY_PATH
--------------------------------------------------------------------------------
C:\app\oracle\product\11.1.0\db_1\NETWORK\ADMIN

SQL>
</code>```

DBMS_SYSTEM.GET_ENV() is guaranteed to return the correct directory for the $ORACLE_HOME used to start the instance; other methods are not.  Only the SYS user has rights on DBMS_SYSTEM by default, but then only the restricted accounts ought to have the CREATE ANY DIRECTORY privilege.

Not sure why you are using PL/SQL to do this.  I'm always in favour of using the database to do as much as possible, but this strikes me as an over-elaborate way of executing what is a simple OS copy.

Body:
I'm trying to write the contents of listener.ora to another file without hardcoding in the directory.

Originally it worked when I specified the directory as:

'C:\app\OracleDB11g\product\11.2.0\dbhome_1\NETWORK\ADMIN'

But I don't want to hard-code because this script will be used different machines/DBs.

CREATE OR REPLACE DIRECTORY LISTENERDIR AS '%ORACLE_HOME%/NETWORK/ADMIN/';
declare
f utl_file.file_type;
fOUT utl_file.file_type;
s varchar2(200);
begin
f := utl_file.fopen('LISTENERDIR','listener.ora','R');
loop
    utl_file.get_line(f,s);
    fOUT := utl_file.fopen('OUTPUT','oraDBoutput.txt','A');
    utl_file.put_line(fOUT,s);
    utl_file.fclose(fOUT);
end loop;
exception
when NO_DATA_FOUND then
    utl_file.fclose(f);
end;
/

drop directory LISTENERDIR;

I have tried using the other slashes, small caps, different variations such as \NETWORK\ADMIN, and even assigning a variable from the dbms_system.get_env() but no avail.

Body:
CREATE OR REPLACE DIRECTORY LISTENERDIR AS

'%ORACLE_HOME%/NETWORK/ADMIN/';

We cannot do this. We have to specify the absolute OS path when we create a directory object.  That's why it worked when you used the full path.  It's in the documentation.  Find out more.

If you really want to create the library dynamically you can do it like this:

SQL> conn / as sysdba
Connected.

SQL> declare
  2      l_home varchar2(255);
  3  begin
  4      dbms_system.get_env('ORACLE_HOME', l_home);
  5
  6      execute immediate 'create directory listenerdir as '''
  7          ||l_home||'\NETWORK\ADMIN''';
  8  end;
  9  /

PL/SQL procedure successfully completed.

SQL>
SQL> select directory_path
  2  from all_directories
  3  where directory_name = 'LISTENERDIR'
  4  /

DIRECTORY_PATH
--------------------------------------------------------------------------------
C:\app\oracle\product\11.1.0\db_1\NETWORK\ADMIN

SQL>

DBMS_SYSTEM.GET_ENV() is guaranteed to return the correct directory for the $ORACLE_HOME used to start the instance; other methods are not.  Only the SYS user has rights on DBMS_SYSTEM by default, but then only the restricted accounts ought to have the CREATE ANY DIRECTORY privilege.

Not sure why you are using PL/SQL to do this.  I'm always in favour of using the database to do as much as possible, but this strikes me as an over-elaborate way of executing what is a simple OS copy.