问:
Problem with uncontrolled modify every time data is saved in django slug
I want to create unique slug.I want to create unique slug. I use some methods to generate unique slug,but I have problem with them.

this is my model and my method to create unique slug:

```<code>#Models.py
class MyModel(models.Model):

    slug = models.SlugField(null=True, blank=True, unique=True)

    def _get_unique_slug(self, slug_input):
        slug = slugify(slug_input)
        unique_slug = slug
        num = 1
        while Curriculum.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        if not self.id:  # Create
            if not self.slug:  # slug is blank
                self.slug = self._get_unique_slug(slug_input=self.title)
            else:  # slug is not blank
                self.slug = self._get_unique_slug(slug_input=self.slug)
        else:  # Update
            self.slug = self._get_unique_slug(slug_input=self.slug)
        super(Curriculum, self).save(*args, **kwargs)
</code>```

This method have two problem:

1. Every time that I save each object(even without modify it), slug changes and '-1' append to it.

2. For some language such as Arabic and Farsi(Persian) slug didn't create.
how can I fix these problems?

答:
slug field have allow_unicode:

```<code>slug = models.SlugField(null=True, blank=True, unique=True, allow_unicode=True, max_length=255)
</code>```

prepopulate slug in ModelAdmin:

```<code>    #admin.py
    class EditModel(admin.ModelAdmin):
              prepopulated_fields = {'slug': ('title',)}
    admin.site.register(ModelName, EditModel)
</code>```

customize slug field data:

```<code>from django.utils.text import slugify

# overwrite your model save method || necessary for : django<1.11.12
def save(self, *args, **kwargs):
    title = self.title
    # allow_unicode=True for support utf-8 languages
    self.slug = slugify(title, allow_unicode=True)
    super(ModelName, self).save(*args, **kwargs)
</code>```

Body:
I want to create unique slug.I want to create unique slug. I use some methods to generate unique slug,but I have problem with them.

this is my model and my method to create unique slug:

#Models.py
class MyModel(models.Model):

    slug = models.SlugField(null=True, blank=True, unique=True)

    def _get_unique_slug(self, slug_input):
        slug = slugify(slug_input)
        unique_slug = slug
        num = 1
        while Curriculum.objects.filter(slug=unique_slug).exists():
            unique_slug = '{}-{}'.format(slug, num)
            num += 1
        return unique_slug

    def save(self, *args, **kwargs):
        if not self.id:  # Create
            if not self.slug:  # slug is blank
                self.slug = self._get_unique_slug(slug_input=self.title)
            else:  # slug is not blank
                self.slug = self._get_unique_slug(slug_input=self.slug)
        else:  # Update
            self.slug = self._get_unique_slug(slug_input=self.slug)
        super(Curriculum, self).save(*args, **kwargs)

This method have two problem:

1. Every time that I save each object(even without modify it), slug changes and '-1' append to it.

2. For some language such as Arabic and Farsi(Persian) slug didn't create.
how can I fix these problems?

Body:
slug field have allow_unicode:

slug = models.SlugField(null=True, blank=True, unique=True, allow_unicode=True, max_length=255)

prepopulate slug in ModelAdmin:

    #admin.py
    class EditModel(admin.ModelAdmin):
              prepopulated_fields = {'slug': ('title',)}
    admin.site.register(ModelName, EditModel)

customize slug field data:

from django.utils.text import slugify

# overwrite your model save method || necessary for : django<1.11.12
def save(self, *args, **kwargs):
    title = self.title
    # allow_unicode=True for support utf-8 languages
    self.slug = slugify(title, allow_unicode=True)
    super(ModelName, self).save(*args, **kwargs)


来源: stackexchange

问:
How to fix "Potential unnecessary eager load detected on `LogEntry.user`"
I'm creating a new Django 2.2 project with plugin nplusone(https://github.com/jmcarp/nplusone). When I try to go on /admin URL I get a next error “Potential unnecessary eager load detected on LogEntry.user”
This problem appears when I have at least 1 record in DB.

models.py

class Post(models.Model):
    author = models.ForeignKey(User,
                               on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    created_date = models.DateTimeField(auto_now_add=True)
    body = models.TextField()
    slug = models.SlugField(max_length=100, unique=True)
    preview_image = models.ImageField(upload_to='images', blank=True)

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'
        ordering = ['-id']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post', args=(self.slug,))
```

<p>admin.py</p>

<pre class="lang-py prettyprint-override"><code>admin.site.register(Post, PostAdmin)
</code>```

DEBUG SQLs

SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2019-04-30 06:11:28.376554' AND "django_session"."session_key" = 'hbwpegj1vpvkv5wdkbqr38ty55s3cm38'); args=('2019-04-30 06:11:28.376554', 'hbwpegj1vpvkv5wdkbqr38ty55s3cm38')
```

<pre class="lang-sql prettyprint-override"><code>SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1; args=(1,)
</code>```

SELECT "django_admin_log"."id", "django_admin_log"."action_time", "django_admin_log"."user_id", "django_admin_log"."content_type_id", "django_admin_log"."object_id", "django_admin_log"."object_repr", "django_admin_log"."action_flag", "django_admin_log"."change_message", "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined", "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model" FROM "django_admin_log" INNER JOIN "auth_user" ON ("django_admin_log"."user_id" = "auth_user"."id") LEFT OUTER JOIN "django_content_type" ON ("django_admin_log"."content_type_id" = "django_content_type"."id") WHERE "django_admin_log"."user_id" = 1 ORDER BY "django_admin_log"."action_time" DESC  LIMIT 10; args=(1,)
```

答:
I found N+1 to rarely be happy with Django admin - either related entries (like user groups) are loaded lazily and it makes a N+1 problem in big listings, or they are prefetched() and then it's on single-user pages that an "unnecessary eager load" is detected.

The problem is that the same base ModelAdmin querysets are used for listing pages and for single-object pages, so avoiding both problems is not easy.

Until someone comes with an easy solution to create different "prefetch" querysets for different admin pages, I've whitelisted these models like so. Just check with the django debug toolbar that no N+1 requests happen on these admin pages.

```<code>NPLUSONE_WHITELIST = [
    {"model": "admin.LogEntry", "field": "user"},
    {"model": "accounts.User", "field": "groups"},
]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a new Django 2.2 project with plugin nplusone(https://github.com/jmcarp/nplusone). When I try to go on /admin URL I get a next error “Potential unnecessary eager load detected on LogEntry.user”
This problem appears when I have at least 1 record in DB.

models.py

class Post(models.Model):
    author = models.ForeignKey(User,
                               on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    created_date = models.DateTimeField(auto_now_add=True)
    body = models.TextField()
    slug = models.SlugField(max_length=100, unique=True)
    preview_image = models.ImageField(upload_to='images', blank=True)

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'
        ordering = ['-id']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post', args=(self.slug,))

admin.py

admin.site.register(Post, PostAdmin)

DEBUG SQLs

SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2019-04-30 06:11:28.376554' AND "django_session"."session_key" = 'hbwpegj1vpvkv5wdkbqr38ty55s3cm38'); args=('2019-04-30 06:11:28.376554', 'hbwpegj1vpvkv5wdkbqr38ty55s3cm38')

SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1; args=(1,)

SELECT "django_admin_log"."id", "django_admin_log"."action_time", "django_admin_log"."user_id", "django_admin_log"."content_type_id", "django_admin_log"."object_id", "django_admin_log"."object_repr", "django_admin_log"."action_flag", "django_admin_log"."change_message", "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined", "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model" FROM "django_admin_log" INNER JOIN "auth_user" ON ("django_admin_log"."user_id" = "auth_user"."id") LEFT OUTER JOIN "django_content_type" ON ("django_admin_log"."content_type_id" = "django_content_type"."id") WHERE "django_admin_log"."user_id" = 1 ORDER BY "django_admin_log"."action_time" DESC  LIMIT 10; args=(1,)

Body:
I found N+1 to rarely be happy with Django admin - either related entries (like user groups) are loaded lazily and it makes a N+1 problem in big listings, or they are prefetched() and then it's on single-user pages that an "unnecessary eager load" is detected.

The problem is that the same base ModelAdmin querysets are used for listing pages and for single-object pages, so avoiding both problems is not easy.

Until someone comes with an easy solution to create different "prefetch" querysets for different admin pages, I've whitelisted these models like so. Just check with the django debug toolbar that no N+1 requests happen on these admin pages.

NPLUSONE_WHITELIST = [
    {"model": "admin.LogEntry", "field": "user"},
    {"model": "accounts.User", "field": "groups"},
]


问:
Convert DateTime format in epplus
I want to read a column from excel into datatable using epplus but whenever i do I get the time in 24 hour format. I want the time to be in 12 hour format as it is in excel.

I have tried changing the date format of excel to "dd/mm/yyyy hh:mm:ss tt" it give me AM/PM but it shows the time in 24 hour format.

```<code>worksheet.Cells["" + firstRowCell.Address + ":" +
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" +
worksheet.Dimension.Rows].Style.Numberformat.Format =  "dd/mm/yyyy hh:mm:ss tt";
</code>```

答:
It sounds like you are reading formatted display value and not the underlying cell value. Maybe this will help you I am not sure Excel saves the date and time as a double of the number of days from 1900-01-01 the decimal part is how it determines hours in the day. This number could also be negative or positive so what I have done in the past to get the correct value is to read the cell value and convert that to a DateTime.

//get the underlying value instead of the display value
var cellValue = worksheet.Cells["" + firstRowCell.Address + ":" +
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" +
worksheet.Dimension.Rows].Value;

var stringValue = $"{cellValue}";

//Now convert the double to a valid DateTime;
DateTime value;
var date = new DateTime(1899, 12, 30);
double doubleValue;

if (double.TryParse(stringValue, out doubleValue) &&
   (doubleValue <= 2958465) &&
   (doubleValue >= -693593))
      value = date.AddDays(doubleValue);

```

<p>Once you have a valid DateTime value you can use ToString to get a proper 12 hour format</p>

<pre class="lang-cs prettyprint-override"><code>value.ToString("dd/mm/yyyy hh:mm:ss tt")
</code>```

Title: Convert DateTime format in epplus

Body:
I want to read a column from excel into datatable using epplus but whenever i do I get the time in 24 hour format. I want the time to be in 12 hour format as it is in excel.

I have tried changing the date format of excel to "dd/mm/yyyy hh:mm:ss tt" it give me AM/PM but it shows the time in 24 hour format.

worksheet.Cells["" + firstRowCell.Address + ":" +
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" +
worksheet.Dimension.Rows].Style.Numberformat.Format =  "dd/mm/yyyy hh:mm:ss tt";

Body:
It sounds like you are reading formatted display value and not the underlying cell value. Maybe this will help you I am not sure Excel saves the date and time as a double of the number of days from 1900-01-01 the decimal part is how it determines hours in the day. This number could also be negative or positive so what I have done in the past to get the correct value is to read the cell value and convert that to a DateTime.

//get the underlying value instead of the display value
var cellValue = worksheet.Cells["" + firstRowCell.Address + ":" +
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" +
worksheet.Dimension.Rows].Value;

var stringValue = $"{cellValue}";

//Now convert the double to a valid DateTime;
DateTime value;
var date = new DateTime(1899, 12, 30);
double doubleValue;

if (double.TryParse(stringValue, out doubleValue) &&
   (doubleValue <= 2958465) &&
   (doubleValue >= -693593))
      value = date.AddDays(doubleValue);

Once you have a valid DateTime value you can use ToString to get a proper 12 hour format

value.ToString("dd/mm/yyyy hh:mm:ss tt")


问:
Add aliases to console_scripts inside setup()
I was wondering if there is any way of specifying aliases to a command defined in console_scripts inside entry_points arg of setup().

Can I do something like this?

entry_points={
          'console_scripts': ['[command,alias0,alias1,alias2]=packagename.__main__:main'],
      },
```

答:
Aliasing absolutely works, but not quite in the way you want it to. As long as a slight amount of code duplication is fine for you, you can do this instead:</p>

```<code>entry_points={
    'console_scripts': [
        'command=packagename.__main__:main',
        'alias0=packagename.__main__:main',
        'alias1=packagename.__main__:main',
        'alias2=packagename.__main__:main'
]}
</code>```

Body:
Aliasing absolutely works, but not quite in the way you want it to. As long as a slight amount of code duplication is fine for you, you can do this instead:

entry_points={
    'console_scripts': [
        'command=packagename.__main__:main',
        'alias0=packagename.__main__:main',
        'alias1=packagename.__main__:main',
        'alias2=packagename.__main__:main'
]}


问:
VBA script: Code Runs fine in Debug mode but not in full run mode
VBA script: Code Runs fine in Debug mode but not in full run mode.
Code is to read each cell in Col I, check for 1st pos IF numeric and then write the Pos of the same in Col J ?

The code runs fine in debug mode but not in full run.

CODE writteN

```<code>Dim CellRef As String
Dim StringLength As Integer
j = 1
i = 1

For j = 2 To LastRow1
   StringLength = Len(Cells(j, "I"))
   i = 1
   For i = 1 To StringLength
      If IsNumeric(Mid((Cells(j, "I")), i, 1)) Then
         Cells(j, "J") = i
         i = StringLength + 1
      End If
   Next i
Next j
</code>```

答:
I'm not sure if you have variables declared before or not. To avoid the that come by not declaring them, I recommend you using Option Explicitat the top of your code.

On the other hand, I guess your problem comes from the ActiveSheet at the moment you are running your macro, since you didn't full qualify your ranges, they go to the ActiveSheet to avoid this you can read the comments:

```<code>Option Explicit
Sub TesT()

    Dim CellRef As String 'not sure if you are using it later
    Dim StringLength As Long ' you used Integer, Byte or Long, Integer is a Long cutted.
    Dim MyRange As Range 'we will set here the working range
    Dim C As Range 'It is always better to loop through cells with For Each
    Dim LastRow1 As Long 'Not sure if you declared it before
    Dim i As Long 'Not sure if you declared it before

    With ThisWorkbook.Sheets("SeetName") 'always full qualify your ranges: workbook-worksheet-range
        LastRow1 = .Cells(.Rows.Count, "I").End(xlUp).Row 'last row on column I
        Set MyRange = .Range("I2:I" & LastRow1) 'this will be your working range
        For Each C In MyRange 'this will loop through all the cells between J2 to J LastRow1
            StringLength = Len(C)
            For i = 1 To StringLength
                If IsNumeric(Mid((C), i, 1)) Then
                   .Cells(j, "J") = i 'full qualify the range, note the "." before Cells, referencing to the with line
                   Exit For 'this will exit the loop so only the first match remains.
                   ' i = StringLength + 1 'don't know why did you do this, but if you intend to keep the first position the above line is it.
                End If
            Next i
        Next C
    End With

End Sub
</code>```

Body:
VBA script: Code Runs fine in Debug mode but not in full run mode.
Code is to read each cell in Col I, check for 1st pos IF numeric and then write the Pos of the same in Col J ?

The code runs fine in debug mode but not in full run.

CODE writteN

Dim CellRef As String
Dim StringLength As Integer
j = 1
i = 1

For j = 2 To LastRow1
   StringLength = Len(Cells(j, "I"))
   i = 1
   For i = 1 To StringLength
      If IsNumeric(Mid((Cells(j, "I")), i, 1)) Then
         Cells(j, "J") = i
         i = StringLength + 1
      End If
   Next i
Next j

Body:
I'm not sure if you have variables declared before or not. To avoid the that come by not declaring them, I recommend you using Option Explicitat the top of your code.

On the other hand, I guess your problem comes from the ActiveSheet at the moment you are running your macro, since you didn't full qualify your ranges, they go to the ActiveSheet to avoid this you can read the comments:

Option Explicit
Sub TesT()

    Dim CellRef As String 'not sure if you are using it later
    Dim StringLength As Long ' you used Integer, Byte or Long, Integer is a Long cutted.
    Dim MyRange As Range 'we will set here the working range
    Dim C As Range 'It is always better to loop through cells with For Each
    Dim LastRow1 As Long 'Not sure if you declared it before
    Dim i As Long 'Not sure if you declared it before

    With ThisWorkbook.Sheets("SeetName") 'always full qualify your ranges: workbook-worksheet-range
        LastRow1 = .Cells(.Rows.Count, "I").End(xlUp).Row 'last row on column I
        Set MyRange = .Range("I2:I" & LastRow1) 'this will be your working range
        For Each C In MyRange 'this will loop through all the cells between J2 to J LastRow1
            StringLength = Len(C)
            For i = 1 To StringLength
                If IsNumeric(Mid((C), i, 1)) Then
                   .Cells(j, "J") = i 'full qualify the range, note the "." before Cells, referencing to the with line
                   Exit For 'this will exit the loop so only the first match remains.
                   ' i = StringLength + 1 'don't know why did you do this, but if you intend to keep the first position the above line is it.
                End If
            Next i
        Next C
    End With

End Sub


问:
How can I convert this join to LINQ syntax?
I want to retrieve all tools used by products with X = 14, how can I convert this select to LINQ?

```<code>SELECT DISTINCT t.* FROM Product p
INNER JOIN ProductTool pt ON pt.Product_ID = p.ID
INNER JOIN Tool t ON t.ID = pt.Tools_ID
WHERE p.X = 14
</code>```

Is GroupJoin what I need or what?

```<code>tools.GroupJoin(products, t=>, p=>, ...)
products.GroupJoin(tools, p=>, t=>, ...)
</code>```

答:
If you have foreign keys setup correctly, the entity framework should pick that relationship up and you should be able to simply do:

var tools = from p in products where p.X == 14 select p.Tool;

ContentLicense: CC BY-SA 3.0

Body:
I want to retrieve all tools used by products with X = 14, how can I convert this select to LINQ?

SELECT DISTINCT t.* FROM Product p
INNER JOIN ProductTool pt ON pt.Product_ID = p.ID
INNER JOIN Tool t ON t.ID = pt.Tools_ID
WHERE p.X = 14

Is GroupJoin what I need or what?

tools.GroupJoin(products, t=>, p=>, ...)
products.GroupJoin(tools, p=>, t=>, ...)


问:
Not In operator eliminates NULL values rows in a table
I would like to retrieve all rows with values except 1,2,3,4,5 in my COLUMNA in TABLEA .

```<code>SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5)
</code>```

But this eliminates the rows with NULL values in COLUMNA too.

I don't want to eliminate NULL values rows and would like to include those rows in the resultset.

Alternatively, I can try below query for the same

```<code>SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5) OR COLUMNA  IS NULL.
</code>```

But I would like to know, why is it necessary to add this OR condition?

答:
Why is the additional necessary?

NULL comparisons almost always results in NULL, rather than true or false.  A WHERE clause filters out all non-true values, so they get filtered out.

This is how SQL defines NULL.  Why is NULL defined like this?

NULL does not mean "missing" in SQL.  It means "unknown".  So, the result of <unknown> not in (1, 2, 3, 4, 5) is "unknown", because the value could be 1 or it might be 0.  Hence it gets filtered.

I will also note that the SQL standard includes NULL-safe comparisons, IS NOT DISTINCT FROM and IS DISTINCT FROM corresponding to = and <> respectively.  These treat NULL as just "any other value", so two NULL values are considered equal.  However, there is no construct for NULL-safe IN and NOT IN, as far as I know.

Body:
I would like to retrieve all rows with values except 1,2,3,4,5 in my COLUMNA in TABLEA .

SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5)

But this eliminates the rows with NULL values in COLUMNA too.

I don't want to eliminate NULL values rows and would like to include those rows in the resultset.

Alternatively, I can try below query for the same

SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5) OR COLUMNA  IS NULL.

But I would like to know, why is it necessary to add this OR condition?


问:
How to jump from parent window to child window in pywinauto
I am trying to automate printer driver setup installation steps. once i click next button it is jumping into small pop up window with OK button, I have to click that button. please help on this.</p>

答: Find the control properties like title, automation_id, control type with the help of print_control_identifiers().</p>


问:
How to merge files order by filename
I want to create a new pdf file using iTextSharp. All my code is working but the new file doesn't are ordered by page number.

Could you kindly let me know how to modify the following code to create new pdf file ordered by file name (page number)

```<code>foreach (var file in Directory.GetFiles(path))
{
    reader = new PdfReader(file);

    for (int i = 0; i < reader.NumberOfPages; i++)
    {
        page = pdf.GetImportedPage(reader, i + 1);
        pdf.AddPage(page);
    }

    pdf.FreeReader(reader); reader.Close();
}
</code>```

Folder contains 102 files. File name is Page_1, Page_2, Page_3 ...

I expected the output with pages ordered

Thank you very much in advance

答:
Since you need to order numerically (i.e. Page_15 comes before Page_2 if you do it alphabetically), you need to extract that from the filename, for example:

```<code>// Needs some work but you get the idea
private int GetNumberFromFilename(string filename)
{
    var baseName = Path.GetFileName(filename);
    var parts = filename.Split('_','.');
    if(int.TryParse(parts[1], out var number))
    {
        return number;
    }
    return 0;
}
</code>```

Now you can get your ordered files like this:

```<code>var files = Directory.GetFiles(path)
    .Where(f => Path.GetFileName(f).StartsWith("Page_")) //filter out non matching files
    .OrderBy(GetNumberFromFilename);
</code>```

Title: How to merge files order by filename

Body:
I want to create a new pdf file using iTextSharp. All my code is working but the new file doesn't are ordered by page number.

Could you kindly let me know how to modify the following code to create new pdf file ordered by file name (page number)

foreach (var file in Directory.GetFiles(path))
{
    reader = new PdfReader(file);

    for (int i = 0; i < reader.NumberOfPages; i++)
    {
        page = pdf.GetImportedPage(reader, i + 1);
        pdf.AddPage(page);
    }

    pdf.FreeReader(reader); reader.Close();
}

Folder contains 102 files. File name is Page_1, Page_2, Page_3 ...

I expected the output with pages ordered

Thank you very much in advance

Body:
Since you need to order numerically (i.e. Page_15 comes before Page_2 if you do it alphabetically), you need to extract that from the filename, for example:

// Needs some work but you get the idea
private int GetNumberFromFilename(string filename)
{
    var baseName = Path.GetFileName(filename);
    var parts = filename.Split('_','.');
    if(int.TryParse(parts[1], out var number))
    {
        return number;
    }
    return 0;
}

Now you can get your ordered files like this:

var files = Directory.GetFiles(path)
    .Where(f => Path.GetFileName(f).StartsWith("Page_")) //filter out non matching files
    .OrderBy(GetNumberFromFilename);


问:
NavigationPage + CarouselPage: weird scroll error
I am playing with the CarouselPage example right now, and since I'd like to move to other pages, I am starting the application with a NavigationPage as the main one:

```<code>    public App()
    {
        InitializeComponent();

        // Need navigation to have modal/nonmodal pages
        //MainPage = new MainPage();
        MainPage = new NavigationPage(new MainPage());
    }
</code>```

The XAML adds safe areas for the iPhone X, and removes the navigation bar:

```<code><?xml version="1.0" encoding="utf-8"?>
<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Stoa" x:Class="Test.MainPage"
              xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
              ios:Page.UseSafeArea="true"
              NavigationPage.HasNavigationBar="False">
    <ContentPage>
        <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS, Android" Value="0,40,0,0" />
            </OnPlatform>
        </ContentPage.Padding>
        <StackLayout>
            <Label Text="Green" FontSize="Medium" HorizontalOptions="Center" />
            <Button BackgroundColor="Green" WidthRequest="200" HeightRequest="200" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage>
    <ContentPage>
        <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS, Android" Value="0,40,0,0" />
            </OnPlatform>
        </ContentPage.Padding>
        <StackLayout>
            <Label Text="Blue" FontSize="Medium" HorizontalOptions="Center" />
            <Button BackgroundColor="Blue" WidthRequest="200" HeightRequest="200" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage>
</CarouselPage>
</code>```

The problem is that now the user can scroll vertically and it loses the margins, apparently:

Is there a way to fix this?

In alternative, how can I navigate away from a carousel view or "fake" a carousel?

答:
This "Safe Area scroll offset" can be fixed with a custom iOS CarouselPageRenderer that sets the UIScrollView
  ContentInsetAdjustmentBehavior to Never

Updated: previous code example checked UIView.Subviews[0] is UIScrollView in OnElementChanged, this could throw a System.IndexOutOfRangeException causing a SIGABRT crash. So instead we check it in ViewDidLoad as suggested here: https://forums.xamarin.com/discussion/104385/ios-11-carousel-page-issues

```<code>[assembly: ExportRenderer(typeof(CarouselPage), typeof(CustomCarouselPageRenderer))]
namespace MyApp.iOS.Renderers
{
    public class CustomCarouselPageRenderer : CarouselPageRenderer
    {
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Prevent vertical carousel scroll on iOS 11,
            //we only want horizontal scroll in the carousel
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
             View.Subviews.OfType<UIScrollView>().Single().ContentInsetAdjustmentBehavior =
             UIScrollViewContentInsetAdjustmentBehavior.Never;
            }
        }
    }
}
</code>```

Body:
I am playing with the CarouselPage example right now, and since I'd like to move to other pages, I am starting the application with a NavigationPage as the main one:

    public App()
    {
        InitializeComponent();

        // Need navigation to have modal/nonmodal pages
        //MainPage = new MainPage();
        MainPage = new NavigationPage(new MainPage());
    }

The XAML adds safe areas for the iPhone X, and removes the navigation bar:

<?xml version="1.0" encoding="utf-8"?>
<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Stoa" x:Class="Test.MainPage"
              xmlns:ios="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
              ios:Page.UseSafeArea="true"
              NavigationPage.HasNavigationBar="False">
    <ContentPage>
        <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS, Android" Value="0,40,0,0" />
            </OnPlatform>
        </ContentPage.Padding>
        <StackLayout>

            <Button BackgroundColor="Green" WidthRequest="200" HeightRequest="200" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage>
    <ContentPage>
        <ContentPage.Padding>
            <OnPlatform x:TypeArguments="Thickness">
                <On Platform="iOS, Android" Value="0,40,0,0" />
            </OnPlatform>
        </ContentPage.Padding>
        <StackLayout>

            <Button BackgroundColor="Blue" WidthRequest="200" HeightRequest="200" HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
        </StackLayout>
    </ContentPage>
</CarouselPage>

The problem is that now the user can scroll vertically and it loses the margins, apparently:

Is there a way to fix this?

In alternative, how can I navigate away from a carousel view or "fake" a carousel?

Body:
This "Safe Area scroll offset" can be fixed with a custom iOS CarouselPageRenderer that sets the UIScrollView
  ContentInsetAdjustmentBehavior to Never

Updated: previous code example checked UIView.Subviews[0] is UIScrollView in OnElementChanged, this could throw a System.IndexOutOfRangeException causing a SIGABRT crash. So instead we check it in ViewDidLoad as suggested here: https://forums.xamarin.com/discussion/104385/ios-11-carousel-page-issues

[assembly: ExportRenderer(typeof(CarouselPage), typeof(CustomCarouselPageRenderer))]
namespace MyApp.iOS.Renderers
{
    public class CustomCarouselPageRenderer : CarouselPageRenderer
    {
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Prevent vertical carousel scroll on iOS 11,
            //we only want horizontal scroll in the carousel
            if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
            {
             View.Subviews.OfType<UIScrollView>().Single().ContentInsetAdjustmentBehavior =
             UIScrollViewContentInsetAdjustmentBehavior.Never;
            }
        }
    }
}


问:
Why my Sitemap show /number and not /title of my posts?
I´ve added the sitemap functionality to my blog, and it works fine. But in my /sitemap.xml file it shows not the title, but the number of the post.
I tried to change the definition in my urls.py file to  but then it shows some weird stuff after my domain.
Maybe i have somewhere some little mistake

My main urls.py file:

```<code>from django.contrib import admin
from django.urls import path, include
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
from blog import views as blog_views

sitemaps = {
'posts': PostSitemap,
}

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
        path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
         name='django.contrib.sitemaps.views.sitemap'),
    path('<int:id>', blog_views.PostDetail, name='post'),
]
</code>```

My sitemaps.py file:

```<code>from django.contrib.sitemaps import Sitemap
from .models import Post

class PostSitemap(Sitemap):

    def items(self):
        return Post.objects.all()
</code>```

My models.py file:

```<code>from django.urls import reverse

def get_absolute_url(self):
    return reverse('post', args=[str(self.id)])
</code>```

答:
Oh, i found my mistake.
I defined in my models.py file self.id. I changed that to self.slug and i changed my urls.py to <slug:slug>

Now it works fine.

Body:
I´ve added the sitemap functionality to my blog, and it works fine. But in my /sitemap.xml file it shows not the title, but the number of the post.
I tried to change the definition in my urls.py file to  but then it shows some weird stuff after my domain.
Maybe i have somewhere some little mistake

My main urls.py file:

from django.contrib import admin
from django.urls import path, include
from django.contrib.sitemaps.views import sitemap
from blog.sitemaps import PostSitemap
from blog import views as blog_views

sitemaps = {
'posts': PostSitemap,
}

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
        path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
         name='django.contrib.sitemaps.views.sitemap'),
    path('<int:id>', blog_views.PostDetail, name='post'),
]

My sitemaps.py file:

from django.contrib.sitemaps import Sitemap
from .models import Post

class PostSitemap(Sitemap):

    def items(self):
        return Post.objects.all()

My models.py file:

from django.urls import reverse

def get_absolute_url(self):
    return reverse('post', args=[str(self.id)])


问:
Multi level view: expandablelistview
I am trying to write multi level tree. I did look at expandablelistview, but it only supports two levels. I did look at other questions(SO) & posts and the most promising post i have found is http://mylifewithandroid.blogspot.com/2011/02/3-level-expandable-lists.html

I understand that i will have to write something custom to handle multiple level tree.
What is the best recommended approach to take?
Can i add an exapandablelistview as a child to an exapanablelistview??

Thanks

答:
It's possible, but it would make the GUI structure too complicated to implement.

First, you have to know that the items rendered of ExpandableListView are given by a BaseExpandableListAdapter. You have to design and implement the same number of adapters as your level-2 items, so that the level-3 lists can be rendered correctly for each level-2 item.

I would suggest you to redesign the GUI. Multilevel ExpandableListView not only complicate the code, maybe also mess up the screen.

Title: Multi level view: expandablelistview


问:
Is there are way to implement a method to upload files and view them from the server in MERN?
I want to implement a function to the user to upload files (just like docs, ppts, text files) and save to DB and another one to view that from getting from the server?
is there are any frameworks or npm modules for that?</p>

答:
Yes.
You can have one api endpoint to send files from your react app in the form of FormData and recieve/handle it in your express app using Multer. Then you can have another api endpoint to send file from your server and you can send the file using res.sendFile().
In your react app you need to access the file convert it into blob and then into dataUrl and then you can view it easily using that dataUrl.


问:
What is the SQL query to calculate average lease time?
I need to calculate an average lease time of my cars grouped by a brand.

For simplicity, I have the following LEASE table in my DB:

```<code>carMake | startDateTime | endDateTime
</code>```

My unfinished SQL query looks like:

```<code>SELECT lease.carMake
FROM lease
WHERE lease.startDateTime <= {?endDate} AND lease.endDateTime >= {?startDate}
SUM ... ???
GROUP BY lease.carMake ;
</code>```

Example:

```<code>carMake |   startDateTime   | endDateTime
MB        01.01.2018 00:00     01.01.2019 00:00
BMW       07.06.2018 21:00     01.01.2019 00:00
MB        06.06.2018 00:00     07.06.2018 00:00
</code>```

Result with query range between 06.06.2018 and 07.06.2018:

```<code>carMake | avgTime
MB        36 hours
BMW       3 hours
</code>```

Database is PostgreSQL

答:
I'm not sure what sql you are using but in SQL Server you can do something like this

```<code>DECLARE @startdate DATETIME= '2018-06-06 00:00:00'
DECLARE @endDate DATETIME= '2018-06-07 00:00:00'

SELECT LeaseTable.CarMake, AVG(LeaseTable.LeaseHours)
FROM
(SELECT lease.carmake,
    DATEDIFF(HH, case when lease.startDate <@startdate then @startdate else lease.startDate end, dateadd(DD, 1 ,case when lease.endDate > @endDate then @endDate else lease.endDate end)) as LeaseHours
    FROM lease
where
    lease.startDate <= @endDate AND lease.endDate >= @startdate) as LeaseTable
GROUP BY LeaseTable.carMake
</code>```

Let me break it down a little:

```<code>SELECT carmake, AVG(LeaseHours) -- know the lease time avr by car manufacture
FROM
(Select
    LeaseInPeriod.carmake,
    DATEDIFF(HH, LeaseInPeriod.PeriodStartDate, LeaseInPeriod.PeriodEndDate) as LeaseHours -- Know the lease time in hour
FROM
(SELECT lease.carmake,
    case when lease.startDate <@startdate then @startdate else lease.startDate end as PeriodStartDate, -- Know the actual lease start date between the perid limits
    dateadd(DD, 1 ,case when lease.endDate > @endDate then @endDate else lease.endDate end) as PeriodEndDate -- Know the actual lease end date between the perid limits
    FROM AS lease
where
    lease.startDate <= @endDate AND lease.endDate >= @startdate) AS LeaseInPeriod
) Leases
GROUP BY Leases.carMake
</code>```

Body:
I need to calculate an average lease time of my cars grouped by a brand.

For simplicity, I have the following LEASE table in my DB:

carMake | startDateTime | endDateTime

My unfinished SQL query looks like:

SELECT lease.carMake
FROM lease
WHERE lease.startDateTime <= {?endDate} AND lease.endDateTime >= {?startDate}
SUM ... ???
GROUP BY lease.carMake ;

Example:

carMake |   startDateTime   | endDateTime
MB        01.01.2018 00:00     01.01.2019 00:00
BMW       07.06.2018 21:00     01.01.2019 00:00
MB        06.06.2018 00:00     07.06.2018 00:00

Result with query range between 06.06.2018 and 07.06.2018:

carMake | avgTime
MB        36 hours
BMW       3 hours

Database is PostgreSQL

Body:
I'm not sure what sql you are using but in SQL Server you can do something like this

DECLARE @startdate DATETIME= '2018-06-06 00:00:00'
DECLARE @endDate DATETIME= '2018-06-07 00:00:00'

SELECT LeaseTable.CarMake, AVG(LeaseTable.LeaseHours)
FROM
(SELECT lease.carmake,
    DATEDIFF(HH, case when lease.startDate <@startdate then @startdate else lease.startDate end, dateadd(DD, 1 ,case when lease.endDate > @endDate then @endDate else lease.endDate end)) as LeaseHours
    FROM lease
where
    lease.startDate <= @endDate AND lease.endDate >= @startdate) as LeaseTable
GROUP BY LeaseTable.carMake

Let me break it down a little:

SELECT carmake, AVG(LeaseHours) -- know the lease time avr by car manufacture
FROM
(Select
    LeaseInPeriod.carmake,
    DATEDIFF(HH, LeaseInPeriod.PeriodStartDate, LeaseInPeriod.PeriodEndDate) as LeaseHours -- Know the lease time in hour
FROM
(SELECT lease.carmake,
    case when lease.startDate <@startdate then @startdate else lease.startDate end as PeriodStartDate, -- Know the actual lease start date between the perid limits
    dateadd(DD, 1 ,case when lease.endDate > @endDate then @endDate else lease.endDate end) as PeriodEndDate -- Know the actual lease end date between the perid limits
    FROM AS lease
where
    lease.startDate <= @endDate AND lease.endDate >= @startdate) AS LeaseInPeriod
) Leases
GROUP BY Leases.carMake


问:
How to iterate over two dictionaries & do calculation with values, conditional on keys?
I have two dictionaries, in both of which the keys are file names and the values are a array. dict_1 has 50 key value pairs, and dict_2 has 25, which are a subset of pairs from dict_1. I want to take each file in dict_1, and calculate the cosine between it's array and each array in dict_2, as long as the file name is not the same. Then take an average of these.

I have tried the following code:

```<code>for key in dict_1:
    cosines = []
    if key != dict_2[key]:
        cos = 1 - spatial.distance.cosine(dict_1[value],dict_2[value])
        cosines.append(cos)
        av = np.mean(cosines)
</code>```

But I am getting the error 'TypeError: unhashable type: 'numpy.ndarray'. I'm not really sure if this isthe best approach anyway. I think I could use itertools.combinations() but I don't know how to exclude keys that are the same. Any help greatly appreciated!

答:
Your comparisons of the keys doesn't accomplish what you want. if key != dict_2[key]: compares the key from dict_1 with a value from dict_2. It sounds like you instead want to compare keys.

Perhaps:

average = []
for key, value in dict_1.items():
    cosines = []
    for key2, value2 in dict_2.items():
        if key != key2:
            cos = # ...
            cosines.append(cos)
    averages.append(np.mean(cosines))
```

Body:
I have two dictionaries, in both of which the keys are file names and the values are a array. dict_1 has 50 key value pairs, and dict_2 has 25, which are a subset of pairs from dict_1. I want to take each file in dict_1, and calculate the cosine between it's array and each array in dict_2, as long as the file name is not the same. Then take an average of these.

I have tried the following code:

for key in dict_1:
    cosines = []
    if key != dict_2[key]:
        cos = 1 - spatial.distance.cosine(dict_1[value],dict_2[value])
        cosines.append(cos)
        av = np.mean(cosines)

But I am getting the error 'TypeError: unhashable type: 'numpy.ndarray'. I'm not really sure if this isthe best approach anyway. I think I could use itertools.combinations() but I don't know how to exclude keys that are the same. Any help greatly appreciated!


问:
How can I generate random coordinates inside a polygon?
I have some coordinates and i want to create some random coordinates that are inside the polygon.

```<code>coords = np.random.rand(20, 2)* 2
</code>```

I have created random coordinates, but they are outside my polygon.

```<code>poly= Polygon([(22.794525711443953, 39.431753895579845), (22.797156635193346,39.43552620818886), (22.79643512096834,39.4363589771401), (22.79243347988472,39.43454099778662), (22.794525711443953, 39.431753895579845)])

def point_inside_polygon(x,y,poly):

    n = len(poly)
    inside =False

    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

coords = np.random.rand(20, 2)* 2
print(coords)
</code>```

答:
One way would be to just generate random coordinates and test if they lie into the polingon using skimage.measure.points_in_poly.

However, this could lead to useless computation and non-deterministic execution times.

A more smart way to do this is to draw your polygon on a numpy array using skimage.draw.polygon

```<code>from skimage.draw import polygon()
import numpy as np

max_size = 50 # Assuming it's square
max_vertices = 6 # length of your coord vector
coords = np.random.randint(0,high=max_size, size=[2, max_vertices])
# Here you got all the coordinates laying inside the polygon
rr, cc = skimage.draw.polygon(coords)

# Now you have to pick an element from rr and the corresponding from cc
# The simplest way is to pick its position in rr or cc
random_index = np.random.choice(list(range(len(rr))))
random_point = (rr[random_index], cc[random_index])

</code>```

For the last section there are multiple choices, this is quite simple if you just want to pick coordinates using a uniform distribution.

If your data is not an image, or you need to use floats without approximations, a way to go would be to subdivide your polygon into triangles, picking a random triangle and then sampling inside that. You can refer to this post for further information.

Body:
I have some coordinates and i want to create some random coordinates that are inside the polygon.

coords = np.random.rand(20, 2)* 2

I have created random coordinates, but they are outside my polygon.

poly= Polygon([(22.794525711443953, 39.431753895579845), (22.797156635193346,39.43552620818886), (22.79643512096834,39.4363589771401), (22.79243347988472,39.43454099778662), (22.794525711443953, 39.431753895579845)])

def point_inside_polygon(x,y,poly):

    n = len(poly)
    inside =False

    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xinters:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

coords = np.random.rand(20, 2)* 2
print(coords)

Body:
One way would be to just generate random coordinates and test if they lie into the polingon using skimage.measure.points_in_poly.

However, this could lead to useless computation and non-deterministic execution times.

A more smart way to do this is to draw your polygon on a numpy array using skimage.draw.polygon

from skimage.draw import polygon()
import numpy as np

max_size = 50 # Assuming it's square
max_vertices = 6 # length of your coord vector
coords = np.random.randint(0,high=max_size, size=[2, max_vertices])
# Here you got all the coordinates laying inside the polygon
rr, cc = skimage.draw.polygon(coords)

# Now you have to pick an element from rr and the corresponding from cc
# The simplest way is to pick its position in rr or cc
random_index = np.random.choice(list(range(len(rr))))
random_point = (rr[random_index], cc[random_index])

For the last section there are multiple choices, this is quite simple if you just want to pick coordinates using a uniform distribution.

If your data is not an image, or you need to use floats without approximations, a way to go would be to subdivide your polygon into triangles, picking a random triangle and then sampling inside that. You can refer to this post for further information.


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答: sprintf only works with char*, you cannot use it with strings. Try _UserDir.c_str() and you should be fine.</p>

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release


问:
Ignore Git commits when pull. Skip commits and continue from latest commit
I pushed the code twice on my repo and pulled it on the server, It had some issues so I had to go back and hard reset to a previous commit. Can I only get changes from last commit ?

Command I used to go back to commit 'C'

git reset --hard C

Visual representation:

commits on repo:

A-B-C-D-E-F

git on server side:

A-B-C'

Locally I only want to push some changes that are in commit 'F'. Now i want to pull changes only from the commit 'F' and skip 'D,E'. On server it tells me I am three commits behind and when I pull it gets files from all the commits. I only want files updated in 'F' commit or any other latest commit.

(Sorry for bad english)

答:
git reset --hard HEAD~1

git push -f

(Example push: git push -f origin bugfix/bug123)

This will undo the last commit and push the updated history to the remote. You need
to pass the -f because you're replacing upstream history in the remote.

And if you want revert or undo a no of commits let's say 3 then the command will change like

git reset --hard HEAD~3

git push -f

For more info


问:
If- statement not working in scrapy
I've built a crawler using scrapy to crawl into a sitemap and scrape required components from all the links in the sitemap.

```<code>class MySpider(SitemapSpider):
 name = "functie"
 allowed_domains = ["xyz.nl"]
 sitemap_urls = ["http://www.xyz.nl/sitemap.xml"]

 def parse(self, response):
  item = MyItem()
  sel = Selector(response)

  item['url'] = response.url
  item['h1'] = sel.xpath("//h1[@class='no-bd']/text()").extract()
  item['jobtype'] = sel.xpath('//input[@name=".Keyword"]/@value').extract()
  item['count'] = sel.xpath('//input[@name="Count"]/@value').extract()
  item['location'] = sel.xpath('//input[@name="Location"]/@value').extract()
  yield item
</code>```

The item['location'] can have null values at some cases. In that particular case i want to scrape other component and store it in item['location'].
The code i've tried is:

```<code>item['location'] = sel.xpath('//input[@name="Location"]/@value').extract()
if not item['location']:
 item['location'] = sel.xpath('//a[@class="location"]/text()').extract()
</code>```

But it doesn't checks the if-condition and returns empty if value is empty in the input field for location. Any help would be highly useful.

答:
I think what you are trying to achieve is best solved with a custom item pipeline.

1) Open pipelines.py and check your desired if condition within a Pipeline class:

```<code>class LocPipeline(object):
    def process_item(self, item, spider):
        # check if key "location" is in item dict
        if not item.get("location"):
            # if not, try specific xpath
            item['location'] = sel.xpath('//a[@class="location"]/text()').extract()
        else:
            # if location was already found, do nothing
            pass

        return item
</code>```

2) The next step is to add the custom LocPipeline() to your settings.py file:

ITEM_PIPELINES = {'myproject.pipelines.LocPipeline': 300}

Adding the custom pipeline to your settings, scrapy will automatically call the LocPipeline().process_item() after MySpider().parse() and search for the alternative XPath if no location is found yet.

Title: If- statement not working in scrapy

Body:
I've built a crawler using scrapy to crawl into a sitemap and scrape required components from all the links in the sitemap.

class MySpider(SitemapSpider):
 name = "functie"
 allowed_domains = ["xyz.nl"]
 sitemap_urls = ["http://www.xyz.nl/sitemap.xml"]

 def parse(self, response):
  item = MyItem()
  sel = Selector(response)

  item['url'] = response.url
  item['h1'] = sel.xpath("//h1[@class='no-bd']/text()").extract()
  item['jobtype'] = sel.xpath('//input[@name=".Keyword"]/@value').extract()
  item['count'] = sel.xpath('//input[@name="Count"]/@value').extract()
  item['location'] = sel.xpath('//input[@name="Location"]/@value').extract()
  yield item

The item['location'] can have null values at some cases. In that particular case i want to scrape other component and store it in item['location'].
The code i've tried is:

item['location'] = sel.xpath('//input[@name="Location"]/@value').extract()
if not item['location']:
 item['location'] = sel.xpath('//a[@class="location"]/text()').extract()

But it doesn't checks the if-condition and returns empty if value is empty in the input field for location. Any help would be highly useful.

Body:
I think what you are trying to achieve is best solved with a custom item pipeline.

1) Open pipelines.py and check your desired if condition within a Pipeline class:

class LocPipeline(object):
    def process_item(self, item, spider):
        # check if key "location" is in item dict
        if not item.get("location"):
            # if not, try specific xpath
            item['location'] = sel.xpath('//a[@class="location"]/text()').extract()
        else:
            # if location was already found, do nothing
            pass

        return item

2) The next step is to add the custom LocPipeline() to your settings.py file:

ITEM_PIPELINES = {'myproject.pipelines.LocPipeline': 300}

Adding the custom pipeline to your settings, scrapy will automatically call the LocPipeline().process_item() after MySpider().parse() and search for the alternative XPath if no location is found yet.


问:
Switching X and Y axis around on Google Line chart
On my X-axis is ip addresses (String) and my Y-Axis is percentages (Numbers), However I want to switch them around and when I try to do it on my code I get "All series on a given axis must be of the same data type" error. I think it's because it does not allow the first column to be a Number.

Switching addColumn/addRow statements around to start with numbers (memory usage and CPU Usage) and end with server IP.
Using arrayToDataTable instead of DataTable.

```<code>           /*<![CDATA[*/
            var serverStatuses = /*[[${serverStatuses}]]*/ 'default';
            /*]]>*/
            var performanceData =new google.visualization.DataTable();

            performanceData.addColumn('number', 'CPU Usage');
            performanceData.addColumn('number', 'Memory Usage');
            performanceData.addColumn('string', 'Server IP');

            for (var n = 0; n < serverStatuses.length; n++) {
                performanceData.addRow([serverStatuses[n].memoryUsage,
                    serverStatuses[n].cpuUsage,
                 serverStatuses[n].ipAddress]);
            }
</code>```

IP addresses on the Y-Axis and Percentages on the X-Axis.

答:
as you've discovered, you cannot have a string on the y-axis of a line chart.

see the data format for specifics...

however, we can use object notation to represent the ip address by a number.

then display the address instead of the number.

when loading a cell in google's data table,

we can provide an intrinsic value, such as --> '127.0.0.1'

or we can use an object, and provide both the value (v:) and the formatted value (f:)

{v: 0, f: '127.0.0.1'}

this will cause the chart to use zero for the value, but display the address on the chart.

this solves half of our problem, by loading the data in the data table.

now we must solve the issue of the labels actually displayed on the y-axis.

here, we can use the ticks option.

the ticks option will accept the same object notation above.

so if we want ip addresses on the y-axis, supply ticks as follows...

```<code>[{v: 0, f: '127.0.0.1'}, {v: 0.1, f: '127.0.0.2'}, {v: 0.2, f: '127.0.0.3'}]
</code>```

see following working snippet for an example...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var serverStatuses = [
    {memoryUsage: 0.1, ipAddress: '127.0.0.1'},
    {memoryUsage: 0.3, ipAddress: '127.0.0.2'},
    {memoryUsage: 0.5, ipAddress: '127.0.0.3'},
    {memoryUsage: 0.7, ipAddress: '127.0.0.4'},
    {memoryUsage: 0.9, ipAddress: '127.0.0.5'},
  ];

  var performanceData = new google.visualization.DataTable();
  performanceData.addColumn('number', 'Memory Usage');
  performanceData.addColumn('number', 'Server IP');

  var axisTicks = [];
  serverStatuses.forEach(function (row, index) {
    var address = {
      v: index,
      f: row.ipAddress
    };
    axisTicks.push(address);
    performanceData.addRow([
      row.memoryUsage,
      address
    ]);
  });

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(performanceData, {
    vAxis: {
      ticks: axisTicks
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

Body:
On my X-axis is ip addresses (String) and my Y-Axis is percentages (Numbers), However I want to switch them around and when I try to do it on my code I get "All series on a given axis must be of the same data type" error. I think it's because it does not allow the first column to be a Number.

Switching addColumn/addRow statements around to start with numbers (memory usage and CPU Usage) and end with server IP.
Using arrayToDataTable instead of DataTable.

           /*<![CDATA[*/
            var serverStatuses = /*[[${serverStatuses}]]*/ 'default';
            /*]]>*/
            var performanceData =new google.visualization.DataTable();

            performanceData.addColumn('number', 'CPU Usage');
            performanceData.addColumn('number', 'Memory Usage');
            performanceData.addColumn('string', 'Server IP');

            for (var n = 0; n < serverStatuses.length; n++) {
                performanceData.addRow([serverStatuses[n].memoryUsage,
                    serverStatuses[n].cpuUsage,
                 serverStatuses[n].ipAddress]);
            }

IP addresses on the Y-Axis and Percentages on the X-Axis.

Body:
as you've discovered, you cannot have a string on the y-axis of a line chart.

see the data format for specifics...

however, we can use object notation to represent the ip address by a number.

then display the address instead of the number.

when loading a cell in google's data table,

we can provide an intrinsic value, such as --> '127.0.0.1'

or we can use an object, and provide both the value (v:) and the formatted value (f:)

{v: 0, f: '127.0.0.1'}

this will cause the chart to use zero for the value, but display the address on the chart.

this solves half of our problem, by loading the data in the data table.

now we must solve the issue of the labels actually displayed on the y-axis.

here, we can use the ticks option.

the ticks option will accept the same object notation above.

so if we want ip addresses on the y-axis, supply ticks as follows...

[{v: 0, f: '127.0.0.1'}, {v: 0.1, f: '127.0.0.2'}, {v: 0.2, f: '127.0.0.3'}]

see following working snippet for an example...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var serverStatuses = [
    {memoryUsage: 0.1, ipAddress: '127.0.0.1'},
    {memoryUsage: 0.3, ipAddress: '127.0.0.2'},
    {memoryUsage: 0.5, ipAddress: '127.0.0.3'},
    {memoryUsage: 0.7, ipAddress: '127.0.0.4'},
    {memoryUsage: 0.9, ipAddress: '127.0.0.5'},
  ];

  var performanceData = new google.visualization.DataTable();
  performanceData.addColumn('number', 'Memory Usage');
  performanceData.addColumn('number', 'Server IP');

  var axisTicks = [];
  serverStatuses.forEach(function (row, index) {
    var address = {
      v: index,
      f: row.ipAddress
    };
    axisTicks.push(address);
    performanceData.addRow([
      row.memoryUsage,
      address
    ]);
  });

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
  chart.draw(performanceData, {
    vAxis: {
      ticks: axisTicks
    }
  });
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


问:
Blurry text when zooming in with Chrome
So I have this really weird issue on a page. The users need to be able to zoom out to make the text even smaller than the 10px I've already set it to. That's all well and good, but for some odd reason, the text gets really blurry at certain areas.

The text in question is in a data table, and it will only appear this way on maybe 2/5 rows, making the behaviour even weirder. Doesn't matter if I resize the window or anything like that, it's always the same 2 rows.

I've looked at multiple other questions, but they all involve issues stemming from transform: scale(), etc. This did lead me to try out multiple fixes (backface-visibility etc), but none of them worked. Using CSS zoom: 90% looks perfectly fine, so it's just when the browser does the zooming.

Would appreciate any suggestions, I've spent far too long on this problem already.

Base font: 400 13px/24px Roboto, "Helvetica Neue", sans-serif

答:
Try using -webkit-font-smoothing: antialiased; like this

```<code>* {
   -webkit-font-smoothing: antialiased;
}
</code>```

Title: Blurry text when zooming in with Chrome

Body:
Try using -webkit-font-smoothing: antialiased; like this

* {
   -webkit-font-smoothing: antialiased;
}


问:
What is the shortest function for reading a cookie by name in JavaScript?
What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)

```<code>function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
</code>```

It does the job, but its ugly, and adds quite a bit of bloat each time.

The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):

```<code>function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}
</code>```

Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.

答:
This will only ever hit document.cookie ONE time.  Every subsequent request will be instant.

```<code>(function(){
    var cookies;

    function readCookie(name,c,C,i){
        if(cookies){ return cookies[name]; }

        c = document.cookie.split('; ');
        cookies = {};

        for(i=c.length-1; i>=0; i--){
           C = c[i].split('=');
           cookies[C[0]] = C[1];
        }

        return cookies[name];
    }

    window.readCookie = readCookie; // or expose it however you want
})();
</code>```

I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)

Your own example slightly compressed to 120 bytes:

```<code>function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}
</code>```

You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.

I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:

```<code>function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}
</code>```

Body:
What is the shortest, accurate, and cross-browser compatible method for reading a cookie in JavaScript?

Very often, while building stand-alone scripts (where I can't have any outside dependencies), I find myself adding a function for reading cookies, and usually fall-back on the QuirksMode.org readCookie() method (280 bytes, 216 minified.)

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

It does the job, but its ugly, and adds quite a bit of bloat each time.

The method that jQuery.cookie uses something like this (modified, 165 bytes, 125 minified):

function read_cookie(key)
{
    var result;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

Note this is not a 'Code Golf' competition: I'm legitimately interested in reducing the size of my readCookie function, and in ensuring the solution I have is valid.

Body:
This will only ever hit document.cookie ONE time.  Every subsequent request will be instant.

(function(){
    var cookies;

    function readCookie(name,c,C,i){
        if(cookies){ return cookies[name]; }

        c = document.cookie.split('; ');
        cookies = {};

        for(i=c.length-1; i>=0; i--){
           C = c[i].split('=');
           cookies[C[0]] = C[1];
        }

        return cookies[name];
    }

    window.readCookie = readCookie; // or expose it however you want
})();

I'm afraid there really isn't a faster way than this general logic unless you're free to use .forEach which is browser dependent (even then you're not saving that much)

Your own example slightly compressed to 120 bytes:

function read_cookie(k,r){return(r=RegExp('(^|; )'+encodeURIComponent(k)+'=([^;]*)').exec(document.cookie))?r[2]:null;}

You can get it to 110 bytes if you make it a 1-letter function name, 90 bytes if you drop the encodeURIComponent.

I've gotten it down to 73 bytes, but to be fair it's 82 bytes when named readCookie and 102 bytes when then adding encodeURIComponent:

function C(k){return(document.cookie.match('(^|; )'+k+'=([^;]*)')||0)[2]}


问:
AssumeDefaultVersionWhenUnspecified is not working as expected
I have been using asp net core versioning component for my WebAPI. Need your help in understanding how AssumeDefaultVersionWhenUnspecified is working. (tried searching for documentation, but couldn't find one)

My startup looks like below

```<code>services.AddApiVersioning(o => {
            o.ReportApiVersions = true;
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.DefaultApiVersion = new ApiVersion(2, 0);
            o.ApiVersionReader = new UrlSegmentApiVersionReader();
        });
</code>```

When the route attribute is something like below

```<code>[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/values")]
[ApiController]
public class ValuesV2Controller : ControllerBase
{
...
}
</code>```

The above route works only when the api version is specified. ie: http://localhost:55401/api/v2/values
If I call like http://localhost:55401/api/values, getting 404 error

My question is this... How AssumeDefaultVersionWhenUnspecified works. Wouldn't it ignore the version in Route? Looks like Route attribute takes precedence over AssumeDefaultVersionWhenUnspecified. If I choose QueryString or Header versioning and when the Route looks like

```<code>[ApiVersion("2.0")]
[Route("api/values")]
</code>```

the default routing reaches the API

Am I missing anything or is my understanding wrong? How shall I achieve default routing to the latest version API using url versioning?

答:
Summarizing the the solution from the github issue linked by Athi S, here's what you need to do :

In ConfigureServices inside Startup.cs file :

```<code>        services.AddApiVersioning(o =>
        {
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);
            //  o.DefaultApiVersion = new ApiVersion(1, 0);
        });
</code>```

You can optionally set ApiVersionSelector to a new instance of CurrentImplementationApiVersionSelector. What this does is, it automatically selects the highest api version registered in controllers. E.g. A controller decorated with [ApiVersion("1.2")] takes precedence over [ApiVersion("1.1")].

If you want to specify default api version explicitly, you can do so by leaving ApiVersionSelector to DefaultApiVersionSelector and setting DefaultApiVersion to your required api version.

In your controllers :

Register the required routes by decorating your controllers with the given Route attributes

```<code>[Route("api/[controller]")]
</code>```

Or if you want the api to work both with and without the api version number specified, you can do so by declaring two routes for the controller.

```<code>[Route("api/[controller]")]
[Route("api/v{version:apiVersion}/[controller]")]
</code>```

Body:
I have been using asp net core versioning component for my WebAPI. Need your help in understanding how AssumeDefaultVersionWhenUnspecified is working. (tried searching for documentation, but couldn't find one)

My startup looks like below

services.AddApiVersioning(o => {
            o.ReportApiVersions = true;
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.DefaultApiVersion = new ApiVersion(2, 0);
            o.ApiVersionReader = new UrlSegmentApiVersionReader();
        });

When the route attribute is something like below

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/values")]
[ApiController]
public class ValuesV2Controller : ControllerBase
{
...
}

The above route works only when the api version is specified. ie: http://localhost:55401/api/v2/values
If I call like http://localhost:55401/api/values, getting 404 error

My question is this... How AssumeDefaultVersionWhenUnspecified works. Wouldn't it ignore the version in Route? Looks like Route attribute takes precedence over AssumeDefaultVersionWhenUnspecified. If I choose QueryString or Header versioning and when the Route looks like

[ApiVersion("2.0")]
[Route("api/values")]

the default routing reaches the API

Am I missing anything or is my understanding wrong? How shall I achieve default routing to the latest version API using url versioning?

Body:
Summarizing the the solution from the github issue linked by Athi S, here's what you need to do :

In ConfigureServices inside Startup.cs file :

        services.AddApiVersioning(o =>
        {
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);
            //  o.DefaultApiVersion = new ApiVersion(1, 0);
        });

You can optionally set ApiVersionSelector to a new instance of CurrentImplementationApiVersionSelector. What this does is, it automatically selects the highest api version registered in controllers. E.g. A controller decorated with [ApiVersion("1.2")] takes precedence over [ApiVersion("1.1")].

If you want to specify default api version explicitly, you can do so by leaving ApiVersionSelector to DefaultApiVersionSelector and setting DefaultApiVersion to your required api version.

In your controllers :

Register the required routes by decorating your controllers with the given Route attributes

[Route("api/[controller]")]

Or if you want the api to work both with and without the api version number specified, you can do so by declaring two routes for the controller.

[Route("api/[controller]")]
[Route("api/v{version:apiVersion}/[controller]")]


问:
Test class for setting same value to two diferents objects
Need help doing test class for this code part! how to do this in a test class

I tried creating the account and equals to the other object.

```<code>for (Account YieldU : AccountList){
           YieldU.Yield__c = a.Yield__c;
           YieldU.Yield2__c = a.Yield2__c;
          ...
</code>```

答:
```<code>list<account> acclist = new list<account>();
    list<Gym__c> gmlist = new list<Gym__c>();
    Account acct = new Account();
    acct.Bike__c= abc;
    acct.m2_total__c = xyz;
    acct.m2_fitness_group__c = def;
    acct.active = true;
    insert acct;
    acclist.add(acct);
    for (account ac:acclist)
    {
        gym__c gm=new gym();
        gm.gym_id__c= ac.id;
        gm.bike__c = ac.bike__c;
        gm.m2_total__c = ac.m2_total__c;
        gm.m2_fitness_group__c = ac.m2_fitness_group__c;
        gm.active__c = ac.active__c;
        gmlist.add(gm);

    }
    insert gmlist;
</code>```

if then also you did not get your result then please share your whole code with me.

Body:
Need help doing test class for this code part! how to do this in a test class

I tried creating the account and equals to the other object.

for (Account YieldU : AccountList){
           YieldU.Yield__c = a.Yield__c;
           YieldU.Yield2__c = a.Yield2__c;
          ...

Body:
list<account> acclist = new list<account>();
    list<Gym__c> gmlist = new list<Gym__c>();
    Account acct = new Account();
    acct.Bike__c= abc;
    acct.m2_total__c = xyz;
    acct.m2_fitness_group__c = def;
    acct.active = true;
    insert acct;
    acclist.add(acct);
    for (account ac:acclist)
    {
        gym__c gm=new gym();
        gm.gym_id__c= ac.id;
        gm.bike__c = ac.bike__c;
        gm.m2_total__c = ac.m2_total__c;
        gm.m2_fitness_group__c = ac.m2_fitness_group__c;
        gm.active__c = ac.active__c;
        gmlist.add(gm);

    }
    insert gmlist;

if then also you did not get your result then please share your whole code with me.


问:
How do I use a freshly compiled LLVM tool directly from LLVM source tree?
I am writing a MachineFunctionPass targeting the X86 architecture which results in a modified llc binary.

In order to test my modified version of llc I have created a bunch of .c programs whose MIR will be handled by my pass.

For the sake of cleanliness, I have added the directory including the sources directly into LLVM's source tree, specifically in $llvm_src_dir/lib/Target/X86/$examples_dir: I have then plugged it into LLVM build system by appending the add_subdirectory() directive to $llvm_src_dir/lib/Target/X86/CMakeLists.txt.

In this way, I will be able to build everything directly from LLVM's build directory.

Now: how do I specify in my $examples_dir/CMakeLists.txt to use LLVM's in-tree llc?

Source tree structure

This is the sources' directory structure. I have omitted all the root's children directories since I've only included the "interesting ones".

LLVM's defines the llc target in tools/llc while my sources live quite deeper in the directory as shown in the following tree:

```<code>llvm_src_dir
├── bindings
├── cmake
├── docs
├── examples
├── include
├── lib
    └── Target
        └── X86
            /*
             * My git repo is here. LLVM's and
             * my MachineFunctionPass' files
             * live here
            */
            ├── .git
            ├── CMakeLists.txt // This is LLVM's X86 CMakeLists.txt
            └── examples
                └── CMakeLists.txt // My CMakeLists.txt
├── projects
├── resources
├── runtimes
├── test
├── tools
    └── llc
        └── CMakeLists.txt // this is where LLVM's llc target is defined
├── unittests
└── utils
</code>```

lib/Target/X86/CMakeLists.txt

This is how I edited the CMakeLists.txt of the architecture I'm targeting:

```<code>set (CMAKE_CXX_STANDARD 14)
set(LLVM_TARGET_DEFINITIONS X86.td)

tablegen(LLVM X86GenAsmMatcher.inc -gen-asm-matcher)
tablegen(LLVM X86GenAsmWriter.inc -gen-asm-writer)
tablegen(LLVM X86GenAsmWriter1.inc -gen-asm-writer -asmwriternum=1)
tablegen(LLVM X86GenCallingConv.inc -gen-callingconv)
tablegen(LLVM X86GenDAGISel.inc -gen-dag-isel)
tablegen(LLVM X86GenDisassemblerTables.inc -gen-disassembler)
tablegen(LLVM X86GenEVEX2VEXTables.inc -gen-x86-EVEX2VEX-tables)
tablegen(LLVM X86GenFastISel.inc -gen-fast-isel)
tablegen(LLVM X86GenGlobalISel.inc -gen-global-isel)
tablegen(LLVM X86GenInstrInfo.inc -gen-instr-info)
tablegen(LLVM X86GenRegisterBank.inc -gen-register-bank)
tablegen(LLVM X86GenRegisterInfo.inc -gen-register-info)
tablegen(LLVM X86GenSubtargetInfo.inc -gen-subtarget)

if (X86_GEN_FOLD_TABLES)
    tablegen(LLVM X86GenFoldTables.inc -gen-x86-fold-tables)
endif ()

add_public_tablegen_target(X86CommonTableGen)

set(MY_SOURCES
        a.cpp
        b.cpp
        c.cpp
        )

set(sources
        ShadowCallStack.cpp
        X86AsmPrinter.cpp
        X86CallFrameOptimization.cpp
        X86CallingConv.cpp
        X86CallLowering.cpp
        X86CmovConversion.cpp
        X86DomainReassignment.cpp
        X86ExpandPseudo.cpp
        X86FastISel.cpp
        X86FixupBWInsts.cpp
        X86FixupLEAs.cpp
        X86AvoidStoreForwardingBlocks.cpp
        X86FixupSetCC.cpp
        X86FlagsCopyLowering.cpp
        X86FloatingPoint.cpp
        X86FrameLowering.cpp
        X86InstructionSelector.cpp
        X86ISelDAGToDAG.cpp
        X86ISelLowering.cpp
        X86IndirectBranchTracking.cpp
        X86InterleavedAccess.cpp
        X86InstrFMA3Info.cpp
        X86InstrFoldTables.cpp
        X86InstrInfo.cpp
        X86EvexToVex.cpp
        X86LegalizerInfo.cpp
        X86MCInstLower.cpp
        X86MachineFunctionInfo.cpp
        X86MacroFusion.cpp
        X86OptimizeLEAs.cpp
        X86PadShortFunction.cpp
        X86RegisterBankInfo.cpp
        X86RegisterInfo.cpp
        X86RetpolineThunks.cpp
        X86SelectionDAGInfo.cpp
        X86ShuffleDecodeConstantPool.cpp
        X86SpeculativeLoadHardening.cpp
        X86Subtarget.cpp
        X86TargetMachine.cpp
        X86TargetObjectFile.cpp
        X86TargetTransformInfo.cpp
        X86VZeroUpper.cpp
        X86WinAllocaExpander.cpp
        X86WinEHState.cpp
        ${MY_SOURCES}
        )

add_llvm_target(X86CodeGen ${sources})

add_subdirectory(AsmParser)
add_subdirectory(Disassembler)
add_subdirectory(InstPrinter)
add_subdirectory(MCTargetDesc)
add_subdirectory(TargetInfo)
add_subdirectory(Utils)
add_subdirectory(examples) // my examples directory
</code>```

What I have already tried

I am currently using find_path() to find llc but this requires llc to be already compiled and therefore my examples CMakeLists.txt will fail the validation if I don't compile llc beforehand.

Assuming the path exists, I finally use an add_custom_command() directive to use llc in my CMakeLists.txt but this is way too hacky in my opinion.

Basically, I need to add the llc target as a dependency for my targets and then use llc's path to compile my examples' .bc files into .s.

Any ideas?

Thank you very much!

答:
I see two possible solutions and for now let me present simpler one.

```<code>project(nested-toolchain C CXX)

# Assume that `llc` target is created somewhere within project
# Even if it is created in later `add_subdirectory` calls,
# We can defer evaluation to its path using generator expression $<TARGET_FILE:llc>

# This is the magic.
# It tells cmake how to produce test1.s from test1.bc using llc binary
# Also will track test1.bc changes and set test1.s as dirty when needed
add_custom_command(OUTPUT test1.s COMMAND $<TARGET_FILE:llc> test1.bc DEPENDS test1.bc)
add_custom_command(OUTPUT test2.s COMMAND $<TARGET_FILE:llc> test2.bc DEPENDS test2.bc)

# Now merge custom commands into single target which can be called by make/ninja/...
# simply call `make tests` to run two commands listed above (and compile llc before that)
add_custom_target(tests SOURCES test1.s test2.s)

</code>```

To sum up: first we know that our CMake project can produce llc binary somewhere from llvm-sources. This binary can be used to produce test.s files with magic command specified.
They depend on corresponding .bc files. These .bc files are joined into single target tests via add_custom_target.

I've used add_custom_target to keep example minimal and it has one flaw: calling make tests will always call all llc commands, as custom targets are always considered "out of date".

If you want to use another tool over .s files, I recommend to chain yet another add_custom_command analogically and use add_custom_target to finish the chain.

This approach should work as long as you are testing single binary (llc). If you wanted to test whole toolchain, I'd go for try_compile.

For completeness, for llc.cpp file as given:

```<code>// Just print args
#include <iostream>
int main(int argc, char **argv) {
  for (int i = 0; i < argc; i++) {
    std::cout << argv[i] << ' ';
  }
  std::cout << "\n";
  return 0;
}
</code>```

ninja tests result in:

```<code>$ ninja tests
[1/2] Generating test2.s
/home/stackoverflow/nested-toolchain/build/llc test2.bc
[2/2] Generating test1.s
/home/stackoverflow/nested-toolchain/build/llc test1.bc
</code>```

Body:
I am writing a MachineFunctionPass targeting the X86 architecture which results in a modified llc binary.

In order to test my modified version of llc I have created a bunch of .c programs whose MIR will be handled by my pass.

For the sake of cleanliness, I have added the directory including the sources directly into LLVM's source tree, specifically in $llvm_src_dir/lib/Target/X86/$examples_dir: I have then plugged it into LLVM build system by appending the add_subdirectory() directive to $llvm_src_dir/lib/Target/X86/CMakeLists.txt.

In this way, I will be able to build everything directly from LLVM's build directory.

Now: how do I specify in my $examples_dir/CMakeLists.txt to use LLVM's in-tree llc?

Source tree structure

This is the sources' directory structure. I have omitted all the root's children directories since I've only included the "interesting ones".

LLVM's defines the llc target in tools/llc while my sources live quite deeper in the directory as shown in the following tree:

llvm_src_dir
├── bindings
├── cmake
├── docs
├── examples
├── include
├── lib
    └── Target
        └── X86
            /*
             * My git repo is here. LLVM's and
             * my MachineFunctionPass' files
             * live here
            */
            ├── .git
            ├── CMakeLists.txt // This is LLVM's X86 CMakeLists.txt
            └── examples
                └── CMakeLists.txt // My CMakeLists.txt
├── projects
├── resources
├── runtimes
├── test
├── tools
    └── llc
        └── CMakeLists.txt // this is where LLVM's llc target is defined
├── unittests
└── utils

lib/Target/X86/CMakeLists.txt

This is how I edited the CMakeLists.txt of the architecture I'm targeting:

set (CMAKE_CXX_STANDARD 14)
set(LLVM_TARGET_DEFINITIONS X86.td)

tablegen(LLVM X86GenAsmMatcher.inc -gen-asm-matcher)
tablegen(LLVM X86GenAsmWriter.inc -gen-asm-writer)
tablegen(LLVM X86GenAsmWriter1.inc -gen-asm-writer -asmwriternum=1)
tablegen(LLVM X86GenCallingConv.inc -gen-callingconv)
tablegen(LLVM X86GenDAGISel.inc -gen-dag-isel)
tablegen(LLVM X86GenDisassemblerTables.inc -gen-disassembler)
tablegen(LLVM X86GenEVEX2VEXTables.inc -gen-x86-EVEX2VEX-tables)
tablegen(LLVM X86GenFastISel.inc -gen-fast-isel)
tablegen(LLVM X86GenGlobalISel.inc -gen-global-isel)
tablegen(LLVM X86GenInstrInfo.inc -gen-instr-info)
tablegen(LLVM X86GenRegisterBank.inc -gen-register-bank)
tablegen(LLVM X86GenRegisterInfo.inc -gen-register-info)
tablegen(LLVM X86GenSubtargetInfo.inc -gen-subtarget)

if (X86_GEN_FOLD_TABLES)
    tablegen(LLVM X86GenFoldTables.inc -gen-x86-fold-tables)
endif ()

add_public_tablegen_target(X86CommonTableGen)

set(MY_SOURCES
        a.cpp
        b.cpp
        c.cpp
        )

set(sources
        ShadowCallStack.cpp
        X86AsmPrinter.cpp
        X86CallFrameOptimization.cpp
        X86CallingConv.cpp
        X86CallLowering.cpp
        X86CmovConversion.cpp
        X86DomainReassignment.cpp
        X86ExpandPseudo.cpp
        X86FastISel.cpp
        X86FixupBWInsts.cpp
        X86FixupLEAs.cpp
        X86AvoidStoreForwardingBlocks.cpp
        X86FixupSetCC.cpp
        X86FlagsCopyLowering.cpp
        X86FloatingPoint.cpp
        X86FrameLowering.cpp
        X86InstructionSelector.cpp
        X86ISelDAGToDAG.cpp
        X86ISelLowering.cpp
        X86IndirectBranchTracking.cpp
        X86InterleavedAccess.cpp
        X86InstrFMA3Info.cpp
        X86InstrFoldTables.cpp
        X86InstrInfo.cpp
        X86EvexToVex.cpp
        X86LegalizerInfo.cpp
        X86MCInstLower.cpp
        X86MachineFunctionInfo.cpp
        X86MacroFusion.cpp
        X86OptimizeLEAs.cpp
        X86PadShortFunction.cpp
        X86RegisterBankInfo.cpp
        X86RegisterInfo.cpp
        X86RetpolineThunks.cpp
        X86SelectionDAGInfo.cpp
        X86ShuffleDecodeConstantPool.cpp
        X86SpeculativeLoadHardening.cpp
        X86Subtarget.cpp
        X86TargetMachine.cpp
        X86TargetObjectFile.cpp
        X86TargetTransformInfo.cpp
        X86VZeroUpper.cpp
        X86WinAllocaExpander.cpp
        X86WinEHState.cpp
        ${MY_SOURCES}
        )

add_llvm_target(X86CodeGen ${sources})

add_subdirectory(AsmParser)
add_subdirectory(Disassembler)
add_subdirectory(InstPrinter)
add_subdirectory(MCTargetDesc)
add_subdirectory(TargetInfo)
add_subdirectory(Utils)
add_subdirectory(examples) // my examples directory

What I have already tried

I am currently using find_path() to find llc but this requires llc to be already compiled and therefore my examples CMakeLists.txt will fail the validation if I don't compile llc beforehand.

Assuming the path exists, I finally use an add_custom_command() directive to use llc in my CMakeLists.txt but this is way too hacky in my opinion.

Basically, I need to add the llc target as a dependency for my targets and then use llc's path to compile my examples' .bc files into .s.

Any ideas?

Thank you very much!

Body:
I see two possible solutions and for now let me present simpler one.

project(nested-toolchain C CXX)

# Assume that `llc` target is created somewhere within project
# Even if it is created in later `add_subdirectory` calls,
# We can defer evaluation to its path using generator expression $<TARGET_FILE:llc>

# This is the magic.
# It tells cmake how to produce test1.s from test1.bc using llc binary
# Also will track test1.bc changes and set test1.s as dirty when needed
add_custom_command(OUTPUT test1.s COMMAND $<TARGET_FILE:llc> test1.bc DEPENDS test1.bc)
add_custom_command(OUTPUT test2.s COMMAND $<TARGET_FILE:llc> test2.bc DEPENDS test2.bc)

# Now merge custom commands into single target which can be called by make/ninja/...
# simply call `make tests` to run two commands listed above (and compile llc before that)
add_custom_target(tests SOURCES test1.s test2.s)

To sum up: first we know that our CMake project can produce llc binary somewhere from llvm-sources. This binary can be used to produce test.s files with magic command specified.
They depend on corresponding .bc files. These .bc files are joined into single target tests via add_custom_target.

I've used add_custom_target to keep example minimal and it has one flaw: calling make tests will always call all llc commands, as custom targets are always considered "out of date".

If you want to use another tool over .s files, I recommend to chain yet another add_custom_command analogically and use add_custom_target to finish the chain.

This approach should work as long as you are testing single binary (llc). If you wanted to test whole toolchain, I'd go for try_compile.

For completeness, for llc.cpp file as given:

// Just print args
#include <iostream>
int main(int argc, char **argv) {
  for (int i = 0; i < argc; i++) {
    std::cout << argv[i] << ' ';
  }
  std::cout << "\n";
  return 0;
}

ninja tests result in:

$ ninja tests
[1/2] Generating test2.s
/home/stackoverflow/nested-toolchain/build/llc test2.bc
[2/2] Generating test1.s
/home/stackoverflow/nested-toolchain/build/llc test1.bc


问:
Fabrics 2.x ssh connection using identity fails to work
Trying to connect to the host described in ssh config using fabrics 2 and identity file.

```<code>con = Connection('my_host')
@task
def tt(c):
    con.run('uname -a')
</code>```

~/.ssh/config :

```<code>Host my_host
    HostName 123.144.76.84
    User ubuntu
    IdentityFile ~/.keys/somekey
</code>```

It fails with

paramiko.ssh_exception.AuthenticationException: Authentication failed.

While $ ssh my_host from the terminal works.

I've tried to do fab -i  ~/.keys/somekey tt with same result.

答:
Fabric accepts a hosts iterable as parameters in tasks. Per the documentation:

An iterable of host-connection specifiers appropriate for eventually instantiating a Connection. The existence of this argument will trigger automatic parameterization of the task when invoked from the CLI, similar to the behavior of --hosts.

One of the members of which could be:

A string appropriate for being the first positional argument to Connection - see its docs for details, but these are typically shorthand-only convenience strings like hostname.example.com or user@host:port.

As for your example, please try this for fabfile.py:

```<code>host_list = ["my_host"]

@task(hosts=host_list)
def tt(c):
    c.run('uname -a')
</code>```

Alternatively, you can omit the host declaration from the fabfile altogether. If you don't specify the host in fabfile.py, you can simply specify it as a host when invoking the fab cli utility. If your fabfile.py is this:

```<code>@task
def tt(c):
    c.run('uname -a')
</code>```

You would now run fab -H my_host tt to run it on the alias tt from your SSH client config.

Hope this helps.

Body:
Trying to connect to the host described in ssh config using fabrics 2 and identity file.

con = Connection('my_host')
@task
def tt(c):
    con.run('uname -a')

~/.ssh/config :

Host my_host
    HostName 123.144.76.84
    User ubuntu
    IdentityFile ~/.keys/somekey

It fails with

paramiko.ssh_exception.AuthenticationException: Authentication failed.

While $ ssh my_host from the terminal works.

I've tried to do fab -i  ~/.keys/somekey tt with same result.

Body:
Fabric accepts a hosts iterable as parameters in tasks. Per the documentation:

An iterable of host-connection specifiers appropriate for eventually instantiating a Connection. The existence of this argument will trigger automatic parameterization of the task when invoked from the CLI, similar to the behavior of --hosts.

One of the members of which could be:

A string appropriate for being the first positional argument to Connection - see its docs for details, but these are typically shorthand-only convenience strings like hostname.example.com or user@host:port.

As for your example, please try this for fabfile.py:

host_list = ["my_host"]

@task(hosts=host_list)
def tt(c):
    c.run('uname -a')

Alternatively, you can omit the host declaration from the fabfile altogether. If you don't specify the host in fabfile.py, you can simply specify it as a host when invoking the fab cli utility. If your fabfile.py is this:

@task
def tt(c):
    c.run('uname -a')

You would now run fab -H my_host tt to run it on the alias tt from your SSH client config.

Hope this helps.


问:
Bootstrap : Add a junction between div
I'm trying to add a junction (a line) between 2 divs in the middle.

```<code><div class="row">
<div class="col-xs-6 col-md-6">
    <div style="background-color:#f39a6f;width:100%;height:100px;">
    ....1
    </div>
</div>
<div class="col-xs-6 col-md-6">
    <div style="background-color:#ffff00;width:100%;height:100px;">
    ....2
    </div>
</div>
</code>```

Thanks for help.

答:
Hope this code will solve your problem.

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

```

Title: Bootstrap : Add a junction between div

Body:
I'm trying to add a junction (a line) between 2 divs in the middle.

    ....1

    ....2

Thanks for help.

Body:
Hope this code will solve your problem.

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

<div class="row no-gutters">
        <div class="col-md-3">
          <div class="card bg-success">
            <div class="card-body"></div>
          </div>
        </div>
        <div class="col-md-2">
          <hr>
        </div>
        <div class="col-md-3">
            <div class="card bg-danger">
                <div class="card-body"></div>
              </div>
        </div>
      </div>


问:
type or namespace could not be found
hello i am doing windows 7 mobile application on Framework 4.
while creating object for class IPEndPoint giving error that type or namespace could not be found.please help me..</p>

答: You need to add using System.Net at the top of your file to include the namespace. However, it's possible, that the class isn't in the win 7 mobile framework. You probably are out of luck then.

Title: type or namespace could not be found