问:
TypeError 'Item' subject is no iterable
I wanted to associate Categories with Subjects and their description.

As I understand the error in items.html. I tried using for to display categories on the site that have a link to objects, but they describe them, but I got this error and don’t understand how to solve it.

views.py:

```<code>from django.shortcuts import render
from shop.models import Category, Item, Comment
from django.http import HttpResponseRedirect, Http404, HttpResponse

def mainpage(request):
    categorys = Category.objects.all().order_by('name')
    return render(request, 'shop/mainpage.html', {'categs':categorys})

def items(request, categ_id):
    try:
        itemss = Item.objects.get(id = categ_id)
    except:
        raise Http404("Not found")

    return render(request, 'shop/items.html', {'itemss':itemss})

def info(request, item_id):
    try:
        item = Item.objects.get(id = item_id)
    except:
        raise Http404("No one item is no found")

    return render(request, 'shop/info.html', {"item":item})
</code>```

models.py:

```<code>from django.db import models

class Category(models.Model):
    name = models.CharField(max_length = 20, unique = True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Категория"
        verbose_name_plural = "Категории"

class Item(models.Model):
    category = models.ForeignKey(Category, on_delete = models.CASCADE)
    name = models.CharField(max_length = 20, default = "Unknown")
    item_desc = models.TextField(default = "Empty")
    publish_date = models.DateTimeField(auto_now = True)
    price = models.CharField(max_length = 20, default = 0)
    quanty = models.CharField(max_length = 10000, default = 0)

    def __str__(self):
        return self.name + "  "

    class Meta:
        verbose_name = "Предмет"
        verbose_name_plural = "Предметы"

class Comment(models.Model):
    item = models.ForeignKey(Item, on_delete = models.CASCADE)
    author_name = models.CharField(max_length = 20, unique = True)
    comment_text = models.TextField(default = "Empty")
    publish_date = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.author_name + "  "

    class Meta:
        verbose_name = "Комментарий"
        verbose_name_plural = "Комментарии"
</code>```

mainpage.html:

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

{% block title %}TradeWithUs{% endblock%}
{% block content %}
    {% if categs %}
        {% for categ in categs %}
            <a href = "{% url 'shop:items' categ.id %}">{{categ.name}}</a></br>
        {% endfor %}
    {% else %}
        No one category was found ):
    {% endif %}
{% endblock %}
</code>```

items.html:

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

{% block title %}TradeWithUs{% endblock%}
{% block content %}
    {% if itemss %}
        {% for iteme in itemss %}
            <a href = "{% url 'shop:info' iteme.id %}">{{iteme.name}}</a></br>
        {% endfor %}
    {% else %}
        No one item was found ):
    {% endif %}
{% endblock %}
</code>```

info.html:

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

{% block title %}{{item.name}}{% endblock %}
{% block content %}
<div>
    <h2><p class="names">{{item.name}}</p></h2>
    <p class="description">{{item.item_desc}}</p>
    <p class = "numbers">Price {{item.price}} ║ Total  {{item.quanty}}</p>
    <hr>
    <em>{{item.publish_date}}</em>  <em>@all rights reserved</em>
</div>
{% endblock%}
</code>```

Here is the whole mistake.

I don’t understand why such an error occurred here, because before creating the categories, objects by reference translated to their description, but as soon as I added the categories, this error appeared

```<code>File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py", line 10, in items
    itemss = Item.objects.list(id = categ_id)
AttributeError: 'Manager' object has no attribute 'list'
[01/Jun/2020 13:24:28] "GET /mainpage/item_1 HTTP/1.1" 500 67313
Internal Server Error: /mainpage/item_1
Traceback (most recent call last):
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py", line 10, in items
    itemss = Item.objects.list(id = categ_id)
AttributeError: 'Manager' object has no attribute 'list'
[01/Jun/2020 13:26:57] "GET /mainpage/item_1 HTTP/1.1" 500 67313
C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 01, 2020 - 13:27:03
Django version 3.0.6, using settings 'Newsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /mainpage/item_1
Traceback (most recent call last):
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py", line 15, in items
    return render(request, 'shop/items.html', {'itemss':itemss})
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 309, in render
    return nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 165, in render
    values = list(values)
TypeError: 'Item' object is not iterable
</code>```

答:
Your issue is this:

```<code> itemss = Item.objects.get(id = categ_id)
</code>```

This is a single Item, and as such not iterable, so when you pass it to itemss and try and do this in the template:

```<code>{% for iteme in itemss %}
</code>```

You get the resulting error.

If you want to use only one item, lose the for loop. If You sometimes want to have multiple items in here and are using this template from other places as welll, then maybe instead of the get, use a filter - that should return an iterable for you.

Title: TypeError 'Item' subject is no iterable

Body:
I wanted to associate Categories with Subjects and their description.

As I understand the error in items.html. I tried using for to display categories on the site that have a link to objects, but they describe them, but I got this error and don’t understand how to solve it.

views.py:

from django.shortcuts import render
from shop.models import Category, Item, Comment
from django.http import HttpResponseRedirect, Http404, HttpResponse

def mainpage(request):
    categorys = Category.objects.all().order_by('name')
    return render(request, 'shop/mainpage.html', {'categs':categorys})

def items(request, categ_id):
    try:
        itemss = Item.objects.get(id = categ_id)
    except:
        raise Http404("Not found")

    return render(request, 'shop/items.html', {'itemss':itemss})

def info(request, item_id):
    try:
        item = Item.objects.get(id = item_id)
    except:
        raise Http404("No one item is no found")

    return render(request, 'shop/info.html', {"item":item})

models.py:

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length = 20, unique = True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Категория"
        verbose_name_plural = "Категории"

class Item(models.Model):
    category = models.ForeignKey(Category, on_delete = models.CASCADE)
    name = models.CharField(max_length = 20, default = "Unknown")
    item_desc = models.TextField(default = "Empty")
    publish_date = models.DateTimeField(auto_now = True)
    price = models.CharField(max_length = 20, default = 0)
    quanty = models.CharField(max_length = 10000, default = 0)

    def __str__(self):
        return self.name + "  "

    class Meta:
        verbose_name = "Предмет"
        verbose_name_plural = "Предметы"

class Comment(models.Model):
    item = models.ForeignKey(Item, on_delete = models.CASCADE)
    author_name = models.CharField(max_length = 20, unique = True)
    comment_text = models.TextField(default = "Empty")
    publish_date = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.author_name + "  "

    class Meta:
        verbose_name = "Комментарий"
        verbose_name_plural = "Комментарии"

mainpage.html:

{% extends 'base.html' %}

{% block title %}TradeWithUs{% endblock%}
{% block content %}
    {% if categs %}
        {% for categ in categs %}
            {{categ.name}}

        {% endfor %}
    {% else %}
        No one category was found ):
    {% endif %}
{% endblock %}

items.html:

{% extends 'base.html' %}

{% block title %}TradeWithUs{% endblock%}
{% block content %}
    {% if itemss %}
        {% for iteme in itemss %}
            {{iteme.name}}

        {% endfor %}
    {% else %}
        No one item was found ):
    {% endif %}
{% endblock %}

info.html:

{% extends 'base.html' %}

{% block title %}{{item.name}}{% endblock %}
{% block content %}

{{item.name}}

{{item.item_desc}}

Price {{item.price}} ║ Total  {{item.quanty}}

    {{item.publish_date}}  @all rights reserved

{% endblock%}

Here is the whole mistake.

I don’t understand why such an error occurred here, because before creating the categories, objects by reference translated to their description, but as soon as I added the categories, this error appeared

File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py", line 10, in items
    itemss = Item.objects.list(id = categ_id)
AttributeError: 'Manager' object has no attribute 'list'
[01/Jun/2020 13:24:28] "GET /mainpage/item_1 HTTP/1.1" 500 67313
Internal Server Error: /mainpage/item_1
Traceback (most recent call last):
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py", line 10, in items
    itemss = Item.objects.list(id = categ_id)
AttributeError: 'Manager' object has no attribute 'list'
[01/Jun/2020 13:26:57] "GET /mainpage/item_1 HTTP/1.1" 500 67313
C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 01, 2020 - 13:27:03
Django version 3.0.6, using settings 'Newsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /mainpage/item_1
Traceback (most recent call last):
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Rodion\Desktop\NewSite\Newsite\Newsite\apps\shop\views.py", line 15, in items
    return render(request, 'shop/items.html', {'itemss':itemss})
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 309, in render
    return nodelist.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\Rodion\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\defaulttags.py", line 165, in render
    values = list(values)
TypeError: 'Item' object is not iterable

Body:
Your issue is this:

 itemss = Item.objects.get(id = categ_id)

This is a single Item, and as such not iterable, so when you pass it to itemss and try and do this in the template:

{% for iteme in itemss %}

You get the resulting error.

If you want to use only one item, lose the for loop. If You sometimes want to have multiple items in here and are using this template from other places as welll, then maybe instead of the get, use a filter - that should return an iterable for you.


来源: stackexchange

问:
Binary Classification with char/string features
Im currently working on a binary classification problem with proteins. The goal is to figure out whether or not a mutation will change the proteins function from active to inactive.
The mutation can happen at 4 different but fixed places in the amino acid chain that makes up the protein. So my feature vector consists of a char code of length 4, where each char represents the amino acid at one of the 4 places where a mutation takes place. In total there are 21 possible amino acids.

My question is how would I turn this string of 4 chars into something numerical for my classification.
What i tried so far is turning each cahr into the ASCII decimal representing the capital letter for that char (e.g. A->65) but this gave me only mediocre results.

I found something about one hot encoding but I don't know how to use it since besides the information about 4 of the total 21 amino acids occur in the mutation also the position at which they occur is important in my case.

This is a sample of the training data:

答:
my feature vector consists of a char code of length 4..
  .. the position at which they occur is important in my case

Expand your four-character string into four one-character strings. This way there will be one feature per site (let's call them "S1", "S2", "S3" and "S4").

This way each protein site will be independent of other sites.

how would I turn this string of 4 chars into something numerical for my classification.

Simply apply one-hot-encoding to each of those one-character features. Assuming you're working in Scikit-Learn environment, you could use sklearn_pandas.DataFrameMapper or sklearn.compose.ColumnTransformer to perform this mapping:

```<code>mapper = DataFrameMapper([
  (["S1", "S2", "S3", "S4"], OneHotEncoder())
])
classifier = LogisticRegression()
pipeline = Pipeline([
  ("mapper", mapper),
  ("classifier", classifier)
])
pipeline.fit(X, y)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
my feature vector consists of a char code of length 4..
  .. the position at which they occur is important in my case

Expand your four-character string into four one-character strings. This way there will be one feature per site (let's call them "S1", "S2", "S3" and "S4").

This way each protein site will be independent of other sites.

how would I turn this string of 4 chars into something numerical for my classification.

Simply apply one-hot-encoding to each of those one-character features. Assuming you're working in Scikit-Learn environment, you could use sklearn_pandas.DataFrameMapper or sklearn.compose.ColumnTransformer to perform this mapping:

mapper = DataFrameMapper([
  (["S1", "S2", "S3", "S4"], OneHotEncoder())
])
classifier = LogisticRegression()
pipeline = Pipeline([
  ("mapper", mapper),
  ("classifier", classifier)
])
pipeline.fit(X, y)


问:
Installing modules in windows not in Anaconda
I installed anaconda and installed various modules in it. Later I uninstalled it but when I try to install packages in Python through command line, it says requirements already satisfied and doesn't install. I want to install modules in simple Python now not in anaconda. How to fix it? Also, if I have uninstalled anaconda, why do I get the requirements satisfied message?</p>

答:
I am not very clear what you are trying to achieve , but you can always install the packages in a new location , and point the Python script to the new locations.

Python -m pip install --target="New location" [package name]


问:
ASP.NET Core 1.1 compiling with C# dynamic Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
I'm using Visual Studio 2017 RC and started a new ASP.NET Core project targeting the full .NET Framework.

This line of code will not compile.

```<code> dynamic handler = _container.GetService(handlerType);

 if (handler == null) _logger.LogError("Can't find handler to handle " + cmd.GetType().Name);
</code>```

I get the following error

```<code>CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
</code>```

After some Googling it looks like this is because I'm missing the Microsoft.CSharp Assembly. There are plenty of people who have stumbled into his issue but not seemingly with .NET Core 1.1.

So I did this Install-Package Microsoft.CSharp and got version 4.3.0. My project still won't build.

If I add an Assembly Reference to Microsoft.CSharp (the GAC'd version) then it Compiles and runs.

Is this a Bug? I would have expected the NuGet package to fix this?

答: Just add the reference of Microsoft.CSharp.dll and your error will be removed.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm using Visual Studio 2017 RC and started a new ASP.NET Core project targeting the full .NET Framework.

This line of code will not compile.

 dynamic handler = _container.GetService(handlerType);

 if (handler == null) _logger.LogError("Can't find handler to handle " + cmd.GetType().Name);

I get the following error

CS0656  Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

After some Googling it looks like this is because I'm missing the Microsoft.CSharp Assembly. There are plenty of people who have stumbled into his issue but not seemingly with .NET Core 1.1.

So I did this Install-Package Microsoft.CSharp and got version 4.3.0. My project still won't build.

If I add an Assembly Reference to Microsoft.CSharp (the GAC'd version) then it Compiles and runs.

Is this a Bug? I would have expected the NuGet package to fix this?


问:
passing ArrayList as argument in safeArgs
I'm trying to pass an ArrayList<String> as an argument while using safeArgs. But when I select ArrayList from the list of serializable and build, it is throwing me these exceptions

```<code>One type argument expected for class ArrayList<E : Any!>
One type argument expected. Use 'ArrayList<*>' if you don't want to pass type arguments
</code>```

I get that I have to set the dataType for the ArrayList but I'm not able to do it nor do I have options while setting up the safeArgs from the Navigation graph screen.

In the Navigation graph XML, the code is generated as

```<code><argument
            android:name="teamsToAdd"
            app:argType="java.util.ArrayList" />
</code>```

is there a way to declare the dataType in the XML of the navigation graph?

答:
Try this:

```<code><argument
    android:name="teamsToAdd"
    app:argType="string[]" />
</code>```

You can also generate this by checking the Array option when generating an argument through the GUI:

As this will require a string array rather than a list, you can then convert your list to an array with:

```<code>parameterList.toTypedArray()
</code>```

And back from an array with:

```<code>receivedArray.toList()
</code>```

Body:
I'm trying to pass an ArrayList<String> as an argument while using safeArgs. But when I select ArrayList from the list of serializable and build, it is throwing me these exceptions

One type argument expected for class ArrayList<E : Any!>
One type argument expected. Use 'ArrayList<*>' if you don't want to pass type arguments

I get that I have to set the dataType for the ArrayList but I'm not able to do it nor do I have options while setting up the safeArgs from the Navigation graph screen.

In the Navigation graph XML, the code is generated as

<argument
            android:name="teamsToAdd"
            app:argType="java.util.ArrayList" />

is there a way to declare the dataType in the XML of the navigation graph?

Body:
Try this:

<argument
    android:name="teamsToAdd"
    app:argType="string[]" />

You can also generate this by checking the Array option when generating an argument through the GUI:

As this will require a string array rather than a list, you can then convert your list to an array with:

parameterList.toTypedArray()

And back from an array with:

receivedArray.toList()


问:
Using functional options instead of method
I tried the below, and it worked well:

package main

import "fmt"

type T interface {
}

type hashMap struct {
    m    map[T]T
    k    []T
}

func (h *hashMap) From(m map[T]T) {
    h.m = m
    h.k = make([]T, len(m))
    i := 0
    for key := range m {
        h.k[i] = key
        i++
    }
}

func main() {
    inv := new(hashMap)
    inv.From(map[T]T{"first": 1})
    fmt.Printf("%v", inv)
}
```

<p>The output was correct as expected:</p>

<pre class="lang-sh prettyprint-override"><code>&{map[first:1] [first]}
</code>```

I'm looking for a way where I can write:

inv := new(hashMap).from(map[T]T{"first": 1})
// instead of:
//  inv := new(hashMap)
//  inv.From(map[T]T{"first": 1})
```

<p>So, I re-wrote the code as below:</p>

<pre class="lang-golang prettyprint-override"><code>package main

import "fmt"

type T interface {
}

type hashMap struct {
    m    map[T]T
    k    []T
    from func(m map[T]T) hashMap    // <---- new
}

func from(m map[T]T) hashMap {        // <----- change of func signature
    h := new(hashMap)
    h.m = m
    h.k = make([]T, len(m))
    i := 0
    for key := range m {
        h.k[i] = key
        i++
    }
    return *h
}

func main() {
    inv := new(hashMap).from(map[T]T{"first": 1})
    fmt.Printf("%v", inv)
}
</code>```

But I got the below output:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x49c2c2]

goroutine 1 [running]:
main.main()
    d:/goplay/hashmap.go:55 +0xf2
exit status 2
```

Any idea how to get it done the way I'm looking for?

答:
You are very close to getting it! First, since you already create the hashMap in main() you don't need to create again in from().  Just delete line 14 and change the signature of from() like this:

```<code>func (h *hashMap) from(m map[T]T) hashMap {
</code>```

Also delete line 11 - in Go you don't need to declare a method of a type just define it.

Try it in the playground

Also it's idiomatic to build a slice using append:

```<code>func (h *hashMap) from(m map[T]T) hashMap {
    h.m = m
    h.k = make([]T, 0, len(m))
    for key := range m {
        h.k = append(h.k, key)
    }
    return *h
}
</code>```

Body:
I tried the below, and it worked well:

package main

import "fmt"

type T interface {
}

type hashMap struct {
    m    map[T]T
    k    []T
}

func (h *hashMap) From(m map[T]T) {
    h.m = m
    h.k = make([]T, len(m))
    i := 0
    for key := range m {
        h.k[i] = key
        i++
    }
}

func main() {
    inv := new(hashMap)
    inv.From(map[T]T{"first": 1})
    fmt.Printf("%v", inv)
}

The output was correct as expected:

&{map[first:1] [first]}

I'm looking for a way where I can write:

inv := new(hashMap).from(map[T]T{"first": 1})
// instead of:
//  inv := new(hashMap)
//  inv.From(map[T]T{"first": 1})

So, I re-wrote the code as below:

package main

import "fmt"

type T interface {
}

type hashMap struct {
    m    map[T]T
    k    []T
    from func(m map[T]T) hashMap    // <---- new
}

func from(m map[T]T) hashMap {        // <----- change of func signature
    h := new(hashMap)
    h.m = m
    h.k = make([]T, len(m))
    i := 0
    for key := range m {
        h.k[i] = key
        i++
    }
    return *h
}

func main() {
    inv := new(hashMap).from(map[T]T{"first": 1})
    fmt.Printf("%v", inv)
}

But I got the below output:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x49c2c2]

goroutine 1 [running]:
main.main()
    d:/goplay/hashmap.go:55 +0xf2
exit status 2

Any idea how to get it done the way I'm looking for?

Body:
You are very close to getting it! First, since you already create the hashMap in main() you don't need to create again in from().  Just delete line 14 and change the signature of from() like this:

func (h *hashMap) from(m map[T]T) hashMap {

Also delete line 11 - in Go you don't need to declare a method of a type just define it.

Try it in the playground

Also it's idiomatic to build a slice using append:

func (h *hashMap) from(m map[T]T) hashMap {
    h.m = m
    h.k = make([]T, 0, len(m))
    for key := range m {
        h.k = append(h.k, key)
    }
    return *h
}


问:
Merge two chunks into one
Sometimes I had to make more chunks in R markup to "fake" an output in R markup. As an example, since I found out printing a wordcloud2 in R markdown is basically not possible by calling the usual wordcloud2 function, I had to print it out on my pdf but letting it seem like the basic function did it.

```<code>```{r}
freq <- data.frame(names(freq),freq, row.names
                 = 1:length(freq))
library(wordcloud2)
```
```{r eval=FALSE}
wordcloud2(freq,color="random-light", backgroundColor = "grey")
```
```{r echo=FALSE, message=FALSE}
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq,color="random-light", backgroundColor = "grey")
saveWidget(hw,"1.html",selfcontained = F)
webshot::webshot("1.html","1.png",vwidth = 700, vheight = 500, delay =10)
```
</code>```

This is what I have done, in simple words I made a non visible chunk print the wordcloud instead of the "graphic" one.

This is the result:

I know that probably nobody would notice, but having the chunks visually separated is not very beautiful.

Is there a way to unify those two?

Thank you in advance.

答:
How about making the whole first chunk "fake", and then copying the parts that need to run into the second chunk?

```<code>```{r eval = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
wordcloud2(freq, color = "random-light", backgroundColor = "grey")
```

```{r echo = F, message = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq, color = "random-light", backgroundColor = "grey")
saveWidget(hw, "1.html", selfcontained = F)
webshot::webshot("1.html", "1.png", vwidth = 700, vheight = 500, delay = 10)
```
</code>```

Alternatively, if you want to avoid copying too much code, you could label the chunks and use the approach in this answer to print them together:

```<code>```{r load_data, echo = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
```

```{r make_wordcloud, eval = F, echo = F}
wordcloud2(freq, color = "random-light", backgroundColor = "grey")
```

```{r display_code, ref.label = c("load_data", "make_wordcloud"), eval = F}
```

```{r make_wordcloud_image, echo = F, message = F}
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq, color = "random-light", backgroundColor = "grey")
saveWidget(hw, "1.html", selfcontained = F)
webshot::webshot("1.html", "1.png", vwidth = 700, vheight = 500, delay = 10)
```
</code>```

Title: Merge two chunks into one

Body:
Sometimes I had to make more chunks in R markup to "fake" an output in R markup. As an example, since I found out printing a wordcloud2 in R markdown is basically not possible by calling the usual wordcloud2 function, I had to print it out on my pdf but letting it seem like the basic function did it.

```{r}
freq <- data.frame(names(freq),freq, row.names
                 = 1:length(freq))
library(wordcloud2)
```
```{r eval=FALSE}
wordcloud2(freq,color="random-light", backgroundColor = "grey")
```
```{r echo=FALSE, message=FALSE}
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq,color="random-light", backgroundColor = "grey")
saveWidget(hw,"1.html",selfcontained = F)
webshot::webshot("1.html","1.png",vwidth = 700, vheight = 500, delay =10)
```

This is what I have done, in simple words I made a non visible chunk print the wordcloud instead of the "graphic" one.

This is the result:

I know that probably nobody would notice, but having the chunks visually separated is not very beautiful.

Is there a way to unify those two?

Thank you in advance.

Body:
How about making the whole first chunk "fake", and then copying the parts that need to run into the second chunk?

```{r eval = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
wordcloud2(freq, color = "random-light", backgroundColor = "grey")
```

```{r echo = F, message = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq, color = "random-light", backgroundColor = "grey")
saveWidget(hw, "1.html", selfcontained = F)
webshot::webshot("1.html", "1.png", vwidth = 700, vheight = 500, delay = 10)
```

Alternatively, if you want to avoid copying too much code, you could label the chunks and use the approach in this answer to print them together:

```{r load_data, echo = F}
freq <- data.frame(sample(LETTERS, 100, replace = T),
                   freq = sample(1:100, 100, replace = T),
                   row.names = 1:100)
library(wordcloud2)
```

```{r make_wordcloud, eval = F, echo = F}
wordcloud2(freq, color = "random-light", backgroundColor = "grey")
```

```{r display_code, ref.label = c("load_data", "make_wordcloud"), eval = F}
```

```{r make_wordcloud_image, echo = F, message = F}
library(htmlwidgets)
webshot::install_phantomjs()
hw = wordcloud2(freq, color = "random-light", backgroundColor = "grey")
saveWidget(hw, "1.html", selfcontained = F)
webshot::webshot("1.html", "1.png", vwidth = 700, vheight = 500, delay = 10)
```


问:
Query and sort on nultiple collections based on time
Our application is planning to use MongoDB for reports.

Our reports are time-based (where the raw data is different events).

We were thinking of creating a separate collection for each day, so we will not need to query a whole large collection when we need to query,aggregate and sort events for a specific day only.

One question is whether this design makes sense.

Another question is what will happen if we need to aggregate and sort event over more than one collection - for one week for example.

Does MongoDB supports this? If it does - how should it be done so it will be efficient n terms of performance?

答:
We were thinking of creating a separate collection for each day, so we will not need to query a whole large collection when we need to query,aggregate and sort events for a specific day only.

  One question is whether this design makes sense.

While using proper indexes, mongoDB should not have problems with a very big collection.
You could read more here: MongoDB indexes

Another question is what will happen if we need to aggregate and sort event over more than one collection - for one week for example.

  Does MongoDB supports this? If it does - how should it be done so it will be efficient n terms of performance?

If you want to go your way, you could use aggregation pipelines and $facet to run multiple queries at once. However this could become a little tricky because you have to generate the collection names from your query parameters. Infact, i think this could be slower and more prone to errors. So i don't recomend this approach.


问:
What is the difference between ListView and SingleChildScrollView in Flutter?
I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

```<code>Scaffold
  body : ListView
    children : Padding/Container
</code>```

SingleChildScrollView:

```<code>Scaffold
  body : SingleChildScrollView
    child : Column
</code>```

答:
ListView, you would use, if you have a list of UI widgets to render, and the number of such widgets is dynamic.

For example: You need to only show a list of contacts on your screen and the list items are more or less similar (UI wise and category wise). Then you would use a Listview.

A SingleChildScrollView can be compared to "ScrollView" in Android. Suppose you have a lot of UI widgets (Buttons, InputFields, Cards, etc), and they start going out of the screen. In such cases, your widgets will overflow and you will start seeing warnings. To fix this, you wrap your UI widgets with a SingleChildScrollView.

For your usecase, "Recommended" section, ListView would be a good choice.

Body:
I have seen few examples using ListView as the main body element of Scaffold and in few tutorials, it's SingleChildScrollView. All that I understood is both allow some axis of scrolling based on the direction that is configured but cannot figure out when to use one over the other?

ListView:

Scaffold
  body : ListView
    children : Padding/Container

SingleChildScrollView:

Scaffold
  body : SingleChildScrollView
    child : Column


问:
How to set the output path of several visual C# projects
I have a solution that contains several c# projects and I would like to be able to set the output path and other properties on all the projects together in a single place. Property Sheets (vsprops) do not seem to be able available for C# projects and the $(SolutionDir) variable is ignored. Are there any other methods to set properties across several C# projects?

Update
By Following the information in the answer by Bas Bossink I was able to set the output path of several projects by creating a common csproj and importing it into the individual project. A few other points:

When building in Visual Studio if changes are made to the common project it is necessary to touch/reload any projects that reference it for the changes to be picked up.

Any properties which are also set in a individual project will override the common properties.

Setting $(SolutionDir) as the output path via the Visual Studio UI does not work as expected because the value is treated as a string literal rather than getting expanded. However, Setting $(SolutionDir) directly into the csproj file with a text editor works as expected.

答:
I would suggest you to use a build tool such as MSBuild or NAnt which would give you more flexibility on your builds. Basically the idea is to kick off a build using (in most cases) a single configurable build file.

I would personally recommend NAnt.

You could find an awesome tutorial on NAnt on JP Boodhoo's blog here

OwnerDisplayName: edobashira

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: edobashira

OwnerDisplayName: AB Kolan


问:
Performance issue when I try to attribute title to DropDownlist using jQuery
I am using below code to select all dropdowns using jQuery and attributing title value to it.

```<code>jq("select option").each(function () {
   jq(this).attr({ 'title': jq(this).html() });
});
</code>```

But the problem is if there are a huge number of values in DropDown it is taking lots of time to attribute title value.

How can I improve the performance of my code?

答:
Using this should increase performance as it acts on the direct object, rather than going through jQuery:

Option 1: increase jQuery performance

```<code>$('select > option').each(function() {
    this.title = this.text;
});
</code>```

Fiddle: http://jsfiddle.net/ZJaKF/

Option 2: use "vanilla Javascript"

Not using .each will increase performance as well, as internally the anonymous function has to be called each iteration. If you really want performance just use "vanilla" Javascript:

```<code>var options = document.getElementById('selectId').options,
    i = options.length;

while (--i > -1) options[i].title = options[i].text;
</code>```

Option 3: use server-side implentation

While outputting the form just set the title attribute to the contents of the option. This would be the fastest solution.

See here for a comparison of benchmarks using different techniques

Body:
I am using below code to select all dropdowns using jQuery and attributing title value to it.

jq("select option").each(function () {
   jq(this).attr({ 'title': jq(this).html() });
});

But the problem is if there are a huge number of values in DropDown it is taking lots of time to attribute title value.

How can I improve the performance of my code?

Body:
Using this should increase performance as it acts on the direct object, rather than going through jQuery:

Option 1: increase jQuery performance

$('select > option').each(function() {
    this.title = this.text;
});

Fiddle: http://jsfiddle.net/ZJaKF/

Option 2: use "vanilla Javascript"

Not using .each will increase performance as well, as internally the anonymous function has to be called each iteration. If you really want performance just use "vanilla" Javascript:

var options = document.getElementById('selectId').options,
    i = options.length;

while (--i > -1) options[i].title = options[i].text;

Option 3: use server-side implentation

While outputting the form just set the title attribute to the contents of the option. This would be the fastest solution.

See here for a comparison of benchmarks using different techniques


问:
Laravel Eloquent hasOneThrough Relation
I'm learning eloquent relationship on Laravel and i got question on the hasonethrough
by using the same table design as Laravel's docs

```<code>tables
mechanics (id, name)
cars (id, model, mechanic_id)
owners (id, name, car_id)
</code>```

then I define the relationship at the mechanic model to access car owner

```<code>class Mechanic extends Model
{
    public function carOwner() {
        return $this->hasOneThrough('App\Owner', 'App\Car');
    }
}
</code>```

this will return

```<code>array:4 [▼
  "id" => 1
  "name" => "Ricky"
  "car_id" => 1
  "laravel_through_key" => 1
]
</code>```

my question is can I get the car model using my hasOnethrough relation ?

答:
yes you can ....

in your Owner model setup the car relation

```<code>class Owner extends Model
{
    public function car() {
        return $this->belongsTo('App\Car','car_id');
    }
}
</code>```

then you could use those relations like this:

```<code>$value=Mechanic::find($mechanic_id)->with('carOwner.car')->get();
</code>```

the $value will hold the car owner with his car

Title: Laravel Eloquent hasOneThrough Relation

Body:
I'm learning eloquent relationship on Laravel and i got question on the hasonethrough
by using the same table design as Laravel's docs

tables
mechanics (id, name)
cars (id, model, mechanic_id)
owners (id, name, car_id)

then I define the relationship at the mechanic model to access car owner

class Mechanic extends Model
{
    public function carOwner() {
        return $this->hasOneThrough('App\Owner', 'App\Car');
    }
}

this will return

array:4 [▼
  "id" => 1
  "name" => "Ricky"
  "car_id" => 1
  "laravel_through_key" => 1
]

my question is can I get the car model using my hasOnethrough relation ?

Body:
yes you can ....

in your Owner model setup the car relation

class Owner extends Model
{
    public function car() {
        return $this->belongsTo('App\Car','car_id');
    }
}

then you could use those relations like this:

$value=Mechanic::find($mechanic_id)->with('carOwner.car')->get();

the $value will hold the car owner with his car


问:
Is there a way to tracking and upload file and folder to S3 with c#?
I want to upload a folder with subfolder and files to S3. At the same, I want to track the process. I can get the files to upload and track the process. However, it only uploads the files, no subfolder if the files are in subfolder.

For example:

```<code>C:\backup
  backup\testfile1.txt
  backup\test\
  Backup\test\testfile2.txt
</code>```

The result after I uploaded to AWS:

```<code> Testfile1.txt
 Testfile2.txt
</code>```

What I want is:

```<code>Testfile1.txt
Test\testfile2.txt

     static void Main(string[] args)
        {
            var credentials = new BasicAWSCredentials("keyID", "secrectKey");
            s3Client = new AmazonS3Client(credentials, bucketRegion);
            TrackMPUAsync().Wait();

        }

        private static async Task TrackMPUAsync()
        {
            string[] files = Directory.GetFileSystemEntries(sourcePath, "*", SearchOption.AllDirectories);
           // string[] directories = Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories);

            try
            {
                var fileTransferUtility = new TransferUtility(s3Client);

                // Use TransferUtilityUploadRequest to configure options.
                // In this example we subscribe to an event.
                foreach(string ss in files)
                {
                    Console.WriteLine(ss);

                        var uploadRequest =
                    new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        FilePath = ss,

                    };

                        uploadRequest.UploadProgressEvent +=
                            new EventHandler<UploadProgressArgs>
                                (uploadRequest_UploadPartProgressEvent);

                        await fileTransferUtility.UploadAsync(uploadRequest);
                        Console.WriteLine("Upload " + ss + " completed");

                }

            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }

        static void uploadRequest_UploadPartProgressEvent(object sender, UploadProgressArgs e)
        {
            // Process event.
            Console.WriteLine("{0}/{1}", e.TransferredBytes, e.TotalBytes);
        }
</code>```

答:
Amazon S3 does not actually use folders or directories.

Instead, the Key (effectively the filename) of an object contains contain the full path of the object.

Therefore, the file should be called Test/testfile2.txt when it is stored in S3.

The Amazon S3 management console will make it 'look' like there are folders, but they aren't actually there.

For example, you could upload an object to folder1/folder2/foo.txt and it will 'appear' as though S3 has created the two folders, but if the object is deleted, the folders will also disappear.

Therefore, you should change your code so that the Key contains the full path of the object as you would like it in the Amazon S3 bucket.

Body:
I want to upload a folder with subfolder and files to S3. At the same, I want to track the process. I can get the files to upload and track the process. However, it only uploads the files, no subfolder if the files are in subfolder.

For example:

C:\backup
  backup\testfile1.txt
  backup\test\
  Backup\test\testfile2.txt

The result after I uploaded to AWS:

 Testfile1.txt
 Testfile2.txt

What I want is:

Testfile1.txt
Test\testfile2.txt

     static void Main(string[] args)
        {
            var credentials = new BasicAWSCredentials("keyID", "secrectKey");
            s3Client = new AmazonS3Client(credentials, bucketRegion);
            TrackMPUAsync().Wait();

        }

        private static async Task TrackMPUAsync()
        {
            string[] files = Directory.GetFileSystemEntries(sourcePath, "*", SearchOption.AllDirectories);
           // string[] directories = Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories);

            try
            {
                var fileTransferUtility = new TransferUtility(s3Client);

                // Use TransferUtilityUploadRequest to configure options.
                // In this example we subscribe to an event.
                foreach(string ss in files)
                {
                    Console.WriteLine(ss);

                        var uploadRequest =
                    new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        FilePath = ss,

                    };

                        uploadRequest.UploadProgressEvent +=
                            new EventHandler<UploadProgressArgs>
                                (uploadRequest_UploadPartProgressEvent);

                        await fileTransferUtility.UploadAsync(uploadRequest);
                        Console.WriteLine("Upload " + ss + " completed");

                }

            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
            }
        }

        static void uploadRequest_UploadPartProgressEvent(object sender, UploadProgressArgs e)
        {
            // Process event.
            Console.WriteLine("{0}/{1}", e.TransferredBytes, e.TotalBytes);
        }


问:
how to get max time from a report
i want to filter my report and only show that row which has maximum time
 first i use

enddate = fr.First().EndDate

but it given me first value occured not the maximum time
i try to use

endDate = fr.Max().EndDate

but failed.

答:
If you only want to get the max date, you can use LINQ Max method. This is similar to what you tried - but you need to pass in the property that you want to compare to get its Max value.

```<code>fr.Max(x => x.EndDate);
</code>```

Using Max instead of OrderByDescending has performance benefits since you only grab the max value from the list and avoid sorting the whole list.

If you want to get the whole object with the maximum EndDate, check this answer: How to perform .Max() on a property of all objects in a collection and return the object with maximum value - it has multiple approaches to solving your problem.

Title: how to get max time from a report

Body:
If you only want to get the max date, you can use LINQ Max method. This is similar to what you tried - but you need to pass in the property that you want to compare to get its Max value.

fr.Max(x => x.EndDate);

Using Max instead of OrderByDescending has performance benefits since you only grab the max value from the list and avoid sorting the whole list.

If you want to get the whole object with the maximum EndDate, check this answer: How to perform .Max() on a property of all objects in a collection and return the object with maximum value - it has multiple approaches to solving your problem.


问:
Fulltext Search with InnoDB
I'm developing a high-volume web application, where part of it is a MySQL database of discussion posts that will need to grow to 20M+ rows, smoothly.

I was originally planning on using MyISAM for the tables (for the built-in fulltext search capabilities), but the thought of the entire table being locked due to a single write operation makes me shutter. Row-level locks make so much more sense (not to mention InnoDB's other speed advantages when dealing with huge tables). So, for this reason, I'm pretty determined to use InnoDB.

The problem is... InnoDB doesn't have built-in fulltext search capabilities.

Should I go with a third-party search system? Like Lucene(c++) / Sphinx? Do any of you database ninjas have any suggestions/guidance? LinkedIn's zoie (based off Lucene) looks like the best option at the moment... having been built around realtime capabilities (which is pretty critical for my application.) I'm a little hesitant to commit yet without some insight...

(FYI: going to be on EC2 with high-memory rigs, using PHP to serve the frontend)

答:
For anyone stuck on an older version of MySQL / MariaDB (i.e. CentOS users) where InnoDB doesn't support Fulltext searches, my solution when using InnoDB tables was to create a separate MyISAM table for the thing I wanted to search.

For example, my main InnoDB table was products with various keys and referential integrity.  I then created a simple MyISAM table called product_search containing two fields, product_id and product_name where the latter was set to a FULLTEXT index. Both fields are effectively a copy of what's in the main product table.

I then search on the MyISAM table using fulltext, and do an inner join back to the InnoDB table.

The contents of the MyISAM table can be kept up-to-date via either triggers or the application's model.

I wouldn't recommend this if you have multiple tables that require fulltext, but for a single table it seems like an adequate work around until you can upgrade.

Title: Fulltext Search with InnoDB


问:
Bootstrap3 Image Below Caption, Rescale Image To Fit
I'm creating a simple carousel with HTML and JS. I have it mostly how I want it to look now, unfortunately there are a few issues:

Running The Snippet:

1) I want the caption to be in the space below the image, not on it. I've done what I can with CSS based on my minor skills and can't figure it out.

2) Also, I want the pictures resized and centred so the fit into the carousel, instead of most of it being cropped out.

Carousel Juts Out

1) I've made the website responsive, and the container has style="text-align:center;text-align: justify;". However if you look at the image below, in some cases when the browser window is minimised,the carousel juts out. How do I resolve this?

.carousel-caption {
  position: relative;
  left: auto;
  top: auto;
  bottom: -95px;
}

.carousel-inner {
  overflow: visible;
  padding-bottom: 95px;
}

#serviceSlider .item {
  height: 400px;
}

#slide1{
  background:url('https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg'); center no-repeat;
}

#slide2{
  background:url('https://cdn.pixabay.com/photo/2017/02/20/18/03/cat-2083492_960_720.jpg'); center no-repeat;
}

#slide3{
  background:url('https://cdn.pixabay.com/photo/2018/05/09/22/44/piglet-3386356_960_720.jpg'); center no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <style>
    .carousel-inner>.item>img,
    .carousel-inner>.item>a>img {
      width: 100%;
      margin: auto;
    }
  </style>

    <div class="container" style="text-align:center;text-align: justify;">
      <br>
      <div id="serviceSlider" class="carousel slide" data-ride="carousel">
        <!-- Indicators -->
        <ol class="carousel-indicators">
          <li data-target="#serviceSlider" data-slide-to="0" class="active"></li>
          <li data-target="#serviceSlider" data-slide-to="1"></li>
          <li data-target="#serviceSlider" data-slide-to="2"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox">
          <div class="item active" id="slide1">
            <div class="carousel-caption">
              <h3>Dog</h3>
              <p>Cute Corgi.</p>
            </div>
          </div>

          <div class="item" id="slide2">
            <div class="carousel-caption">
              <h3>Cat</h3>
              <p>Cute cat.</p>
            </div>
          </div>

          <div class="item" id="slide3">
            <div class="carousel-caption">
              <h3>Pigs</h3>
              <p>Sleepy pigs.</p>
            </div>
          </div>

        </div>

        <!-- Left and right controls -->

          <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>

          <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
          <span class="sr-only">Next</span>

      </div>
    </div></code>```

答:
You don't have to do much just make some changes in class of caption carousel. Try copy and pasting to see if it works. No additional changes in css.</p>

```<code><div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <div class="carousel-item active">
            <img src="https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg" class="d-block w-100" alt="...">
            <div class="text-center d-none d-md-block">
                <h5>First slide label</h5>
                <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
            </div>
        </div>
        <div class="carousel-item">
            <img src="https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg" class="d-block w-100" alt="...">
            <div class="text-center d-none d-md-block">
                <h5>Second slide label</h5>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            </div>
        </div>
        <div class="carousel-item">
            <img src="https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg" class="d-block w-100" alt="...">
            <div class="text-center d-none d-md-block">
                <h5>Third slide label</h5>
                <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
            </div>
        </div>
    </div>
    <a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
    </a>
</div>
</code>```

Body:
I'm creating a simple carousel with HTML and JS. I have it mostly how I want it to look now, unfortunately there are a few issues:

Running The Snippet:

1) I want the caption to be in the space below the image, not on it. I've done what I can with CSS based on my minor skills and can't figure it out.

2) Also, I want the pictures resized and centred so the fit into the carousel, instead of most of it being cropped out.

Carousel Juts Out

1) I've made the website responsive, and the container has style="text-align:center;text-align: justify;". However if you look at the image below, in some cases when the browser window is minimised,the carousel juts out. How do I resolve this?

.carousel-caption {
  position: relative;
  left: auto;
  top: auto;
  bottom: -95px;
}

.carousel-inner {
  overflow: visible;
  padding-bottom: 95px;
}

#serviceSlider .item {
  height: 400px;
}

#slide1{
  background:url('https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg'); center no-repeat;
}

#slide2{
  background:url('https://cdn.pixabay.com/photo/2017/02/20/18/03/cat-2083492_960_720.jpg'); center no-repeat;
}

#slide3{
  background:url('https://cdn.pixabay.com/photo/2018/05/09/22/44/piglet-3386356_960_720.jpg'); center no-repeat;
}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

Dog

Cute Corgi.

Cat

Cute cat.

Pigs

Sleepy pigs.

          Previous

          Next

Body:
You don't have to do much just make some changes in class of caption carousel. Try copy and pasting to see if it works. No additional changes in css.

<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        <div class="carousel-item active">
            <img src="https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg" class="d-block w-100" alt="...">
            <div class="text-center d-none d-md-block">
                <h5>First slide label</h5>
                <p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
            </div>
        </div>
        <div class="carousel-item">
            <img src="https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg" class="d-block w-100" alt="...">
            <div class="text-center d-none d-md-block">
                <h5>Second slide label</h5>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
            </div>
        </div>
        <div class="carousel-item">
            <img src="https://cdn.pixabay.com/photo/2020/03/31/19/20/dog-4988985_960_720.jpg" class="d-block w-100" alt="...">
            <div class="text-center d-none d-md-block">
                <h5>Third slide label</h5>
                <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
            </div>
        </div>
    </div>
    <a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev">
        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next">
        <span class="carousel-control-next-icon" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
    </a>
</div>


问:
How to extract href link title with selenium?
I am having issues figuring out how to extract all 100 of the link titles on the page with selenium. I have the code to extract only the links but how would I go about doing the same but for the link titles? Any help would be appreciated, thanks!

What I have:

```<code>from selenium import webdriver
driver = webdriver.Chrome('/Users/wwds/Downloads/chromedriver')
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')

elems = driver.find_elements_by_css_selector(".ndm-result-title [href]")
links = [elem.get_attribute('href') for elem in elems]
</code>```

答:
Try find the element with xpath, and get the title by .text like below:

```<code>driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')
elems = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//details[@id='all']//a[@target]")))
links = [elem.text for elem in elems]
</code>```

Following import:

```<code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
I am having issues figuring out how to extract all 100 of the link titles on the page with selenium. I have the code to extract only the links but how would I go about doing the same but for the link titles? Any help would be appreciated, thanks!

What I have:

from selenium import webdriver
driver = webdriver.Chrome('/Users/wwds/Downloads/chromedriver')
driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')

elems = driver.find_elements_by_css_selector(".ndm-result-title [href]")
links = [elem.get_attribute('href') for elem in elems]

Body:
Try find the element with xpath, and get the title by .text like below:

driver.get('https://www150.statcan.gc.ca/n1/en/type/data?count=100')
elems = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//details[@id='all']//a[@target]")))
links = [elem.text for elem in elems]

Following import:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


问:
Sharing Resource (Resx) file as a linked item in different projects across solution
I have a solution named 'MyApplication' with two projects:

ProjectA (namespace MyApplication.ProjectA) {.Net Core 2.1}
ProjectB (namespace MyApplication.ProjectB) {.Net Core 2.1 Test Project}

ProjectA contains a resource file named 'Messages.resx'.

I have Messages.resx Add As Link in ProjectB and whenever I am reading value from Messages.resx in ProjectB it is throwing System.Resources.MissingManifestResourceException.
I don't want to directly reference ProjectA inside ProjectB. Also adding a third library project with Resource file in it and referring it in both ProjectA and ProjectB is not an option.
How can I add resource as Add As Link and consume it?

答:
For example, I have two mvc projects: WebApplication1 and WebApplication3.

And I have a Resource file(MyData.resx) in WebApplication3:

MyData.resx:

Now, based on your needs, I have MyData.resx Add as link in WebApplication1:

Then, I can get the data from the .rexs file in WebApplication1 controller like below:

```<code> public IActionResult Index()
    {
        var rm = new ResourceManager("WebApplication1.Resources.MyData", Assembly.GetExecutingAssembly());
        string username = rm.GetString("Username");
        return View();
    }
</code>```

Result:

Note: the baseName in the ResourceManager should be the current project namespace.

Body:
For example, I have two mvc projects: WebApplication1 and WebApplication3.

And I have a Resource file(MyData.resx) in WebApplication3:

MyData.resx:

Now, based on your needs, I have MyData.resx Add as link in WebApplication1:

Then, I can get the data from the .rexs file in WebApplication1 controller like below:

 public IActionResult Index()
    {
        var rm = new ResourceManager("WebApplication1.Resources.MyData", Assembly.GetExecutingAssembly());
        string username = rm.GetString("Username");
        return View();
    }

Result:

Note: the baseName in the ResourceManager should be the current project namespace.


问:
How to check if a image has any text or not?
I'm looking for a simple solution that would return a boolean if ANY kind of English text is present in an image file. I wish to use this to detect memes. For example, the following file should be detected as an image with text.

I've come across elaborate machine learning techniques using OpenCV but I haven't been able to fully implement it. Is there any quicker, simpler, and just as effective solution for this?

I look forward to your valuable feedback!

答:
You can use OpenCV and pytesseract to perform your task.

```<code>import cv2
import pytesseract
img = cv2.imread('YOUR_IMAGE_PATH')
text = pytesseract.image_to_string(img)
print(text)
</code>```

Body:
You can use OpenCV and pytesseract to perform your task.

import cv2
import pytesseract
img = cv2.imread('YOUR_IMAGE_PATH')
text = pytesseract.image_to_string(img)
print(text)


问:
stdout and need to flush it C++
I have some C++ code that uses cout statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush(); at the end.

I don't quite understand why this flush operation is needed.

Anyone have any insight?

答: Is the data that isn't automatically getting flushed lacking a \n at the end? By default, standard out doesn't get delivered until a carriage return is seen.

Title: stdout and need to flush it C++


问:
Can FIWARE context providers be used for historical data with QuantumLeap?
FIWARE offers using context providers to fetch data from external sources for entities that are queried through the context broker.

With QuantumLeap, historical data can be stored in a time series database such as CrateDB.

Is it possible to combine these two concepts? When querying for historical data in a QuantumLeap setup, could some data instead be fetched from another database via a registered context provider (or a similar proxy implementation)? Preferably using out-of-the-box FIWARE components without too much custom magic.

答: You can always send the information to the QuantumLeap using the proper protocol. For this purpose, inside the FIWARE Ecosystem we have defined the IoT Agents to translate the common transport protocols and payload formats towards NGSI protocol. Additionally, there is other component, FIWARE Draco that could be used in order to translate the information from one DB to other. In case of QuantumLeap, and also any other FIWARE component, the normal way of working is through subscription to the source of data and this is the major reason why we put always in the architectures the FIWARE Orion Context Broker, whose purpose is to notify subscribers any update in the context information.</p>


问:
J7 Prime SamsungExperienceServices keeps stopping
Samsung J7 Prime always give an error saying Samsung Experience Services keeps stopping

答: I faced this difficulty last couple of days and found the solution. Go to play store and type "Samsung Experience Service". Then select uninstall. store will ask to update. do update and restart your smart phone and then.... enjoy!!!</p>


问:
How to get the minimum deployment target in the xcode project
I want to retrieve the minimum deployment target in the xcode project.
IPHONEOS_DEPLOYMENT_TARGET = 13.2;
I wanted to check whether the version is 13.2 or lesser.
Is there any way or any command which returns the deployment target.
I want to read it from the ruby code.</p>

答:
you can check the target version by below code and perform your desired action

In Swift:

```<code>    if #available(iOS 13.2, *) {
        // your code for iOS 13.2 or above versions
    } else {
        // Fallback on earlier versions or your code for earlier versions
    }
</code>```

In Objective C:

```<code>    if (@available(iOS 13.2, *)) {
        // your code for iOS 13.2 or above versions
     } else {
        // Fallback on earlier versions or your code for earlier versions
     }
</code>```

In Ruby:

Using the plist gem, like this:

```<code>require 'plist'
info = Plist.parse_xml('path/to/Info.plist')
puts info["CFBundleShortVersionString"]
puts info["CFBundleVersion"]
</code>```

Use this reference: How to get target's version by Ruby (or Xcodeproj)

also, https://www.rubydoc.info/gems/xcodeproj/Xcodeproj/Project/Object/XCConfigurationList

Body:
you can check the target version by below code and perform your desired action

In Swift:

    if #available(iOS 13.2, *) {
        // your code for iOS 13.2 or above versions
    } else {
        // Fallback on earlier versions or your code for earlier versions
    }

In Objective C:

    if (@available(iOS 13.2, *)) {
        // your code for iOS 13.2 or above versions
     } else {
        // Fallback on earlier versions or your code for earlier versions
     }

In Ruby:

Using the plist gem, like this:

require 'plist'
info = Plist.parse_xml('path/to/Info.plist')
puts info["CFBundleShortVersionString"]
puts info["CFBundleVersion"]

Use this reference: How to get target's version by Ruby (or Xcodeproj)

also, https://www.rubydoc.info/gems/xcodeproj/Xcodeproj/Project/Object/XCConfigurationList


问:
Why my django form cleaned data returns None everytime?
I am using the self-referential Foreign Key in my models. In the views when I used the form.cleaned_data.get('parent') it returns None but when I used request.POST.get('parent') it returns the value. Why the cleaned_data is not working here?

models

```<code>class Category(models.Model):
    parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL)
    slug = models.SlugField(unique=True, max_length=50)
    title = models.CharField(max_length=255, unique=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
</code>```

forms

```<code>class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['title', 'slug']
</code>```

views

```<code>def create_category(request):
    form = CreateCategoryForm()
    categories = Category.objects.order_by('-created')
    if request.method == 'POST':
        form = CreateCategoryForm(request.POST)
        if form.is_valid():
            # parent = request.POST.get('parent') # works
            # parent = form.cleaned_data.get('parent') # returns None
            category = form.save(commit=False)
            category.parent = form.cleaned_data.get('parent')
            category.save()
            messages.success(request, 'Created Successfully.')
            return redirect('list_categories')
    return render(request, 'add_category.html', {'form':form, 'categories':categories})
</code>```

template

```<code>       <form action="" method="post">
              {% csrf_token %}

            <div class="form-group">
              <label>Category Name</label>
              <input type="text" name="title" class="form-control"
              value="{{form.title.value|default_if_none:''}}"/>
                {% if form.title.errors %}
                 <span class="error">{{form.title.errors|striptags}}</span>
                {% endif %}
            </div>
            <div class="form-group">
            <label for="select" class="">Category Parent</label>
                <select name="parent" id="exampleSelect"
              class="form-control">
                 <option selected>Select</option>
                {% for category in categories %}
              <option value="{{category.pk}}">{{category.title}}</option>
                {% endfor %}
            </select>
            </div>
</code>```

答:
So your first issue, is that you don't include the field in the modelform, so fix that:

class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['title', 'slug', 'parent']
```

<p>Second is that you render the form field yourself in the template, thus not making use of Django's attribute handling. To fix that:</p>

<pre class="lang-html prettyprint-override"><code>            <div class="form-group">
                <label for="{{form.parent.id_for_label}}">Category Parent</label>
                {{form.parent}}
            </div>
</code>```

Now the select will not have a the correct html class, but we can pass this to the form field. Complete solution:

class CreateCategoryForm(forms.ModelForm):
    # ModelForm will take care of setting required to False
    parent = forms.ModelChoiceField(queryset=Category.objects.order_by('-created'), attrs={'class': 'form-control'})
    class Meta:
        model = Category
        fields = ['title', 'slug', 'parent']

# view
def create_category(request):
    form = CreateCategoryForm()
    if request.method == 'POST':
        form = CreateCategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.parent = form.cleaned_data.get('parent')
            category.save()
            messages.success(request, 'Created Successfully.')
            return redirect('list_categories')
    return render(request, 'add_category.html', {'form':form})
```

Body:
I am using the self-referential Foreign Key in my models. In the views when I used the form.cleaned_data.get('parent') it returns None but when I used request.POST.get('parent') it returns the value. Why the cleaned_data is not working here?

models

class Category(models.Model):
    parent = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL)
    slug = models.SlugField(unique=True, max_length=50)
    title = models.CharField(max_length=255, unique=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

forms

class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['title', 'slug']

views

def create_category(request):
    form = CreateCategoryForm()
    categories = Category.objects.order_by('-created')
    if request.method == 'POST':
        form = CreateCategoryForm(request.POST)
        if form.is_valid():
            # parent = request.POST.get('parent') # works
            # parent = form.cleaned_data.get('parent') # returns None
            category = form.save(commit=False)
            category.parent = form.cleaned_data.get('parent')
            category.save()
            messages.success(request, 'Created Successfully.')
            return redirect('list_categories')
    return render(request, 'add_category.html', {'form':form, 'categories':categories})

template

       <form action="" method="post">
              {% csrf_token %}

              Category Name
              <input type="text" name="title" class="form-control"
              value="{{form.title.value|default_if_none:''}}"/>
                {% if form.title.errors %}
                 {{form.title.errors|striptags}}
                {% endif %}

            Category Parent
                <select name="parent" id="exampleSelect"
              class="form-control">
                 <option selected>Select</option>
                {% for category in categories %}
              <option value="{{category.pk}}">{{category.title}}</option>
                {% endfor %}
            </select>

Body:
So your first issue, is that you don't include the field in the modelform, so fix that:

class CreateCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['title', 'slug', 'parent']

Second is that you render the form field yourself in the template, thus not making use of Django's attribute handling. To fix that:

            <div class="form-group">
                <label for="{{form.parent.id_for_label}}">Category Parent</label>
                {{form.parent}}
            </div>

Now the select will not have a the correct html class, but we can pass this to the form field. Complete solution:

class CreateCategoryForm(forms.ModelForm):
    # ModelForm will take care of setting required to False
    parent = forms.ModelChoiceField(queryset=Category.objects.order_by('-created'), attrs={'class': 'form-control'})
    class Meta:
        model = Category
        fields = ['title', 'slug', 'parent']

# view
def create_category(request):
    form = CreateCategoryForm()
    if request.method == 'POST':
        form = CreateCategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.parent = form.cleaned_data.get('parent')
            category.save()
            messages.success(request, 'Created Successfully.')
            return redirect('list_categories')
    return render(request, 'add_category.html', {'form':form})


问:
unexpected behavior using the DirectorySearcher "server is not operational"
I'm experiencing a very weird issue using the DirectorySearcher class when trying to query groups over LDAP.

```<code>using(var directoryEntry = new DirectoryEntry(thePath,theUserName,ThePassword)
{
var ONLY_GROUPS = "(objectClass=group)"
var filter = string.format("(&{0}({1}=*{2}*))",ONLY_GROUPS,"Name","theGroupName");
using(var searcher = new DirectorySearcher(directoryEntry,filter))
{
...
 searcher.FindAll();
...
}

</code>```

In some cases on our production code when calling the FindAll function some customers are getting a ComException "server is not operational".
which means that the machine trying to connect to the LDAP server has no connection to it.

but as part of our code flow we are calling on the same LDAP a different query for retrieving Domain Controllers, which always works.
When calling the LDAP query for retrieving groups we get the ComException.

another notes

We have C++ code that runs the groups query over the same LDAP which works.

In addition I've created an executable that runs the same production code and it works for the failing customers (so I guess we've excluded the option this is connectivity issue)

I am running out with ideas when can cause this issue.

答:
here is the code for getting ldap groups

```<code>using (DirectoryEntry entry = new DirectoryEntry("LDAP://thedomain.com:636/dc=thedomain,dc=com", directory.LdapBindUser, directory.LdapBindPassword))
                {
                    string filter = "(&(objectClass=group))";
                    using (DirectorySearcher searcher = new DirectorySearcher(entry, filter))
                    {
                        searcher.FindAll();
                    }
                }
</code>```

here is the code for getting ldap domain controllers

```<code>
using (DirectoryEntry entry = new DirectoryEntry("LDAP://thedomain.com:636/dc=thedomain,dc=com", directory.LdapBindUser, directory.LdapBindPassword))
                {
                    string filter = "(&(objectCategory=computer)(|(primaryGroupID=516)(primaryGroupID=521)))";
                    using (DirectorySearcher searcher = new DirectorySearcher(entry, filter))
                    {
                        searcher.FindAll();
                    }
                }

</code>```

Body:
I'm experiencing a very weird issue using the DirectorySearcher class when trying to query groups over LDAP.

using(var directoryEntry = new DirectoryEntry(thePath,theUserName,ThePassword)
{
var ONLY_GROUPS = "(objectClass=group)"
var filter = string.format("(&{0}({1}=*{2}*))",ONLY_GROUPS,"Name","theGroupName");
using(var searcher = new DirectorySearcher(directoryEntry,filter))
{
...
 searcher.FindAll();
...
}

In some cases on our production code when calling the FindAll function some customers are getting a ComException "server is not operational".
which means that the machine trying to connect to the LDAP server has no connection to it.

but as part of our code flow we are calling on the same LDAP a different query for retrieving Domain Controllers, which always works.
When calling the LDAP query for retrieving groups we get the ComException.

another notes

We have C++ code that runs the groups query over the same LDAP which works.

In addition I've created an executable that runs the same production code and it works for the failing customers (so I guess we've excluded the option this is connectivity issue)

I am running out with ideas when can cause this issue.

Body:
here is the code for getting ldap groups

using (DirectoryEntry entry = new DirectoryEntry("LDAP://thedomain.com:636/dc=thedomain,dc=com", directory.LdapBindUser, directory.LdapBindPassword))
                {
                    string filter = "(&(objectClass=group))";
                    using (DirectorySearcher searcher = new DirectorySearcher(entry, filter))
                    {
                        searcher.FindAll();
                    }
                }

here is the code for getting ldap domain controllers

using (DirectoryEntry entry = new DirectoryEntry("LDAP://thedomain.com:636/dc=thedomain,dc=com", directory.LdapBindUser, directory.LdapBindPassword))
                {
                    string filter = "(&(objectCategory=computer)(|(primaryGroupID=516)(primaryGroupID=521)))";
                    using (DirectorySearcher searcher = new DirectorySearcher(entry, filter))
                    {
                        searcher.FindAll();
                    }
                }


问:
How to speed up Get-ChildItem in Powershell
Just wandering how could I speed up the Get-ChildItem in Powershell?

I have the following script to search for a file that created by today and copy it over to another folder.

```<code>$fromDirectory = "test_file_*.txt"
$fromDirectory = "c:\sour\"
$toDirectory = "c:\test\"

Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory
</code>```

Due to the folder that I search have 124,553 history files, it's take me age for the search. Does any know how could I improve my script to speed up my search and copy?

答:
This is a well-known feature of NTFS. Microsoft's docs say that the limit for decreasing performance is about 50 000 files in a directory.

If the file names are of very similar, creation of 8dot3 legacy names will start to slow down when there are about 300 000 files. Though you have "only" 120 k files, it's the same order of magnitude.

Some previous questions discuss this issue. Sadly, there is no a single good solution but better hierarchy in directories. The usual tricks are to disable 8dot3 with fsutil and last access date via registry, but those will help only so much.

Can you redesign the directory structure? Moving old files into, say, year-quarter subdirs might keep the main directory clean enough. To find out file's year-quarter, a quick way is like so,

```<code>gci | % {
  $("{2} => {1}\Q{0:00}" -f [Math]::ceiling( ($_.LastAccessTime.toString('MM'))/3),
    $_.LastAccessTime.ToString('yyyy'),
    $_.Name
  )
}
</code>```

Body:
Just wandering how could I speed up the Get-ChildItem in Powershell?

I have the following script to search for a file that created by today and copy it over to another folder.

$fromDirectory = "test_file_*.txt"
$fromDirectory = "c:\sour\"
$toDirectory = "c:\test\"

Get-ChildItem $fromDirectory -Include $fileName -Recurse | Where {$_.LastWriteTime -gt (Get-Date).Date} | Copy-Item -Destination $toDirectory

Due to the folder that I search have 124,553 history files, it's take me age for the search. Does any know how could I improve my script to speed up my search and copy?

Body:
This is a well-known feature of NTFS. Microsoft's docs say that the limit for decreasing performance is about 50 000 files in a directory.

If the file names are of very similar, creation of 8dot3 legacy names will start to slow down when there are about 300 000 files. Though you have "only" 120 k files, it's the same order of magnitude.

Some previous questions discuss this issue. Sadly, there is no a single good solution but better hierarchy in directories. The usual tricks are to disable 8dot3 with fsutil and last access date via registry, but those will help only so much.

Can you redesign the directory structure? Moving old files into, say, year-quarter subdirs might keep the main directory clean enough. To find out file's year-quarter, a quick way is like so,

gci | % {
  $("{2} => {1}\Q{0:00}" -f [Math]::ceiling( ($_.LastAccessTime.toString('MM'))/3),
    $_.LastAccessTime.ToString('yyyy'),
    $_.Name
  )
}


问:
How to play access and play the video programmatically?
I am developing an application. In that my requirement is access the video from iPhone and play that videos and select one from that videos. So please tell me how to access and play the videos in iPhone programmatically.</p>

答: This site is not to do your homework for you.  Please read Apple docs on Media Player Framework.  Then download sample code from iOS Developer Library.  Once you have written your own code and getting a specific error you cannot resolve, then post your question on SO.</p>


问:
Getting below error when i am installing robot framework-appiumlibrary
```<code>D:\Users\SBhagyad>pip install robotframework-appiumlibrary
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting robotframework-appiumlibrary
  Using cached robotframework_appiumlibrary-1.5.0.6-py2.py3-none-any.whl (33 kB)
Requirement already satisfied: robotframework>=2.6.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (3.1.2)
Requirement already satisfied: six>=1.10.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (1.14.0)
Collecting Appium-Python-Client>=0.28
  Using cached Appium-Python-Client-1.0.1.tar.gz (51 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\python27\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"'; __file__='"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'd:\users\sbhagyad\appdata\local\temp\1\pip-pip-egg-info-dvpaun'
         cwd: d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\setup.py", line 19, in <module>
        from appium.common.helper import library_version
      File "appium\common\helper.py", line 20
        def extract_const_attributes(cls: type) -> Dict[str, Any]:
                                        ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

Error

Getting Error when i am trying to install robot framework-appiumlibrary CMD
Please help to provide any solution for this
I am Using Python 2.7 and Robot Framework 3.1.2 (Python 2.7.16 on win32)

答:
You can install the specific version of the appium library which is compatible with Python 2.7 using below command:

```<code>pip install robotframework-appiumlibrary==<compatible_library_version>
</code>```

where compatible_library_version is the version number compatible with Python 2.7

Body:
D:\Users\SBhagyad>pip install robotframework-appiumlibrary
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting robotframework-appiumlibrary
  Using cached robotframework_appiumlibrary-1.5.0.6-py2.py3-none-any.whl (33 kB)
Requirement already satisfied: robotframework>=2.6.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (3.1.2)
Requirement already satisfied: six>=1.10.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (1.14.0)
Collecting Appium-Python-Client>=0.28
  Using cached Appium-Python-Client-1.0.1.tar.gz (51 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\python27\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"'; __file__='"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'd:\users\sbhagyad\appdata\local\temp\1\pip-pip-egg-info-dvpaun'
         cwd: d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\setup.py", line 19, in <module>
        from appium.common.helper import library_version
      File "appium\common\helper.py", line 20
        def extract_const_attributes(cls: type) -> Dict[str, Any]:
                                        ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Error

Getting Error when i am trying to install robot framework-appiumlibrary CMD
Please help to provide any solution for this
I am Using Python 2.7 and Robot Framework 3.1.2 (Python 2.7.16 on win32)

Body:
You can install the specific version of the appium library which is compatible with Python 2.7 using below command:

pip install robotframework-appiumlibrary==<compatible_library_version>

where compatible_library_version is the version number compatible with Python 2.7


问:
How to multi-thread in ONNX Runtime?
Using ONNX Runtime to run inference on deep learning models.  Lets say I have 4 different models, each with its own input image, can I run them in parallel in 4 threads?   Would there be one "environment" and then 4 sessions (using same environment)?  </p>

答:
Yes - one environment and 4 separate sessions is how you'd do it.

'read only state' of weights and biases are specific to a model.

A session has a 1:1 relationship with a model, and those sorts of things aren't shared across sessions as you only need one session per model given you can call Run concurrently with different input sizes (assuming the model supports dynamic batch/input sizes).

Regarding threading, the default is a per-session threadpools, but it's also possible to share global threadpools across sessions.

How you do that differs by the API used:

For the C API use CreateEnvWithGlobalThreadPools.

For the C++ API provide OrtThreadingOptions when constructing Ort::Env.

Title: How to multi-thread in ONNX Runtime?


问:
How to use `html()` to insert text into an element?
I want to display "00:00" on the page but the page is empty I don't know why it's not working.

```<code>$(document).ready(function(){
    var minut = $("#minut").html;
    var mid = $("#mid").html;
    var sec = $("sec").html;
    minut = "00";
    mid = ":";
    sec = "00";
});
</code>```

HTML

```<code><span id="minut"></span>
<span id="mid"></span>
<span id="sec"></span>
</code>```

答:
Use .text() to display text within the div you are querying... Check out snippit

You were also missing a # symbol in your sec selector.

$(document).ready(function(){

 let minut = $("#minut");
 let mid = $("#mid");
 let sec = $("#sec");
 minut.text("00");
 mid.text(":");
 sec.text("00");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minut"></span>
<span id="mid"></span>
<span id="sec"></span></code>```

Body:
I want to display "00:00" on the page but the page is empty I don't know why it's not working.

$(document).ready(function(){
    var minut = $("#minut").html;
    var mid = $("#mid").html;
    var sec = $("sec").html;
    minut = "00";
    mid = ":";
    sec = "00";
});

HTML

Body:
Use .text() to display text within the div you are querying... Check out snippit

You were also missing a # symbol in your sec selector.

$(document).ready(function(){

 let minut = $("#minut");
 let mid = $("#mid");
 let sec = $("#sec");
 minut.text("00");
 mid.text(":");
 sec.text("00");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minut"></span>
<span id="mid"></span>
<span id="sec"></span>