答:
If you are talking about output tables for LaTeX, HTML or Word, then you want to use a package for that purpose. There's a list of possible packages here. (Disclaimer: I wrote huxtable, which is one of the options.) Or you could just use knitr's built in kable.

In huxtable, here's how to do it:

```<code>library(huxtable)
# sample data:
tbl <- table(sample(letters[1:5], 20, replace = TRUE),
      sample(LETTERS[11:15], 20, replace = TRUE))
huxtbl <- as_hux(tbl, add_rownames = FALSE)
huxtbl <- rbind(rep('', 5), huxtbl)
colspan(huxtbl)[1, 1] <- 5
huxtbl[1, 1] <- 'Table title goes here'
huxtbl
</code>```

Which produces something like:

```<code>  V1   V2   V3   V4   V5
   Table title goes here
   K    L    M    N    O
   0    0    1    1    1
   0    1    3    1    0
   1    0    2    0    0
   1    2    1    1    1
   0    1    0    2    0
</code>```

on-screen, and exports the table to markdown, HTML or LaTeX.

Title: Creating a row for table name

Body:
I have a table as such:

    +-----------+----------------+----------+
    |           |     Type 1     | Type 2   |
    +-----------+----------------+----------+
    |    Mean   |     31,2       |    16,0  |
    |   Median  |     51,3       |    16,0  |
    |    Max    |     40,4       |    6,0   |
    |    Min    |     100,0      |    16,0  |
    |    Q1     |     34,6       |    16,0  |
    |    Q3     |     16,0       |    16,0  |
    +---+------------+-----------+----------+

How can I add a title to it, so it becomes:

    +-----------+----------------+----------+
    |        INSERT TABLE TITLE HERE        |
    +-----------+----------------+----------+
    |           |     Type 1     | Type 2   |
    +-----------+----------------+----------+
    |    Mean   |     31,2       |    16,0  |
    |   Median  |     51,3       |    16,0  |
    |    Max    |     40,4       |    6,0   |
    |    Min    |     100,0      |    16,0  |
    |    Q1     |     34,6       |    16,0  |
    |    Q3     |     16,0       |    16,0  |
    +---+------------+-----------+----------+

Body:
If you are talking about output tables for LaTeX, HTML or Word, then you want to use a package for that purpose. There's a list of possible packages here. (Disclaimer: I wrote huxtable, which is one of the options.) Or you could just use knitr's built in kable.

In huxtable, here's how to do it:

library(huxtable)
# sample data:
tbl <- table(sample(letters[1:5], 20, replace = TRUE),
      sample(LETTERS[11:15], 20, replace = TRUE))
huxtbl <- as_hux(tbl, add_rownames = FALSE)
huxtbl <- rbind(rep('', 5), huxtbl)
colspan(huxtbl)[1, 1] <- 5
huxtbl[1, 1] <- 'Table title goes here'
huxtbl

Which produces something like:

  V1   V2   V3   V4   V5
   Table title goes here
   K    L    M    N    O
   0    0    1    1    1
   0    1    3    1    0
   1    0    2    0    0
   1    2    1    1    1
   0    1    0    2    0

on-screen, and exports the table to markdown, HTML or LaTeX.


来源: stackexchange

问:
MS word 2016 Macro
I am new to VBA but I have a word 2016 template and it has the following sections:

```<code>Base Amount:    $

Service Fee:    $

Sales Tax %     $
Other tax %:    $
Tax 2     %:    $
</code>```

My goal is if an amount is missing from any of the lines, then delete that line.

I tried recording the macro and then making changes but no luck.

```<code>Sub TEST()
    Dim i As Long
    With Selection.Tables(1)
        For i = .Rows.Count To 1 Step -1
            If Len(.Cell(i, 2).Range.Text) = 2 Then
                .Rows(i).Delete
            End If
        Next i
    End With
End Sub
</code>```

答:
I've added :

the function Trim to remove useless spaces, so that you'll only have data left

changed the = to <=

Code :

```<code>Sub TEST()
    Dim i As Integer
    With Selection.Tables(1)
        For i = .Rows.Count To 1 Step -1
            If Len(Trim(.Cell(i, 2).Range.Text)) <= 2 Then
                .Rows(i).Delete
            End If
        Next i
    End With 'Selection.Tables(1)
End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Title: MS word 2016 Macro

Body:
I am new to VBA but I have a word 2016 template and it has the following sections:

Base Amount:    $

Service Fee:    $

Sales Tax %     $
Other tax %:    $
Tax 2     %:    $

My goal is if an amount is missing from any of the lines, then delete that line.

I tried recording the macro and then making changes but no luck.

Sub TEST()
    Dim i As Long
    With Selection.Tables(1)
        For i = .Rows.Count To 1 Step -1
            If Len(.Cell(i, 2).Range.Text) = 2 Then
                .Rows(i).Delete
            End If
        Next i
    End With
End Sub

Body:
I've added :

the function Trim to remove useless spaces, so that you'll only have data left

changed the = to <=

Code :

Sub TEST()
    Dim i As Integer
    With Selection.Tables(1)
        For i = .Rows.Count To 1 Step -1
            If Len(Trim(.Cell(i, 2).Range.Text)) <= 2 Then
                .Rows(i).Delete
            End If
        Next i
    End With 'Selection.Tables(1)
End Sub


问:
Datatable Horizontal scrolling not working
HTML Code:

```<code><table  class="display table table-bordered table-striped" id="example" cellspacing="0" width="100%">
  <thead>
  <tr>
      <th>Create Date</th>
      <th>Project Name</th>
      <th>Property Type</th>
      <th>Project Address</th>
      <th>Area</th>
      <th>ZIP Code</th>
      <th>City</th>
      <th>State</th>
      <th>Owner Name</th>
      <th>Owner E-mail</th>
      <th>Owner Mobile</th>
      <th>Owner Type</th>
      <th>BHK</th>
      <th>Bathroom</th>
      <th>Balcony</th>
      <th>Builtup</th>
      <th>Carpet</th>
      <th>Unit</th>
      <th>Furniture Status</th>
      <th>Sell Type</th>
      <th>Sell Price</th>
      <th>Registration Charge</th>
      <th>Monthly Rent</th>
      <th>Maintanace</th>
      <th>Security Deposit</th>
      <th>Bachelors</th>
  </tr>
  </thead>
  <tbody>
    <tr class="gradeX">
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
        <td>1</td>
    </tr>
  </tbody>
  <tfoot>
  <tr>
      <th>Create Date</th>
      <th>Project Name</th>
      <th>Property Type</th>
      <th>Project Address</th>
      <th>Area</th>
      <th>ZIP Code</th>
      <th>City</th>
      <th>State</th>
      <th>Owner Name</th>
      <th>Owner E-mail</th>
      <th>Owner Mobile</th>
      <th>Owner Type</th>
      <th>BHK</th>
      <th>Bathroom</th>
      <th>Balcony</th>
      <th>Builtup</th>
      <th>Carpet</th>
      <th>Unit</th>
      <th>Furniture Status</th>
      <th>Sell Type</th>
      <th>Sell Price</th>
      <th>Registration Charge</th>
      <th>Monthly Rent</th>
      <th>Maintanace</th>
      <th>Security Deposit</th>
      <th>Bachelors</th>
  </tr>
  </tfoot>
</table>
</code>```

jQuery Code:

```<code>  $(document).ready(function() {
      $('#example').dataTable( {
          "aaSorting": [[ 4, "desc" ]],
          "scrollX": true
      } );
  } );
</code>```

I copied jQuery code from official datatable website. but it not wotking in my website. I tried sscrollX. It working but it changing width of th and td. How can I resolve it? please help me. And sorry for my weak English.

答:
Add this css to your datatable container :</p>

```<code>    overflow-x: auto;
</code>```

Body:
HTML Code:

      Create Date
      Project Name
      Property Type
      Project Address
      Area
      ZIP Code
      City
      State
      Owner Name
      Owner E-mail
      Owner Mobile
      Owner Type
      BHK
      Bathroom
      Balcony
      Builtup
      Carpet
      Unit
      Furniture Status
      Sell Type
      Sell Price
      Registration Charge
      Monthly Rent
      Maintanace
      Security Deposit
      Bachelors

        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1
        1

      Create Date
      Project Name
      Property Type
      Project Address
      Area
      ZIP Code
      City
      State
      Owner Name
      Owner E-mail
      Owner Mobile
      Owner Type
      BHK
      Bathroom
      Balcony
      Builtup
      Carpet
      Unit
      Furniture Status
      Sell Type
      Sell Price
      Registration Charge
      Monthly Rent
      Maintanace
      Security Deposit
      Bachelors

jQuery Code:

  $(document).ready(function() {
      $('#example').dataTable( {
          "aaSorting": [[ 4, "desc" ]],
          "scrollX": true
      } );
  } );

I copied jQuery code from official datatable website. but it not wotking in my website. I tried sscrollX. It working but it changing width of th and td. How can I resolve it? please help me. And sorry for my weak English.

Body:
Add this css to your datatable container :

    overflow-x: auto;


问:
Python; csv writer must start on new line
I have a script that uses os.walk and I want to add the current working directories on the first line of the output file. I included os.path.realpath to my code to get the current working directory, but the following command of csv.writer adds the output on the first row, so directly after my directory text and I want csv.writer to start on a new line, not on the first line. I know that I can add "/n' to start on a new line, but how do I add to the os.path.realpath command?
Thanks</p>

```<code>import os
import csv
from itertools import chain
from collections import defaultdict

def get_file_values(find_files, output_name):
    for root, dirs, files in os.walk(os.getcwd()):
        if all(x in files for x in find_files):
            outputs = []
            for f in find_files:
                d = {}
                with open(os.path.join(root, f), 'r') as f1:
                    for line in f1:
                        ta = line.split()
                        d[ta[1]] = int(ta[0])
                outputs.append(d)

            d3 = defaultdict(list)
            for k, v in chain(*(d.items() for d in outputs)):
                d3[k].append(v)

            with open(os.path.join(root, output_name), 'w+') as fnew:
                fnew.write(os.path.realpath(root))
                writer = csv.writer(fnew)
                for k, v in d3.items():
                    writer.writerow([k] + v)

get_file_values(['genes.gff.genespercontig.csv', 'hmmer.analyze.txt.results.txt'], 'output_contigsvsgenes.csv')
</code>```

答:
os.path.realpath() returns a string, just append a newline to that:

```<code>fnew.write(os.path.realpath(root) + '\n')
</code>```

Body:
I have a script that uses os.walk and I want to add the current working directories on the first line of the output file. I included os.path.realpath to my code to get the current working directory, but the following command of csv.writer adds the output on the first row, so directly after my directory text and I want csv.writer to start on a new line, not on the first line. I know that I can add "/n' to start on a new line, but how do I add to the os.path.realpath command?
Thanks

import os
import csv
from itertools import chain
from collections import defaultdict

def get_file_values(find_files, output_name):
    for root, dirs, files in os.walk(os.getcwd()):
        if all(x in files for x in find_files):
            outputs = []
            for f in find_files:
                d = {}
                with open(os.path.join(root, f), 'r') as f1:
                    for line in f1:
                        ta = line.split()
                        d[ta[1]] = int(ta[0])
                outputs.append(d)

            d3 = defaultdict(list)
            for k, v in chain(*(d.items() for d in outputs)):
                d3[k].append(v)

            with open(os.path.join(root, output_name), 'w+') as fnew:
                fnew.write(os.path.realpath(root))
                writer = csv.writer(fnew)
                for k, v in d3.items():
                    writer.writerow([k] + v)

get_file_values(['genes.gff.genespercontig.csv', 'hmmer.analyze.txt.results.txt'], 'output_contigsvsgenes.csv')

Body:
os.path.realpath() returns a string, just append a newline to that:

fnew.write(os.path.realpath(root) + '\n')


问:
Can't provide correct system library to Swift on Heroku
I am trying to deploy Swift on Heroku, I want to compile a project that uses Perect.

I specified this build-pack for Swift.

The first issue was this one:

In file included from
  /tmp/.../Packages/LinuxBridge-2.0.2/LinuxBridge/LinuxBridge.c:2:
  /tmp/.../Packages/LinuxBridge-2.0.2/LinuxBridge/include/LinuxBridge.h:6:10:
  fatal error: 'uuid/uuid.h' file not found
  #include <uuid/uuid.h>

Apparently that's because this library isn't there by default, so to install it I added another build pack that enables to install those using apt.

This build pack requires you to provide a Aptfile that contains the name of the required libraries, here is mine:

```<code>openssl
libssl-dev
uuid-dev
</code>```

Unfortunately, when trying to build again there is still the same issue (it can't find uuid), and yet, it seems that the apt build pack was able to install what I wanted (from what I see in the logs).

Does anyone know how to solve this issue?

Thank you.

答:
Although not exactly the same scenario (I am using Perfect-SMTP on Kitura), I was getting the same error complaining about uuid.h not being found. The following made it go away:

```<code>apt-get install uuid-dev
</code>```

Hope it helps...

Body:
I am trying to deploy Swift on Heroku, I want to compile a project that uses Perect.

I specified this build-pack for Swift.

The first issue was this one:

In file included from
  /tmp/.../Packages/LinuxBridge-2.0.2/LinuxBridge/LinuxBridge.c:2:
  /tmp/.../Packages/LinuxBridge-2.0.2/LinuxBridge/include/LinuxBridge.h:6:10:
  fatal error: 'uuid/uuid.h' file not found
  #include <uuid/uuid.h>

Apparently that's because this library isn't there by default, so to install it I added another build pack that enables to install those using apt.

This build pack requires you to provide a Aptfile that contains the name of the required libraries, here is mine:

openssl
libssl-dev
uuid-dev

Unfortunately, when trying to build again there is still the same issue (it can't find uuid), and yet, it seems that the apt build pack was able to install what I wanted (from what I see in the logs).

Does anyone know how to solve this issue?

Thank you.

Body:
Although not exactly the same scenario (I am using Perfect-SMTP on Kitura), I was getting the same error complaining about uuid.h not being found. The following made it go away:

apt-get install uuid-dev

Hope it helps...


问:
Log4Net not writing to the database
I've checked the connection string (I got it from the server explorer).

I've checked the commandText in log4net config.

I've checked the database permissions (integrated security is fine and works outside of the log4net class).

I've checked the repository's configured property (it is configured, it finds the config file fine).

I've also checked that the fields defined in the config file match the attributes (field size etc.) of the table in the database.

Any ideas?

When I'm debugging it seems to be hitting all the right methods at all the right times, with no exceptions raised.

```<code><log4net>

  <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
    <bufferSize value="1" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="" />
    <commandText value="INSERT INTO dbo.Log4Net ([Date],[Thread],[Level],[Logger],[Message]) VALUES ('01-01-2001', 'test', 'test', 'test', 'test')"/>
    <!--<commandText value="INSERT INTO dbo.Log4Net ([Date],[Thread],[Level],[Logger],[Message],[Exception],[MachineName],[CultureId],[SourcePage],[Details],[Method]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception, @MachineName, @CultureId, @SourcePage, @Details, @Method)" />-->
    <parameter>
      <parameterName value="@log_date"/>
      <dbType value="DateTime"/>
      <layout type="log4net.Layout.RawTimeStampLayout"/>
    </parameter>
    <parameter>
      <parameterName value="@thread"/>
      <dbType value="String"/>
      <size value="255"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread"/>
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level"/>
      <dbType value="String"/>
      <size value="50"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level"/>
      </layout>
    </parameter>

...more parameters

    <securitycontext type="log4net.Util.WindowsSecurityContext">
      <credentials value="Process">
      </credentials>
    </securitycontext>
  </appender>

  <appender name="FileAppender" type="log4net.Appender.FileAppender">
    <param name="File" value="LogTest.txt"/>
    <param name="AppendToFile" value="true"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-2p %c [%x] - %m%n"/>
    </layout>
  </appender>

  <root>
    <appender-ref ref="ADONetAppender"/>
    <appender-ref ref="FileAppender"/>
  </root>

</log4net>
</code>```

It's writing to neither appender.

答: I ran into a similar issue yesterday, Log4Net was just not writing to the database. I copied the configuration from another existing appender that successfully writes logs to the database. My solution was to run SQL Server Profiler to try and catch what was happening. Profiler showed that the INSERT statements were being sent by Log4Net, but it was failing on the SQL Server side. Manually running the INSERT statement in SQL Server Management Studio showed me exactly what was wrong with it, in my case, it was inserting NULL into a column that didn't accept NULL.</p>

Title: Log4Net not writing to the database

Body:
I've checked the connection string (I got it from the server explorer).

I've checked the commandText in log4net config.

I've checked the database permissions (integrated security is fine and works outside of the log4net class).

I've checked the repository's configured property (it is configured, it finds the config file fine).

I've also checked that the fields defined in the config file match the attributes (field size etc.) of the table in the database.

Any ideas?

When I'm debugging it seems to be hitting all the right methods at all the right times, with no exceptions raised.

<log4net>

  <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
    <bufferSize value="1" />
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <connectionString value="" />
    <commandText value="INSERT INTO dbo.Log4Net ([Date],[Thread],[Level],[Logger],[Message]) VALUES ('01-01-2001', 'test', 'test', 'test', 'test')"/>

    <parameter>
      <parameterName value="@log_date"/>
      <dbType value="DateTime"/>
      <layout type="log4net.Layout.RawTimeStampLayout"/>
    </parameter>
    <parameter>
      <parameterName value="@thread"/>
      <dbType value="String"/>
      <size value="255"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%thread"/>
      </layout>
    </parameter>
    <parameter>
      <parameterName value="@log_level"/>
      <dbType value="String"/>
      <size value="50"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level"/>
      </layout>
    </parameter>

...more parameters

    <securitycontext type="log4net.Util.WindowsSecurityContext">
      <credentials value="Process">
      </credentials>
    </securitycontext>
  </appender>

  <appender name="FileAppender" type="log4net.Appender.FileAppender">
    <param name="File" value="LogTest.txt"/>
    <param name="AppendToFile" value="true"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-2p %c [%x] - %m%n"/>
    </layout>
  </appender>

  <root>
    <appender-ref ref="ADONetAppender"/>
    <appender-ref ref="FileAppender"/>
  </root>

</log4net>

It's writing to neither appender.


问:
Move mongo database from vagrant outside of VM
Hello guys I'm trying to find a way to move my mongo database inside vagrant outside of it. I'm reading some posts in this forum but they're related to postgres and mysql.

When I run npm start this is the code I have in my package.json

"start": "MONGODB=mongodb://localhost:27017....```

So the problem is that the databse will get saved in Virtual Machine localhost, so, by the time it runs it won't be accessible outside of VM. How can I change this localhost path to communicate outside?

答:
I did it, this link gave me the answer:  Vagrant reverse port forwarding?

It seems that by default mongo will be located in 10.0.2.2  outside of vagrant, so if I run inside vagrant: mongo 10.0.2.2:27017  it connects to my databases outside of vagrant.

Therefore, this is what I need to put in my package.json to run npm start...

"start": "MONGODB=mongodb://10.0.2.2:27017/```

Body:
Hello guys I'm trying to find a way to move my mongo database inside vagrant outside of it. I'm reading some posts in this forum but they're related to postgres and mysql.

When I run npm start this is the code I have in my package.json

"start": "MONGODB=mongodb://localhost:27017....

So the problem is that the databse will get saved in Virtual Machine localhost, so, by the time it runs it won't be accessible outside of VM. How can I change this localhost path to communicate outside?


问:
What are the best wiki engine with good authorization features?
What is the best wiki engine with good authorization features?</p>

答:
Define "good". =)

Some would say that the original wiki script has the best authorization features in a wiki sense of the word, seeing that Ward Cunningham defined Wiki as:

The simplest online database that
  could possibly work.

That said, I can share my experience with hosting Mediawiki sites and that is that I often find that I would like to be able to define privileges on a group/page and group/section kind of way. But it always depends on the application. I use UseModWiki for robowiki.net and it works excellently even though it has the most rudimentary authorization system (next after the original wiki script then).

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: PEZ


问:
How to use relative URL's in website with two base URL's
I have our basic corporate static html website installed in our web root directory and our billing software installed in /portal. I have integrated the websites to look like a single site by including the /menu.tpl smarty template file in the /portal/header.tpl file. However, if I use relative URL's, the menu sysem doesnt work as the base url for the billing script is /portal. i.e. if I create a link to faq.php in the menu.tpl and I load a page on the portal site, the link in the menu back to the faq page is now /portal/faq.php whereby if I load a page off the root site the link is just /faq.php as it should be.

The obvious answer is to just use absolute URL's, but I need the site to be portable as I have many developers who need to install and test it.

I cant find anyway to resolve this. Any ideas?

答:
I ran into the same problem as you a while ago, and after trying a lot of dead ends, I finally ended up with the following solution:

For any URL you need to be a chamelion, i.e. change its path depending on the environment, insert a PHP function that writes out the correct URL.

If you include the PHP function from a single central file, then you can change all of the URL's in the entire site automatically, based on a setting, or some pre-detected switch such as the current domain name, etc.

Example:

```<code><?php print_base_url_plus("/menu.php"); ?>
</code>```

... where print_base_url_plus() is a function which appends the base URL onto the output.

You may find that you have to change some of the URL's to be php, so they are preprocessed by the PHP engine, or, you can alter the web settings so that standard .htm files are piped through the PHP engine, just like .php files.

Body:
I ran into the same problem as you a while ago, and after trying a lot of dead ends, I finally ended up with the following solution:

For any URL you need to be a chamelion, i.e. change its path depending on the environment, insert a PHP function that writes out the correct URL.

If you include the PHP function from a single central file, then you can change all of the URL's in the entire site automatically, based on a setting, or some pre-detected switch such as the current domain name, etc.

Example:

<?php print_base_url_plus("/menu.php"); ?>

... where print_base_url_plus() is a function which appends the base URL onto the output.

You may find that you have to change some of the URL's to be php, so they are preprocessed by the PHP engine, or, you can alter the web settings so that standard .htm files are piped through the PHP engine, just like .php files.


问:
C# Multiple ItemSources in Datagrid
I used to have the following DataGrid:

```<code><sdk:DataGrid x:Name="dataGrid" Grid.Row="0" Style="{StaticResource tableStyle}" ItemsSource="{Binding PagedView}">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding Path=EventID, StringFormat='#{0}'}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Width="Auto" Header="EventID"/>
        <sdk:DataGridTextColumn Binding="{Binding EventDescription}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Width="Auto" Header="Description"/>
        <sdk:DataGridTextColumn Binding="{Binding EventStatu.Description}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Width="Auto" Header="Status"/>
        <sdk:DataGridTemplateColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" SortMemberPath="Detector.Track.TrackName" Width="Auto" Header="Track">
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="3,0">
                        <TextBlock Text="{Binding Path=Detector.Track.TrackName}" />
                        <TextBlock Text="{Binding Path=Detector.DetectorID, StringFormat=' ({0})'}" />
                    </StackPanel>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTextColumn Binding="{Binding StartedOn.LocalDateTime, StringFormat={StaticResource DateFormat}}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Header="Started" Width="Auto"/>
        <sdk:DataGridTextColumn Binding="{Binding EndedOn.LocalDateTime, FallbackValue=N/A, StringFormat={StaticResource DateFormat}}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Header="Stopped" Width="Auto"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>
</code>```

And the .cs

```<code>private void EventsLoaded(LoadOperation<Event> loadOperation)
{
    events.Clear();

    if(loadOperation.HasError)
    {
        loadOperation.MarkErrorAsHandled();
    }
    else
    {
        foreach (Event evnt in loadOperation.Entities)
        {
            events.Add(evnt);//For adding the whole event row
        }
    }
}
</code>```

This gave me the following rows as a result:

```<code>EventID     Description     Status      Track       Started       Stopped
</code>```

Now this is all correct and working. However, i want to add a extra column with the difference in time between Started and Stopped.

For this, i have added the following:

In the designer i added:

```<code><sdk:DataGridTextColumn Binding="{Binding Path=timediff}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Header="Duration" Width="Auto"/>
</code>```

In the .Cs i added:

```<code>string Difference = string.Empty;
TimeSpan duration = evnt.EndedOn.Value.Subtract(evnt.StartedOn);
if (duration.Days > 0)
{
    Difference += string.Format("Event duration: {0} day(s) and {1} hour(s) \r\n",
    duration.Days, duration.Hours);
}
else if (duration.Hours > 0)
{
    Difference += string.Format("Event duration: {0} hour(s) and {1} minute(s) \r\n",
    duration.Hours, duration.Minutes);
}
else
{
    Difference += string.Format("Event duration: {0} minute(s) \r\n",
    duration.Minutes);
}

List<TimeInfo> timeinfo = new List<TimeInfo>();
timeinfo.Add(new TimeInfo() { timediff = Difference });
</code>```

And

```<code>public class TimeInfo
{
    public string timediff { get; set; }
}
</code>```

Now, when i run the program again, it shows me the following columns:

```<code>EventID     Description     Status      Track       Started       Stopped       Duration
</code>```

Everything is filled in except Duration.
When i add the following in my .Cs code:

```<code>dataGrid.ItemsSource = timeinfo;
</code>```

and run the application, it only fills in the duration field, and leaves the rest empty.

Is there a possibility that i can show both of the itemsources in 1 grid?

答:
i red your problem. How i did understand your ItemSource can´t read Difference property. In first case you access to "dataGrid" where you say that he`s ItemSource is "timeinfo" and in second case you are having "PagedView" list where are your propertyes.

First suggestion is to orrient to MVVM concept, that means (for example):

```<code><ListView ItemsSource="{Binding PagedView}" DataContext="{Binding YourClassName}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <GridViewColumn Width="200">
                <Grid>
                    <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="30"/>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="30"/>
                    </Grid.ColumnDefinitions>
                     <TextBlock  Grid.Row="0" Grid.Column="1" Text="{Binding EventID}">
                     <TextBlock  Grid.Row="0" Grid.Column="2" Text="{Binding EventDescription}">
                </Grid>
            </GridViewColumn>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

I took your first and secon Colums as example. But for rest you cann add more colums in ColumnDefinition and down define more TextBlocks. And that is your View. Class YourClassName represents your ListView View-Model :

```<code>public class YourClassName {

    public YourClassName(string eventId, string eventDescr)
    {
        EventID = eventId;
        EventDescription = eventDescr;
    }
    private string mEventID;
    public string EventID{
        get { return mEventID; }
        set { SetProperty(ref mEventID, value); }
    }

            private string mEventDescription;
    public string EventDescription{
        get { return mEventDescription; }
        set { SetProperty(ref mEventDescription, value); }
    }
}
</code>```

Now you need Property of your Class:

```<code>private List<YourClassName> mPagedView;
public List<YourClassName> PagedView {
    get { return mPagedView; }
    set { SetProperty(ref mPagedView, value); }
}
</code>```

In your MainViewModel for example in Constructor you make instance of your class:

```<code>PageView = new List<YourClassName>();
PageView.Add("MYID","Blabla");
</code>```

In this case you avoid x:Name which is public and i use it only when i must.

I hope that it helped at least a little bit.

Regards!

Title: C# Multiple ItemSources in Datagrid

Body:
I used to have the following DataGrid:

<sdk:DataGrid x:Name="dataGrid" Grid.Row="0" Style="{StaticResource tableStyle}" ItemsSource="{Binding PagedView}">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding Path=EventID, StringFormat='#{0}'}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Width="Auto" Header="EventID"/>
        <sdk:DataGridTextColumn Binding="{Binding EventDescription}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Width="Auto" Header="Description"/>
        <sdk:DataGridTextColumn Binding="{Binding EventStatu.Description}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Width="Auto" Header="Status"/>
        <sdk:DataGridTemplateColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" SortMemberPath="Detector.Track.TrackName" Width="Auto" Header="Track">
            <sdk:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Margin="3,0">
                        <TextBlock Text="{Binding Path=Detector.Track.TrackName}" />
                        <TextBlock Text="{Binding Path=Detector.DetectorID, StringFormat=' ({0})'}" />
                    </StackPanel>
                </DataTemplate>
            </sdk:DataGridTemplateColumn.CellTemplate>
        </sdk:DataGridTemplateColumn>
        <sdk:DataGridTextColumn Binding="{Binding StartedOn.LocalDateTime, StringFormat={StaticResource DateFormat}}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Header="Started" Width="Auto"/>
        <sdk:DataGridTextColumn Binding="{Binding EndedOn.LocalDateTime, FallbackValue=N/A, StringFormat={StaticResource DateFormat}}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Header="Stopped" Width="Auto"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

And the .cs

private void EventsLoaded(LoadOperation<Event> loadOperation)
{
    events.Clear();

    if(loadOperation.HasError)
    {
        loadOperation.MarkErrorAsHandled();
    }
    else
    {
        foreach (Event evnt in loadOperation.Entities)
        {
            events.Add(evnt);//For adding the whole event row
        }
    }
}

This gave me the following rows as a result:

EventID     Description     Status      Track       Started       Stopped

Now this is all correct and working. However, i want to add a extra column with the difference in time between Started and Stopped.

For this, i have added the following:

In the designer i added:

<sdk:DataGridTextColumn Binding="{Binding Path=timediff}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" Header="Duration" Width="Auto"/>

In the .Cs i added:

string Difference = string.Empty;
TimeSpan duration = evnt.EndedOn.Value.Subtract(evnt.StartedOn);
if (duration.Days > 0)
{
    Difference += string.Format("Event duration: {0} day(s) and {1} hour(s) \r\n",
    duration.Days, duration.Hours);
}
else if (duration.Hours > 0)
{
    Difference += string.Format("Event duration: {0} hour(s) and {1} minute(s) \r\n",
    duration.Hours, duration.Minutes);
}
else
{
    Difference += string.Format("Event duration: {0} minute(s) \r\n",
    duration.Minutes);
}

List<TimeInfo> timeinfo = new List<TimeInfo>();
timeinfo.Add(new TimeInfo() { timediff = Difference });

And

public class TimeInfo
{
    public string timediff { get; set; }
}

Now, when i run the program again, it shows me the following columns:

EventID     Description     Status      Track       Started       Stopped       Duration

Everything is filled in except Duration.
When i add the following in my .Cs code:

dataGrid.ItemsSource = timeinfo;

and run the application, it only fills in the duration field, and leaves the rest empty.

Is there a possibility that i can show both of the itemsources in 1 grid?

Body:
i red your problem. How i did understand your ItemSource can´t read Difference property. In first case you access to "dataGrid" where you say that he`s ItemSource is "timeinfo" and in second case you are having "PagedView" list where are your propertyes.

First suggestion is to orrient to MVVM concept, that means (for example):

<ListView ItemsSource="{Binding PagedView}" DataContext="{Binding YourClassName}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <GridViewColumn Width="200">
                <Grid>
                    <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="30"/>
                    <ColumnDefinition Width="10"/>
                    <ColumnDefinition Width="30"/>
                    </Grid.ColumnDefinitions>
                     <TextBlock  Grid.Row="0" Grid.Column="1" Text="{Binding EventID}">
                     <TextBlock  Grid.Row="0" Grid.Column="2" Text="{Binding EventDescription}">
                </Grid>
            </GridViewColumn>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I took your first and secon Colums as example. But for rest you cann add more colums in ColumnDefinition and down define more TextBlocks. And that is your View. Class YourClassName represents your ListView View-Model :

public class YourClassName {

    public YourClassName(string eventId, string eventDescr)
    {
        EventID = eventId;
        EventDescription = eventDescr;
    }
    private string mEventID;
    public string EventID{
        get { return mEventID; }
        set { SetProperty(ref mEventID, value); }
    }

            private string mEventDescription;
    public string EventDescription{
        get { return mEventDescription; }
        set { SetProperty(ref mEventDescription, value); }
    }
}

Now you need Property of your Class:

private List<YourClassName> mPagedView;
public List<YourClassName> PagedView {
    get { return mPagedView; }
    set { SetProperty(ref mPagedView, value); }
}

In your MainViewModel for example in Constructor you make instance of your class:

PageView = new List<YourClassName>();
PageView.Add("MYID","Blabla");

In this case you avoid x:Name which is public and i use it only when i must.

I hope that it helped at least a little bit.

Regards!


问:
Angular animations as a separate file not in-lined
I've been fiddling with Angular animations and was wondering if there's a best/recommended way to avoid inline styling ... for instance,

```<code>@Component({
selector: 'page-that-needs-anime',
templateUrl: './anime.component.html',
styleUrls: ['./anime.component.scss'],
animations: [
trigger('animeTrigger', [
state('in', style({transform: 'translateY(0)'})),
transition('void => *', [
  animate(700, keyframes([
    style({opacity: 0, transform: 'translateY(-100%)', offset: 0}),
    style({opacity: 1, transform: 'translateY(25px)',  offset: 0.3}),
    style({opacity: 1, transform: 'translateY(0)',     offset: 1.0})
  ]))
]) //you get the idea ... *Import statement is taken out for brevity
</code>```

Anyway the "animations" could use a reference like styleUrls & templateUrl above? I've seen someone referred it as a const but was wondering if there was an 'Angular official' way.

答:
You can keep your animations in separate files.

```<code>// animations.ts
import { trigger, state, style, transition, animate } from '@angular/animations';

export const Animations = {
    animeTrigger: trigger('animeTrigger', [
        state('in', style({transform: 'translateY(0)'})),
        transition('void => *', [
        animate(700, keyframes([
            style({opacity: 0, transform: 'translateY(-100%)', offset: 0}),
            style({opacity: 1, transform: 'translateY(25px)',  offset: 0.3}),
            style({opacity: 1, transform: 'translateY(0)',     offset: 1.0})
        ]))
    ])

}
</code>```

Component

```<code>import { Animations } from './animations'

@Component({
    selector: 'page-that-needs-anime',
    templateUrl: './anime.component.html',
    styleUrls: ['./anime.component.scss'],
    animations: [
        Animations.animeTrigger
    ]
})
</code>```

Body:
I've been fiddling with Angular animations and was wondering if there's a best/recommended way to avoid inline styling ... for instance,

@Component({
selector: 'page-that-needs-anime',
templateUrl: './anime.component.html',
styleUrls: ['./anime.component.scss'],
animations: [
trigger('animeTrigger', [
state('in', style({transform: 'translateY(0)'})),
transition('void => *', [
  animate(700, keyframes([
    style({opacity: 0, transform: 'translateY(-100%)', offset: 0}),
    style({opacity: 1, transform: 'translateY(25px)',  offset: 0.3}),
    style({opacity: 1, transform: 'translateY(0)',     offset: 1.0})
  ]))
]) //you get the idea ... *Import statement is taken out for brevity

Anyway the "animations" could use a reference like styleUrls & templateUrl above? I've seen someone referred it as a const but was wondering if there was an 'Angular official' way.

Body:
You can keep your animations in separate files.

// animations.ts
import { trigger, state, style, transition, animate } from '@angular/animations';

export const Animations = {
    animeTrigger: trigger('animeTrigger', [
        state('in', style({transform: 'translateY(0)'})),
        transition('void => *', [
        animate(700, keyframes([
            style({opacity: 0, transform: 'translateY(-100%)', offset: 0}),
            style({opacity: 1, transform: 'translateY(25px)',  offset: 0.3}),
            style({opacity: 1, transform: 'translateY(0)',     offset: 1.0})
        ]))
    ])

}

Component

import { Animations } from './animations'

@Component({
    selector: 'page-that-needs-anime',
    templateUrl: './anime.component.html',
    styleUrls: ['./anime.component.scss'],
    animations: [
        Animations.animeTrigger
    ]
})

ContentLicense: CC BY-SA 4.0


问:
How I do Static page in Vue js with full-featured Webpack
I'm using:

- full-featured Webpack.

- vue-material (material design)

My app is a SPA (Single Page App).

I need to create a home page with marketing and area to login and link to create a new user.
In this initial page I do not need the Toolbar, Sidenav, etc ...

In this page I need SEO.

I thought of something hybrid... SPA + some pages.

Should I create a page (html) in static folder? I do not know how to configure the route for this ...

What is the best way to solve this?

答:
You can have multiple strategies for this.

One could be to use Server-Side Rendering as explained in vue js documentaiton which is quite easy to understand.

The other one would be to have a static html page which will be the entry point to your app. It will be SEO optimized and you will have a call to action button that will redirect to your actual vuejs app. So in your webserver the url https://example.org redirects to your static page, and when you click on the link, it will redirect you to https://example.org/app which would be the entrypoint of your vuejs app.


问:
How to inverse a conditional in JavaScript
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

```<code>       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }
</code>```

答:
In boolean algebra, to invert a logic based on another logical condition you'd use the XOR operator. This is because the truth table is:

```<code>a       b       result
true    false   true
false   false   false
true    true    false
false   true    true
</code>```

Notice that if we rename b as inverse:

```<code>a       inverse      result
true    not_inverse  same_as_a
false   not_inverse  same_as_a
true    inverse      opposite_of_a
false   inverse      opposite_of_a
</code>```

So what you want is:

```<code>if ((capitalisation === "lowercase")  XOR  inverse) ...
</code>```

Unfortunately javascript does not have a logical XOR operator, only a bitwise ^ operator. However, it's easy to implement XOR as (a && !b) || (!a && b). This gives us:

```<code>if (((capitalisation === "lowercase") && !inverse) ||
    ((capitalisation !== "lowercase") && inverse)) ...
</code>```

Body:
I have a function that changes the case of some text and returns it, based on the value of capitalisation. I would like to pass another parameter called inverse, which if true, basically performs the opposite; so if capitalisation is lowercase, it will make the text lower case instead of uppercase.

It's important that the value of capitalisation does not change, because it's used by other parts of the application.

I'm looking for a really succinct way to do this with minimal code.

       capitalisation = "lowercase";

       function switchCase(text, inverse) {
            if (capitalisation === "lowercase") {
                text = text.toLowerCase();
            } else {
                text = text.toUpperCase();
            }
            return text;
        }

Body:
In boolean algebra, to invert a logic based on another logical condition you'd use the XOR operator. This is because the truth table is:

a       b       result
true    false   true
false   false   false
true    true    false
false   true    true

Notice that if we rename b as inverse:

a       inverse      result
true    not_inverse  same_as_a
false   not_inverse  same_as_a
true    inverse      opposite_of_a
false   inverse      opposite_of_a

So what you want is:

if ((capitalisation === "lowercase")  XOR  inverse) ...

Unfortunately javascript does not have a logical XOR operator, only a bitwise ^ operator. However, it's easy to implement XOR as (a && !b) || (!a && b). This gives us:

if (((capitalisation === "lowercase") && !inverse) ||
    ((capitalisation !== "lowercase") && inverse)) ...


问:
Objective-c Sorting NSArray with alphanumeric strings in correct order
I have an array of strings that contain numbers i.e. Shift 1 RT9909 I sort the array as follows:

```<code>NSSet *forms = dataObject.rtForms;

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
NSArray *sorted = [forms sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];
</code>```

This works fine while the number of elements is under 10. After this point Shift 10 RT9909 is placed in front Shift 2 RT9909.

So my question is how can I sort the array so that Shift 10 RT9909 would follow Shift 9 RT9909

答:
As Larme suggested you need to use Comparator with NSNumericSearch, you can also combined with NSSortDescriptor

```<code>NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];
</code>```

Body:
I have an array of strings that contain numbers i.e. Shift 1 RT9909 I sort the array as follows:

NSSet *forms = dataObject.rtForms;

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES];
NSArray *sorted = [forms sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];

This works fine while the number of elements is under 10. After this point Shift 10 RT9909 is placed in front Shift 2 RT9909.

So my question is how can I sort the array so that Shift 10 RT9909 would follow Shift 9 RT9909

Body:
As Larme suggested you need to use Comparator with NSNumericSearch, you can also combined with NSSortDescriptor

NSSortDescriptor *nameDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"type" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:nameDescriptor]];


问:
sonarqube plugin for vb6, plsql
Currently I am working on Jenkins and Sonar, to create a build-test-deploy pipeline. We have a project with vb6 coding and pl/sql files. I have configured sonar-scanner to perform the code quality on these source files.

However, when the scanner is connecting with SonarQube server post-scan, to upload report, I am getting an exception. This exception says, SonarQube plugin for vb6 needs license key.

When I checked the SonarQube configuration GUI, it shows licenses required for 3 of the plugins - VB6, VB.Net, PL/SQL.

I am not sure which license key needs to be supplied, for each.

Please suggest.

答: You can write to SonarQube, buy the licenses and then insert the keys in the corresponding fields beneath Administration->Licenses.</p>

Title: sonarqube plugin for vb6, plsql


问:
The member <some column> is not supported in SubSonic
I am using the T4 templates of SubSonic 3.0 to generate classes and such for me. Well in my database I have a Zipcode table with these columns

ZipCode_rid

Zipcode (the actual zipcode in number format)

State

etc

Well, when the T4 templates run, instead of having a column like Zipcode.Zipcode I get Zipcode.ZipcodeX. Then, when trying to run a simple query across this table I get the cryptic error

The member 'ZipcodeX' is not supported

The query is something simple like this

```<code>var z= from z in Zipcode.All()
       where (z.ZipcodeX == "12345")
       select z;
</code>```

Is this a bug in SubSonic or am I messing something up? What workarounds are there?

I have temporarily worked around this issue by renaming the Zipcode column to ZipCode.. but this isn't a very good long term solution

答:
I am not sure if this will work but you can give it a try. It is a bit of a pain but I did get it to go.

Step 1
In settings.ttinclude there is a function

string CleanUp(string tableName)

Create a new one just under it like this (adding whatever extension/rename algorithm you like

string CleanUp(string colName, string tableName){

```<code>  string result=colName;

  //strip blanks
  result=result.Replace(" ","");

  //put your logic here...
  if (result.ToLower() == tableName.ToLower())
  {
      result = colName + "X";
  }

  return result;
</code>```

}

Step 2
In SQLServer.ttinclude (or the equivalent file for your data source) there is at about line 167 a line like:

col.CleanName = CleanUp(col.Name);

Change this to:

col.CleanName = CleanUp(col.Name, tbl.Name);

Step 3
This is where the pain really starts. Grab the source code for SubSonic.Core (Yes :( ) and in DatabaseTable.cs change

```<code>    public IColumn GetColumnByPropertyName(string PropertyName)
</code>```

to

```<code>    public virtual IColumn GetColumnByPropertyName(string PropertyName)
</code>```

Step 4
In Structs.tt after

public static string <#= col.CleanName #>Column{
                  get{
                    return "<#= col.Name #>";
                }
            }

add the following

<#          if (col.CleanName != col.Name) { #>

```<code>       public override IColumn GetColumnByPropertyName(string columName){
           if (columName == "<#= col.CleanName #>")
               return <#=col.CleanName#>;
            else
               return base.GetColumnByPropertyName(columName);
        }
</code>```

<#          } #>

You will probably need to regenerate all the .cs files after doing this.

Body:
I am using the T4 templates of SubSonic 3.0 to generate classes and such for me. Well in my database I have a Zipcode table with these columns

ZipCode_rid

Zipcode (the actual zipcode in number format)

State

etc

Well, when the T4 templates run, instead of having a column like Zipcode.Zipcode I get Zipcode.ZipcodeX. Then, when trying to run a simple query across this table I get the cryptic error

The member 'ZipcodeX' is not supported

The query is something simple like this

var z= from z in Zipcode.All()
       where (z.ZipcodeX == "12345")
       select z;

Is this a bug in SubSonic or am I messing something up? What workarounds are there?

I have temporarily worked around this issue by renaming the Zipcode column to ZipCode.. but this isn't a very good long term solution

Body:
I am not sure if this will work but you can give it a try. It is a bit of a pain but I did get it to go.

Step 1
In settings.ttinclude there is a function

string CleanUp(string tableName)

Create a new one just under it like this (adding whatever extension/rename algorithm you like

string CleanUp(string colName, string tableName){

  string result=colName;

  //strip blanks
  result=result.Replace(" ","");

  //put your logic here...
  if (result.ToLower() == tableName.ToLower())
  {
      result = colName + "X";
  }

  return result;

}

Step 2
In SQLServer.ttinclude (or the equivalent file for your data source) there is at about line 167 a line like:

col.CleanName = CleanUp(col.Name);

Change this to:

col.CleanName = CleanUp(col.Name, tbl.Name);

Step 3
This is where the pain really starts. Grab the source code for SubSonic.Core (Yes :( ) and in DatabaseTable.cs change

    public IColumn GetColumnByPropertyName(string PropertyName)

to

    public virtual IColumn GetColumnByPropertyName(string PropertyName)

Step 4
In Structs.tt after

public static string <#= col.CleanName #>Column{
                  get{
                    return "<#= col.Name #>";
                }
            }

add the following

<#          if (col.CleanName != col.Name) { #>

       public override IColumn GetColumnByPropertyName(string columName){
           if (columName == "<#= col.CleanName #>")
               return <#=col.CleanName#>;
            else
               return base.GetColumnByPropertyName(columName);
        }

<#          } #>

You will probably need to regenerate all the .cs files after doing this.


问:
Comparing a char with multiple characters
```<code>for(int j=0 ; j<str.length() ; j++) {
    if(char[j]==(a||e||i||o||u))
        count++;
}
</code>```

I know the result of (a||e||i||o||u) is a Boolean so can't compare but how can we check for multiple character presence?

答:
If I really need to work with a char[] array and not with a String instance, I always use the Character class and regular expressions. If you don't know what regular expressions are you should learn them because they are very useful when working with strings. Also, you can practice at Regexr.

For your example I'd use this:

```<code>char[] data = "programming in Java is fun".toCharArray();
int counter = 0;

for(int i = 0; i<data.length; i++){
    if(Character.toString(data[i]).matches("[aeiou]")){
        counter++;
    }
}

System.out.println(counter); // writes: 8
</code>```

What the if statement does is basically it makes a new String instance containing the current character just to be able to use the methods from the String class. The method boolean matches(String regex) checks whether your string satisfies the conditions given with the regex argument.

Body:
for(int j=0 ; j<str.length() ; j++) {
    if(char[j]==(a||e||i||o||u))
        count++;
}

I know the result of (a||e||i||o||u) is a Boolean so can't compare but how can we check for multiple character presence?

Body:
If I really need to work with a char[] array and not with a String instance, I always use the Character class and regular expressions. If you don't know what regular expressions are you should learn them because they are very useful when working with strings. Also, you can practice at Regexr.

For your example I'd use this:

char[] data = "programming in Java is fun".toCharArray();
int counter = 0;

for(int i = 0; i<data.length; i++){
    if(Character.toString(data[i]).matches("[aeiou]")){
        counter++;
    }
}

System.out.println(counter); // writes: 8

What the if statement does is basically it makes a new String instance containing the current character just to be able to use the methods from the String class. The method boolean matches(String regex) checks whether your string satisfies the conditions given with the regex argument.


问:
Using async/await + Bluebird to promisifyAll
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await. I know that async/await it's just Promises in the background, so is there a native way to promisify a method or function? Currently I'm using the Bluebird, but I don't know if it's a bad pattern.

Example:

    const Bluebird = require("bluebird");
    const { access } = require("fs");

    const accessAsync = Bluebird.promisify(access);

    async function checkInput(options) {
      await accessAsync(options.file);
      /// etc
      return options;
    }

    module.exports = (options) => {
      Promise.resolve(options)
        .then(checkInput)
    };
```

I'm combining both native Promises and Bluebird. Should I only use Bluebird?

答: Using Bluebird as well as Promises is only increasing your overhead. It means Bluebird is sufficient enough to handle other promises.</p>

Body:
I'm constructing a library that uses async/await, and I would like to know if it is possible to use native modules like fs with the async/await. I know that async/await it's just Promises in the background, so is there a native way to promisify a method or function? Currently I'm using the Bluebird, but I don't know if it's a bad pattern.

Example:

    const Bluebird = require("bluebird");
    const { access } = require("fs");

    const accessAsync = Bluebird.promisify(access);

    async function checkInput(options) {
      await accessAsync(options.file);
      /// etc
      return options;
    }

    module.exports = (options) => {
      Promise.resolve(options)
        .then(checkInput)
    };

I'm combining both native Promises and Bluebird. Should I only use Bluebird?


问:
Why I can't add header to interceptor requeset OkHttp on Retrofit?
Could you please point me my wrong in code, I couldn't add header "Authorization" to the interceptor. When I make a request it throws error retrofit2.adapter.rxjava.HttpException: HTTP 401 Unauthorized . But when I add Header token for each request

```<code>@Header("Authorization") String token
</code>```

Then it works.

Here is my code:

```<code> protected Retrofit retrofit;
protected OkHttpClient client;
protected T api;
protected UserCredential userCredential;

public RestClient(Class<T> type) {
    if (client == null) {
        synchronized (OkHttpClient.class) {
            client = new OkHttpClient();
            client.newBuilder().addInterceptor(chain -> {
                Request original = chain.request();
                Request.Builder builder = original.newBuilder();
                if (GrabDoiApplication.getInstance().getCurrentCredentials() != null) {
                    String token = GrabDoiApplication.getInstance().getCurrentCredentials().getToken();
                    if (token != null) {
                        builder.addHeader("Authorization", token);
                    }
                }
                builder.method(original.method(), original.body());

                return chain.proceed(builder.build());
            }).build();

            if (retrofit == null) {
                synchronized (Retrofit.class) {
                    Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                            .baseUrl(Constants.GRABDOI_SERVER_URL)
                            .client(client)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
                    retrofit = retrofitBuilder.build();
                }
            }
        }
    }
    api = retrofit.create(type);
}
</code>```

答:
You can try to put the access to the static method out of the interceptor's body:</p>

```<code>    public RestClient(Class<T> type) {
    if (retrofit != null) {
        return;
    }
    synchronized (OkHttpClient.class) {
        client = new OkHttpClient();
        OkHttpClient.Builder builder = client.newBuilder();
        final String token;
        if (GrabDoiApplication.getInstance().getCurrentCredentials() != null &&
                (token = GrabDoiApplication.getInstance().getCurrentCredentials().getToken()) != null) {
            builder.addInterceptor(chain -> {
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("Authorization", token);
                builder.method(original.method(), original.body());
                return chain.proceed(builder.build());
            });
        }
        client = builder.build();

        synchronized (Retrofit.class) {
            Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                    .baseUrl(Constants.GRABDOI_SERVER_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
            retrofit = retrofitBuilder.build();
        }
    }

    api = retrofit.create(type);
}
</code>```

Body:
Could you please point me my wrong in code, I couldn't add header "Authorization" to the interceptor. When I make a request it throws error retrofit2.adapter.rxjava.HttpException: HTTP 401 Unauthorized . But when I add Header token for each request

@Header("Authorization") String token

Then it works.

Here is my code:

 protected Retrofit retrofit;
protected OkHttpClient client;
protected T api;
protected UserCredential userCredential;

public RestClient(Class<T> type) {
    if (client == null) {
        synchronized (OkHttpClient.class) {
            client = new OkHttpClient();
            client.newBuilder().addInterceptor(chain -> {
                Request original = chain.request();
                Request.Builder builder = original.newBuilder();
                if (GrabDoiApplication.getInstance().getCurrentCredentials() != null) {
                    String token = GrabDoiApplication.getInstance().getCurrentCredentials().getToken();
                    if (token != null) {
                        builder.addHeader("Authorization", token);
                    }
                }
                builder.method(original.method(), original.body());

                return chain.proceed(builder.build());
            }).build();

            if (retrofit == null) {
                synchronized (Retrofit.class) {
                    Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                            .baseUrl(Constants.GRABDOI_SERVER_URL)
                            .client(client)
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
                    retrofit = retrofitBuilder.build();
                }
            }
        }
    }
    api = retrofit.create(type);
}

Body:
You can try to put the access to the static method out of the interceptor's body:

    public RestClient(Class<T> type) {
    if (retrofit != null) {
        return;
    }
    synchronized (OkHttpClient.class) {
        client = new OkHttpClient();
        OkHttpClient.Builder builder = client.newBuilder();
        final String token;
        if (GrabDoiApplication.getInstance().getCurrentCredentials() != null &&
                (token = GrabDoiApplication.getInstance().getCurrentCredentials().getToken()) != null) {
            builder.addInterceptor(chain -> {
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("Authorization", token);
                builder.method(original.method(), original.body());
                return chain.proceed(builder.build());
            });
        }
        client = builder.build();

        synchronized (Retrofit.class) {
            Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
                    .baseUrl(Constants.GRABDOI_SERVER_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create());
            retrofit = retrofitBuilder.build();
        }
    }

    api = retrofit.create(type);
}


问:
Difference between basic and url base64 encoding in Java 8
The Java 8 Base64 library has two variants that can be used in URI building: the "Basic" one and the "URL and Filename safe". The documentation points to RFC 4648 Table 2 as an explanation for the differences.

After reading the spec it still isn't clear to me what the practical difference is between both encodings: are both standards "widely" supported? What about browsers specifically? Is the URL and filename safe encoding recommended for data URI encoding? Are there known support limitations?

答:
Running some tests, encoding a data URI using base64 "URL and filename safe" produces URIs that are not recognised by Chrome.

Example: data:text/plain;base64,TG9yZW0/aXBzdW0= is properly decoded to Lorem?ipsum, while its URL-safe counterpart data:text/plain;base64,TG9yZW0_aXBzdW0= is not (ERR_INVALID_URL).


问:
What's the preferred way to implement a hook or callback in Python?
I'd like to provide the capability for users of one of my modules to extend its capabilities by providing an interface to call a user's function. For example, I want to give users the capability to be notified when an instance of a class is created and given the opportunity to modify the instance before it is used.

The way I've implemented it is to declare a module-level factory function that does the instantiation:

```<code># in mymodule.py
def factory(cls, *args, **kwargs):
    return cls(*args, **kwargs)
</code>```

Then when I need an instance of a class in mymodule, I do factory(cls, arg1, arg2) rather than cls(arg1, arg2).

To extend it, a programmer would write in another module a function like this:

```<code>def myFactory(cls, *args, **kwargs):
    instance = myFactory.chain(cls, *args, **kwargs)
    # do something with the instance here if desired
    return instance
</code>```

Installation of the above callback looks like this:

```<code>myFactory.chain, mymodule.factory = mymodule.factory, myFactory
</code>```

This seems straightforward enough to me, but I was wondering if you, as a Python programmer, would expect a function to register a callback rather than doing it with an assignment, or if there were other methods you would expect. Does my solution seem workable, idiomatic, and clear to you?

I am looking to keep it as simple as possible; I don't think most applications will actually need to chain more than one user callback, for example (though unlimited chaining comes "for free" with the above pattern). I doubt they will need to remove callbacks or specify priorities or order.  Modules like python-callbacks or PyDispatcher seem to me like overkill, especially the latter, but if there are compelling benefits to a programmer working with my module, I'm open to them.

答:
Taking aaronsterling's idea a bit further:</p>

```<code>class C(object):
  _oncreate = []

  def __new__(cls):
    return reduce(lambda x, y: y(x), cls._oncreate, super(C, cls).__new__(cls))

  @classmethod
  def oncreate(cls, func):
    cls._oncreate.append(func)

c = C()
print hasattr(c, 'spew')

@C.oncreate
def spew(obj):
  obj.spew = 42
  return obj

c = C()
print c.spew
</code>```

Body:
I'd like to provide the capability for users of one of my modules to extend its capabilities by providing an interface to call a user's function. For example, I want to give users the capability to be notified when an instance of a class is created and given the opportunity to modify the instance before it is used.

The way I've implemented it is to declare a module-level factory function that does the instantiation:

# in mymodule.py
def factory(cls, *args, **kwargs):
    return cls(*args, **kwargs)

Then when I need an instance of a class in mymodule, I do factory(cls, arg1, arg2) rather than cls(arg1, arg2).

To extend it, a programmer would write in another module a function like this:

def myFactory(cls, *args, **kwargs):
    instance = myFactory.chain(cls, *args, **kwargs)
    # do something with the instance here if desired
    return instance

Installation of the above callback looks like this:

myFactory.chain, mymodule.factory = mymodule.factory, myFactory

This seems straightforward enough to me, but I was wondering if you, as a Python programmer, would expect a function to register a callback rather than doing it with an assignment, or if there were other methods you would expect. Does my solution seem workable, idiomatic, and clear to you?

I am looking to keep it as simple as possible; I don't think most applications will actually need to chain more than one user callback, for example (though unlimited chaining comes "for free" with the above pattern). I doubt they will need to remove callbacks or specify priorities or order.  Modules like python-callbacks or PyDispatcher seem to me like overkill, especially the latter, but if there are compelling benefits to a programmer working with my module, I'm open to them.

Body:
Taking aaronsterling's idea a bit further:

class C(object):
  _oncreate = []

  def __new__(cls):
    return reduce(lambda x, y: y(x), cls._oncreate, super(C, cls).__new__(cls))

  @classmethod
  def oncreate(cls, func):
    cls._oncreate.append(func)

c = C()
print hasattr(c, 'spew')

@C.oncreate
def spew(obj):
  obj.spew = 42
  return obj

c = C()
print c.spew


问:
Formula or functions to find Upper Quartile and Lower Quartile in SQL Server
I am trying to get the upper quartile, median and lower quartile in SQL Server. Is there any function or formula? Please advice - many thanks </p>

答: It sounds like you need the ntile function with either 4 (which ranks all the values based on column into 4 buckets ) or 3 which ranks all values in based on a column into three buckets.</p>


问:
Unity ios build folder is empty
I want to build my project for IOS. I choose folder and build my project. at the end of the build, my folder is empty. Why? Can you help me?

There is an error on console:

Failed running /Applications/Unity/Unity.app/Contents/Tools/UnusedByteCodeStripper2/UnusedBytecodeStripper2.exe --api NET_2_0_Subset -out "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/Managed/tempStrip" -l none -c link -b False -x "/Applications/Unity/PlaybackEngines/iOSSupport/Whitelists/Core.xml" -f "/Applications/Unity/Unity.app/Contents/il2cpp/LinkerDescriptors" -x "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/Managed/../platform_native_link.xml" -x "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/methods_pointedto_by_uievents.xml" -x "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/preserved_derived_types.xml" -x "/Users/arifsanat/Desktop/CityCars/Assets/link.xml" -d "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/Managed" -a  "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/Managed/Assembly-CSharp.dll" -a  "/Users/arifsanat/Desktop/CityCars/Temp/StagingArea/Data/Managed/UnityEngine.UI.dll"

stdout:
SweepReport:
System.MonoType => Mono.Cecil.TypeDefinitionMono.Cecil.TypeDefinitionMono.Cecil.TypeDefinitionMono.Cecil.TypeDefinitionMono.Cecil.TypeDefinition
Mono.Cecil.MethodDefinition => System.Void .ctor()System.Void .ctor(System.String)System.String get_Comment()System.Void .ctor()System.Boolean get_CanTransformMultipleBlocks()
Mono.Cecil.FieldDefinition => System.String commentSystem.Func3<System.Int32,System.Int32,System.Int32> <>f__am$cache0System.Func3 <>f__am$cache1System.Func3<System.Double,System.Double,System.Double> <>f__am$cache2System.Func3 <>f__am$cache3
Fatal error in Mono CIL Linker
Mono.Cecil.ResolutionException: Failed to resolve UnityEngine.RenderTexture
  at UnusedBytecodeStripper2.AddUnresolvedStubsStep.Process () <0x10afdf960 + 0x002fd> in :0
  at Mono.Linker.Steps.BaseStep.Process (Mono.Linker.LinkContext context) <0x1096e9ed0 + 0x0006b> in :0
  at Mono.Linker.Pipeline.Process (Mono.Linker.LinkContext context) <0x1096e8f90 + 0x000e6> in :0
  at Mono.Linker.Driver.Run (IEqualityComparer1 typeComparer, IEqualityComparer1 methodComparer) <0x108606520 + 0x00be7> in :0
  at Mono.Linker.Driver.RunDriverWithErrorHandling (Mono.Linker.Driver driver, IEqualityComparer1 typeComparer, IEqualityComparer1 methodComparer) <0x1086064d0 + 0x00026> in :0
  at Mono.Linker.Driver.RunDriver (Mono.Linker.Driver driver, IEqualityComparer1 typeComparer, IEqualityComparer1 methodComparer) <0x1086063e0 + 0x0003b> in :0

答: It may be because you are building it into the Assets folder? Try saving it to a folder outside the Unity project.</p>

Title: Unity ios build folder is empty


问:
Powershell Switch Statement String Match Not Working
I am having trouble getting a simple switch statement to work in a Powershell script I'm using. Had previously been using nested if's and wanted to clean up a bit. Code is below.

When I walk it through Powershell ISE in debug and evaluate the tests (e.g. $_ -match 'match1' ) it does evaluate to true as expected based on the value of $mystring.  However, it never seems to properly execute the code associated with that value in the Switch block.  I'm sure I'm missing something obvious, and appreciate any guidance.  Hope my description makes sense.  I'm running v5.1.

```<code>Switch ($myString)
{
  ($_ -match 'match1') { somecodeblock }
  ($_ -match 'match2') { somecodeblock }
  ($_ -match 'match3') { somecodeblock }
  ($_ -match 'match3') { somecodeblock }
  ($_ -match 'match4') { somecodeblock }
  ($_ -match 'match4') { somecodeblock }
}
</code>```

答:
The correct syntax is to use curly braces around your test when using $_ (you are currently using brackets):

```<code>Switch ($myString)
{
   {$_ -match 'match1'} {somecodeblock}
}
</code>```

When you are not using $_ they can be ommitted from the test entirely, and you could do this if you used the -wildcard parameter:

```<code>Switch -wildcard ($myString)
{
   '*match1*' {somecodeblock}
}
</code>```

Body:
I am having trouble getting a simple switch statement to work in a Powershell script I'm using. Had previously been using nested if's and wanted to clean up a bit. Code is below.

When I walk it through Powershell ISE in debug and evaluate the tests (e.g. $_ -match 'match1' ) it does evaluate to true as expected based on the value of $mystring.  However, it never seems to properly execute the code associated with that value in the Switch block.  I'm sure I'm missing something obvious, and appreciate any guidance.  Hope my description makes sense.  I'm running v5.1.

Switch ($myString)
{
  ($_ -match 'match1') { somecodeblock }
  ($_ -match 'match2') { somecodeblock }
  ($_ -match 'match3') { somecodeblock }
  ($_ -match 'match3') { somecodeblock }
  ($_ -match 'match4') { somecodeblock }
  ($_ -match 'match4') { somecodeblock }
}

Body:
The correct syntax is to use curly braces around your test when using $_ (you are currently using brackets):

Switch ($myString)
{
   {$_ -match 'match1'} {somecodeblock}
}

When you are not using $_ they can be ommitted from the test entirely, and you could do this if you used the -wildcard parameter:

Switch -wildcard ($myString)
{
   '*match1*' {somecodeblock}
}


问:
Filter Beautiful Soup 4 findings from parsed page
Evening,

I came to a dead-end while trying to figure how to solve this one.

In short I am parsing a product page with a  tag using BS4's findAll() function.I get the correct response but the area I am searching is "plain text" without tags that I can filter by using BS4 as far as I understand

```<code>def find_product(counter):
url = base_url
print('Looking in ' + url)
while not matches[counter]:
    print(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
    try:
        response1 = search_session.get(url)
    except:
        print('Unable to connect to site...')
        if counter == checkout_qty - 1:
            sys.exit()
        else:
            continue

    soup1 = bs(response1.text, 'html.parser')
    #soup1.find_all('script')
    soup2 = soup1.findAll('script', text = re.compile('id                : ')) #using text recompiling doesn't really do anything,just gives a slightly cleaner output of findings.
    print(soup2)
    for ids in soup2:
        link = ids.find(text = re.compile('id'))
        #i think i should use it somehow here,but I lack knowledge
        #this loop is unfinished

    break
</code>```

This is what I am parsing from the product page.

```<code><main class="B__container">
      <script>

  product.p = {
    id             : 47755536459,
    title          : "PRODUCT NAME",
    handle         : "PRODUCT HANDLE",
    vendor         : "",
    available      : ,
    images         : ["image-link.com\/files\/1111"],
    featured_image : "image-link.com\/files\/1111",
    options        : ["Size"],
    tags           : [],
    price          : 24000,
    variants       : []
  };

    product.p.variants.push({
      id                : 40113207495,
      parent_id         : 10025946759,
      available         : false,
      featured_image    : null,
      public_title      : null,
      requires_shipping : true,
      price             : 24000,
      options           : ["4"],
      option1           : "4",
      option2           : "",
      option3           : "",
      option4           : ""
    });

    product.p.variants.push({
      id                : 40113207559,
      parent_id         : 10025946759,
      available         : false,
      featured_image    : null,
      public_title      : null,
      requires_shipping : true,
      price             : 24000,
      options           : ["4.5"],
      option1           : "4.5",
      option2           : "",
      option3           : "",
      option4           : ""
    });

    product.p.variants.push({
      id                : 40113207623,
      parent_id         : 10025946759,
      available         : false,
      featured_image    : null,
      public_title      : null,
      requires_shipping : true,
      price             : 24000,
      options           : ["5"],
      option1           : "5",
      option2           : "",
      option3           : "",
      option4           : ""
    });
  </script>
</code>```

My goal is to extract the id with the number and then later send it off to a separate function.

The problem,lack of knowledge or I lack skills of how to use BS4 to its full potential to get out what I want.

答:
Try this code... it's just string manipulation to fetch the necessary info.. in this case, id value.

split data at \n

for each element in this list, check if substring id is present

if True, print the row after a few manipulations (strip, split, replace)

Code:

```<code>s = soup2.text
data = s.split('\n')

for i, d in enumerate(data):
    if " id " in d:
        print(data[i].strip().split(':')[1].replace(',', ''))
</code>```

Output:

```<code>47755536459
40113207495
40113207559
40113207623
</code>```

Edited Code:

```<code>for ids in soup2:
    s = ids.text
    data = s.split('\n')

    for i, d in enumerate(data):
        if " id " in d:
            print(data[i].strip().split(':')[1].replace(',', ''))
</code>```

Instead of print, you can append each id to a list and use them later.

Body:
Evening,

I came to a dead-end while trying to figure how to solve this one.

In short I am parsing a product page with a  tag using BS4's findAll() function.I get the correct response but the area I am searching is "plain text" without tags that I can filter by using BS4 as far as I understand

def find_product(counter):
url = base_url
print('Looking in ' + url)
while not matches[counter]:
    print(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
    try:
        response1 = search_session.get(url)
    except:
        print('Unable to connect to site...')
        if counter == checkout_qty - 1:
            sys.exit()
        else:
            continue

    soup1 = bs(response1.text, 'html.parser')
    #soup1.find_all('script')
    soup2 = soup1.findAll('script', text = re.compile('id                : ')) #using text recompiling doesn't really do anything,just gives a slightly cleaner output of findings.
    print(soup2)
    for ids in soup2:
        link = ids.find(text = re.compile('id'))
        #i think i should use it somehow here,but I lack knowledge
        #this loop is unfinished

    break

This is what I am parsing from the product page.

My goal is to extract the id with the number and then later send it off to a separate function.

The problem,lack of knowledge or I lack skills of how to use BS4 to its full potential to get out what I want.

Body:
Try this code... it's just string manipulation to fetch the necessary info.. in this case, id value.

split data at \n

for each element in this list, check if substring id is present

if True, print the row after a few manipulations (strip, split, replace)

Code:

s = soup2.text
data = s.split('\n')

for i, d in enumerate(data):
    if " id " in d:
        print(data[i].strip().split(':')[1].replace(',', ''))

Output:

47755536459
40113207495
40113207559
40113207623

Edited Code:

for ids in soup2:
    s = ids.text
    data = s.split('\n')

    for i, d in enumerate(data):
        if " id " in d:
            print(data[i].strip().split(':')[1].replace(',', ''))

Instead of print, you can append each id to a list and use them later.


问:
Eureka forms dynamic values
I want to set my the values of my fields dynamically based on the input I get from an API call.
So for this I get the answers from the server, parse it to objects and I'm trying to set the value.
However this is impossible because the rowBy(tag:) method returns a BaseRow so I don't know what type the row is. And a BaseRow doesn't have the parameter value.

Is there a known method that allows me to check what field type it is and set the value?

```
ItemProducer.itemGetFormAnswers(withArguments: arguments) { (success, responseData, error) in</p>

```MBProgressHUD.hide(for: self.view, animated: true)
switch(success) {
case .responseTrue:
    for dataObject in responseData?["data"] as! [[AnyHashable:Any]] {
        let answerObject = Answer.parseJSON(dataObject)
        if (answerObject != nil) {
            self.answers[(answerObject?.questionID)!] = answerObject

            //Add answer
            if let row = self.form.rowBy(tag: String(describing: answerObject?.questionID)) {
                let date = Date.init(timeIntervalSince1970: Double((answerObject?.answer)!)!)
                row.value = date
                row.reload()
            }
        }
    }
    self.tableView?.reloadData()
    break
default:
    print("failed to get the answers")
    break
}
```

<p>}```

答:
Do you want to check for a specific class?

```<code>if myObject is MyClass {
    // myObject is of type MyClass
}
</code>```

Thus you could also try in more detail:

```<code>guard let _ : MyRow = self.form.rowBy(tag: String(describing: answerObject?.questionID)) else {
                        // do your logic
                        return
                    }
</code>```

If you don't know what kind of json obkject you have serialized in your dict, you could check for specific attributes like this:

```<code>if let mySpecificAttribute = answerObject["mySpecificAttribute "] as? String {
    // answerObject got a value for key "mySpecificAttribute "
}
</code>```

Title: Eureka forms dynamic values

Body:
I want to set my the values of my fields dynamically based on the input I get from an API call.
So for this I get the answers from the server, parse it to objects and I'm trying to set the value.
However this is impossible because the rowBy(tag:) method returns a BaseRow so I don't know what type the row is. And a BaseRow doesn't have the parameter value.

Is there a known method that allows me to check what field type it is and set the value?

```
ItemProducer.itemGetFormAnswers(withArguments: arguments) { (success, responseData, error) in</p>

<pre><code>MBProgressHUD.hide(for: self.view, animated: true)
switch(success) {
case .responseTrue:
    for dataObject in responseData?["data"] as! [[AnyHashable:Any]] {
        let answerObject = Answer.parseJSON(dataObject)
        if (answerObject != nil) {
            self.answers[(answerObject?.questionID)!] = answerObject

            //Add answer
            if let row = self.form.rowBy(tag: String(describing: answerObject?.questionID)) {
                let date = Date.init(timeIntervalSince1970: Double((answerObject?.answer)!)!)
                row.value = date
                row.reload()
            }
        }
    }
    self.tableView?.reloadData()
    break
default:
    print("failed to get the answers")
    break
}
</code></pre>

<p>}```

Body:
Do you want to check for a specific class?

if myObject is MyClass {
    // myObject is of type MyClass
}

Thus you could also try in more detail:

guard let _ : MyRow = self.form.rowBy(tag: String(describing: answerObject?.questionID)) else {
                        // do your logic
                        return
                    }

If you don't know what kind of json obkject you have serialized in your dict, you could check for specific attributes like this:

if let mySpecificAttribute = answerObject["mySpecificAttribute "] as? String {
    // answerObject got a value for key "mySpecificAttribute "
}


问:
Converting date in excel
I need to convert the below date format in excel.

Currently I have: Fri Jan 06 05:10:31 2017

Current Format : ddd MMM dd hh:mm:ss yyyy

I wanted to be in the following format: dd/mm/yyyy hh:mm:ss

答:
You can format it and everything from the formula bar (no need to go in and set formatting).

```<code>=TEXT(MID(A1,5,LEN(A1)),"dd/mm/yyyy hh:mm:ss")
</code>```

Title: Converting date in excel

Body:
You can format it and everything from the formula bar (no need to go in and set formatting).

=TEXT(MID(A1,5,LEN(A1)),"dd/mm/yyyy hh:mm:ss")


问:
dashboard cannot login with admin account
After I installed the dashboard on 2 Ubuntu16 nodes, I can login the web page dashboard.
All the instructions is followed from

https://docs.openstack.org/project-install-guide/ocata/ubuntu-services.html
nova-manage ---version===15.0.1
keystone is already the newest version (2:11.0.0-0ubuntu1.1~cloud0)

Checking on apache error log is like this:
[wsgi:error] [pid 21177:tid 140685076526848] Login failed for user "admin", remote address x.x.x.x
[wsgi:error] [pid 21177:tid 140685076526848] Login failed for user "admin", remote address x.x.x.x

There were plenty of this error after freshing web page.
I didn't change admin account password, when I check openstack status, like openstack user list, etc. It will show the directly result.
In my case, I believe the keystone service is working, for dashborad is granted all host visit.

ps -ef|grep keystone
root     16785 16296  0 16:44 pts/0    00:00:00 grep --color=auto keystone
keystone 21178 21172  0 09:32 ?        00:00:02 (wsgi:keystone-pu -k start
keystone 21179 21172  0 09:32 ?        00:00:02 (wsgi:keystone-pu -k start
keystone 21180 21172  0 09:32 ?        00:00:02 (wsgi:keystone-pu -k start
keystone 21181 21172  0 09:32 ?        00:00:02 (wsgi:keystone-pu -k start
keystone 21182 21172  0 09:32 ?        00:00:02 (wsgi:keystone-pu -k start
keystone 21183 21172  0 09:32 ?        00:00:02 (wsgi:keystone-ad -k start
keystone 21184 21172  0 09:32 ?        00:00:02 (wsgi:keystone-ad -k start
keystone 21185 21172  0 09:32 ?        00:00:02 (wsgi:keystone-ad -k start
keystone 21186 21172  0 09:32 ?        00:00:02 (wsgi:keystone-ad -k start
keystone 21187 21172  0 09:32 ?        00:00:02 (wsgi:keystone-ad -k start

So I got 2 concerns:
1. how to fix it :)
2 I found after sync with keystone local database, I found it can't find keystone service, which I can't restart it both /etc/init.d/keystone (cannot find keystone service name) and systemctl restart keystone(no keytone).

Any help will be appreciated.

答:
I had the same issue with Ocata.

Please try to restart below services:

```<code>systemctl restart mariadb.service httpd.service memcached.service
</code>```

After restart DB I got access to log in for a first time.

Body:
I had the same issue with Ocata.

Please try to restart below services:

systemctl restart mariadb.service httpd.service memcached.service

After restart DB I got access to log in for a first time.


问:
flow-type import types from external file - name is already bound
I have the following component:

```<code>// @flow

import React from 'react';

import TEA_DATA from './Tea.data';
import TeaInfo from './TeaInfo.component';

const Tea = () => <TeaInfo teaData={TEA_DATA}/>;

export default Tea;
</code>```

Then I have the following Tea.data.types.js file:

```<code>// @flow

export type id = string;
export type image = string;
export type header = string;
export type text = Array<string>;
export type brewTime = Array<any>;

export type TEA_DATA = {
  id: id,
  image: image,
  header: header,
  text: text,
  brewTime: brewTime
};
</code>```

And then I have the following tea.data.js file:

```<code>// @flow

import black from '../images/blacktea.png';
import white from '../images/whitetea.png';
import oolong from '../images/oolongtea.png';
import green from '../images/greentea.png';

import type TEA_DATA from './Tea.data.types';

const TEA_DATA = [{
  id: 'wtid',
  image: white,
  header: 'White tea',
  text: [
    "Currently there is no generally accepted definition of white tea and very little international agreement - some sources use the term to refer to tea that is merely dried with no additional processing, some to tea made from the buds and immature tea leaves picked shortly before the buds have fully opened and allowed to wither and dry in natural sun,[citation needed] while others include tea buds and very young leaves which have been steamed or fired before drying. Most definitions agree, however, that white tea is not rolled or oxidized, resulting in a flavour characterized as \"lighter\" than green or traditional black teas.",
    "In spite of its name, brewed white tea is pale yellow. Its name derives from the fine silvery-white hairs on the unopened buds of the tea plant, which give the plant a whitish appearance. It is harvested primarily in China, mostly in the Fujian province, but more recently produced in Eastern Nepal, Taiwan, Northern Thailand, Galle (Southern Sri Lanka) and India."
  ],
  brewTime: {
    mild: 1,
    strong: 3
  }
}...];

export default TEA_DATA;
</code>```

According to the flow docs this is the correct way to import data types, but I am getting the following error:

src/Tea/Tea.data.js:10  10: const TEA_DATA = [{
             ^^^^^^^^ TEA_DATA. name is already bound   8: import type TEA_DATA from './Tea.data.types';
                   ^^^^^^^^ type TEA_DATA

src/Tea/Tea.data.js:58  58: export default TEA_DATA;
                      ^^^^^^^^ TEA_DATA. type referenced from value position   8: import type TEA_DATA from './Tea.data.types';
                   ^^^^^^^^ type TEA_DATA

What am I doing wrong?

答:
You just have to name your type something different. Flow does not allow you to have both a type and a value with the same name in the same scope. You have imported the type TEA_DATA and you have also named a constant TEA_DATA in the same file.

Also, in this case you should use

```<code>import type {TEA_DATA} from './Tea.data.types';
</code>```

(note the curly braces for destructuring) so that you import only the type TEA_DATA and not the whole module.

Body:
I have the following component:

// @flow

import React from 'react';

import TEA_DATA from './Tea.data';
import TeaInfo from './TeaInfo.component';

const Tea = () => <TeaInfo teaData={TEA_DATA}/>;

export default Tea;

Then I have the following Tea.data.types.js file:

// @flow

export type id = string;
export type image = string;
export type header = string;
export type text = Array<string>;
export type brewTime = Array<any>;

export type TEA_DATA = {
  id: id,
  image: image,
  header: header,
  text: text,
  brewTime: brewTime
};

And then I have the following tea.data.js file:

// @flow

import black from '../images/blacktea.png';
import white from '../images/whitetea.png';
import oolong from '../images/oolongtea.png';
import green from '../images/greentea.png';

import type TEA_DATA from './Tea.data.types';

const TEA_DATA = [{
  id: 'wtid',
  image: white,
  header: 'White tea',
  text: [
    "Currently there is no generally accepted definition of white tea and very little international agreement - some sources use the term to refer to tea that is merely dried with no additional processing, some to tea made from the buds and immature tea leaves picked shortly before the buds have fully opened and allowed to wither and dry in natural sun,[citation needed] while others include tea buds and very young leaves which have been steamed or fired before drying. Most definitions agree, however, that white tea is not rolled or oxidized, resulting in a flavour characterized as \"lighter\" than green or traditional black teas.",
    "In spite of its name, brewed white tea is pale yellow. Its name derives from the fine silvery-white hairs on the unopened buds of the tea plant, which give the plant a whitish appearance. It is harvested primarily in China, mostly in the Fujian province, but more recently produced in Eastern Nepal, Taiwan, Northern Thailand, Galle (Southern Sri Lanka) and India."
  ],
  brewTime: {
    mild: 1,
    strong: 3
  }
}...];

export default TEA_DATA;

According to the flow docs this is the correct way to import data types, but I am getting the following error:

src/Tea/Tea.data.js:10  10: const TEA_DATA = [{
             ^^^^^^^^ TEA_DATA. name is already bound   8: import type TEA_DATA from './Tea.data.types';
                   ^^^^^^^^ type TEA_DATA

src/Tea/Tea.data.js:58  58: export default TEA_DATA;
                      ^^^^^^^^ TEA_DATA. type referenced from value position   8: import type TEA_DATA from './Tea.data.types';
                   ^^^^^^^^ type TEA_DATA

What am I doing wrong?

Body:
You just have to name your type something different. Flow does not allow you to have both a type and a value with the same name in the same scope. You have imported the type TEA_DATA and you have also named a constant TEA_DATA in the same file.

Also, in this case you should use

import type {TEA_DATA} from './Tea.data.types';

(note the curly braces for destructuring) so that you import only the type TEA_DATA and not the whole module.


问:
Declaring a Task Property and awaiting it
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

```<code>Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}
</code>```

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!

答: You're only creating a Task but it is not running even with await here. Try to Start() it, or you can assign T1 = Task.Run(your => lambda) and then it should work when you awaiting it

Body:
I'm stuck in something I thought so simple that it drives me out of myself.

I need to declare a Task in some point and run it later, I thought of:

Task T1 { get; set; }

public async Task CreateAndAwaitAsync()
{
    T1 = new Task(() => {
        // time consuming work like:
        System.Threading.Thread.Sleep(1000);
    }

    await T1;
}

Of course the body of the lambda AND the method are just for the sake of this example (as I said I need to run it later), but no matter what, with await T1 I just cannot make it into the lambda! What am I missing?? I feel stupid because I have been using the async-await paradigm for quite the few years already that I didn't even imagine this wouldn't work!


问:
List sorting - two lists into one
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

```<code>names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])
</code>```

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

答:
If you wanna do this with just loops, You could implement some sorting algorithm by yourself and along the way, interchange corresponding elements in names along with wages.

Here's an example with Bubble Sort:

```<code>for j in range(len(wages)-1,0,-1):
    for i in range(j):
        if wages[i]>wages[i+1]:
            tempWage = wages[i]
            wages[i] = wages[i+1]
            wages[i+1] = tempWage

            tempName = names[i]
            names[i] = names[i+1]
            names[i+1] = tempName
</code>```

Title: List sorting - two lists into one

Body:
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

Body:
If you wanna do this with just loops, You could implement some sorting algorithm by yourself and along the way, interchange corresponding elements in names along with wages.

Here's an example with Bubble Sort:

for j in range(len(wages)-1,0,-1):
    for i in range(j):
        if wages[i]>wages[i+1]:
            tempWage = wages[i]
            wages[i] = wages[i+1]
            wages[i+1] = tempWage

            tempName = names[i]
            names[i] = names[i+1]
            names[i+1] = tempName