问:
Jenkins, vstest.console.exe, and PowerShell

Problem

This is a bit of a two fold problem.

I am working on a Job that runs unit tests found within a target project. I have two variants that I am working with and I am trying to get one of them to work properly.

Variant A

I am using the VsTestRunner plugin however, I do not know how to capture its input so that I can place that information into an external log.

Variant B

I have forgone the VsTestRunner plugin and am working with the vstest.console.exe through PowerShell, but have found the following problem:

How do I terminate the script and fail the build if any of the tests fail?

I tried looking through the code of the above plugin, but it's in Java (which I have limited experience with) and I could not find how exactly it terminates the code. I also could not find any resources on this... and the documentation for vstest.console.exe has nothing about use cases outside its option variables. I have also tried looking through the vstest.console.exe.config file in hopes that had something I could use... but that was a bust too.

Question

Variant A: Is it possible to capture the output of a Jenkins plugin? If so, how?

Variant B: How do I terminate the script and fail the Jenkins build if any of the tests fail?

答:
Shout out to @4c74356b41 for nudging me in the right direction.

After re-examining the code, I found that my first problem for Variant B was that I had put the check for $LastExitCode was in the wrong place. This at least allowed me to get the desired fail I was looking for. Once I had this, it was a matter of utilizing some variation of the following:

```<code>Try {
    & $vsTestConsole $testFile /any /necessary /options

    If ($LastExitCode -ne 0) {
        throw "TestFailure"
    }
}
Catch {
    # Custom error specifically for failed tests
    If ($_.Exception.Message -ieq 'TestFailure') {
        Write-Host "One or more tests failed, ending action"
        # Terminate PS Script with an Exit Code of 1 so that Jenkins Fails the build
        # Exiting in this manner also prevents the addition of unnecessary fluff
        # This way you can fully customize the error response
        [Environment]::Exit(1)
    }
</code>```

Body:
Shout out to @4c74356b41 for nudging me in the right direction.

After re-examining the code, I found that my first problem for Variant B was that I had put the check for $LastExitCode was in the wrong place. This at least allowed me to get the desired fail I was looking for. Once I had this, it was a matter of utilizing some variation of the following:

Try {
    & $vsTestConsole $testFile /any /necessary /options

    If ($LastExitCode -ne 0) {
        throw "TestFailure"
    }
}
Catch {
    # Custom error specifically for failed tests
    If ($_.Exception.Message -ieq 'TestFailure') {
        Write-Host "One or more tests failed, ending action"
        # Terminate PS Script with an Exit Code of 1 so that Jenkins Fails the build
        # Exiting in this manner also prevents the addition of unnecessary fluff
        # This way you can fully customize the error response
        [Environment]::Exit(1)
    }


来源: stackexchange

问:
Android : Border only on corners
In my android app, I need border only on four corners as shown in fig (white colored).

```<code>    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="6">
        <VideoView
            android:id="@+id/video1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />
        <View
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            android:background="@drawable/cornerbg" />
    </RelativeLayout>
</code>```

cornerbg.xml

```<code>        <?xml version="1.0" encoding="utf-8"?>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

        <item>
            <shape android:shape="rectangle" >
                <solid android:color="@color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="@color/btn_border"
                    android:dashWidth="50dp" // I tried this but not getting expected
                    android:dashGap="60dp"/>

            </shape>
        </item>
        </layer-list>
</code>```

How can I write xml for this?

Please help,
Thanks

答:
I know it's a question of a long time ago, but I had the same problem.

I solved by creating secondary layout and including in my main layout.

I hope this solution can help somebody.

main_layout.xml

```<code><RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="6">

    <VideoView
        android:id="@+id/video1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center" />

    <include layout="@layout/camera_box_layout" />

</RelativeLayout>
</code>```

camera_box_layout.xml

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="40dp"
    android:background="@android:color/transparent">

    <!-- Top horizzontal lines -->
    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />

    <!-- Top vertical lines -->
    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />

    <!-- Bottom horizzontal lines -->
    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />

    <!-- Bottom vertical lines -->
    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />
</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android : Border only on corners

Body:
In my android app, I need border only on four corners as shown in fig (white colored).

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="6">
        <VideoView
            android:id="@+id/video1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />
        <View
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerInParent="true"
            android:background="@drawable/cornerbg" />
    </RelativeLayout>

cornerbg.xml

        <?xml version="1.0" encoding="utf-8"?>
        <layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

        <item>
            <shape android:shape="rectangle" >
                <solid android:color="@color/transparent" />
                <stroke
                    android:width="1dp"
                    android:color="@color/btn_border"
                    android:dashWidth="50dp" // I tried this but not getting expected
                    android:dashGap="60dp"/>

            </shape>
        </item>
        </layer-list>

How can I write xml for this?

Please help,
Thanks

Body:
I know it's a question of a long time ago, but I had the same problem.

I solved by creating secondary layout and including in my main layout.

I hope this solution can help somebody.

main_layout.xml

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="6">

    <VideoView
        android:id="@+id/video1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center" />

    <include layout="@layout/camera_box_layout" />

</RelativeLayout>

camera_box_layout.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="40dp"
    android:background="@android:color/transparent">

    <!-- Top horizzontal lines -->
    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />

    <!-- Top vertical lines -->
    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />

    <!-- Bottom horizzontal lines -->
    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="100dp"
        android:layout_height="2dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />

    <!-- Bottom vertical lines -->
    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/darker_gray" />

    <View
        android:layout_width="2dp"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:background="@android:color/darker_gray" />
</RelativeLayout>


问:
Show hide multiple divs based on select value
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

```<code><form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div data-response="op1">
      This is content for option 1.
    </div>
    <div data-response="op2">
      This is content for option 2.
    </div>
    <div data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>
</code>```

答:
Really all you need is to hide all the divs using some CSS by default, and then use the change function to get the value and select the div based on that value:

$('#select-box').change(function(){

   var selectVal = $(this).val();
   $('.content, #other-questions').hide();
   $('.content[data-response="op' + selectVal + '"], #other-questions').show();

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content, #other-questions {
display: none;
}</code>```

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>```

I've updated my answer to include classes which are better for selecting elements than data attributes.

Body:
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>

Body:
Really all you need is to hide all the divs using some CSS by default, and then use the change function to get the value and select the div based on that value:

$('#select-box').change(function(){

   var selectVal = $(this).val();
   $('.content, #other-questions').hide();
   $('.content[data-response="op' + selectVal + '"], #other-questions').show();

});

.content, #other-questions {
display: none;
}

<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>

<form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div class="content" data-response="op1">
      This is content for option 1.
    </div>
    <div class="content" data-response="op2">
      This is content for option 2.
    </div>
    <div class="content" data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>

I've updated my answer to include classes which are better for selecting elements than data attributes.


问:
list order base on number
how to make the list from top.base on the number
now its like this :

valencia - 3

felicia - 2

gisela - 1

kania - 4

tania - 5

but i want to make

gisela - 1

felicia - 2

valencia - 3

kania - 4

tania - 5

heres the code

```<code><div id="root" class="ipeka">
<div v-for="list in lists" :key="list.no">
    {{list.name}} - {{list.no}}
</div></div>

<script>
var app = new Vue({
    el:'#root',
    data:{
        lists:[
            {name:'valencia',no:3},
            {name:'felicia',no:2},
            {name:'gisela',no:1},
            {name:'kania',no:4},
            {name:'tania',no:5},
        ]
    }

})
</code>```

答:
This is typically accomplished with a computed property.

console.clear()

var app = new Vue({
  el: '#root',
  data: {
    lists: [
      { name: 'valencia', no: 3},
      { name: 'felicia', no: 2 },
      { name: 'gisela', no: 1 },
      { name: 'kania', no: 4 },
      { name: 'tania', no: 5 },
    ]
  },
  computed: {
    sortedList() {
      return this.lists.sort((a, b) => a.no - b.no)
    }
  }

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="root" class="ipeka">
  <div v-for="list in sortedList" :key="list.no">
    {{list.name}} - {{list.no}}
  </div>
</div></code>```

Title: list order base on number

Body:
how to make the list from top.base on the number
now its like this :

valencia - 3

felicia - 2

gisela - 1

kania - 4

tania - 5

but i want to make

gisela - 1

felicia - 2

valencia - 3

kania - 4

tania - 5

heres the code

    {{list.name}} - {{list.no}}

Body:
This is typically accomplished with a computed property.

console.clear()

var app = new Vue({
  el: '#root',
  data: {
    lists: [
      { name: 'valencia', no: 3},
      { name: 'felicia', no: 2 },
      { name: 'gisela', no: 1 },
      { name: 'kania', no: 4 },
      { name: 'tania', no: 5 },
    ]
  },
  computed: {
    sortedList() {
      return this.lists.sort((a, b) => a.no - b.no)
    }
  }

})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<div id="root" class="ipeka">
  <div v-for="list in sortedList" :key="list.no">
    {{list.name}} - {{list.no}}
  </div>
</div>

ContentLicense: CC BY-SA 4.0


问:
How to structure relationships between models in Ruby On Rails
I'm developing an application to schedule soccer matches for two teams at a time. So, for example I need to schedule a match for two teams, but I'm not sure how can I structure the database relation between these two entities.

One solution I thought is a relation many to many between them, and in the Associative Table(match_teams) I put a is_visitor field, to indicate which team is playing outside home:

team model:

```<code>class Team < ApplicationRecord
    has_many :match_team
    has_many :matches, through: :match_team
end
</code>```

match model:

```<code>class Match < ApplicationRecord
    has_many :match_team
    has_many :teams, through: :match_team
end
</code>```

match_team model:

```<code>class MatchTeam < ApplicationRecord
  belongs_to :match
  belongs_to :team
end
</code>```

team migration:

```<code>class CreateTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :teams do |t|
      t.timestamps
    end
  end
end
</code>```

match migration:

```<code>class CreateMatches < ActiveRecord::Migration[5.1]
  def change
    create_table :matches do |t|
      t.timestamps
    end
  end
end
</code>```

match_teams migration:

```<code>class CreateMatchTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :match_teams do |t|
        t.belongs_to :match, index: true, foreign_key: true
        t.belongs_to :team, index: true, foreign_key: true
        t.boolean "is_visitor", default: false
      t.timestamps
    end
  end
end
</code>```

So, I can do something like:

```<code>#create team here
#create team2 here

match = Match.new()
match.teams = [team, team2]
match.save!

match_team_associative = match.match_team
match_team_associative.each do |item|
  if item.team_id == team.id
    item.is_visitor = true
    item.save!
  end
end
</code>```

I don't know if this is the better solution, or if it's ok the manner I'm changing the value of is_visitor field in the associative table.

Another soluction I think would be has two relations one to many between these entitties team and match. A table matches would have a foreign key for teams called team, and another foreign key for teams called visitor_team, like:

matches table:

```<code>id | team | visitor_team
1  |    1 | 2
</code>```

But this second soluction I could't implement, I don't know how to do that. I find something here but I could't make it work. Does anyone can help me telling me how to make it work that way?

Which of these two solution is better? I think maybe the second, but it couldn't make it work.

I appreciate any help.

Thank you.

答:
The logic is, to have a match, and two teams in a match. One team will be hosting and one will be a visitor. Even if they play on neutral ground one team is still technically a host.

```<code>class Team < ApplicationRecord
  has_many :hosted_matches, class_name: 'Match', foreign_key: :hosting_team_id
  has_many :visited_matches, class_name: 'Match', foreign_key: :visiting_team_id
end

class Match < ApplicationRecord
  belongs_to :hosting_team, class_name: 'Team'
  belongs_to :visiting_team, class_name: 'Team'
end

...

# create team here
# create team2 here

match = Match.new(hosting_team: team, visiting_team: team2)
match.save!
</code>```

Migrations

```<code>class CreateTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :teams do |t|
      t.timestamps
    end
  end
end

class CreateMatches < ActiveRecord::Migration[5.1]
  def change
    create_table :matches do |t|
      t.integer :hosting_team_id
      t.integer :visiting_team_id
      t.timestamps
    end
  end
end
</code>```

Body:
I'm developing an application to schedule soccer matches for two teams at a time. So, for example I need to schedule a match for two teams, but I'm not sure how can I structure the database relation between these two entities.

One solution I thought is a relation many to many between them, and in the Associative Table(match_teams) I put a is_visitor field, to indicate which team is playing outside home:

team model:

class Team < ApplicationRecord
    has_many :match_team
    has_many :matches, through: :match_team
end

match model:

class Match < ApplicationRecord
    has_many :match_team
    has_many :teams, through: :match_team
end

match_team model:

class MatchTeam < ApplicationRecord
  belongs_to :match
  belongs_to :team
end

team migration:

class CreateTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :teams do |t|
      t.timestamps
    end
  end
end

match migration:

class CreateMatches < ActiveRecord::Migration[5.1]
  def change
    create_table :matches do |t|
      t.timestamps
    end
  end
end

match_teams migration:

class CreateMatchTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :match_teams do |t|
        t.belongs_to :match, index: true, foreign_key: true
        t.belongs_to :team, index: true, foreign_key: true
        t.boolean "is_visitor", default: false
      t.timestamps
    end
  end
end

So, I can do something like:

#create team here
#create team2 here

match = Match.new()
match.teams = [team, team2]
match.save!

match_team_associative = match.match_team
match_team_associative.each do |item|
  if item.team_id == team.id
    item.is_visitor = true
    item.save!
  end
end

I don't know if this is the better solution, or if it's ok the manner I'm changing the value of is_visitor field in the associative table.

Another soluction I think would be has two relations one to many between these entitties team and match. A table matches would have a foreign key for teams called team, and another foreign key for teams called visitor_team, like:

matches table:

id | team | visitor_team
1  |    1 | 2

But this second soluction I could't implement, I don't know how to do that. I find something here but I could't make it work. Does anyone can help me telling me how to make it work that way?

Which of these two solution is better? I think maybe the second, but it couldn't make it work.

I appreciate any help.

Thank you.

Body:
The logic is, to have a match, and two teams in a match. One team will be hosting and one will be a visitor. Even if they play on neutral ground one team is still technically a host.

class Team < ApplicationRecord
  has_many :hosted_matches, class_name: 'Match', foreign_key: :hosting_team_id
  has_many :visited_matches, class_name: 'Match', foreign_key: :visiting_team_id
end

class Match < ApplicationRecord
  belongs_to :hosting_team, class_name: 'Team'
  belongs_to :visiting_team, class_name: 'Team'
end

...

# create team here
# create team2 here

match = Match.new(hosting_team: team, visiting_team: team2)
match.save!

Migrations

class CreateTeams < ActiveRecord::Migration[5.1]
  def change
    create_table :teams do |t|
      t.timestamps
    end
  end
end

class CreateMatches < ActiveRecord::Migration[5.1]
  def change
    create_table :matches do |t|
      t.integer :hosting_team_id
      t.integer :visiting_team_id
      t.timestamps
    end
  end
end


问:
Automate Facebook Signup not able to select female radio button
I am trying to create new account on FB but I am not able to select radio buttons and signup button

```<code>public void f() {
      driver.findElement(By.id("u_0_g")).sendKeys("Anamika");
      driver.findElement(By.id("u_0_i")).sendKeys("Singh");
      driver.findElement(By.id("u_0_l")).sendKeys("9718257931");
      driver.findElement(By.id("u_0_s")).sendKeys("P@ssw0rd1");
      WebElement add=driver.findElement(By.id("day"));
      Select dropDown=new Select(add);

      dropDown.selectByIndex(6);
      add=driver.findElement(By.id("month"));
      dropDown=new Select(add);
      dropDown.selectByIndex(4);
      add=driver.findElement(By.id("year"));
      dropDown=new Select(add);
      dropDown.selectByIndex(6);

      driver.findElement(By.cssSelector("[id=u_0_j]")).click();
      driver.findElement(By.cssSelector("[id=u_0_n]")).click();
      //WebElement lstitem=driver.findElement(By.id("u_0_6"));
      //driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
      //if(elem.isSelected())

      //driver.findElement(By.id("u_0_10")).click();
      //else
          //System.out.println("Button not selected");
  }
  @BeforeMethod
  public void beforeMethod() {
      driver=new FirefoxDriver();
            driver.get("https://www.facebook.com/");//get to hit the URL

  }

  @AfterMethod
  public void afterMethod() {
      //driver.quit();
  }

}
</code>```

Getting Following error:

org.openqa.selenium.ElementNotInteractableException:

答:
According to FB home page

xPath for female:

```<code>//*[@name='sex' and @value='1']
</code>```

xPath for male:

```<code>//*[@name='sex' and @value='2']
</code>```

Body:
I am trying to create new account on FB but I am not able to select radio buttons and signup button

public void f() {
      driver.findElement(By.id("u_0_g")).sendKeys("Anamika");
      driver.findElement(By.id("u_0_i")).sendKeys("Singh");
      driver.findElement(By.id("u_0_l")).sendKeys("9718257931");
      driver.findElement(By.id("u_0_s")).sendKeys("P@ssw0rd1");
      WebElement add=driver.findElement(By.id("day"));
      Select dropDown=new Select(add);

      dropDown.selectByIndex(6);
      add=driver.findElement(By.id("month"));
      dropDown=new Select(add);
      dropDown.selectByIndex(4);
      add=driver.findElement(By.id("year"));
      dropDown=new Select(add);
      dropDown.selectByIndex(6);

      driver.findElement(By.cssSelector("[id=u_0_j]")).click();
      driver.findElement(By.cssSelector("[id=u_0_n]")).click();
      //WebElement lstitem=driver.findElement(By.id("u_0_6"));
      //driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
      //if(elem.isSelected())

      //driver.findElement(By.id("u_0_10")).click();
      //else
          //System.out.println("Button not selected");
  }
  @BeforeMethod
  public void beforeMethod() {
      driver=new FirefoxDriver();
            driver.get("https://www.facebook.com/");//get to hit the URL

  }

  @AfterMethod
  public void afterMethod() {
      //driver.quit();
  }

}

Getting Following error:

org.openqa.selenium.ElementNotInteractableException:

Body:
According to FB home page

xPath for female:

//*[@name='sex' and @value='1']

xPath for male:

//*[@name='sex' and @value='2']


问:
Creating overlapping elements
I'm trying to display a span overlapping a canvas element along the canvas' left border.

```<code><!doctype html />
<html>
  <head>
    <title>Z-Index</title>
  </head>

  <body>
    <div id="timeline_wrapper"></div>
    <script type="text/javascript">

        var canvas = document.createElement('canvas');
        canvas.setAttribute('width', 500);
        canvas.setAttribute('height', 500);
        canvas.setAttribute('style', 'border: 1px solid; position: absolute; top: 8px; left: 8px; z-index: 0;');
        document.getElementById("timeline_wrapper").appendChild(canvas);

        // draw back button
        var back = document.createElement('div');
        back.setAttribute('width', 50);
        back.setAttribute('height', 500);
        back.setAttribute('style', 'background-color: #336699; position: absolute; left: 8px; top: 8px; z-index: 1');
        document.getElementById("timeline_wrapper").appendChild(back);

    </script>
  </body>
</html>
</code>```

No matter what I've tried, the back element doesn't show up at all.
Apart from the back element being positioned at 50, 50 from top, left, does someone know what I'm doing wrong?

Cheers,
Joshua

答: Without seeing the rest of your code, my first guess is that the problem is because of the span tag. Spans are inline elements, which means they don't behave the same as block elements. Try using css to change the display property of the span to 'block', or simply use a div instead of a span.</p>

ContentLicense: CC BY-SA 2.5

Title: Creating overlapping elements

Body:
I'm trying to display a span overlapping a canvas element along the canvas' left border.

<!doctype html />

    <title>Z-Index</title>

No matter what I've tried, the back element doesn't show up at all.
Apart from the back element being positioned at 50, 50 from top, left, does someone know what I'm doing wrong?

Cheers,
Joshua


问:
Python byte string data stream
I am working in Python(3) on a Raspberry Pi 3.  My application is data acquisition and logging.  My question has to do with properly splitting and interpreting serial data received as byte strings:

Raw data continuously accumulated in and read from an input buffer over two or more non-queried (USB) serial ports are received in the following general form in my application.  The string tends to be much longer, but the following should be sufficient for an example:

b'+00000\r\n-00210\r\n+00360\r\n+00300\r\n-00163\r\n+00399\r\n'

I am using serial.read(serial.in_waiting) to receive the data.  I find this to be the best method, as my independent data sources are asynchronous, continuously spitting-out their values (approximately 50 samples per second) and have slightly differing data-broadcast rates (just enough to be a nuisance).

I have found that I cannot reliably use "readline()" to simplify my task for a few reasons, including - and please do comment on this point if you have any insights on this - the fact that, for whatever reason, the "in_waiting" value is not reset to zero on my system after a "readline()".

Unfortunately, the "in_waiting" approach often produces data, not so neatly terminated as shown above.  Possible variants, representing what might make it over the serial port on a given read attempt include:

b'+00000\r\n-00210\r\n+00360\r\n+00300\r\n-00163\r\n+003'

or

b'+00000\r\n-00210\r\n+00360\r\n+00300\r\n-00163\r'

or

b'+00000\r\n-00210\r\n+00360\r\n+00300\r\n-00163'

or

b'+00000\r\n-00210\r\n+00360\r\n+00300\r\n-'

That is, not all terminal data are fully-formed when they are read.

I have been attempting to use "decode" and "split" and "list" and "map" functions to interpret all available, complete data (those data that are properly terminated with \r\n) in order that I may do additional work with the numerical values on the fly. All the while, my intent is to retain any partial data that may have been received on the end of the read, so that they can be appended on the next read cycle.

My attempts have not met with success for all cases above, and that is why I am appealing to members more familiar with the Python programming language than I am for guidance.

Please kindly consider commenting on what would be the most efficient way (in Python) to:

1. Get from data such as I show above into a list of integer values.

2. Exclude incomplete, trailing data from the conversion, if it is not properly terminated.

3. Retain any incomplete trailing data for appending on subsequent read.

If you have dealt with a circumstance like mine in the past, I am hoping to learn from your experience, as I continue exploring the matter on my own.

答:
[This is not an answer, but it was too long for a comment]

Take everything I say with a grain of salt, I'm no expert, I'm just throwing some ideas around!

Are all complete values the same lenght? In that case you could dump it all into a io.BytesIO streams (https://docs.python.org/3/library/io.html#binary-i-o) and grab the next n bytes (where n = len(complete_value))?

You say you've tried solving this with decode, split, list, and map. Could you explain what you did exactly? Because I don't see what's wrong with something like:

```<code>incomplete_value = b''
my_ints = []
while <there_is_data>:
    tmp = incomplete_value + get_my_data() # get a new batch of data and append it
    tmp_split = tmp.split(b'\r\n') # split the data on newlines
    complete_data = tmp_split[:-1] # get all but the last item
    incomplete_value = tmp_split[-1] # save the last item
    my_ints += [int.from_bytes(x) for x in complete_data] # creates a list of ints
</code>```

Title: Python byte string data stream

Body:
[This is not an answer, but it was too long for a comment]

Take everything I say with a grain of salt, I'm no expert, I'm just throwing some ideas around!

Are all complete values the same lenght? In that case you could dump it all into a io.BytesIO streams (https://docs.python.org/3/library/io.html#binary-i-o) and grab the next n bytes (where n = len(complete_value))?

You say you've tried solving this with decode, split, list, and map. Could you explain what you did exactly? Because I don't see what's wrong with something like:

incomplete_value = b''
my_ints = []
while <there_is_data>:
    tmp = incomplete_value + get_my_data() # get a new batch of data and append it
    tmp_split = tmp.split(b'\r\n') # split the data on newlines
    complete_data = tmp_split[:-1] # get all but the last item
    incomplete_value = tmp_split[-1] # save the last item
    my_ints += [int.from_bytes(x) for x in complete_data] # creates a list of ints


问:
Share element adapter to Activity
I try to share element from RecycleView Adapter to Activity but I got this error:

incompatible types: Context cannot be converted to Activity

```<code>        holder.img_pro.setTransitionName(context.getString(R.string.share));

        Intent i = new Intent(context, Details_activity.class);
        Pair<View, String> pair1 = Pair.create(holder.img_pro, holder.img_pro.getTransitionName());
        i.putExtra(AppConstants.SCREEN, "0");

        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(context, pair1);
        context.startActivity(i, options.toBundle());
</code>```

Anybody can help me?

Thanks

答: ActivityOptionsCompat.makeSceneTransitionAnimation() first parameter accepts Activity and you are passing Context try to cast your Context to Activity or pass the Activity to your click handling which I hope its outside the ViewHolder

Title: Share element adapter to Activity

Body:
I try to share element from RecycleView Adapter to Activity but I got this error:

incompatible types: Context cannot be converted to Activity

        holder.img_pro.setTransitionName(context.getString(R.string.share));

        Intent i = new Intent(context, Details_activity.class);
        Pair<View, String> pair1 = Pair.create(holder.img_pro, holder.img_pro.getTransitionName());
        i.putExtra(AppConstants.SCREEN, "0");

        ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(context, pair1);
        context.startActivity(i, options.toBundle());

Anybody can help me?

Thanks


问:
XPages Open view and open XPage in edit mode
I've told a view to open using an XPage, but how do I open that XPage in edit mode?</p>

答:
In addition to the readonly properties that Peter mentioned:
It is possible that a custom control got its own data source while the one from a parent (e.g. the xpage) is in edit mode. That's the mistake i make often while binding controls to data fields. </p>


问:
Double foreach loop with where condition in laravel blade
I have relations like this

```<code>User->hasMany->reviews
Review->belongsTo->user

Review->hasMany->ReviewAnswer
ReviewAnswer->belongsTo->Review
</code>```

Now I try to display answers for specific review. My reviewAnswer table looks like:

```<code>Id, review ID, text
</code>```

But the problem is when I do that:

```<code>@foreach($user->reviews as $data)
  @foreach($data->reviewAnswers->where('review_id', $data->id) as $answer)
    {{$answer->text}}
  @endforeach
@endforeach
</code>```

Then reviews displays okay, but I get the same answers for every review. How to repair that?

答:
Try using the hasManyThrough() option which the eloquent models provide you.

Link: Laravel Eloquent Relations

This means in your case you would add:

```<code>class User extends Model {
    public function reviewAnswers(
        return $this->hasManyThrough(ReviewAnswer::class,Review::class);
    )
}
</code>```

and then simply access it in blade as:

```<code>@foreach($user->reviewAnswers() as $reviewAnswer) {
    {{$reviewAnswer->text}}
}
</code>```

Body:
I have relations like this

User->hasMany->reviews
Review->belongsTo->user

Review->hasMany->ReviewAnswer
ReviewAnswer->belongsTo->Review

Now I try to display answers for specific review. My reviewAnswer table looks like:

Id, review ID, text

But the problem is when I do that:

@foreach($user->reviews as $data)
  @foreach($data->reviewAnswers->where('review_id', $data->id) as $answer)
    {{$answer->text}}
  @endforeach
@endforeach

Then reviews displays okay, but I get the same answers for every review. How to repair that?

Body:
Try using the hasManyThrough() option which the eloquent models provide you.

Link: Laravel Eloquent Relations

This means in your case you would add:

class User extends Model {
    public function reviewAnswers(
        return $this->hasManyThrough(ReviewAnswer::class,Review::class);
    )
}

and then simply access it in blade as:

@foreach($user->reviewAnswers() as $reviewAnswer) {
    {{$reviewAnswer->text}}
}


问:
NativeCallableAttribute missing in .Net Core application
I found this implementation of NativeCallableAttribute in coreclr repository on github. It looks like it was added 2 years ago and you can find unit tests showing that it works just like Unmanaged exports for .Net Framework.

I've created a new .Net core 2.0 project and there is no NativeCallableAttribute present in System.Runtime.InteropServices namespace. Is there some nuget package I have to add to use this class? I've tried nuget package System.Runtime.InteropServices but still the attribute is missing.

答:
NativeCallableAttribute resides in System.Private.CoreLib assembly. Just reference it from you project and add using directive for System.Runtime.InteropServices namespace.

UPDATE:

Where do I get System.Private.CoreLib? Cannot find it on nuget and
  AddReference dialog in VisualStudio does not have it for my .Net Core
  project.

I have added assembly reference with ReSharper. You could do the same by adding following section to your csproj file:

```<code><ItemGroup>
  <Reference Include="System.Private.CoreLib">
    <HintPath>C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.5\System.Private.CoreLib.dll</HintPath>
  </Reference>
</ItemGroup>
</code>```

Body:
NativeCallableAttribute resides in System.Private.CoreLib assembly. Just reference it from you project and add using directive for System.Runtime.InteropServices namespace.

UPDATE:

Where do I get System.Private.CoreLib? Cannot find it on nuget and
  AddReference dialog in VisualStudio does not have it for my .Net Core
  project.

I have added assembly reference with ReSharper. You could do the same by adding following section to your csproj file:

<ItemGroup>
  <Reference Include="System.Private.CoreLib">
    <HintPath>C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.5\System.Private.CoreLib.dll</HintPath>
  </Reference>
</ItemGroup>


问:
How to get the Correct orientation of the image selected from the Default Image gallery
I have gone through some of the links to get the correct image orientation of the image selected from the  default image gallery to be worked standard in all devices the exif tag always returns 0.

EXIF orientation tag value always 0 for image taken with portrait camera app android

Exif orientation tag returns 0

Exif data TAG_ORIENTATION always 0

http://mobisocial.stanford.edu/news/2011/08/rotating-images-in-android/

How to get an exact solution that will work on all devices?

答:
For those who come along this post, make sure to use the exifinterface from the Android Support Library that was introduced in December 2016:

```<code>compile "com.android.support:exifinterface:25.1.0" // or newer
</code>```

Details about this library can be found in the according Android Developers Blog post: Introducing the ExifInterface Support Library

They also included a sample code for dealing with rotation information stored in the exif interface:

```<code>int rotation = 0;
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

switch (orientation) {
   case ExifInterface.ORIENTATION_ROTATE_90:
     rotation = 90;
     break;
  case ExifInterface.ORIENTATION_ROTATE_180:
     rotation = 180;
     break;
  case ExifInterface.ORIENTATION_ROTATE_270:
     rotation = 270;
     break;
}
</code>```

Body:
For those who come along this post, make sure to use the exifinterface from the Android Support Library that was introduced in December 2016:

compile "com.android.support:exifinterface:25.1.0" // or newer

Details about this library can be found in the according Android Developers Blog post: Introducing the ExifInterface Support Library

They also included a sample code for dealing with rotation information stored in the exif interface:

int rotation = 0;
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

switch (orientation) {
   case ExifInterface.ORIENTATION_ROTATE_90:
     rotation = 90;
     break;
  case ExifInterface.ORIENTATION_ROTATE_180:
     rotation = 180;
     break;
  case ExifInterface.ORIENTATION_ROTATE_270:
     rotation = 270;
     break;
}


问:
rails: text_area size
Sign in:
http://glowing-fire-495.heroku.com/newpost

email: admin@admin.com
pw: password

or you can create your own account.

I am using wmd for the rich text editor for the Content.

However, I am not sure how to control the size of the text area box.

The code for it right now is:

```<code>  <div class = "field">
     <%= f.label :content%><br/>
     <%= f.text_area :content, :cols =>30, :rows => 100%>   </div>
</code>```

答: You set in custom.css on line 365 the height of the textarea to 4ems. Try adding a different value to resize it.

Title: rails: text_area size

Body:
Sign in:
http://glowing-fire-495.heroku.com/newpost

email: admin@admin.com
pw: password

or you can create your own account.

I am using wmd for the rich text editor for the Content.

However, I am not sure how to control the size of the text area box.

The code for it right now is:

     <%= f.label :content%>

     <%= f.text_area :content, :cols =>30, :rows => 100%>


问:
Watch All emails Through Gsuite Account
I'm familiar with the concepts of push notification with Gmail and 'webhooks' in general.
My question is - is there a way to get push notifications about all Gmail Users Emails that are related to the same Gsuite Account?
I know that there is a way to get global token by
Perform G Suite Domain-Wide Delegation of Authority
but I can't find enough info about how to listen to all user's emails and if it's even possible.

答:
The Gmail API uses the Cloud Pub/Sub API to deliver push notifications. This allows notification via a variety of methods including webhooks and polling on a single subscription endpoint.

```<code>POST "https://www.googleapis.com/gmail/v1/users/me/watch"
Content-type: application/json

{
  topicName: "projects/myproject/topics/mytopic",
  labelIds: ["INBOX"],
}
</code>```

Info on how to implement domain wide dedication

Title: Watch All emails Through Gsuite Account

Body:
The Gmail API uses the Cloud Pub/Sub API to deliver push notifications. This allows notification via a variety of methods including webhooks and polling on a single subscription endpoint.

POST "https://www.googleapis.com/gmail/v1/users/me/watch"
Content-type: application/json

{
  topicName: "projects/myproject/topics/mytopic",
  labelIds: ["INBOX"],
}

Info on how to implement domain wide dedication


问:
Error: utf8_mime2text() has new signature, but U8T_CANONICAL is missing
I am attempting to install php on a VM running CentOS 7, but when I try to configure php, I run into the following error:

My Configuration Settings:

```<code>./configure --enable-bcmath --with-bz2 --enable-calendar --with-curl --enable-exif --enable-ftp --with-gd --with-jpeg-dir --with-png-dir --with-freetype-dir --enable-gd-native-ttf --with-imap --with-imap-ssl --with-kerberos --enable-mbstring --with-mcrypt --with-mhash --with-mysql --with-mysqli --with-openssl --with-pcre-regex --with-pdo-mysql --with-zlib-dir --with-regex --enable-sysvsem --enable-sysvshm --enable-sysvmsg --enable-soap --enable-sockets --with-xmlrpc --enable-zip --with-zlib --enable-inline-optimization --enable-mbregex --enable-opcache --enable-fpm --prefix=/usr/local/php
</code>```

Error:

```<code>configure: error: utf8_mime2text() has new signature, but U8T_CANONICAL is missing. This should not happen. Check config.log for additional information.
</code>```

I've gone through about a dozen threads that saying that I need to install libc-client-devel, but when I try to do that (using yum), I get an error that the package doesn't exist.

What am I missing here?

答: Found the solution for my problem if anyone who looks at this later is wondering. I needed to enable the EPEL Repository for those missing packages to be available. After I imported that repository, everything installed fine.</p>

Body:
I am attempting to install php on a VM running CentOS 7, but when I try to configure php, I run into the following error:

My Configuration Settings:

./configure --enable-bcmath --with-bz2 --enable-calendar --with-curl --enable-exif --enable-ftp --with-gd --with-jpeg-dir --with-png-dir --with-freetype-dir --enable-gd-native-ttf --with-imap --with-imap-ssl --with-kerberos --enable-mbstring --with-mcrypt --with-mhash --with-mysql --with-mysqli --with-openssl --with-pcre-regex --with-pdo-mysql --with-zlib-dir --with-regex --enable-sysvsem --enable-sysvshm --enable-sysvmsg --enable-soap --enable-sockets --with-xmlrpc --enable-zip --with-zlib --enable-inline-optimization --enable-mbregex --enable-opcache --enable-fpm --prefix=/usr/local/php

Error:

configure: error: utf8_mime2text() has new signature, but U8T_CANONICAL is missing. This should not happen. Check config.log for additional information.

I've gone through about a dozen threads that saying that I need to install libc-client-devel, but when I try to do that (using yum), I get an error that the package doesn't exist.

What am I missing here?


问:
store woocommerce checkout form data to custom table using api
I want to send the values of the checkout form to my API in woo commerce when customer clicks on the place order button, so that i can store this data using API. But i don't know how to use hooks to achieve this. Please can anybody suggest me a way to do this.</p>

答:
Can you try below hook once?
that will work when you will click on proceed to checkout button from cart page. That will return all fields . And in this you can pass your API and pass your details , </p>

```<code>add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
    print_r($fields);
    $url= 'https://restcountries.eu/rest/v1/name/United States'; //API URL
    $MSAPI_Call = curl_init();
    curl_setopt($MSAPI_Call, CURLOPT_URL,$url);
    curl_setopt($MSAPI_Call, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($MSAPI_Call, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($MSAPI_Call);
    print_r($response);
    die();
     return $response;
}
</code>```

Body:
Can you try below hook once?
that will work when you will click on proceed to checkout button from cart page. That will return all fields . And in this you can pass your API and pass your details ,

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
    print_r($fields);
    $url= 'https://restcountries.eu/rest/v1/name/United States'; //API URL
    $MSAPI_Call = curl_init();
    curl_setopt($MSAPI_Call, CURLOPT_URL,$url);
    curl_setopt($MSAPI_Call, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($MSAPI_Call, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($MSAPI_Call);
    print_r($response);
    die();
     return $response;
}


问:
New xamarin.forms project creation gives NU11002 Unable to find package Xamarin.Forms with version (>= 250121934.0.0)
Recently i updated my visual studio 2017 enterprise to 15.5.0. I am trying to create xamarin forms project as Blank App, platfom Android + ios, UI Technology Xamarin.Forms, code sharing strategy .net standart. When i try to build the default created project i got the following error;

Severity  Code    Description Project File    Line    Suppression State
  Error NU1102  Unable to find package Xamarin.Forms with version (>=
  250121934.0.0)
    - Found 163 version(s) in nuget.org [ Nearest version: 2.5.0.121934 ]
    - Found 0 version(s) in Microsoft Visual Studio Offline Packages

I can not also remove and install xamarin.forms nuget. Any ideas?

答: Install xamarin.forms on all projects, in my case I was missing in the iOS project, it was enough to install the xamarin.forms nuget and everything worked normally. I hope it helps. </p>


问:
Maximum function nesting level of '100' reached, aborting after upgrading to Laravel 5.1
I'm getting this error message in my Laravel application after I upgraded to Laravel 5.1.

```<code>FatalErrorException in Dispatcher.php line 200:
Maximum function nesting level of '100' reached, aborting!
</code>```

This issue occurs on some URLs of my app. I have done dozens of composer update but issue still persist. Any suggestion at all will be appreciated

答:
This issue is due to xdebug extension is enabled,
to fix this either you have to disable xdebug extension or edit php.ini file and  change xdebug.max_nesting_level to 200 ( as by default this parameter is not included in php.ini and have to add it )

like :

xdebug.max_nesting_level=200

Body:
I'm getting this error message in my Laravel application after I upgraded to Laravel 5.1.

FatalErrorException in Dispatcher.php line 200:
Maximum function nesting level of '100' reached, aborting!

This issue occurs on some URLs of my app. I have done dozens of composer update but issue still persist. Any suggestion at all will be appreciated


问:
How to add a character like ("," , "[" , "]") at the end of a JSON-Object

I have a Python-script that makes an File with invalid JSON.
Now I want to manipulate this JSON-File so it becomes a valid JSON-file by adding a comma between every object, at the beginning of the File a '[' and at the end a ']'.
Is there a way to make this with JSON alone or do i have to find a way with other read and write functions?

Exsample_File.json:

```<code>    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    }
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    }
     ....
    n times
</code>```

New_File.json:

```<code>    [
    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    },
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    },
     ....
    n times
    ]
</code>```

This is the function that makes this JSON-File. I dont want to touch the other code where the str is generated.

```<code>data = json.loads(str)
    with open('Example_File.json','ab')as outfile:
        json.dump(data, outfile, indent=2)
</code>```

So far i dont have an idea to solve this problem. so there is no code sample that would help.

The result should be like the New-File

答:
You may have to read the content as string, manipulate it and load as JSON. Something like this,

```<code>import json

with open('Example.json','r') as f:
  data = f.read()

data = "[" + data.replace("}", "},", data.count("}")-1) + "]"
json_data = json.loads(data)
</code>```

It seems your data has numbers begins with 0, so you may ended up with an exception "ValueError". You may refer how to deal the issue from Why is JSON invalid if an integer begins with 0

Note: I manually removed 0 from "Example.json"

Body:
I have a Python-script that makes an File with invalid JSON.
Now I want to manipulate this JSON-File so it becomes a valid JSON-file by adding a comma between every object, at the beginning of the File a '[' and at the end a ']'.
Is there a way to make this with JSON alone or do i have to find a way with other read and write functions?

Exsample_File.json:

    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    }
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    }
     ....
    n times

New_File.json:

    [
    {
    "firstName": "Bidhan",
    "lastName": "Chatterjee",
    "age": 40,
    "email":"bidhan@example.com"
    },
    {
    "firstName": "hanbid",
    "lastName": "jeeChatter",
    "age": 10,
    "email":"example@bidhan.com"
    },
     ....
    n times
    ]

This is the function that makes this JSON-File. I dont want to touch the other code where the str is generated.

data = json.loads(str)
    with open('Example_File.json','ab')as outfile:
        json.dump(data, outfile, indent=2)

So far i dont have an idea to solve this problem. so there is no code sample that would help.

The result should be like the New-File

Body:
You may have to read the content as string, manipulate it and load as JSON. Something like this,

import json

with open('Example.json','r') as f:
  data = f.read()

data = "[" + data.replace("}", "},", data.count("}")-1) + "]"
json_data = json.loads(data)

It seems your data has numbers begins with 0, so you may ended up with an exception "ValueError". You may refer how to deal the issue from Why is JSON invalid if an integer begins with 0

Note: I manually removed 0 from "Example.json"


问:
Using foreach with ArrayList - automatic casting?
```<code>ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}
</code>```

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

答:
According to c# specification of foreach statement, your code is equivalent to </p>

```<code>ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

IEnumerator enumerator = (x).GetEnumerator();
try {
   while (enumerator.MoveNext()) {
      string element = (string)enumerator.Current; // here is casting occures
      // loop body;
   }
}
finally {
   IDisposable disposable = enumerator as System.IDisposable;
   if (disposable != null) disposable.Dispose();
}
</code>```

Body:
ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

Body:
According to c# specification of foreach statement, your code is equivalent to

ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

IEnumerator enumerator = (x).GetEnumerator();
try {
   while (enumerator.MoveNext()) {
      string element = (string)enumerator.Current; // here is casting occures
      // loop body;
   }
}
finally {
   IDisposable disposable = enumerator as System.IDisposable;
   if (disposable != null) disposable.Dispose();
}


问:
JQuery Autocomplete malfunction
First time posting so I apologise for any mistakes and for if this has been answered before.

There might be something obvious that I've missed but this function doesn't filter the list of variables. When I enter "0" it shows nothing, but then when I type "j" (and a few other characters such as "e", "c" and "b") the function shows everything in the array.

```<code><head>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
    $(function()
    {
        var data = [{"Part_no":"0001","Part_description":"Part 1"},{"Part_no":"0002","Part_description":"Part 2"}]

        $( "#project" ).autocomplete({
            minLength: 1,
            source: data,
            select: function( event, ui )
            {
                $( "#project" ).val( ui.item.Part_no );
                $( "#project-description" ).html( ui.item.Part_description );

                return false;
            }
        })
        .autocomplete( "instance" )._renderItem = function( ul, item )
        {
          return $( "<li>" )
            .append( "<div>" + item.Part_no + "<br>" + item.Part_description + "</div>" )
            .appendTo( ul );
        };
    });
    </script>
</head>
<body>
    <input id="project">
</body>
</code>```

Thank you for looking.

答:
I think the format of the data passed is not correct. As per this documentation http://api.jqueryui.com/autocomplete/#option-source . You need to pass the array of the string or array of the object with label and value properties. So you have to decide what you want to search on "Part No" or "Part Description". In case you want the auto complete only on the part No , pass on that as array

```<code>         var data = ["001","002","003""];
</code>```

create another array for the detail description

```<code>         var desc = ["Desc 1 " ,"Desc 2" , "Desc 3"];
</code>```

So once user select the data , you will get the position of the data or the value that you can map into the desc array to get more detail you want to use.

Title: JQuery Autocomplete malfunction

Body:
First time posting so I apologise for any mistakes and for if this has been answered before.

There might be something obvious that I've missed but this function doesn't filter the list of variables. When I enter "0" it shows nothing, but then when I type "j" (and a few other characters such as "e", "c" and "b") the function shows everything in the array.

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    <input id="project">

Thank you for looking.

Body:
I think the format of the data passed is not correct. As per this documentation http://api.jqueryui.com/autocomplete/#option-source . You need to pass the array of the string or array of the object with label and value properties. So you have to decide what you want to search on "Part No" or "Part Description". In case you want the auto complete only on the part No , pass on that as array

         var data = ["001","002","003""];

create another array for the detail description

         var desc = ["Desc 1 " ,"Desc 2" , "Desc 3"];

So once user select the data , you will get the position of the data or the value that you can map into the desc array to get more detail you want to use.


问:
Spring boot security, oauth2 and thymeleaf static resource cannot be found
I have added my css and js under Resource then static folder. When I access path  "forgotpassword" all my static resource are loaded correctly.
enter image description here

However when I try to access the same path but this time with a trailing slash "forgotpassword/"  all my static resource are not loaded. I get status 404 not found
enter image description here

Here is my security configuration

```<code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-20)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    static private Logger logger = LoggerFactory.getLogger(Oauth2AuthserverApplication.class);

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .authorizeRequests()
                .antMatchers("/resources/**", "/forgotpassword/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .requestMatchers().antMatchers("/forgotpassword/**", "/login", "/oauth/authorize", "/oauth/confirm_access");
        // @formatter:on
    }

}
</code>```

答:
For css this is what i had to do th:href="@{/css/Default/css/style.css}"
and for js th:src="@{/js/jquery/dist/jquery.min.js}"

Body:
I have added my css and js under Resource then static folder. When I access path  "forgotpassword" all my static resource are loaded correctly.
enter image description here

However when I try to access the same path but this time with a trailing slash "forgotpassword/"  all my static resource are not loaded. I get status 404 not found
enter image description here

Here is my security configuration

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-20)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    static private Logger logger = LoggerFactory.getLogger(Oauth2AuthserverApplication.class);

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .authorizeRequests()
                .antMatchers("/resources/**", "/forgotpassword/**")
                .permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .requestMatchers().antMatchers("/forgotpassword/**", "/login", "/oauth/authorize", "/oauth/confirm_access");
        // @formatter:on
    }

}


问:
Getting "type or namespace name could not be found" but everything seems ok?
I'm getting a:

type or namespace name could not be found

error for a C# WPF app in VS2010. This area of code was compiling fine, but suddenly I'm getting this error. I've tried removing the Project Reference and the using statement, shutting VS2010 and restarting, but still I have this issue.

Any ideas why this might be occurring, where it seems like I'm doing the right thing re Reference & using statement?

I also noted in VS2010 that intellisense for that namespace is working ok, so it seems like VS2010 has the project reference and is seeing the namespace on one hand, but during compile doesn't see it?

答:
I had same problem as discussed: VS 2017 underlines a class in referenced project as error but the solution builds ok and even intellisense works.

Here is how I managed to solve this issu:

Unload the referenced project

Open .proj file in VS ( i was looking for duplicates as someone suggested here)

Reload project again (I did not change or even save the proj file as I did not have any duplicates)


问:
How do I remove a duplicate from a SELECT DISTINCT over multiple columns?
I have the following select statement:

```<code>SELECT DISTINCT a.month,
                a.date
           FROM a
       ORDER BY a.bar DESC NULLS LAST;
</code>```

month is a char, date is a date. I need to use the date column because that's the thing i'm ordering the results by. I'm getting this result:

```<code>foo | bar

 x---|---20-nov-15 00:00:00
 y---|---31-oct-15 00:00:00
 y---|---30-oct-15 00:00:00
 z---|---28-sept-15 00:00:00
</code>```

I am in need of a WHERE statement that would eliminate that duplicate Y from the result, I've been looking everywhere and couldn't find a solution

答:
The way I'd do it: (You don't need to use SELECT DISTINCT...

```<code>SELECT * FROM
        (SELECT *
        ,ROW_NUMBER() OVER(PARTITION BY FOO
                                ORDER BY BAR DESC) AS RN
            FROM @RESULT) x
        WHERE RN = 1
</code>```

You use the row number and partition to separate your data by Foo and then order by descending Bar. (You can add more partitions as and when needed)

Then take Row number 1 to take the Maximum date for each Foo

Full working:

```<code>DECLARE @RESULT TABLE
   ([Foo] CHAR(1)  ,[Bar] DATETIME)

INSERT   INTO @RESULT
         SELECT   'x', '2015-11-20T00:00:00'
INSERT   INTO @RESULT
         SELECT   'y', '2015-10-31T00:00:00'
INSERT   INTO @RESULT
         SELECT   'y', '2015-10-30T00:00:00'
INSERT   INTO @RESULT
         SELECT   'z', '2015-09-28T00:00:00'

SELECT * FROM
        (SELECT *
        ,ROW_NUMBER() OVER(PARTITION BY FOO
                                ORDER BY BAR DESC) AS RN
            FROM @RESULT) x
        WHERE RN = 1
</code>```

Body:
I have the following select statement:

SELECT DISTINCT a.month,
                a.date
           FROM a
       ORDER BY a.bar DESC NULLS LAST;

month is a char, date is a date. I need to use the date column because that's the thing i'm ordering the results by. I'm getting this result:

foo | bar

 x---|---20-nov-15 00:00:00
 y---|---31-oct-15 00:00:00
 y---|---30-oct-15 00:00:00
 z---|---28-sept-15 00:00:00

I am in need of a WHERE statement that would eliminate that duplicate Y from the result, I've been looking everywhere and couldn't find a solution

Body:
The way I'd do it: (You don't need to use SELECT DISTINCT...

SELECT * FROM
        (SELECT *
        ,ROW_NUMBER() OVER(PARTITION BY FOO
                                ORDER BY BAR DESC) AS RN
            FROM @RESULT) x
        WHERE RN = 1

You use the row number and partition to separate your data by Foo and then order by descending Bar. (You can add more partitions as and when needed)

Then take Row number 1 to take the Maximum date for each Foo

Full working:

DECLARE @RESULT TABLE
   ([Foo] CHAR(1)  ,[Bar] DATETIME)

INSERT   INTO @RESULT
         SELECT   'x', '2015-11-20T00:00:00'
INSERT   INTO @RESULT
         SELECT   'y', '2015-10-31T00:00:00'
INSERT   INTO @RESULT
         SELECT   'y', '2015-10-30T00:00:00'
INSERT   INTO @RESULT
         SELECT   'z', '2015-09-28T00:00:00'

SELECT * FROM
        (SELECT *
        ,ROW_NUMBER() OVER(PARTITION BY FOO
                                ORDER BY BAR DESC) AS RN
            FROM @RESULT) x
        WHERE RN = 1


问:
LaunchDaemon exits immediately, but keeps running when I run it directly
I have never written a LaunchDaemon before, so I'm starting with a dead-simple one.  Even my simple one does not appear to execute.

I'm running macOS Sierra 10.12.5.

EDIT: My system.log is full of the following:

```<code>Dec  6 00:02:47 Michaels-Mac-mini com.apple.xpc.launchd[1] (com.frescologic.hello): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Dec  6 00:02:57 Michaels-Mac-mini com.apple.xpc.launchd[1] (com.frescologic.hello[1386]): Service could not initialize: 16F73: xpcproxy + 11769 [1505][34964CF1-9965-3B4D-ADC7-6FBC6669C56D]: 0x2
</code>```

However when I run hello directly from the command line, it keeps running.

My configuration file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.frescologic.hello</string>
    <key>ProgramArguments</key>
    <array>
        <string>hello</string>
        <string>world</string>
    </array>
    <key>KeepAlive</key>
    <true/>
</dict>
</code>```

My daemon's source:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, const char * argv[])
{
    FILE *outFile;

    if ( argc != 2 ){

        fprintf( stderr, "Usage:\n $ %s world\n", argv[ 0 ] );
        exit( 1 );
    }

    outFile = fopen( "/tmp/foo", "w" );
    if ( outFile == NULL ) exit( 1 );

    while ( 1 ){
        fprintf( outFile, "%s\n", argv[ 1 ] );
        sleep( 10 );
    }

    return 0;
}
</code>```

The relevant permissions:

```<code>$ ls -l /Library/LaunchDaemons/com.frescologic.hello.plist
-rw-r--r--@ 1 root  wheel  375 Dec  5 21:47 /Library/LaunchDaemons/com.frescologic.hello.plist
</code>```

and

```<code>$ ls -l /usr/local/libexec
total 40
-rwxr-xr-x  1 root  wheel  18240 Dec  5 21:45 hello
</code>```

Launchctl claims it's running:

```<code>$ sudo launchctl list | grep hello
Password:
-   78  com.frescologic.hello
</code>```

But ps does not:

```<code>$ ps -ef | grep hello
  501   737   387   0 10:38PM ttys000    0:00.00 grep hello
</code>```

and

```<code>$ ps -ax | grep hello
  743 ttys000    0:00.00 grep hello
</code>```

The log file does not exist:

```<code>$ cd /tmp
$ ls
com.apple.launchd.JOJDWGHX78    com.apple.launchd.oUj51Uvj6v
</code>```

Help Me O-Stackoverflow You're My Only Hope!

答:
Stephàne answered this on darwin-drivers@lists.apple.com.  Add the "Program" key to the property list with the full path of the executable:</p>

```<code><key>Program</key>
<string>/usr/local/libexec/hello</string>
</code>```

Body:
I have never written a LaunchDaemon before, so I'm starting with a dead-simple one.  Even my simple one does not appear to execute.

I'm running macOS Sierra 10.12.5.

EDIT: My system.log is full of the following:

Dec  6 00:02:47 Michaels-Mac-mini com.apple.xpc.launchd[1] (com.frescologic.hello): Service only ran for 0 seconds. Pushing respawn out by 10 seconds.
Dec  6 00:02:57 Michaels-Mac-mini com.apple.xpc.launchd[1] (com.frescologic.hello[1386]): Service could not initialize: 16F73: xpcproxy + 11769 [1505][34964CF1-9965-3B4D-ADC7-6FBC6669C56D]: 0x2

However when I run hello directly from the command line, it keeps running.

My configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.frescologic.hello</string>
    <key>ProgramArguments</key>
    <array>
        <string>hello</string>
        <string>world</string>
    </array>
    <key>KeepAlive</key>
    <true/>
</dict>

My daemon's source:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, const char * argv[])
{
    FILE *outFile;

    if ( argc != 2 ){

        fprintf( stderr, "Usage:\n $ %s world\n", argv[ 0 ] );
        exit( 1 );
    }

    outFile = fopen( "/tmp/foo", "w" );
    if ( outFile == NULL ) exit( 1 );

    while ( 1 ){
        fprintf( outFile, "%s\n", argv[ 1 ] );
        sleep( 10 );
    }

    return 0;
}

The relevant permissions:

$ ls -l /Library/LaunchDaemons/com.frescologic.hello.plist
-rw-r--r--@ 1 root  wheel  375 Dec  5 21:47 /Library/LaunchDaemons/com.frescologic.hello.plist

and

$ ls -l /usr/local/libexec
total 40
-rwxr-xr-x  1 root  wheel  18240 Dec  5 21:45 hello

Launchctl claims it's running:

$ sudo launchctl list | grep hello
Password:
-   78  com.frescologic.hello

But ps does not:

$ ps -ef | grep hello
  501   737   387   0 10:38PM ttys000    0:00.00 grep hello

and

$ ps -ax | grep hello
  743 ttys000    0:00.00 grep hello

The log file does not exist:

$ cd /tmp
$ ls
com.apple.launchd.JOJDWGHX78    com.apple.launchd.oUj51Uvj6v

Help Me O-Stackoverflow You're My Only Hope!

Body:
Stephàne answered this on darwin-drivers@lists.apple.com.  Add the "Program" key to the property list with the full path of the executable:

<key>Program</key>
<string>/usr/local/libexec/hello</string>


问:
Opencv imshow() freezes when updating
For my image processing algorithm I'm using python / OpenCV. The output of my algorithm shall be updated im the same window over and over again.

However sometimes the window freezes and doesn't update at all, but the algorithm is still running and updated the picture a multiple times in the meantime. The window turns dark gray on this Ubuntu machine.

Here is an excerpt of the involved code:

```<code>for i in range(0,1000):
    img = loadNextImg()
    procImg = processImg(img)
    cv2.imshow("The result", procImg)
    cv2.waitKey(1)
</code>```

N.B.: processImg() takes about 1-2 s for its procedures. The line cv2.imshow(procImg) creates the window in first instance (i.e. there is no preceding invocation)

答:
If your window is going grey then it might be take more processing power. So try to resize image into smaller size image and execute. Sometimes times it freezes while running in ipython notebooks due to pressing any key while performing operation. I had personally executed your problem but I didn't get grey screen while doing it. I did executing directly using terminal. Code and steps are shown below.

```<code>import argparse
import cv2
import numpy as np

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image, grab its dimensions, and show it
image = cv2.imread(args["image"])
(h, w) = image.shape[:2]
cv2.imshow("Original", image)
cv2.waitKey(0)

for i in range(0,1000):
    image = cv2.imread(args["image"])
    cv2.imshow("The result",image);
    cv2.waitKey(0)
</code>```

Run it in terminal:

source activate env_name

python Filename.py --image Imagename.png

This will get to your result in one window only(updating each time) without freezing and if you want seperate image in every new window then add .format(i) as given below. But Remember to run in terminal only not in jupyter notebooks.

You can check using terminal commands in this video link
https://www.youtube.com/watch?v=8O-FW4Wm10s

```<code>for i in range(0,1000):
    image = cv2.imread(args["image"])
    cv2.imshow("The result{}".format(i),image);
    cv2.waitKey(0)
</code>```

This may help to get you 1000 images separately.

Title: Opencv imshow() freezes when updating

Body:
For my image processing algorithm I'm using python / OpenCV. The output of my algorithm shall be updated im the same window over and over again.

However sometimes the window freezes and doesn't update at all, but the algorithm is still running and updated the picture a multiple times in the meantime. The window turns dark gray on this Ubuntu machine.

Here is an excerpt of the involved code:

for i in range(0,1000):
    img = loadNextImg()
    procImg = processImg(img)
    cv2.imshow("The result", procImg)
    cv2.waitKey(1)

N.B.: processImg() takes about 1-2 s for its procedures. The line cv2.imshow(procImg) creates the window in first instance (i.e. there is no preceding invocation)

Body:
If your window is going grey then it might be take more processing power. So try to resize image into smaller size image and execute. Sometimes times it freezes while running in ipython notebooks due to pressing any key while performing operation. I had personally executed your problem but I didn't get grey screen while doing it. I did executing directly using terminal. Code and steps are shown below.

import argparse
import cv2
import numpy as np

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())

# load the image, grab its dimensions, and show it
image = cv2.imread(args["image"])
(h, w) = image.shape[:2]
cv2.imshow("Original", image)
cv2.waitKey(0)

for i in range(0,1000):
    image = cv2.imread(args["image"])
    cv2.imshow("The result",image);
    cv2.waitKey(0)

Run it in terminal:

source activate env_name

python Filename.py --image Imagename.png

This will get to your result in one window only(updating each time) without freezing and if you want seperate image in every new window then add .format(i) as given below. But Remember to run in terminal only not in jupyter notebooks.

You can check using terminal commands in this video link
https://www.youtube.com/watch?v=8O-FW4Wm10s

for i in range(0,1000):
    image = cv2.imread(args["image"])
    cv2.imshow("The result{}".format(i),image);
    cv2.waitKey(0)

This may help to get you 1000 images separately.


问:
HTML5 Video centering source
I have a video that I will be mainly displaying on a portrait screen and I would like the video to be the full height of the screen but centered so the centre of the video is the centre of the screen. I have my current CSS and HTML below. This will display the video of 100% the height but the actual source (video) is played from the left-hand side of itself, not the centre. Is there anyway to do what I'm asking? Also, the video maybe displayed landscape and would need the same result.

Left of this image is what im getting, right is what I want

```<code>.videoContainer
{
    position:absolute;
    height:100%;
    width:100%;
    overflow: hidden;
}

.videoContainer video
{
    width: auto;
    height: 100%
}

  <div class="videoContainer">
    <video width="944" height="532" controls preload="auto" poster="posterimg.jpg">
        <source src="test.mp4" type="video/mp4" />
        <source src="test.webm" type="video/webm">
        <source src="test.ogv" type="video/ogg" type='video/ogg; codecs="theora, vorbis"'>
    </video>
  </div>
</code>```

答:
You probaly mean the object-fit property in CSS. This will scale the video to fill the video container element, keeping its ratio intact.

You can change the height of the video in the snippet below. You will notice the video will scale itself to the exact height of its container.

With object-fit: cover;

body, html {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

video {
  height: 100%;
  width: 100%;
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video controls>
  <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
  <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video></code>```

Without object-fit: cover;

body, html {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

video {
  height: 100%;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video controls>
  <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
  <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video></code>```

You can make nice full width video's with this property. It will fill the whole container with the video. Instead of having these top and bottom bars. Which is normaly caused by the automatic scaling to its correct ratio.

Title: HTML5 Video centering source

Body:
I have a video that I will be mainly displaying on a portrait screen and I would like the video to be the full height of the screen but centered so the centre of the video is the centre of the screen. I have my current CSS and HTML below. This will display the video of 100% the height but the actual source (video) is played from the left-hand side of itself, not the centre. Is there anyway to do what I'm asking? Also, the video maybe displayed landscape and would need the same result.

Left of this image is what im getting, right is what I want

.videoContainer
{
    position:absolute;
    height:100%;
    width:100%;
    overflow: hidden;
}

.videoContainer video
{
    width: auto;
    height: 100%
}

    <video width="944" height="532" controls preload="auto" poster="posterimg.jpg">
        <source src="test.mp4" type="video/mp4" />
        <source src="test.webm" type="video/webm">
        <source src="test.ogv" type="video/ogg" type='video/ogg; codecs="theora, vorbis"'>
    </video>

Body:
You probaly mean the object-fit property in CSS. This will scale the video to fill the video container element, keeping its ratio intact.

You can change the height of the video in the snippet below. You will notice the video will scale itself to the exact height of its container.

With object-fit: cover;

body, html {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

video {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

<video controls>
  <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
  <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>

Without object-fit: cover;

body, html {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}

video {
  height: 100%;
  width: 100%;
}

<video controls>
  <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
  <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
  <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
  <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
</video>

You can make nice full width video's with this property. It will fill the whole container with the video. Instead of having these top and bottom bars. Which is normaly caused by the automatic scaling to its correct ratio.


问:
Run specific test using gradle in scala test module

I have following structure for my "tests" module written in scala

```<code>tests/
    build.gradle
    src/
         resources/
         scala/
             system/basic/SomeTests.scala
</code>```

I can run all tests under scala folder using

```<code>./gradlew tests:test
</code>```

How can I run only SomeTests.scala from command line?

答:
If it is not different to Java, then by using the --tests task parameter like

```<code>./gradlew tests:test --tests system.basic.SomeTests
</code>```

to run all tests in that class, or e.g.

```<code>./gradlew tests:test --tests system.basic.SomeTests.foo
</code>```

to only run the foo test method.

Body:
I have following structure for my "tests" module written in scala

tests/
    build.gradle
    src/
         resources/
         scala/
             system/basic/SomeTests.scala

I can run all tests under scala folder using

./gradlew tests:test

How can I run only SomeTests.scala from command line?

Body:
If it is not different to Java, then by using the --tests task parameter like

./gradlew tests:test --tests system.basic.SomeTests

to run all tests in that class, or e.g.

./gradlew tests:test --tests system.basic.SomeTests.foo

to only run the foo test method.


问:
Dynamic Model Creation Loopback
I am trying to model the following using embedsOne relation:

```<code>var modelName = 'Customer';
var results = {};
results[modelName] = {
  "name": modelName,
  options: {
    idInjection: false
  },
  properties: {
    "custid": {
      "required": true,
      "type": "string",
      "id":1,
      "length": 30
    },
    "name": {
      "required": true,
      "type": "number",
      "id":1,
      "length": 30
    },
    "address":{
      "required": true,
      "type": "object",
      "properties": {
        "city": {
          "required": true,
          "type": "string",
          "length": 30
        }
      }
    }
  }
};
</code>```

I used the following code to create the embedsOne relations between Customer (Parent model) and the Address (being child model)

```<code>modelProps = results[modelName].properties;

  Object.keys(modelProps).forEach(function (field) {
    if(modelProps[field].type === "object") {
      childProps = modelProps[field];
      childProps.name = field;
      delete modelProps[field];

    }});

  console.log("modeproper: ",modelProps);
  console.log(childProps);

  var model1 = {
    "name": "Customer",
    "plural": childProps.name,
    "base": "PersistedModel",
    "idInjection": false,
    "properties": childProps.properties,
    "public": false
  };

  var childModel = loopback.createModel(model1);

  childModel.public = false;

  var config = {
    dataSource: 'dssodayana',
    "public": false
  };
  app.model(childModel, config);

  var model = {
    "name": "Customer",
    "plural": "Customer",
    "base": "PersistedModel",
    "idInjection": false,
    "properties": modelProps
  };
  var parentModel = loopback.createModel(model);
  app.model(parentModel, config);

  console.log();

  **parentModel.embedsOne(childModel, {
    as: "test", // default to the relation name - address
    property: "address" // default to addressItem
  });**
  app.model(parentModel);
</code>```

Now, I want to view the parentModel. Is it possible to write this Model to a disk file or convert it to a json?

答:
If you want to create models dynamically based on your database schema you can use this method inside your app start:

```<code>ds.discoverModelDefinitions(modelDefinitionsConf, function(err, data){
  for (var el in data) {
    (function(modelName){
      if (acceptedTables.indexOf(modelName) >= 0) {
          ds.discoverSchema(modelName, function (err, schema) {
            var test = ds.createModel(schema.name, schema.properties, schema.options);
            app.model(test, {public : true, dataSource: ds });
          });
      }
    })(data[el].name)
  }
});
</code>```

This will iterate over your tables in provided database source and dynamically create models and expose them in the api.

Title: Dynamic Model Creation Loopback

Body:
I am trying to model the following using embedsOne relation:

var modelName = 'Customer';
var results = {};
results[modelName] = {
  "name": modelName,
  options: {
    idInjection: false
  },
  properties: {
    "custid": {
      "required": true,
      "type": "string",
      "id":1,
      "length": 30
    },
    "name": {
      "required": true,
      "type": "number",
      "id":1,
      "length": 30
    },
    "address":{
      "required": true,
      "type": "object",
      "properties": {
        "city": {
          "required": true,
          "type": "string",
          "length": 30
        }
      }
    }
  }
};

I used the following code to create the embedsOne relations between Customer (Parent model) and the Address (being child model)

modelProps = results[modelName].properties;

  Object.keys(modelProps).forEach(function (field) {
    if(modelProps[field].type === "object") {
      childProps = modelProps[field];
      childProps.name = field;
      delete modelProps[field];

    }});

  console.log("modeproper: ",modelProps);
  console.log(childProps);

  var model1 = {
    "name": "Customer",
    "plural": childProps.name,
    "base": "PersistedModel",
    "idInjection": false,
    "properties": childProps.properties,
    "public": false
  };

  var childModel = loopback.createModel(model1);

  childModel.public = false;

  var config = {
    dataSource: 'dssodayana',
    "public": false
  };
  app.model(childModel, config);

  var model = {
    "name": "Customer",
    "plural": "Customer",
    "base": "PersistedModel",
    "idInjection": false,
    "properties": modelProps
  };
  var parentModel = loopback.createModel(model);
  app.model(parentModel, config);

  console.log();

  **parentModel.embedsOne(childModel, {
    as: "test", // default to the relation name - address
    property: "address" // default to addressItem
  });**
  app.model(parentModel);

Now, I want to view the parentModel. Is it possible to write this Model to a disk file or convert it to a json?

Body:
If you want to create models dynamically based on your database schema you can use this method inside your app start:

ds.discoverModelDefinitions(modelDefinitionsConf, function(err, data){
  for (var el in data) {
    (function(modelName){
      if (acceptedTables.indexOf(modelName) >= 0) {
          ds.discoverSchema(modelName, function (err, schema) {
            var test = ds.createModel(schema.name, schema.properties, schema.options);
            app.model(test, {public : true, dataSource: ds });
          });
      }
    })(data[el].name)
  }
});

This will iterate over your tables in provided database source and dynamically create models and expose them in the api.