问:
Using Shadow DOM within ContentEditable to create protected blocks of text
Recently I've been developing a simple editor using ContentEditable. The requirements for the application are simple, with the one exception of being able to insert blocks of text which are protected from the normal editing actions.

These blocks of text cannot be edited and must behave as a single character for the purposes of moving the cursor through them or deleting them.

An example of the resulting HTML looks like this:

```<code><div id="editor" contenteditable style="height: 400px; border: 1px solid black; margin: 4px; padding: 4px; overflow:auto;">
  "This is standard text with a "
    <span class="attrib">
      #shadow-root
        "PROTECTED"
      "_"
    </span>
  " block"
</div>
</code>```

Whilst this provides the protected section of text I need, it has a couple of major problems that I cannot resolve:

The text after the shadow DOM element does not display.

The cursor does not move through the shadowDOM element at all.

Is there a better way to do this or is it just not possible to use the shadow DOM in this way?

答:
Solution 1

You can force the contenteditable attribute to false in your protected element:

  "This is standard text with a
  PROTECTED
   block"

```
</div>
</div>
</p>

<p><strong>Solution 2</strong></p>

<p>If you want to use Shadow DOM without <code>contenteditable=false</code>:</p>

<p>You can observe the caret position using <code>window.getSelection().anchorOffset</code>, and check if the position have changed. </p>

<p>If not, you'll have to move the caret to the next text node (if possible) with Selection's <code>setBaseAndExtent()</code>.</p>

<p>Here is a minimal example which works when the <code>[Right Arrow]</code> key is pressed:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>editor.querySelector( '.attrib' )
      .attachShadow({mode: 'open' } )
      .innerHTML = 'PROTECTED'

editor.addEventListener( 'keydown', onkeydown )

var position = 0

function onkeydown( ev )
{
  if ( ev.key == "ArrowRight" )
  {
    setTimeout( function ()
    {
      var sel = window.getSelection()
      if ( position == sel.anchorOffset )
      {
        var anchor = sel.anchorNode
        if ( anchor.nextSibling && anchor.nextSibling.nextSibling )
        {
          console.warn( 'move next' )
          var next = anchor.nextSibling.nextSibling
          sel.setBaseAndExtent( next, 1, next, 1)
        }
      }
      position = sel.anchorOffset
    } )
  }
}</code>```

.attrib {
    background: lightblue ;
}

#editor {
    height: 100px; width:400px; border: 1px solid black; margin: 4px; padding: 4px; overflow:auto
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="editor" contenteditable>"This
  is standard text with a <span class="attrib">TEST</span> block"
</div></code>```

Body:
Recently I've been developing a simple editor using ContentEditable. The requirements for the application are simple, with the one exception of being able to insert blocks of text which are protected from the normal editing actions.

These blocks of text cannot be edited and must behave as a single character for the purposes of moving the cursor through them or deleting them.

An example of the resulting HTML looks like this:

  "This is standard text with a "

      #shadow-root
        "PROTECTED"
      "_"

  " block"

Whilst this provides the protected section of text I need, it has a couple of major problems that I cannot resolve:

The text after the shadow DOM element does not display.

The cursor does not move through the shadowDOM element at all.

Is there a better way to do this or is it just not possible to use the shadow DOM in this way?

Body:
Solution 1

You can force the contenteditable attribute to false in your protected element:

<div id="editor" contenteditable style="height: 100px; border: 1px solid black; margin: 4px; padding: 4px; overflow:auto;">
  "This is standard text with a
  <span contenteditable="false">PROTECTED</span>
   block"
</div>

Solution 2

If you want to use Shadow DOM without contenteditable=false:

You can observe the caret position using window.getSelection().anchorOffset, and check if the position have changed.

If not, you'll have to move the caret to the next text node (if possible) with Selection's setBaseAndExtent().

Here is a minimal example which works when the [Right Arrow] key is pressed:

editor.querySelector( '.attrib' )
      .attachShadow({mode: 'open' } )
      .innerHTML = 'PROTECTED'

editor.addEventListener( 'keydown', onkeydown )

var position = 0

function onkeydown( ev )
{
  if ( ev.key == "ArrowRight" )
  {
    setTimeout( function ()
    {
      var sel = window.getSelection()
      if ( position == sel.anchorOffset )
      {
        var anchor = sel.anchorNode
        if ( anchor.nextSibling && anchor.nextSibling.nextSibling )
        {
          console.warn( 'move next' )
          var next = anchor.nextSibling.nextSibling
          sel.setBaseAndExtent( next, 1, next, 1)
        }
      }
      position = sel.anchorOffset
    } )
  }
}

.attrib {
    background: lightblue ;
}

#editor {
    height: 100px; width:400px; border: 1px solid black; margin: 4px; padding: 4px; overflow:auto
}

<div id="editor" contenteditable>"This
  is standard text with a <span class="attrib">TEST</span> block"
</div>


来源: stackexchange

问:
Notepad++ find string in parantheses
I try to fetch the string modlgn_username inside the paranthesis from the following string:

$this->webDriver->findElement(WebDriverBy::id("modlgn_username"))->click();

This is my regular expression:

```<code>\$this->webDriver->findElement\(WebDriverBy::id\("([A-z0-9]+)"\)\)->click\(\);
</code>```

However I get Find: Can't find text \$this->webDriver->findElement(WebDriverBy::id("([A-Za-z0-9])"))->click();

It works in online regex tester though:

https://regex101.com/r/6oDry3/1

答:
You have to add underscore in the character class or your regex and A-z is not a correct range, it inludes [\]^_ and backquote:

```<code>\$this->webDriver->findElement\(WebDriverBy::id\("([A-Za-z0-9_]+)"\)\)->click\(\);
</code>```

and this character class can be now reduce to \w:

```<code>\$this->webDriver->findElement\(WebDriverBy::id\("(\w+)"\)\)->click\(\);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Notepad++ find string in parantheses

Body:
I try to fetch the string modlgn_username inside the paranthesis from the following string:

$this->webDriver->findElement(WebDriverBy::id("modlgn_username"))->click();

This is my regular expression:

\$this->webDriver->findElement\(WebDriverBy::id\("([A-z0-9]+)"\)\)->click\(\);

However I get Find: Can't find text \$this->webDriver->findElement(WebDriverBy::id("([A-Za-z0-9])"))->click();

It works in online regex tester though:

https://regex101.com/r/6oDry3/1

Body:
You have to add underscore in the character class or your regex and A-z is not a correct range, it inludes [\]^_ and backquote:

\$this->webDriver->findElement\(WebDriverBy::id\("([A-Za-z0-9_]+)"\)\)->click\(\);

and this character class can be now reduce to \w:

\$this->webDriver->findElement\(WebDriverBy::id\("(\w+)"\)\)->click\(\);


问:
Definition of Multi-threading
Not really programming related this question, but I still hope it fits somehow here :).
I wrote the following sentence in my work:

```<code>Mulitthreading refers to the ability of an OS to subdivide an application into
threads, where each of the them are capable to execute independently.
</code>```

I was told, that this definition of thread is too narrow. I am not really sure why this is the case, could somebody be so kind to explain me what I missed?

Thank you

答:
A thread fundamentally, is a saved execution context - a set of saved registers and a stack, that you can resume and continue execution of. This thread can be executed on a processor (these days, many machines of course can execute multiple threads at the same time).

The critical aspect of "multi-threading" is, that an operating system can emulate execution of many threads at the same time, by preempting (stopping) a thread once it has run for a certain amount of time (a "quantum"), then scheduling another thread to run, based on a certain algorithm that is OS-specific.

ContentLicense: CC BY-SA 2.5

Title: Definition of Multi-threading

Body:
Not really programming related this question, but I still hope it fits somehow here :).
I wrote the following sentence in my work:

Mulitthreading refers to the ability of an OS to subdivide an application into
threads, where each of the them are capable to execute independently.

I was told, that this definition of thread is too narrow. I am not really sure why this is the case, could somebody be so kind to explain me what I missed?

Thank you


问:
DEP0001 : Unexpected Error: -2147023728
I was deploying my simple UWP app on Windows Phone (Lumia 535)

Phone:
Ver: 1607 - Build : 10.014393.953

Target:  (Enable Developer Mode - Phone & PC)

ERROR

DEP0001 : Unexpected Error: -2147023728

If I compile / run: (ARM - Device) Configuration

UPDATED: (I already turn this on - deploy)

I have this one already updated.

After tweaking some time I get this error:

I tried to make a file and sideload it -> Project -> Store -> Create Package

My package was corrupted during phone manual installation.

I could not find anything related to this error in Google.

答:
Based on the Third Screenshot, It looks like your App is not configured to deploy under ARM Configuration.

Click on the Dropdown next to Build Type(Debug\Release) And open Configuration Manager.

Make sure you have Deploy checked. Like in the screenshot Below.

Good Luck.

Title: DEP0001 : Unexpected Error: -2147023728


问:
How can I make the entire image clickable on my wordpress.org site?
Right now my posts can only be clicked by clicking the title, but I would love for the entire image to link to each individual post.

```<code><article id="post-<?php the_ID(); ?>" <?php post_class('card-box col-lg-4 col-md-6 col-sm-12 col-xs-12'); ?>>
    <div class="card" data-background="image" data-src="<?php esc_url( the_post_thumbnail_url( 'large' ) ); ?>">
             <div class="header">
                    <?php
                    $categories = get_the_category();
                    if ( ! empty( $categories ) ) {
                    ?>
                        <div class="category">
                            <h6>
                                <span class="category">
                                    <?php  echo '<a class="category" href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>'; ?>
                                </span>
                            </h6>
                        </div>
                    <?php } ?>
                </div>
                <div class="content">
                    <?php the_title( '<h4 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h4>' ); ?>
                    <span class="date"><?php echo esc_html( get_the_date() ); ?></span>
                </div>
                <div class="filter"></div>
                </div> <!-- end card -->
        </article>
</code>```

I don't want to use js because I've been told that's not SEO friendly.

I've tried using the  tag from the entry-title and surrounding the whole div with that same link, but it did not work.

答:
The following should work if the rest of the code works. What I did: I copied the  tag from the h4 element (the post title) and put it around the image (lines 2-4, no other changes in original code):

```<code><article id="post-<?php the_ID(); ?>" <?php post_class( 'card-box col-lg-4 col-md-6 col-sm-12 col-xs-12'); ?>>
  <a href="<?php the_permalink(); ?>">
    <div class="card" data-background="image" data-src="<?php esc_url( the_post_thumbnail_url( 'large' ) ); ?>">
    </a>
  <div class="header">
    <?php
                    $categories = get_the_category();
                    if ( ! empty( $categories ) ) {
                    ?>
      <div class="category">
        <h6>
          <span class="category">
                                    <?php  echo '<a class="category" href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>'; ?>
                                </span>
        </h6>
      </div>
      <?php } ?>
  </div>
  <div class="content">
    <?php the_title( '<h4 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h4>' ); ?>
    <span class="date"><?php echo esc_html( get_the_date() ); ?></span>
  </div>
  <div class="filter"></div>
  </div>
  <!-- end card -->
</article>
</code>```

Body:
Right now my posts can only be clicked by clicking the title, but I would love for the entire image to link to each individual post.

<article id="post-<?php the_ID(); ?>" <?php post_class('card-box col-lg-4 col-md-6 col-sm-12 col-xs-12'); ?>>
    <div class="card" data-background="image" data-src="<?php esc_url( the_post_thumbnail_url( 'large' ) ); ?>">

                    <?php
                    $categories = get_the_category();
                    if ( ! empty( $categories ) ) {
                    ?>

                                    <?php  echo 'term_id ) ) . '">' . esc_html( $categories[0]->name ) . ''; ?>

                    <?php } ?>

                    <?php the_title( '
', '
' ); ?>
                    <?php echo esc_html( get_the_date() ); ?>

I don't want to use js because I've been told that's not SEO friendly.

I've tried using the  tag from the entry-title and surrounding the whole div with that same link, but it did not work.

Body:
The following should work if the rest of the code works. What I did: I copied the <a> tag from the h4 element (the post title) and put it around the image (lines 2-4, no other changes in original code):

<article id="post-<?php the_ID(); ?>" <?php post_class( 'card-box col-lg-4 col-md-6 col-sm-12 col-xs-12'); ?>>
  <a href="<?php the_permalink(); ?>">
    <div class="card" data-background="image" data-src="<?php esc_url( the_post_thumbnail_url( 'large' ) ); ?>">
    </a>
  <div class="header">
    <?php
                    $categories = get_the_category();
                    if ( ! empty( $categories ) ) {
                    ?>
      <div class="category">
        <h6>
          <span class="category">
                                    <?php  echo '<a class="category" href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>'; ?>
                                </span>
        </h6>
      </div>
      <?php } ?>
  </div>
  <div class="content">
    <?php the_title( '<h4 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h4>' ); ?>
    <span class="date"><?php echo esc_html( get_the_date() ); ?></span>
  </div>
  <div class="filter"></div>
  </div>
  <!-- end card -->
</article>


问:
SonarQube scanner for MSBuild searches for a type under wrong assembly
I'm having a weird error with the SonarQube scanner for MSBuild (scanning C# code).

When running the tool on my project, i am getting this error:

```<code>"D:\Repro\Buggy.sln" (Rebuild target) (1) ->
"D:\Repro\Buggy.Editor.csproj" (Rebuild target) (3) ->
(RunCodeAnalysis target) ->
  MSBUILD : error : CA0001 : Could not find type 'UnityEngine.UI.Selectable' in assembly 'UnityEditor.UI, Version=1.0.0.0, Culture=neutral'. [D:\Repro\Buggy.Editor.csproj]

    2 Warning(s)
    1 Error(s)
</code>```

Note that i was able to create a minimal "repro" project that demonstrates this error (found here).

It's hard to tell why running MSBuild would attempt to look for the type named "UnityEngine.UI.Selectable" under that assembly (this type exists, but in a different assembly).

The .sln file i am scanning contains 2 projects (one references the other).

How can i find out what's going on here? and whether this is a bug in the scanner or with how i am using the tool ?

答:
I was finally able to find what was causing this issue.

Running using the latest C# plugin version (5.5.1.522), analysis still fails with the same error.

I also tried running analysis from VS2015 - failed with the same error message.

Digging even deeper - the offending assembly UnityEditor.UI.dll originally references the required UnityEngine.UI.dll, but somehow gets processed to strip that assembly reference.

This is the reason for failure. When executing the analysis, the "tampered" or modified DLL is used.

See more info on this thread i just created: https://forum.unity3d.com/threads/unityeditor-ui-dll-is-tampered-with-before-copying-to-library-unityassemblies.446053/

I reverted the DLL to the original version and everything works correctly.
So, not a SonarQube bug, but still annoying (and strange!)

This processing of the assemblies is done I believe by VSTU (Visual Studio Tools for Unity), and i also contacted one of the devs on that project - Jb Evain, currently waiting for a fix).

Body:
I'm having a weird error with the SonarQube scanner for MSBuild (scanning C# code).

When running the tool on my project, i am getting this error:

"D:\Repro\Buggy.sln" (Rebuild target) (1) ->
"D:\Repro\Buggy.Editor.csproj" (Rebuild target) (3) ->
(RunCodeAnalysis target) ->
  MSBUILD : error : CA0001 : Could not find type 'UnityEngine.UI.Selectable' in assembly 'UnityEditor.UI, Version=1.0.0.0, Culture=neutral'. [D:\Repro\Buggy.Editor.csproj]

    2 Warning(s)
    1 Error(s)

Note that i was able to create a minimal "repro" project that demonstrates this error (found here).

It's hard to tell why running MSBuild would attempt to look for the type named "UnityEngine.UI.Selectable" under that assembly (this type exists, but in a different assembly).

The .sln file i am scanning contains 2 projects (one references the other).

How can i find out what's going on here? and whether this is a bug in the scanner or with how i am using the tool ?


问:
Ruby: undefined method `delete', deleting parent and child data at the same time
I'm a newbie programmer, basically I'm trying to delete a record from a database table, however this record would be used on a child table with a composed primary key taking both from different tables.

This is the class of the table I need to delete the child data from.

```<code>class Detalle_Mapa
  include DataMapper::Resource
  storage_names[:default] = 'detalle_ma'

  property :clave_mapa, String, :length => 2, :required => true, :key => true
  property :clave_asig, String, :length => 10, :required => true, :key => true
  property :clave_cuatri, String, :length => 2, :required => true

  belongs_to :mapa_curricular, 'Mapa_Curricular', :child_key => [:clave_mapa], :key => true
  belongs_to :cuatrimestre, 'Cuatrimestre', :child_key => [:clave_cuatri], :key => true
  belongs_to :asignatura, 'Asignatura', :child_key => [:clave_asig]

end
</code>```

So now when I try to delete data from the parent table, it won't delete it since the PK is being used on the child table for other data. If this was normal SQL sintax it wouldn't be a big deal but I'm having a hard time finding a way around it on Ruby.

This is the basic method that works when deleting data that's not being used as a FK.

```<code>delete '/deleteMapCurricular/:clave_mapa' do
  @mapa = Mapa_Curricular.get(params[:clave_mapa])
  if @mapa
     @mapa.destroy
     redirect '/catMapCurricular'
  end
end
</code>```

And this is one of the ways I've tried to delete the child data, which is clearly not right...

```<code>     Detalle_Mapa.where(:clave_mapa => [params[:clave_mapa]]).delete_all
</code>```

Is there an easy way to just delete a bunch of data from a database that I'm not aware of? Or what I'm I not getting about this ActiveRecords on Ruby?

I'm sorry if the question is ambiguous or if I'm not explaining myself clearly, I usually find everything on forums and there is no need to ask myself. Any help will be greatly appreciated :)

答:
Sorry for not giving out the exact answer. But I can tell a concept in this answer

```<code>class User < ActiveRecord::Base
  has_many :fruits, dependent: :destroy
end

class Fruit < ActiveRecord::Base
  belongs_to :user
end
</code>```

So in the above example, if you delete a user, the associated fruits for that user will also be deleted automatically.

Body:
I'm a newbie programmer, basically I'm trying to delete a record from a database table, however this record would be used on a child table with a composed primary key taking both from different tables.

This is the class of the table I need to delete the child data from.

class Detalle_Mapa
  include DataMapper::Resource
  storage_names[:default] = 'detalle_ma'

  property :clave_mapa, String, :length => 2, :required => true, :key => true
  property :clave_asig, String, :length => 10, :required => true, :key => true
  property :clave_cuatri, String, :length => 2, :required => true

  belongs_to :mapa_curricular, 'Mapa_Curricular', :child_key => [:clave_mapa], :key => true
  belongs_to :cuatrimestre, 'Cuatrimestre', :child_key => [:clave_cuatri], :key => true
  belongs_to :asignatura, 'Asignatura', :child_key => [:clave_asig]

end

So now when I try to delete data from the parent table, it won't delete it since the PK is being used on the child table for other data. If this was normal SQL sintax it wouldn't be a big deal but I'm having a hard time finding a way around it on Ruby.

This is the basic method that works when deleting data that's not being used as a FK.

delete '/deleteMapCurricular/:clave_mapa' do
  @mapa = Mapa_Curricular.get(params[:clave_mapa])
  if @mapa
     @mapa.destroy
     redirect '/catMapCurricular'
  end
end

And this is one of the ways I've tried to delete the child data, which is clearly not right...

     Detalle_Mapa.where(:clave_mapa => [params[:clave_mapa]]).delete_all

Is there an easy way to just delete a bunch of data from a database that I'm not aware of? Or what I'm I not getting about this ActiveRecords on Ruby?

I'm sorry if the question is ambiguous or if I'm not explaining myself clearly, I usually find everything on forums and there is no need to ask myself. Any help will be greatly appreciated :)

Body:
Sorry for not giving out the exact answer. But I can tell a concept in this answer

class User < ActiveRecord::Base
  has_many :fruits, dependent: :destroy
end

class Fruit < ActiveRecord::Base
  belongs_to :user
end

So in the above example, if you delete a user, the associated fruits for that user will also be deleted automatically.


问:
How to list all folders and files in those folders using Exchange Web Services Managed API?
I just discovered the Exchanged Web Services Managed API and I've been playing around with it to try and gain an understanding because I believe it may provide a solution to an issue I've been working on.

Background

I've read a lot of the documentation and have a general sense of things. In particular, I set up something very similar to this LINK.

However, I want to display a folder, then display all of the related EmailMessage items after the folder, and so on and so forth through all folders/sub-folders. The code I've written so far, will list a folder, but it will list all of the emails that I returned instead of just those emails related to the folder. I'm searching for unread items just to keep the list small for the time-being.

Code

```<code>private static void GetAllItems(ExchangeService service)
    {
        List<Folder> lstFolderIds = new List<Folder>();

        // Fill list with all public folders and sub-folders
        GetAllFolders(service, lstFolderIds);

        List<EmailMessage> emails = new List<EmailMessage>();

        foreach(Folder folder in lstFolderIds)
        {
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            ItemView view = new ItemView(int.MaxValue);
            view.PropertySet = PropertySet.IdOnly;

            FindItemsResults<Item> searchResults = service.FindItems(folder.Id, sf, view);

            if (searchResults.Items.Count > 0)
            {
                foreach (var item in searchResults.Items)
                {
                    try
                    {
                        if (item is EmailMessage)
                        {
                            emails.Add((EmailMessage)item);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception: {0}", ex.Message);
                        Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                        Console.WriteLine("Source: {0}", ex.Source);
                        Console.WriteLine("HResult: {0}", ex.HResult);
                    }
                }
            }
        }

        PropertySet properties = (BasePropertySet.FirstClassProperties);
        service.LoadPropertiesForItems(emails, properties);

        foreach (Folder folder in lstFolderIds)
        {
            object folderName;
            object displayName;
            object childFolderCount;
            object unreadCount;
            object totalCount;

            folderName = folder.TryGetProperty(FolderSchema.ParentFolderId, out folderName) ? folder.ParentFolderId.FolderName.Value.ToString() : "N/A";
            displayName = folder.TryGetProperty(FolderSchema.DisplayName, out displayName) ? folder.DisplayName.ToString() : "N/A";
            childFolderCount = folder.TryGetProperty(FolderSchema.ChildFolderCount, out childFolderCount) ? folder.ChildFolderCount.ToString() : "N/A";
            unreadCount = folder.TryGetProperty(FolderSchema.UnreadCount, out unreadCount) ? folder.UnreadCount.ToString() : "N/A";
            totalCount = folder.TryGetProperty(FolderSchema.TotalCount, out totalCount) ? folder.TotalCount.ToString() : "N/A";

            Console.WriteLine("Parent Folder: {0}", folderName);
            Console.WriteLine("Folder Display Name: {0}", displayName);
            Console.WriteLine("Child Folder Count: {0}", childFolderCount);
            Console.WriteLine("Folder Unread Count: {0}", unreadCount);
            Console.WriteLine("Folder Total Count: {0}", totalCount);
            Console.WriteLine("---------------------------------------------------------");
            foreach (EmailMessage email in emails)
            {
                object parentFolderName;
                object subject;
                object retentionDate;

                parentFolderName = email.TryGetProperty(EmailMessageSchema.ParentFolderId, out parentFolderName) ? email.ParentFolderId.FolderName.Value.ToString() : "N/A";
                subject = email.TryGetProperty(EmailMessageSchema.Subject, out subject) ? email.Subject.ToString() : "N/A";
                retentionDate = email.TryGetProperty(EmailMessageSchema.RetentionDate, out retentionDate) ? retentionDate.ToString() : "N/A";

                Console.WriteLine("\tParent Folder Name: {0}", parentFolderName);
                Console.WriteLine("\tSubject: {0}", subject);
                Console.WriteLine("\tRetention Date: {0}", retentionDate);
                //}
            }

            Console.WriteLine("");
            Console.WriteLine("Press or select Enter...");
            Console.Read();
        }
    }
</code>```

Part of the problem is that I can't figure out how to get the folder name for the folder or the parent folder name for the EmailMessage. I can get the folder ID for the folder and the parent folder ID for the EmailMessage, but they are identical for all items that are returned, so it must not be right.

I read in this LINK that I may need to carry out an additional bind to relate the folders with the EmailMessage items, but I'm not exactly sure how to do that.

Expected Output

```<code>Parent Folder:
Folder Display Name: Inbox
Child Folder Count: 1
Folder Unread Count: 2
Folder Total Count: 51
---------------------------------------------------------
    Parent Folder Name: Inbox
    Subject: New Coversheets for TPS Reports
    Retention Date: 10/31/2017 11:59:59 PM

    Parent Folder Name: Inbox
    Subject: Have you seen my stapler?
    Retention Date: 07/31/2017 11:59:59 PM

Parent Folder:
Folder Display Name: Sent Items
Child Folder Count: 0
Folder Unread Count: 0
Folder Total Count: 27
---------------------------------------------------------
    No Un-Read Items
</code>```

Questions

How do I list the folder hierarchy with related EmailMessages that match my search condition?

Is the FolderId/ParentFolderId that I'm currently obtaining the Id for the MsgFolderRoot or is there any way to tell?

How do I obtain the Folder.FolderId.FolderName.Value and the EmailMessage.ParentFolderId.FolderName.Value?

If binding is necessary for #2, does anyone have an example or link they would share that illustrates the action?

Update(s)

Added a section for expected output before questions.

Thanks.

答:
After perusing the object browser, I discovered that the use of the FolderName property is mutually exclusive from the FolderId property, which explained why my parentFolderId.FolderName.Value code was always returning null.

I reorganized my code to build the hierarchy and used the ParentFolderId property for an EmailMessage to bind to the parent folder, which allowed me to obtain the parent folder's DisplayName property.

Body:
I just discovered the Exchanged Web Services Managed API and I've been playing around with it to try and gain an understanding because I believe it may provide a solution to an issue I've been working on.

Background

I've read a lot of the documentation and have a general sense of things. In particular, I set up something very similar to this LINK.

However, I want to display a folder, then display all of the related EmailMessage items after the folder, and so on and so forth through all folders/sub-folders. The code I've written so far, will list a folder, but it will list all of the emails that I returned instead of just those emails related to the folder. I'm searching for unread items just to keep the list small for the time-being.

Code

private static void GetAllItems(ExchangeService service)
    {
        List<Folder> lstFolderIds = new List<Folder>();

        // Fill list with all public folders and sub-folders
        GetAllFolders(service, lstFolderIds);

        List<EmailMessage> emails = new List<EmailMessage>();

        foreach(Folder folder in lstFolderIds)
        {
            SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            ItemView view = new ItemView(int.MaxValue);
            view.PropertySet = PropertySet.IdOnly;

            FindItemsResults<Item> searchResults = service.FindItems(folder.Id, sf, view);

            if (searchResults.Items.Count > 0)
            {
                foreach (var item in searchResults.Items)
                {
                    try
                    {
                        if (item is EmailMessage)
                        {
                            emails.Add((EmailMessage)item);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception: {0}", ex.Message);
                        Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                        Console.WriteLine("Source: {0}", ex.Source);
                        Console.WriteLine("HResult: {0}", ex.HResult);
                    }
                }
            }
        }

        PropertySet properties = (BasePropertySet.FirstClassProperties);
        service.LoadPropertiesForItems(emails, properties);

        foreach (Folder folder in lstFolderIds)
        {
            object folderName;
            object displayName;
            object childFolderCount;
            object unreadCount;
            object totalCount;

            folderName = folder.TryGetProperty(FolderSchema.ParentFolderId, out folderName) ? folder.ParentFolderId.FolderName.Value.ToString() : "N/A";
            displayName = folder.TryGetProperty(FolderSchema.DisplayName, out displayName) ? folder.DisplayName.ToString() : "N/A";
            childFolderCount = folder.TryGetProperty(FolderSchema.ChildFolderCount, out childFolderCount) ? folder.ChildFolderCount.ToString() : "N/A";
            unreadCount = folder.TryGetProperty(FolderSchema.UnreadCount, out unreadCount) ? folder.UnreadCount.ToString() : "N/A";
            totalCount = folder.TryGetProperty(FolderSchema.TotalCount, out totalCount) ? folder.TotalCount.ToString() : "N/A";

            Console.WriteLine("Parent Folder: {0}", folderName);
            Console.WriteLine("Folder Display Name: {0}", displayName);
            Console.WriteLine("Child Folder Count: {0}", childFolderCount);
            Console.WriteLine("Folder Unread Count: {0}", unreadCount);
            Console.WriteLine("Folder Total Count: {0}", totalCount);
            Console.WriteLine("---------------------------------------------------------");
            foreach (EmailMessage email in emails)
            {
                object parentFolderName;
                object subject;
                object retentionDate;

                parentFolderName = email.TryGetProperty(EmailMessageSchema.ParentFolderId, out parentFolderName) ? email.ParentFolderId.FolderName.Value.ToString() : "N/A";
                subject = email.TryGetProperty(EmailMessageSchema.Subject, out subject) ? email.Subject.ToString() : "N/A";
                retentionDate = email.TryGetProperty(EmailMessageSchema.RetentionDate, out retentionDate) ? retentionDate.ToString() : "N/A";

                Console.WriteLine("\tParent Folder Name: {0}", parentFolderName);
                Console.WriteLine("\tSubject: {0}", subject);
                Console.WriteLine("\tRetention Date: {0}", retentionDate);
                //}
            }

            Console.WriteLine("");
            Console.WriteLine("Press or select Enter...");
            Console.Read();
        }
    }

Part of the problem is that I can't figure out how to get the folder name for the folder or the parent folder name for the EmailMessage. I can get the folder ID for the folder and the parent folder ID for the EmailMessage, but they are identical for all items that are returned, so it must not be right.

I read in this LINK that I may need to carry out an additional bind to relate the folders with the EmailMessage items, but I'm not exactly sure how to do that.

Expected Output

Parent Folder:
Folder Display Name: Inbox
Child Folder Count: 1
Folder Unread Count: 2
Folder Total Count: 51
---------------------------------------------------------
    Parent Folder Name: Inbox
    Subject: New Coversheets for TPS Reports
    Retention Date: 10/31/2017 11:59:59 PM

    Parent Folder Name: Inbox
    Subject: Have you seen my stapler?
    Retention Date: 07/31/2017 11:59:59 PM

Parent Folder:
Folder Display Name: Sent Items
Child Folder Count: 0
Folder Unread Count: 0
Folder Total Count: 27
---------------------------------------------------------
    No Un-Read Items

Questions

How do I list the folder hierarchy with related EmailMessages that match my search condition?

Is the FolderId/ParentFolderId that I'm currently obtaining the Id for the MsgFolderRoot or is there any way to tell?

How do I obtain the Folder.FolderId.FolderName.Value and the EmailMessage.ParentFolderId.FolderName.Value?

If binding is necessary for #2, does anyone have an example or link they would share that illustrates the action?

Update(s)

Added a section for expected output before questions.

Thanks.


问:
YouTube Data API: recordingDetails not available after uploading a video via YouTube uploader
I uploaded my .mov file via the standard YouTube Upload (https://www.youtube.com/upload).
The video does contain the geolocation data and the date created, I have confirmed with exiftool.

However, recordingDetails does not come through when testing via https://developers.google.com/youtube/v3/docs/videos/list#try-it.

Does YouTube strip out the recordingDetails if I upload the video at https://www.youtube.com/upload?

Are there restrictions on video types, privacy settings, or anything else that would prevent recordingDetails from being available?

Or, if put differently, are recordingDetailsdetails only available if I manually provide them via my own API upload script?

I'm using a client-side only framework, and trying to accomplish this without relying on a server script that would parse the geolocation from the video.

Thank you!

答:
It seems that the recordingDetails will only be returned with the videos that have set a recording time. I tried different videoId and I cannot get any result with it. So meaning if the video doesn't have the attributes for it, then the API will not return any data.

From this documentation, the recordingDetails object encapsulates information about the location, date and address where the video was recorded. So you need to manually include it in the video for you to fetch this information.


问:
How to implement Facebook and Twitter into an iPhone app
Hey guys! I'm making my own Facebook app (or Twitter) and I would like to know how to implement it into your iPHone app.
If anyone could help me, send me a link or something
Thanks!</p>

答:
http://www.getsharekit.com/

ShareKit allows you to add support for many social sites to your app. It's super great and free. Check it out. You can look at the code to see how endlessly complicated the facebook/twitter apis are :)


问:
Why the ExecuteNonQuery catch exception {"validation error for column \"ORGTABLE\".\"FIKEYID\", value \"* null *\""}
Why the ExecuteNonQuery catch exception {"validation error for column \"ORGTABLE\".\"FIKEYID\", value \"* null *\""}

```<code>string stValuesPlaceHolder = "@p0";
for (int iii = 1; iii < liststFieldValuesNoKeyId.Count; iii++)
    stValuesPlaceHolder += ", @p" + (iii).ToString();

FbTransaction fbTransaction = fbConn.BeginTransaction();
FbCommand fbCmd = new FbCommand("INSERT INTO " + stTableName + "(" + stFieldNamesNoKeyId + ") VALUES ( " + stValuesPlaceHolder + " )", fbConn, fbTransaction);

for (int iii = 0; iii < liststFieldValuesNoKeyId.Count; iii++) {
    string stPlaceHolder = "@p" + (iii).ToString();
    string stValue = liststFieldValuesNoKeyId[iii];
    fbCmd.Parameters.AddWithValue(stPlaceHolder, stValue);
}

fbCmd.ExecuteNonQuery();
fbTransaction.Commit();
</code>```

The stTableName is OrgTable.

The fields names are:

```<code>fstPriority, fstInfo, fstDateCreated, fstDateModified, fiKeyID.
</code>```

The field definitions are:

```<code>fstPriority VARCHAR(30), fstInfo VARCHAR(100), fstDateCreated VARCHAR(30), fstDateModified VARCHAR(30), fiKeyID INTEGER PRIMARY KEY
</code>```

In this section of the code:

```<code>stFieldNamesNoKeyId = "fstPriority, fstInfo, fstDateCreated, fstDateModified".

stValuesPlaceHolder = "@p0, @p1, @p2, @p3"
</code>```

Four
    fbCmd.Parameters.AddWithValue:

```<code>stPlaceHolder = "@p0" ... stValue = "1st value";

stPlaceHolder = "@p1" ... stValue = "2nd value";

stPlaceHolder = "@p2" ... stValue = "3rd value";

stPlaceHolder = "@p3" ... stValue = "4th value";
</code>```

I did not add a value for fiKeyID as it as the PRIMARY KEY.

答:
Definitions:

```<code>public const string stMAIN_TABLE_NAME = " OrgTable ";
public const string stDELETED_TABLE_NAME = "  BackupTable ";

public const string stFIELD_DEFINITIONS = " fstPriority VARCHAR(30)" +
                                          ", fstInfo VARCHAR(100)" +
                                          ", fstDateCreated VARCHAR(30)" +
                                          ", fstDateModified VARCHAR(30)" +
                                          ", fiKeyID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY ";

public const string stFIELD_NAMES_NO_KEY_ID = " fstPriority" +
                                              ", fstInfo" +
                                              ", fstDateCreated" +
                                              ", fstDateModified ";

public const string stFIELD_NAMES_KEY_ID = " fiKeyID ";

public const string stFIELD_NAMES = stFIELD_NAMES_NO_KEY_ID + ", " + stFIELD_NAMES_KEY_ID;
</code>```

Code:

```<code>//------------------------------
static private bool boCreateDatabaseTables(string stPathFilename,
                                           string stUserID,
                                           string stPassword,
                                           List<string> liststTableNames,
                                           List<string> liststFieldDefinitions)
{
  bool boErrorFlag = false;
  int iTablesCount = liststTableNames.Count();
  string stOpenConn = new FbConnectionStringBuilder {
    Database = stPathFilename,
    UserID = stUserID,
    Password = stPassword,
    ServerType = FbServerType.Embedded,
    ClientLibrary = stCLIENT_LIBRARY
    }.ToString();
  using (FbConnection fbConn = new FbConnection(stOpenConn)) {
    try {
      fbConn.Open();

      FbTransaction fbTransaction = fbConn.BeginTransaction();
      for (int ii = 0; ii < iTablesCount; ii++) {
        string stSql = "CREATE TABLE " + liststTableNames[ii] + "( " + liststFieldDefinitions[ii] + ")";
        FbCommand fbCmd = new FbCommand(stSql, fbConn, fbTransaction);
        fbCmd.ExecuteNonQuery();
      }
      fbTransaction.Commit();
    }
    catch (Exception ex) {
      boErrorFlag = true;
      MessageBox.Show("catch ... GlobalsFirebird ... boCreateDatabaseTables ... " + ex.Message);
    }
}
return boErrorFlag;
}//boCreateDatabaseTables
//------------------------------
//------------------------------
static public bool boAddRow(string stPathFilename,
                            string stUserID,
                            string stPassword,
                            string stTableName,
                            string stFieldNamesNoKeyId,
                            string stFieldNamesKeyId,
                            List<string> liststFieldValuesNoKeyId)
{
  bool boErrorFlag = false;
  string stOpenConn = new FbConnectionStringBuilder {
    Database = stPathFilename,
    UserID = stUserID,
    Password = stPassword,
    ServerType = FbServerType.Embedded,
    ClientLibrary = stCLIENT_LIBRARY
  }.ToString();

  using(FbConnection fbConn = new FbConnection(stOpenConn)) {
    fbConn.Open();
    try {
      string stValuesPlaceHolder = "@p0";
      for (int iii = 1; iii < liststFieldValuesNoKeyId.Count; iii++)
        stValuesPlaceHolder += ", @p" + (iii).ToString();
      FbTransaction fbTransaction = fbConn.BeginTransaction();
      string stCmd = "INSERT INTO " + stTableName + "(" + stFieldNamesNoKeyId + ") VALUES ( " + stValuesPlaceHolder + " ) RETURNING  " + stFieldNamesKeyId;
      FbCommand fbCmd = new FbCommand(stCmd, fbConn, fbTransaction);

      for (int iii = 0; iii < liststFieldValuesNoKeyId.Count; iii++) {
        string stPlaceHolder = "@p" + (iii).ToString();
        string stValue = liststFieldValuesNoKeyId[iii];
        fbCmd.Parameters.AddWithValue(stPlaceHolder, stValue);
      }
      fbCmd.Parameters.Add(new FbParameter() { Direction = System.Data.ParameterDirection.Output });
      fbCmd.ExecuteNonQuery();
      fbTransaction.Commit();
    }
    catch (Exception ex) {
      boErrorFlag = true;
      MessageBox.Show("catch ... GlobalsFirebird ... boAddRow ... " + ex.Message);
    }
  }
  return boErrorFlag;
}//boAddRow
//------------------------------
</code>```

Body:
Why the ExecuteNonQuery catch exception {"validation error for column \"ORGTABLE\".\"FIKEYID\", value \"* null *\""}

string stValuesPlaceHolder = "@p0";
for (int iii = 1; iii < liststFieldValuesNoKeyId.Count; iii++)
    stValuesPlaceHolder += ", @p" + (iii).ToString();

FbTransaction fbTransaction = fbConn.BeginTransaction();
FbCommand fbCmd = new FbCommand("INSERT INTO " + stTableName + "(" + stFieldNamesNoKeyId + ") VALUES ( " + stValuesPlaceHolder + " )", fbConn, fbTransaction);

for (int iii = 0; iii < liststFieldValuesNoKeyId.Count; iii++) {
    string stPlaceHolder = "@p" + (iii).ToString();
    string stValue = liststFieldValuesNoKeyId[iii];
    fbCmd.Parameters.AddWithValue(stPlaceHolder, stValue);
}

fbCmd.ExecuteNonQuery();
fbTransaction.Commit();

The stTableName is OrgTable.

The fields names are:

fstPriority, fstInfo, fstDateCreated, fstDateModified, fiKeyID.

The field definitions are:

fstPriority VARCHAR(30), fstInfo VARCHAR(100), fstDateCreated VARCHAR(30), fstDateModified VARCHAR(30), fiKeyID INTEGER PRIMARY KEY

In this section of the code:

stFieldNamesNoKeyId = "fstPriority, fstInfo, fstDateCreated, fstDateModified".

stValuesPlaceHolder = "@p0, @p1, @p2, @p3"

Four
    fbCmd.Parameters.AddWithValue:

stPlaceHolder = "@p0" ... stValue = "1st value";

stPlaceHolder = "@p1" ... stValue = "2nd value";

stPlaceHolder = "@p2" ... stValue = "3rd value";

stPlaceHolder = "@p3" ... stValue = "4th value";

I did not add a value for fiKeyID as it as the PRIMARY KEY.

Body:
Definitions:

public const string stMAIN_TABLE_NAME = " OrgTable ";
public const string stDELETED_TABLE_NAME = "  BackupTable ";

public const string stFIELD_DEFINITIONS = " fstPriority VARCHAR(30)" +
                                          ", fstInfo VARCHAR(100)" +
                                          ", fstDateCreated VARCHAR(30)" +
                                          ", fstDateModified VARCHAR(30)" +
                                          ", fiKeyID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY ";

public const string stFIELD_NAMES_NO_KEY_ID = " fstPriority" +
                                              ", fstInfo" +
                                              ", fstDateCreated" +
                                              ", fstDateModified ";

public const string stFIELD_NAMES_KEY_ID = " fiKeyID ";

public const string stFIELD_NAMES = stFIELD_NAMES_NO_KEY_ID + ", " + stFIELD_NAMES_KEY_ID;

Code:

//------------------------------
static private bool boCreateDatabaseTables(string stPathFilename,
                                           string stUserID,
                                           string stPassword,
                                           List<string> liststTableNames,
                                           List<string> liststFieldDefinitions)
{
  bool boErrorFlag = false;
  int iTablesCount = liststTableNames.Count();
  string stOpenConn = new FbConnectionStringBuilder {
    Database = stPathFilename,
    UserID = stUserID,
    Password = stPassword,
    ServerType = FbServerType.Embedded,
    ClientLibrary = stCLIENT_LIBRARY
    }.ToString();
  using (FbConnection fbConn = new FbConnection(stOpenConn)) {
    try {
      fbConn.Open();

      FbTransaction fbTransaction = fbConn.BeginTransaction();
      for (int ii = 0; ii < iTablesCount; ii++) {
        string stSql = "CREATE TABLE " + liststTableNames[ii] + "( " + liststFieldDefinitions[ii] + ")";
        FbCommand fbCmd = new FbCommand(stSql, fbConn, fbTransaction);
        fbCmd.ExecuteNonQuery();
      }
      fbTransaction.Commit();
    }
    catch (Exception ex) {
      boErrorFlag = true;
      MessageBox.Show("catch ... GlobalsFirebird ... boCreateDatabaseTables ... " + ex.Message);
    }
}
return boErrorFlag;
}//boCreateDatabaseTables
//------------------------------
//------------------------------
static public bool boAddRow(string stPathFilename,
                            string stUserID,
                            string stPassword,
                            string stTableName,
                            string stFieldNamesNoKeyId,
                            string stFieldNamesKeyId,
                            List<string> liststFieldValuesNoKeyId)
{
  bool boErrorFlag = false;
  string stOpenConn = new FbConnectionStringBuilder {
    Database = stPathFilename,
    UserID = stUserID,
    Password = stPassword,
    ServerType = FbServerType.Embedded,
    ClientLibrary = stCLIENT_LIBRARY
  }.ToString();

  using(FbConnection fbConn = new FbConnection(stOpenConn)) {
    fbConn.Open();
    try {
      string stValuesPlaceHolder = "@p0";
      for (int iii = 1; iii < liststFieldValuesNoKeyId.Count; iii++)
        stValuesPlaceHolder += ", @p" + (iii).ToString();
      FbTransaction fbTransaction = fbConn.BeginTransaction();
      string stCmd = "INSERT INTO " + stTableName + "(" + stFieldNamesNoKeyId + ") VALUES ( " + stValuesPlaceHolder + " ) RETURNING  " + stFieldNamesKeyId;
      FbCommand fbCmd = new FbCommand(stCmd, fbConn, fbTransaction);

      for (int iii = 0; iii < liststFieldValuesNoKeyId.Count; iii++) {
        string stPlaceHolder = "@p" + (iii).ToString();
        string stValue = liststFieldValuesNoKeyId[iii];
        fbCmd.Parameters.AddWithValue(stPlaceHolder, stValue);
      }
      fbCmd.Parameters.Add(new FbParameter() { Direction = System.Data.ParameterDirection.Output });
      fbCmd.ExecuteNonQuery();
      fbTransaction.Commit();
    }
    catch (Exception ex) {
      boErrorFlag = true;
      MessageBox.Show("catch ... GlobalsFirebird ... boAddRow ... " + ex.Message);
    }
  }
  return boErrorFlag;
}//boAddRow
//------------------------------


问:
script to sort sheet by 2 colums
Please help make the script. As written below, I wrote a script that worked for some time. Now it does not work and I need help writing a new one.
The challenge is this: when you make changes in column F, K and O - occurs first check the availability of the text in the column to the - then if there is a text should start sorting first by F column - then sorting by a column O
There is a scheme of action sequences by the link:
https://drive.google.com/file/d/0B5qSx6LqB8U-d01URS1BcEVtNGs/view?usp=sharing

I will be happy if someone can help me.
In any case, thanks for your time and attention :) Have a nice day :)

29/03/17 I need help "Service error: spreadsheets"
A very recently worked script:

```<code>    function onEdit() {
var ss = SpreadsheetApp.getActiveSheet();
var r = SpreadsheetApp.getActiveRange();
var cols = r.getColumn();
var rows = r.getRow();
var who = ss.getRange(rows,11).getValue();
if (who !== "") {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]
sheet.sort(6);
sheet.sort(15);}
}
</code>```

Today received an error:
Service error: spreadsheets

The script stopped working at all, help, please.

答:
I'm not following how this completes your action sequence flow chart, but I believe this should get it running as before. I've seen other posts where people get this same Service Error message form previously working scripts, and I believe Google is trying to change how certain tasks are done to help their server loads.

function onEdit() {
var ss = SpreadsheetApp.getActive();
var r = SpreadsheetApp.getActiveRange();
var cols = r.getColumn();
var rows = r.getRow();
var who = ss.getActiveSheet().getRange(rows,11).getValue();
if (who !== "") {
var sheet = ss.getSheets()[0];
sheet.sort(6);
sheet.sort(15);}
}```

I removed the duplicate definition of var ss and tweaked var ss, var who and var sheet to work without it.

Title: script to sort sheet by 2 colums

Body:
Please help make the script. As written below, I wrote a script that worked for some time. Now it does not work and I need help writing a new one.
The challenge is this: when you make changes in column F, K and O - occurs first check the availability of the text in the column to the - then if there is a text should start sorting first by F column - then sorting by a column O
There is a scheme of action sequences by the link:
https://drive.google.com/file/d/0B5qSx6LqB8U-d01URS1BcEVtNGs/view?usp=sharing

I will be happy if someone can help me.
In any case, thanks for your time and attention :) Have a nice day :)

29/03/17 I need help "Service error: spreadsheets"
A very recently worked script:

    function onEdit() {
var ss = SpreadsheetApp.getActiveSheet();
var r = SpreadsheetApp.getActiveRange();
var cols = r.getColumn();
var rows = r.getRow();
var who = ss.getRange(rows,11).getValue();
if (who !== "") {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0]
sheet.sort(6);
sheet.sort(15);}
}

Today received an error:
Service error: spreadsheets

The script stopped working at all, help, please.

Body:
I'm not following how this completes your action sequence flow chart, but I believe this should get it running as before. I've seen other posts where people get this same Service Error message form previously working scripts, and I believe Google is trying to change how certain tasks are done to help their server loads.

function onEdit() {
var ss = SpreadsheetApp.getActive();
var r = SpreadsheetApp.getActiveRange();
var cols = r.getColumn();
var rows = r.getRow();
var who = ss.getActiveSheet().getRange(rows,11).getValue();
if (who !== "") {
var sheet = ss.getSheets()[0];
sheet.sort(6);
sheet.sort(15);}
}

I removed the duplicate definition of var ss and tweaked var ss, var who and var sheet to work without it.


问:
Get static image from Google map for given area
I know that Google Maps provides an API for getting static images:

https://developers.google.com/maps/documentation/static-maps/intro

However that API gets as input a center point, zoom level and output image size.

In my case, I need an image that fits a given area taking as input the NW (top-left) and SE (bottom right) coordinates describing the rectangle of my area. I don't see that option within Google Maps API, so I'm wondering if there is another way to accomplish this.

答:
You can omit the center and zoom parameters if you specify at least one marker. In this case you can show a certain area with a marker.

For example, I have bounds of Barcelona in Spain:

41.320004,2.069526 and 41.469576,2.22801

I can easily calculate the center position of the bounds:

41.39479,2.148768

Now, let's put a marker in the center of bounds and use the visible parameter of Static Maps API to specify NW and SE.

visible (optional) specifies one or more locations that should remain visible on the map, though no markers or other indicators will be displayed. Use this parameter to ensure that certain features or map locations are shown on the Google Static Maps API.

https://maps.googleapis.com/maps/api/staticmap?size=600x400&markers=icon%3Ahttp%3A%2F%2Fwww.google.com%2Fmapfiles%2Farrow.png%7C41.39479%2C2.148768&visible=41.320004%2C2.069526%7C41.469576%2C2.22801&key=api_key

Code snippet

```

As a result, you have an image with specified area. I think you can even go further if you create a transparent png file for marker icon.

Hope it helps!

Body:
You can omit the center and zoom parameters if you specify at least one marker. In this case you can show a certain area with a marker.

For example, I have bounds of Barcelona in Spain:

41.320004,2.069526 and 41.469576,2.22801

I can easily calculate the center position of the bounds:

41.39479,2.148768

Now, let's put a marker in the center of bounds and use the visible parameter of Static Maps API to specify NW and SE.

visible (optional) specifies one or more locations that should remain visible on the map, though no markers or other indicators will be displayed. Use this parameter to ensure that certain features or map locations are shown on the Google Static Maps API.

https://maps.googleapis.com/maps/api/staticmap?size=600x400&markers=icon%3Ahttp%3A%2F%2Fwww.google.com%2Fmapfiles%2Farrow.png%7C41.39479%2C2.148768&visible=41.320004%2C2.069526%7C41.469576%2C2.22801&key=api_key

Code snippet

<img src="https://maps.googleapis.com/maps/api/staticmap?size=600x400&markers=icon%3Ahttp%3A%2F%2Fwww.google.com%2Fmapfiles%2Farrow.png%7C41.39479%2C2.148768&visible=41.320004%2C2.069526%7C41.469576%2C2.22801&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&signature=WkICJTRmmI1EgDK2VJI4l9lt3qA=" title="" />

As a result, you have an image with specified area. I think you can even go further if you create a transparent png file for marker icon.

Hope it helps!

ContentLicense: CC BY-SA 4.0


问:
MongoDB insert raises duplicate key error
I am getting the following error when trying to do a bulk insert into an empty mongodb collection.

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index:
  cmdDistros.locDistro.$id  dup key: { :
  ObjectId('51dac9d0c74cd81acd85c0fd') }

I am not specifying an _id when I create any of the documents, so mongodb should create the unique index correct?  Here is the code I used:

```<code>#Populate database with uniform distribution
            entries = []
            for coor in freeIndices:
                for theta in range(360):
                    entry = {"x" : coor[0], "y" : coor[1], "heading" : theta}
                    for i in range(numData):
                            entry["data" + str(i)] = 1./numData
                    entries.append(entry)
            print "Entries created, loading into database..."

            locDistro.insert(entries)
</code>```

Taking fate out of mongoDB's hands, I tried creating my own index using:

```<code>#Populate database with uniform distribution
            entries = []
            idNum = 0
            for coor in freeIndices:
                for theta in range(360):
                    print idNum
                    entry = {"_id" : idNum, "x" : coor[0], "y" : coor[1], "heading" : theta}
                    idNum += 1
                    for i in range(numData):
                            entry["data" + str(i)] = 1./numData
                    entries.append(entry)
            print "Entries created, loading into database..."

            locDistro.insert(entries, manipulate = False)
</code>```

The print statement showed each idnum as the documents were created, and they were all unique and incremented just as expected.  However on insert, I received the error:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index:
  cmdDistros.locDistro.$id  dup key: { : 0 }

and only one document was inserted into my database.

I am completely stumped, anyone have an answer as to why this might be happening?

答:
Delete the key "_id":

```<code>for i in xrange(2):
    doc['i'] = i
    if '_id' in doc:
        del doc['_id']
    collection.insert(doc)
</code>```

Or manually create a new one:

```<code>from bson.objectid import ObjectId

for i in xrange(2):
    doc['i'] = i
    doc['_id'] = ObjectId()
    collection.insert(doc)
</code>```

Getting "err" : "E11000 duplicate key error when inserting into mongo using the Java driver

Body:
I am getting the following error when trying to do a bulk insert into an empty mongodb collection.

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index:
  cmdDistros.locDistro.$id  dup key: { :
  ObjectId('51dac9d0c74cd81acd85c0fd') }

I am not specifying an _id when I create any of the documents, so mongodb should create the unique index correct?  Here is the code I used:

#Populate database with uniform distribution
            entries = []
            for coor in freeIndices:
                for theta in range(360):
                    entry = {"x" : coor[0], "y" : coor[1], "heading" : theta}
                    for i in range(numData):
                            entry["data" + str(i)] = 1./numData
                    entries.append(entry)
            print "Entries created, loading into database..."

            locDistro.insert(entries)

Taking fate out of mongoDB's hands, I tried creating my own index using:

#Populate database with uniform distribution
            entries = []
            idNum = 0
            for coor in freeIndices:
                for theta in range(360):
                    print idNum
                    entry = {"_id" : idNum, "x" : coor[0], "y" : coor[1], "heading" : theta}
                    idNum += 1
                    for i in range(numData):
                            entry["data" + str(i)] = 1./numData
                    entries.append(entry)
            print "Entries created, loading into database..."

            locDistro.insert(entries, manipulate = False)

The print statement showed each idnum as the documents were created, and they were all unique and incremented just as expected.  However on insert, I received the error:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error index:
  cmdDistros.locDistro.$id  dup key: { : 0 }

and only one document was inserted into my database.

I am completely stumped, anyone have an answer as to why this might be happening?

Body:
Delete the key "_id":

for i in xrange(2):
    doc['i'] = i
    if '_id' in doc:
        del doc['_id']
    collection.insert(doc)

Or manually create a new one:

from bson.objectid import ObjectId

for i in xrange(2):
    doc['i'] = i
    doc['_id'] = ObjectId()
    collection.insert(doc)

Getting "err" : "E11000 duplicate key error when inserting into mongo using the Java driver


问:
MultiThreading Windows Application
Lets say i have a form with 2 textboxs

im in a different thread and i want to compine texts in those two textboxs i understand that i can invoke each one of them and get the value then concatenate them but

i was thinking of a way to invoke 2 controls at once without hanging the main thread.

, i tried invoking textboxes one by one  then get values but that hanged my main thread for some reasons

any idea of how to do that without hanging the main thread ?

Sample:

```<code>    txtFrom.Invoke(new MethodInvoker(() => strFrom = txtFrom.Text));
        txtTo.Invoke(new MethodInvoker(() => strTo = txtTo.Text));
        txtMessageBody.Invoke(new MethodInvoker(() => strMessageBody = txtMessageBody.Text));
        txtStartDate.Invoke(new MethodInvoker(() => strStartDate = txtStartDate.Text));
        txtEndDate.Invoke(new MethodInvoker(() => strEndDate = txtEndDate.Text));
        ddlStatus.Invoke(new MethodInvoker(() => intStatus = ddlStatus.SelectedIndex));
</code>```

thanks in advance

Enviroments:

Windows 7.
.Net 4
Windows Form
C#

答:
Since you say invoke 2 controls at once without hanging the main thread, I suspect there is some confusion here.

When you Invoke a control in WinForms as you describe, code within those MethodInvokes is actually executed on the UI/main thread. This is by design, invoking those controls will execute code on the UI thread so that the controls may be accessed on the thread they were created by originally. Thus, any lengthy operation in that code will hang the UI thread.

The lengthy operation should therefore be started on a separate thread, perhaps using the BackgroundWorker .

Title: MultiThreading Windows Application

Body:
Lets say i have a form with 2 textboxs

im in a different thread and i want to compine texts in those two textboxs i understand that i can invoke each one of them and get the value then concatenate them but

i was thinking of a way to invoke 2 controls at once without hanging the main thread.

, i tried invoking textboxes one by one  then get values but that hanged my main thread for some reasons

any idea of how to do that without hanging the main thread ?

Sample:

    txtFrom.Invoke(new MethodInvoker(() => strFrom = txtFrom.Text));
        txtTo.Invoke(new MethodInvoker(() => strTo = txtTo.Text));
        txtMessageBody.Invoke(new MethodInvoker(() => strMessageBody = txtMessageBody.Text));
        txtStartDate.Invoke(new MethodInvoker(() => strStartDate = txtStartDate.Text));
        txtEndDate.Invoke(new MethodInvoker(() => strEndDate = txtEndDate.Text));
        ddlStatus.Invoke(new MethodInvoker(() => intStatus = ddlStatus.SelectedIndex));

thanks in advance

Enviroments:

Windows 7.
.Net 4
Windows Form
C#


问:
Need to bifurcate pom.xml based on the requirement
I have one project in GIT, which I am cloning and running my tests through Maven and selenium.

Now I want to run those test-cases against Jenkins CI.

Since I have multiple projects in GIT, I have multiple pom.xml in my repository..

My question is - How can I run specific project on specific run.. If I want to run project1 first and then I want to run project2 by just changing the pom.xml through command line. How can I do it.

Thanks.

答: You can execute your "mvn" job in the project directory you want to build. For example, if you have /project1/pom.xml and /project2/pom.xml, you can choose which project run first by setting your working directory in /project1 or in /project2 then running your mvn command.</p>


问:
angular 2 - how to hide nav bar in some components
I am created nav bar separately in nav.component.html ,how to hide nav bar in some components like login.component.

nav.component.html

```<code><nav class="navbar navbar-default navbar-fixed-top navClass">
    <div class="container-fluid">
        <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed"
                        (click)="toggleState()">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>
         <div class="collapse navbar-collapse"
              [ngClass]="{ 'in': isIn }">
          enter code here   <ul class="nav navbar-nav">
               <li class="active"><a href="#">Home</a></li>
               <li><a href="#">about</a></li>

            </ul>

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

答:
Navbar control and formatting is often needed throughout an app, so a NavbarService is useful. Inject in those components where you need.

navbar.service.ts:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class NavbarService {
  visible: boolean;

  constructor() { this.visible = false; }

  hide() { this.visible = false; }

  show() { this.visible = true; }

  toggle() { this.visible = !this.visible; }

  doSomethingElseUseful() { }

  ...
}
</code>```

navbar.component.ts:

```<code>import { Component } from '@angular/core';
import { NavbarService } from './navbar.service';

@Component({
  moduleId: module.id,
  selector: 'sd-navbar',
  templateUrl: 'navbar.component.html'
})

export class NavbarComponent {

  constructor( public nav: NavbarService ) {}
}
</code>```

navbar.component.html:

```<code><nav *ngIf="nav.visible">
 ...
</nav>
</code>```

example.component.ts:

```<code>import { Component, OnInit } from '@angular/core';
import { NavbarService } from './navbar.service';

@Component({
})
export class ExampleComponent implements OnInit {

  constructor( public nav: NavbarService ) {}
}
ngOnInit() {
  this.nav.show();
  this.nav.doSomethingElseUseful();
}
</code>```

Body:
I am created nav bar separately in nav.component.html ,how to hide nav bar in some components like login.component.

nav.component.html

                <button type="button" class="navbar-toggle collapsed"
                        (click)="toggleState()">
                Toggle navigation

            </button>

          enter code here

Home

about

Body:
Navbar control and formatting is often needed throughout an app, so a NavbarService is useful. Inject in those components where you need.

navbar.service.ts:

import { Injectable } from '@angular/core';

@Injectable()
export class NavbarService {
  visible: boolean;

  constructor() { this.visible = false; }

  hide() { this.visible = false; }

  show() { this.visible = true; }

  toggle() { this.visible = !this.visible; }

  doSomethingElseUseful() { }

  ...
}

navbar.component.ts:

import { Component } from '@angular/core';
import { NavbarService } from './navbar.service';

@Component({
  moduleId: module.id,
  selector: 'sd-navbar',
  templateUrl: 'navbar.component.html'
})

export class NavbarComponent {

  constructor( public nav: NavbarService ) {}
}

navbar.component.html:

<nav *ngIf="nav.visible">
 ...
</nav>

example.component.ts:

import { Component, OnInit } from '@angular/core';
import { NavbarService } from './navbar.service';

@Component({
})
export class ExampleComponent implements OnInit {

  constructor( public nav: NavbarService ) {}
}
ngOnInit() {
  this.nav.show();
  this.nav.doSomethingElseUseful();
}


问:
Proper placement of q.all inside array.map with _.forEach
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

```<code>'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }
</code>```

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

```<code>.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});
</code>```

...but it's still not returning anything. What am I doing wrong?

答:
It was almost correct the first time!

When you did:

```<code>var promises = [];
empIDcoll.map(function (id) {
    return EmployeeInfo.find({ employeeID: id }, function (err, results) {
        if (err) { return err; }
        _.forEach(results, function (item) {
            if (item) {
                tempCtr.push({
                    employeeID: item.employeeID,
                    employeeName: item.employeeName
                });
                promises.push(tempCtr);
            }
        });
    });

    q.all(promises).then(function (results) {
        return res.json(results);
    });
});
</code>```

You had the q.all location wrong (inside the .map); and you pushed objects inside your promises array, instead of actual promises. Try to do something like:

```<code>// Here, we will build an array of promises by transforming each element of `empIDcoll` to a promise (via `.map`).
var promises = empIDcoll.map(function (id) {
    return EmployeeInfo.find({ employeeID: id }).exec(); // I assume that .exec() will return a promise.
});

q.all(promises).then(function (results) { // `results` will be an array, each element will contain the result of each promise pushed to `promises`.
    return res.json(results);
});
</code>```

Try this. This may need some tweaking maybe (let us know), for I don't really know the structure of your application / models.

Body:
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});

...but it's still not returning anything. What am I doing wrong?

Body:
It was almost correct the first time!

When you did:

var promises = [];
empIDcoll.map(function (id) {
    return EmployeeInfo.find({ employeeID: id }, function (err, results) {
        if (err) { return err; }
        _.forEach(results, function (item) {
            if (item) {
                tempCtr.push({
                    employeeID: item.employeeID,
                    employeeName: item.employeeName
                });
                promises.push(tempCtr);
            }
        });
    });

    q.all(promises).then(function (results) {
        return res.json(results);
    });
});

You had the q.all location wrong (inside the .map); and you pushed objects inside your promises array, instead of actual promises. Try to do something like:

// Here, we will build an array of promises by transforming each element of `empIDcoll` to a promise (via `.map`).
var promises = empIDcoll.map(function (id) {
    return EmployeeInfo.find({ employeeID: id }).exec(); // I assume that .exec() will return a promise.
});

q.all(promises).then(function (results) { // `results` will be an array, each element will contain the result of each promise pushed to `promises`.
    return res.json(results);
});

Try this. This may need some tweaking maybe (let us know), for I don't really know the structure of your application / models.


问:
How to use let variable across example blocks without reinitiating the let block?
I want to create FactoryGirl object and use across groups without re-initiating let block multiple times. There should be only one user created in Database. How can i achieve it?

```<code>describe MyCLass do
  let(:adm) { FactoryGirl.create(:user) }

  describe "test for" do
    #want to use :adm here
  end

  describe "test2 for" do
    #want to use :adm here
  end

  describe "test3" do
    #want to use :adm here
  end
end
</code>```

*I am new to RSpec

答:
There should be only one user created in database. How can i achieve it?

By cleaning the database after each test. It's the generally recommended approach. Look up DatabaseCleaner gem, for example.

Body:
I want to create FactoryGirl object and use across groups without re-initiating let block multiple times. There should be only one user created in Database. How can i achieve it?

describe MyCLass do
  let(:adm) { FactoryGirl.create(:user) }

  describe "test for" do
    #want to use :adm here
  end

  describe "test2 for" do
    #want to use :adm here
  end

  describe "test3" do
    #want to use :adm here
  end
end

*I am new to RSpec


问:
tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform
I built TensorFlow from source on Ubuntu 14.04 LTS.
I got the following error:

tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.

```<code>$ bazel build --config=opt --config=cuda //tensorflow/tools/pip_package:build_pip_package

...

cc1plus: warning: unrecognized command line option "-Wno-self-assign" [enabled by default]
Target //tensorflow/tools/pip_package:build_pip_package up-to-date:
  bazel-bin/tensorflow/tools/pip_package/build_pip_package
INFO: Elapsed time: 3222.284s, Critical Path: 2243.74s
ubuntu@ip-10-0-1-32:~/tensorflow$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
Tue Mar 21 22:17:06 UTC 2017 : === Using tmpdir: /tmp/tmp.JVDbpc8IYs
~/tensorflow/bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles ~/tensorflow
~/tensorflow
/tmp/tmp.JVDbpc8IYs ~/tensorflow
Tue Mar 21 22:17:07 UTC 2017 : === Building wheel
warning: no files found matching '*.dll' under directory '*'
warning: no files found matching '*.lib' under directory '*'
~/tensorflow
Tue Mar 21 22:17:29 UTC 2017 : === Output wheel file is in: /tmp/tensorflow_pkg

$ sudo pip install /tmp/tensorflow_pkg/tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl
tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.
Storing debug log for failure in /home/ubuntu/.pip/pip.log

ubuntu@ip-10-0-1-202:~$ python -m pip install --upgrade pip
Requirement already up-to-date: pip in ./anaconda/lib/python2.7/site-packages
ubuntu@ip-10-0-1-202:~$ man pip
ubuntu@ip-10-0-1-202:~$ pip --version
pip 9.0.1 from /home/ubuntu/anaconda/lib/python2.7/site-packages (python 2.7)

vi /home/ubuntu/.pip/pip.log:

tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.
Exception information:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 257, in run
    InstallRequirement.from_line(name, None))
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 168, in from_line
    raise UnsupportedWheel("%s is not a supported wheel on this platform." % wheel.filename)
UnsupportedWheel: tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.
</code>```

I'm getting the same error with a protobuf wheel:

```<code>sudo -H pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0b2.post2-cp27-none-linux_x86_64.whl
protobuf-3.0.0b2.post2-cp27-none-linux_x86_64.whl is not a supported wheel on this platform.
</code>```

答:
sudo retrieved the 3.4 version of 'pip' (instead of the 2.7 version):

ubuntu@ip-10-0-1-152:~/tensorflow$ sudo pip --version
pip 9.0.1 from /usr/local/lib/python3.4/dist-packages/pip-9.0.1-py3.4.egg (python 3.4)

Body:
I built TensorFlow from source on Ubuntu 14.04 LTS.
I got the following error:

tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.

$ bazel build --config=opt --config=cuda //tensorflow/tools/pip_package:build_pip_package

...

cc1plus: warning: unrecognized command line option "-Wno-self-assign" [enabled by default]
Target //tensorflow/tools/pip_package:build_pip_package up-to-date:
  bazel-bin/tensorflow/tools/pip_package/build_pip_package
INFO: Elapsed time: 3222.284s, Critical Path: 2243.74s
ubuntu@ip-10-0-1-32:~/tensorflow$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
Tue Mar 21 22:17:06 UTC 2017 : === Using tmpdir: /tmp/tmp.JVDbpc8IYs
~/tensorflow/bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles ~/tensorflow
~/tensorflow
/tmp/tmp.JVDbpc8IYs ~/tensorflow
Tue Mar 21 22:17:07 UTC 2017 : === Building wheel
warning: no files found matching '*.dll' under directory '*'
warning: no files found matching '*.lib' under directory '*'
~/tensorflow
Tue Mar 21 22:17:29 UTC 2017 : === Output wheel file is in: /tmp/tensorflow_pkg

$ sudo pip install /tmp/tensorflow_pkg/tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl
tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.
Storing debug log for failure in /home/ubuntu/.pip/pip.log

ubuntu@ip-10-0-1-202:~$ python -m pip install --upgrade pip
Requirement already up-to-date: pip in ./anaconda/lib/python2.7/site-packages
ubuntu@ip-10-0-1-202:~$ man pip
ubuntu@ip-10-0-1-202:~$ pip --version
pip 9.0.1 from /home/ubuntu/anaconda/lib/python2.7/site-packages (python 2.7)

vi /home/ubuntu/.pip/pip.log:

tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.
Exception information:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 257, in run
    InstallRequirement.from_line(name, None))
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 168, in from_line
    raise UnsupportedWheel("%s is not a supported wheel on this platform." % wheel.filename)
UnsupportedWheel: tensorflow-1.0.1-cp27-cp27mu-linux_x86_64.whl is not a supported wheel on this platform.

I'm getting the same error with a protobuf wheel:

sudo -H pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/protobuf-3.0.0b2.post2-cp27-none-linux_x86_64.whl
protobuf-3.0.0b2.post2-cp27-none-linux_x86_64.whl is not a supported wheel on this platform.


问:
Custom SQL query in JPA repositories
For the following query:

```<code>@Query("SELECT fd FROM DPPFile fd WHERE fd.ID= ':ID'")
List<DPPFile> findByID(@Param("ID")String ID/);
</code>```

I'm getting the following weird exception:

```<code>Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
    at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:502)
    at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:140)
    at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:100)
    at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:160)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:151)
    at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:121)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
</code>```

I'd expect this exception if I was using ?1 instead of the named parameter approach. Using the ?1 fails as well so I'm not sure what's going wrong here.
The DPPFile class has a member called ID as well as getter/setter.

(The reason I'm not using the default "findByID" with no query on top of it function is because I want to extend the query with additional parameters)

答: Don't put the parameter in single quotes otherwise it is resolved as a literal. Hence the query will not be registered.</p>

Title: Custom SQL query in JPA repositories

Body:
For the following query:

@Query("SELECT fd FROM DPPFile fd WHERE fd.ID= ':ID'")
List<DPPFile> findByID(@Param("ID")String ID/);

I'm getting the following weird exception:

Caused by: java.lang.IllegalArgumentException: Parameter with that position [1] did not exist
    at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:502)
    at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:692)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:181)
    at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:140)
    at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:100)
    at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:160)
    at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:151)
    at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:121)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)

I'd expect this exception if I was using ?1 instead of the named parameter approach. Using the ?1 fails as well so I'm not sure what's going wrong here.
The DPPFile class has a member called ID as well as getter/setter.

(The reason I'm not using the default "findByID" with no query on top of it function is because I want to extend the query with additional parameters)


问:
Sending List into Partial View
I'm still trying to get my head wrapped around .net MVC, and maybe I'm just not searching the right key words to find my answer.

In short, I have a partial view that has a list that I want to include in the main view.

Index.cshtml:

```<code>@Html.Action("Checklist")
</code>```

Checklist.cshtml:

```<code>@model List<Area>
<div class="row">
    <div class="col-md-4">
        <h4 class="text-center">Outcomes</h4>
        @foreach (var item in Model)
        {
            <p>@Html.DisplayFor(modelItem => item)</p>
        }
    </div>
</div>
</code>```

Controller:

```<code>public PartialViewResult Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Select(oa => oa.Area).Distinct();
        return PartialView("Checklist", outcomeAreas.ToList());
    }
</code>```

Edit: I get a weird rendering now in the html when testing the website.  if you look at the page source code, I see:

```<code>System.Collections.Generic.List`1[System.String] List<Area>
</code>```

答:
I think this specific error is related to the fact that the lamdba doesn't use the same alias:

```<code><p>@Html.DisplayFor(modelItem => item.Area)</p>
</code>```

to

```<code><p>@Html.DisplayFor(item => item.Area)</p>
</code>```

The lambda alias and usage has to match.   I think this is what the CS1001 error usually refers to, but @Ben's answer is a change also needed; either have the model expect IEnumerable, or as he said, call ToList() in the action method to ensure it's a list type.

Title: Sending List into Partial View

Body:
I'm still trying to get my head wrapped around .net MVC, and maybe I'm just not searching the right key words to find my answer.

In short, I have a partial view that has a list that I want to include in the main view.

Index.cshtml:

@Html.Action("Checklist")

Checklist.cshtml:

@model List<Area>

Outcomes

        @foreach (var item in Model)
        {

@Html.DisplayFor(modelItem => item)

        }

Controller:

public PartialViewResult Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Select(oa => oa.Area).Distinct();
        return PartialView("Checklist", outcomeAreas.ToList());
    }

Edit: I get a weird rendering now in the html when testing the website.  if you look at the page source code, I see:

System.Collections.Generic.List`1[System.String] List<Area>

Body:
I think this specific error is related to the fact that the lamdba doesn't use the same alias:

<p>@Html.DisplayFor(modelItem => item.Area)</p>

to

<p>@Html.DisplayFor(item => item.Area)</p>

The lambda alias and usage has to match.   I think this is what the CS1001 error usually refers to, but @Ben's answer is a change also needed; either have the model expect IEnumerable, or as he said, call ToList() in the action method to ensure it's a list type.


问:
react: uncaught TypeError: Cannot read property 'state' of undefined
I am trying to get 'state' object in function Application which is out from General class and I am getting this error "Uncaught TypeError: Cannot read property 'state' of undefined".
  The code is</p>

```<code>class General extends Comment {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
}

const Application = () => {
  return (
    <div> Hello world beginner: {this.state.comments}</div>
  );
};

render(<Application/>, document.getElementById('container'));
</code>```

答:
Application is stateless component. Not to say that arrow functions have lexical scoping of context.

Use props for stateless components.

```<code>const Application = (props) => {
  return (
    <div> Hello world beginner: {props.comments}</div>
  );
};
</code>```

Or extend React.Component

```<code>class Application extends React.Component {
  constructor() {
     // init state
  }

  render() {
    return <div> Hello world beginner: {this.state.comments}</div>
  }
}
</code>```

Body:
I am trying to get 'state' object in function Application which is out from General class and I am getting this error "Uncaught TypeError: Cannot read property 'state' of undefined".
  The code is

class General extends Comment {
  constructor() {
    super();
    this.state = { comments: first_comment};
  }
}

const Application = () => {
  return (

 Hello world beginner: {this.state.comments}

  );
};

render(<Application/>, document.getElementById('container'));

Body:
Application is stateless component. Not to say that arrow functions have lexical scoping of context.

Use props for stateless components.

const Application = (props) => {
  return (
    <div> Hello world beginner: {props.comments}</div>
  );
};

Or extend React.Component

class Application extends React.Component {
  constructor() {
     // init state
  }

  render() {
    return <div> Hello world beginner: {this.state.comments}</div>
  }
}