答:
That line in your config is short for

```<code>if Rails.env.test?
  config.stretches = 1
else
  config.stretches = 11
end
</code>```

ie. in tests config.stretches is 1, the rest of the time it is 11.

Raising the number of stretches will indeed increase the amount of time it takes to hash a password. The stretches parameter increases time exponentially: changing it from 11 to 12 doubles the time, so yes it will reduce the number of requests your app can handle.

However, typically you only incur this cost during operations such as a user setting their password or logging in, which is only a small fraction of overall requests in general.

Title: Bcrypt stretches (with Devise) and Heroku dynos

Body:
I am currently reviewing security of my admin model generated with Devise. It raises a lot of questions on how a web dyno at Heroku processes the password encription.

first question :

My default Devise setup for bcrypt cost is config.stretches = Rails.env.test? ? 1 : 11 Does it mean there are eleven stretches for the test environment ? It seems the default stretches is 11 and I can confirm my hash under development environment is 11 too. So why specifiying 11 for test ?

I plan raising to 12 with config.stretches = 12

second question :

If I raise the strectches, the encryption time will increase. Will it freeze my app and prevent other visitors to make http requests to the app ? How many concurrent http requests can be made to a web dyno and how many concurrent password encryption can also be made to a web dyno (if this is different).

My knowledge of dynos is not deep, but I know a worker dyno can thread multiple Sidekiq workers depending on the processor cores .. Though the dyno don't specify the number of cores, and I don't know if this apply to web dynos too.

Basically I know that raising strectches will increase encrypting time, yet will it affect the whole app efficiency ?

Body:
That line in your config is short for

if Rails.env.test?
  config.stretches = 1
else
  config.stretches = 11
end

ie. in tests config.stretches is 1, the rest of the time it is 11.

Raising the number of stretches will indeed increase the amount of time it takes to hash a password. The stretches parameter increases time exponentially: changing it from 11 to 12 doubles the time, so yes it will reduce the number of requests your app can handle.

However, typically you only incur this cost during operations such as a user setting their password or logging in, which is only a small fraction of overall requests in general.


来源: stackexchange

问:
Is it possible to dynamically add code to/extend a class?
I want to write a sort of "plugin/module" system for my code, and it would make it much easier if I could "add" stuff into a class after it's been defined.

For example, something like this:

```<code>class foo {
  public function a() {
     return 'b';
  }
}
</code>```

There's the class. Now I want to add another function/variable/const to it, after it's defined.

I realize that this is probably not possible, but I need confirmation.

答:
I have a few methods for you to try. :) Have fun coding.

Method for only one class:

```<code>class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}
</code>```

Method for when you want to deal with more than one class:

```<code>class modMe {
    private $_MODS = array();
    public function __construct__() {
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}
class mainClass extends modMe {
    function __construct(...){
        $this -> __construct__();
    }
}
</code>```

Now lets try to use them:

```<code>$MODS_ENABLED = array();
$MODS_ENABLED[] = new mod_mail();
$myObj = new main_class(...);
$myObj -> mail("me@me.me","you@you.you","subject","message/body","Extra:Headers;More:Headers");
# Hey look, my mail class was just added into my main_class for later use.
</code>```

Note:

I am currently using the first method (I only have one class, the mods are exceptions) in my own CMS that I have made from scratch (http://sitegen.com.au), and it works great, my reason on needing this is because I have my main_class that is getting generated after I have required all mods in ./mods-enabled/* creating functions and changing how other functions work, I will also come back here another time with a solution for two mods to both change a function without one winning as it ran first. I have split my plugins in two, mods that run on every site, and plugins that have settings for a site and may not even be enabled.

Have fun programming.

ContentLicense: CC BY-SA 2.5

Body:
I want to write a sort of "plugin/module" system for my code, and it would make it much easier if I could "add" stuff into a class after it's been defined.

For example, something like this:

class foo {
  public function a() {
     return 'b';
  }
}

There's the class. Now I want to add another function/variable/const to it, after it's defined.

I realize that this is probably not possible, but I need confirmation.

Body:
I have a few methods for you to try. :) Have fun coding.

Method for only one class:

class main_class {
    private $_MODS = array(),...;
    public ...;
    public function __construct(...) {
        ...
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    ...
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}

Method for when you want to deal with more than one class:

class modMe {
    private $_MODS = array();
    public function __construct__() {
        global $MODS_ENABLED;
        $this -> $_MODS = $MODS_ENABLED;
    }
    public function __get( $var ) {
        foreach ( $this->_MODS as $mod )
            if ( property_exists( $mod, $var ) )
                return $mod -> $var;
    }
    public function __call( $method, $args ) {
        foreach ( $this->_MODS as $mod )
            if ( method_exists( $mod, $method ) )
                return call_user_method_array( $method, $mod, $args );
    }
}
class mainClass extends modMe {
    function __construct(...){
        $this -> __construct__();
    }
}

Now lets try to use them:

$MODS_ENABLED = array();
$MODS_ENABLED[] = new mod_mail();
$myObj = new main_class(...);
$myObj -> mail("me@me.me","you@you.you","subject","message/body","Extra:Headers;More:Headers");
# Hey look, my mail class was just added into my main_class for later use.

Note:

I am currently using the first method (I only have one class, the mods are exceptions) in my own CMS that I have made from scratch (http://sitegen.com.au), and it works great, my reason on needing this is because I have my main_class that is getting generated after I have required all mods in ./mods-enabled/* creating functions and changing how other functions work, I will also come back here another time with a solution for two mods to both change a function without one winning as it ran first. I have split my plugins in two, mods that run on every site, and plugins that have settings for a site and may not even be enabled.

Have fun programming.


问:
Convert decimal to byte array
assume I have decimal X

I want to calculate 3 byte as a,b,c where a.bc Gig is near X.

I want it to be clean and as short as it possible.

I've already implement it but it is very bad but works.

for example X = 2972117368, I want a = 2, b = 7, c = 6 . how?

2972117368/(1024*1024*1024) = 2.76799999922514

X will be always lesser than 9.99 gigabyte.

答:
Is seems like you're most of the way there:

```<code>decimal x = 2972117368;
double gig = Convert.ToDouble(x) / 1073741824.0;

byte a = (byte)Math.Floor(gig); // works for up to 127 gig - actually up to 256
byte b = (byte)(Math.Floor(gig * 10) % 10);
byte c = (byte)(Math.Floor(gig * 100) % 10);
</code>```

Edited: For some typos & logical errors

Title: Convert decimal to byte array

Body:
Is seems like you're most of the way there:

decimal x = 2972117368;
double gig = Convert.ToDouble(x) / 1073741824.0;

byte a = (byte)Math.Floor(gig); // works for up to 127 gig - actually up to 256
byte b = (byte)(Math.Floor(gig * 10) % 10);
byte c = (byte)(Math.Floor(gig * 100) % 10);

Edited: For some typos & logical errors


问:
Nested Recycler View skipping frames
I am using nested recycler view, that is a recycler view inside the rows of another recycler view.
During scroll, it skips frames and is very slow.
What can I do to avoid this?

What some research helped me figure out:-
Use something like epoxy.
Please give some insight into how to solve this?
If I have to use epoxy, please get me some basic code for epoxy.

What I have tried?

Outer recycler view:-

```<code>val manager = LinearLayoutManager(activity)
      manager.orientation = LinearLayoutManager.VERTICAL
      mRecyclerView.setLayoutManager(manager)
      mRecyclerView.setHasFixedSize(true)

      /**
       *Below measures help in making the recycler view efficient
       */
      mAgendaAdapter.setHasStableIds(true)
      mRecyclerView.setItemViewCacheSize(30)
      mRecyclerView.setDrawingCacheEnabled(true)
      mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH)
      mRecyclerView.setNestedScrollingEnabled(false)

      /*************************************************************
</code>```

Also :-

```<code>override fun onViewRecycled(holder: ObjectHolder) {

    if(holder!=null){
      holder.recyclerView.adapter =null
      holder.phaseTv.text=null
      holder.unitIdTv.text= null

    }

    super.onViewRecycled(holder)

  }
</code>```

Similar measures for inner recycler view also.
I have used a 2D arraylist as data structure.
The nested recycler view is attached to view holder.

答: I don't know if it would be good for you. I'm using ExpandableRecyclerview to have recyclerview in an other recyclerview : https://github.com/thoughtbot/expandable-recycler-view </p>

ContentLicense: CC BY-SA 3.0

Title: Nested Recycler View skipping frames

Body:
I am using nested recycler view, that is a recycler view inside the rows of another recycler view.
During scroll, it skips frames and is very slow.
What can I do to avoid this?

What some research helped me figure out:-
Use something like epoxy.
Please give some insight into how to solve this?
If I have to use epoxy, please get me some basic code for epoxy.

What I have tried?

Outer recycler view:-

val manager = LinearLayoutManager(activity)
      manager.orientation = LinearLayoutManager.VERTICAL
      mRecyclerView.setLayoutManager(manager)
      mRecyclerView.setHasFixedSize(true)

      /**
       *Below measures help in making the recycler view efficient
       */
      mAgendaAdapter.setHasStableIds(true)
      mRecyclerView.setItemViewCacheSize(30)
      mRecyclerView.setDrawingCacheEnabled(true)
      mRecyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH)
      mRecyclerView.setNestedScrollingEnabled(false)

      /*************************************************************

Also :-

override fun onViewRecycled(holder: ObjectHolder) {

    if(holder!=null){
      holder.recyclerView.adapter =null
      holder.phaseTv.text=null
      holder.unitIdTv.text= null

    }

    super.onViewRecycled(holder)

  }

Similar measures for inner recycler view also.
I have used a 2D arraylist as data structure.
The nested recycler view is attached to view holder.


问:
WPF Binding a Object to a Control Crash without debug info
I'm trying to bind an object to a control variable and when running the application it errors and gives the error message: "The application is in break mode"  Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).  Is there a way to debug this without just putting random break points in the code and start narrowing down?

Also, here is the code that has been causing the issue and not sure why.  I'm trying to seporate my current Control into 2 different ones.  While trying to bind a object to a control variable, it crashes without ever setting it.

```<code>public partial class SummaryFileControl : UserControl {
    public SummaryFileControl() {
        InitializeComponent();
    }

    public SummaryFile SummaryFile {
        get { return (SummaryFile)GetValue(SummaryFileProperty); }
        set { SetValue(SummaryFileProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SummaryFile.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SummaryFileProperty =
        DependencyProperty.Register("SummaryFile", typeof(SummaryFile), typeof(MainControls), new PropertyMetadata(null));
</code>```

And then I try to call it using:

```<code><controls:SummaryFileControl SummaryFile="{Binding SumFile}" />
</code>```

I've also tried this:

```<code><controls:SummaryFileControl SummaryFile="{Binding ElementName=SumFile,Path=SumFile}" />
</code>```

In the XAML I already reference the object, I am just trying to move it to it's own control and it works just fine like so:

```<code><TextBox Grid.Column="1" Text="{Binding SumFile.ExpectedValue}" IsEnabled="false"  />
</code>```

答:
Look at your DependencyProperty declaration, you should mention your control type as SummaryFileControl not as MainControls.</p>

```<code> public static readonly DependencyProperty SummaryFileProperty =
        DependencyProperty.Register("SummaryFile", typeof(SummaryFile), typeof(SummaryFileControl), new PropertyMetadata(null));
</code>```

Body:
I'm trying to bind an object to a control variable and when running the application it errors and gives the error message: "The application is in break mode"  Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).  Is there a way to debug this without just putting random break points in the code and start narrowing down?

Also, here is the code that has been causing the issue and not sure why.  I'm trying to seporate my current Control into 2 different ones.  While trying to bind a object to a control variable, it crashes without ever setting it.

public partial class SummaryFileControl : UserControl {
    public SummaryFileControl() {
        InitializeComponent();
    }

    public SummaryFile SummaryFile {
        get { return (SummaryFile)GetValue(SummaryFileProperty); }
        set { SetValue(SummaryFileProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SummaryFile.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SummaryFileProperty =
        DependencyProperty.Register("SummaryFile", typeof(SummaryFile), typeof(MainControls), new PropertyMetadata(null));

And then I try to call it using:

<controls:SummaryFileControl SummaryFile="{Binding SumFile}" />

I've also tried this:

<controls:SummaryFileControl SummaryFile="{Binding ElementName=SumFile,Path=SumFile}" />

In the XAML I already reference the object, I am just trying to move it to it's own control and it works just fine like so:

<TextBox Grid.Column="1" Text="{Binding SumFile.ExpectedValue}" IsEnabled="false"  />

Body:
Look at your DependencyProperty declaration, you should mention your control type as SummaryFileControl not as MainControls.

 public static readonly DependencyProperty SummaryFileProperty =
        DependencyProperty.Register("SummaryFile", typeof(SummaryFile), typeof(SummaryFileControl), new PropertyMetadata(null));


问:
Reading and capturing the ACL
I have been asked to write an application that will allow a user to select a database and have it read and store the ACL (including Roles) into a document. I haven't been able to find any way that let's you scan an ACL and capture the contents like that. </p>

答:
Here is code to mail you this info:
Server: XYZ
Filename: e_drev\abc.nsf
Replica-ID: 41256E1B0019C95C
Enforce consistent ACL is NOT set
Administration server: None
ACL Entry   Access Level    Roles(s)    UserType    Can delete  Can create
-Default-   Manager access  [Configure] Unspecified    Yes           Yes

Dim session As New NotesSession
    Dim nam As NotesName

    Dim db As NotesDatabase
    Dim maildoc As NotesDocument

    Dim acl As NotesACL
    Dim entry As NotesACLEntry
    Dim entryName As String
    Dim level As String
    Dim roles As String
    Dim uType As String
    Dim rti As NotesRichTextItem
    Dim rtnav As NotesRichTextNavigator
    Dim rtt As NotesRichTextTable

```<code>Set nam = session.CreateName(session.UserName)

Dim workspace As New NotesUIWorkspace
Dim askme As Variant

askme = workspace.Prompt("13","Mail me ACL and DB-info", "Select database to report on: ")
Set db = session.GetDatabase(askme(0), askme(1))
Set acl = db.ACL

Dim richStyle As NotesRichTextStyle
Set richStyle = session.CreateRichTextStyle
richStyle.NotesFont = FONT_HELV
richStyle.FontSize = 9
richStyle.Bold = True

Dim plainStyle As NotesRichTextStyle
Set plainStyle = session.CreateRichTextStyle
plainStyle.Bold = False

Set maildoc = New NotesDocument( db )

Set rti = maildoc.CreateRichTextItem("body")
Call rti.AppendText("Server: " + db.Server + Chr(13))
Call rti.AppendText("Filename: " + db.FilePath + Chr(13))
Call rti.AppendText("Replica-ID: " + db.ReplicaID + Chr(13))

If acl.UniformAccess Then
    Call rti.AppendText("Enforce consistent ACL is set" + Chr(13))
Else
    Call rti.AppendText("Enforce consistent ACL is NOT set" + Chr(13))
End If

If acl.AdministrationServer <> "" Then
    Call rti.AppendText("Administration server: " + acl.AdministrationServer + Chr(13))
Else
    Call rti.AppendText("Administration server: None" + Chr(13))
End If

Call rti.AppendTable(1, 6)

Set rtnav = rti.CreateNavigator
Call rtnav.FindFirstElement(RTELEM_TYPE_TABLE)
Set rtt = rtnav.GetElement

Call rtnav.FindFirstElement(RTELEM_TYPE_TABLECELL)
</code>```

' create table headings
    Call rti.AppendStyle(richStyle)

```<code>Call rti.BeginInsert(rtnav)
rti.AppendText("ACL Entry")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Access Level")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Roles(s)")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("UserType")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Can delete")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Can create")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Set entry = acl.GetFirstEntry

While Not ( entry Is Nothing )
    entryName = entry.Name

    If ( entry.Level = ACLLEVEL_NOACCESS ) Then
        level = "No access"
    Elseif ( entry.Level = ACLLEVEL_DEPOSITOR ) Then
        level = "Depositor"
    Elseif ( entry.Level = ACLLEVEL_READER ) Then
        level = "Reader"
    Elseif ( entry.Level = ACLLEVEL_AUTHOR ) Then
        level = "Author"
    Elseif ( entry.Level = ACLLEVEL_EDITOR ) Then
        level = "Editor"
    Elseif ( entry.Level = ACLLEVEL_DESIGNER ) Then
        level = "Designer"
    Elseif ( entry.Level = ACLLEVEL_MANAGER ) Then
        level = "Manager access"
    End If

    Forall role In entry.Roles

        If Isarray(entry.Roles) Then
            roles = roles & role & " "
        End If

    End Forall

    If ( entry.UserType = ACLTYPE_UNSPECIFIED ) Then
        uType = "Unspecified"
    Elseif ( entry.UserType = ACLTYPE_PERSON ) Then
        uType = "Person"
    Elseif ( entry.UserType = ACLTYPE_SERVER ) Then
        uType = "Server"
    Elseif ( entry.UserType = ACLTYPE_MIXED_GROUP ) Then
        uType = "Mixed group"
    Elseif ( entry.UserType = ACLTYPE_PERSON_GROUP ) Then
        uType = "Person group"
    Elseif ( entry.UserType = ACLTYPE_SERVER_GROUP ) Then
        uType = "Server group"
    End If

    Call rtt.AddRow(1)
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Call rti.AppendStyle(plainStyle)    ' turn off bold
    Call rti.BeginInsert(rtnav)
    rti.AppendText(entryName)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Call rti.BeginInsert(rtnav)
    rti.AppendText(level)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Call rti.BeginInsert(rtnav)
    rti.AppendText(roles)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    'UserType
    Call rti.BeginInsert(rtnav)
    rti.AppendText(uType)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    'CanDelete
    Call rti.BeginInsert(rtnav)
    If entry.CanDeleteDocuments Then
        rti.AppendText("Yes")
    Else
        rti.AppendText("No")
    End If
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    'CanCreate
    Call rti.BeginInsert(rtnav)
    If entry.CanCreateDocuments Then
        rti.AppendText("Yes")
    Else
        rti.AppendText("No")
    End If
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Set entry = acl.GetnextEntry(entry)
    roles = ""

Wend

maildoc.form="Memo"
maildoc.subject="ACL and database info for " & db.Title
Call maildoc.Send( False, session.UserName) ' use current name for to address

Messagebox "An email has been sent to " &  nam.Abbreviated , 0 , "Action Complete"
</code>```

Title: Reading and capturing the ACL

Body:
Here is code to mail you this info:
Server: XYZ
Filename: e_drev\abc.nsf
Replica-ID: 41256E1B0019C95C
Enforce consistent ACL is NOT set
Administration server: None
ACL Entry   Access Level    Roles(s)    UserType    Can delete  Can create
-Default-   Manager access  [Configure] Unspecified    Yes           Yes

Dim session As New NotesSession
    Dim nam As NotesName

    Dim db As NotesDatabase
    Dim maildoc As NotesDocument

    Dim acl As NotesACL
    Dim entry As NotesACLEntry
    Dim entryName As String
    Dim level As String
    Dim roles As String
    Dim uType As String
    Dim rti As NotesRichTextItem
    Dim rtnav As NotesRichTextNavigator
    Dim rtt As NotesRichTextTable

Set nam = session.CreateName(session.UserName)

Dim workspace As New NotesUIWorkspace
Dim askme As Variant

askme = workspace.Prompt("13","Mail me ACL and DB-info", "Select database to report on: ")
Set db = session.GetDatabase(askme(0), askme(1))
Set acl = db.ACL

Dim richStyle As NotesRichTextStyle
Set richStyle = session.CreateRichTextStyle
richStyle.NotesFont = FONT_HELV
richStyle.FontSize = 9
richStyle.Bold = True

Dim plainStyle As NotesRichTextStyle
Set plainStyle = session.CreateRichTextStyle
plainStyle.Bold = False

Set maildoc = New NotesDocument( db )

Set rti = maildoc.CreateRichTextItem("body")
Call rti.AppendText("Server: " + db.Server + Chr(13))
Call rti.AppendText("Filename: " + db.FilePath + Chr(13))
Call rti.AppendText("Replica-ID: " + db.ReplicaID + Chr(13))

If acl.UniformAccess Then
    Call rti.AppendText("Enforce consistent ACL is set" + Chr(13))
Else
    Call rti.AppendText("Enforce consistent ACL is NOT set" + Chr(13))
End If

If acl.AdministrationServer <> "" Then
    Call rti.AppendText("Administration server: " + acl.AdministrationServer + Chr(13))
Else
    Call rti.AppendText("Administration server: None" + Chr(13))
End If

Call rti.AppendTable(1, 6)

Set rtnav = rti.CreateNavigator
Call rtnav.FindFirstElement(RTELEM_TYPE_TABLE)
Set rtt = rtnav.GetElement

Call rtnav.FindFirstElement(RTELEM_TYPE_TABLECELL)

' create table headings
    Call rti.AppendStyle(richStyle)

Call rti.BeginInsert(rtnav)
rti.AppendText("ACL Entry")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Access Level")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Roles(s)")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("UserType")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Can delete")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Call rti.BeginInsert(rtnav)
rti.AppendText("Can create")
Call rti.EndInsert
Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

Set entry = acl.GetFirstEntry

While Not ( entry Is Nothing )
    entryName = entry.Name

    If ( entry.Level = ACLLEVEL_NOACCESS ) Then
        level = "No access"
    Elseif ( entry.Level = ACLLEVEL_DEPOSITOR ) Then
        level = "Depositor"
    Elseif ( entry.Level = ACLLEVEL_READER ) Then
        level = "Reader"
    Elseif ( entry.Level = ACLLEVEL_AUTHOR ) Then
        level = "Author"
    Elseif ( entry.Level = ACLLEVEL_EDITOR ) Then
        level = "Editor"
    Elseif ( entry.Level = ACLLEVEL_DESIGNER ) Then
        level = "Designer"
    Elseif ( entry.Level = ACLLEVEL_MANAGER ) Then
        level = "Manager access"
    End If

    Forall role In entry.Roles

        If Isarray(entry.Roles) Then
            roles = roles & role & " "
        End If

    End Forall

    If ( entry.UserType = ACLTYPE_UNSPECIFIED ) Then
        uType = "Unspecified"
    Elseif ( entry.UserType = ACLTYPE_PERSON ) Then
        uType = "Person"
    Elseif ( entry.UserType = ACLTYPE_SERVER ) Then
        uType = "Server"
    Elseif ( entry.UserType = ACLTYPE_MIXED_GROUP ) Then
        uType = "Mixed group"
    Elseif ( entry.UserType = ACLTYPE_PERSON_GROUP ) Then
        uType = "Person group"
    Elseif ( entry.UserType = ACLTYPE_SERVER_GROUP ) Then
        uType = "Server group"
    End If

    Call rtt.AddRow(1)
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Call rti.AppendStyle(plainStyle)    ' turn off bold
    Call rti.BeginInsert(rtnav)
    rti.AppendText(entryName)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Call rti.BeginInsert(rtnav)
    rti.AppendText(level)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Call rti.BeginInsert(rtnav)
    rti.AppendText(roles)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    'UserType
    Call rti.BeginInsert(rtnav)
    rti.AppendText(uType)
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    'CanDelete
    Call rti.BeginInsert(rtnav)
    If entry.CanDeleteDocuments Then
        rti.AppendText("Yes")
    Else
        rti.AppendText("No")
    End If
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    'CanCreate
    Call rti.BeginInsert(rtnav)
    If entry.CanCreateDocuments Then
        rti.AppendText("Yes")
    Else
        rti.AppendText("No")
    End If
    Call rti.EndInsert
    Call rtnav.FindNextElement(RTELEM_TYPE_TABLECELL)

    Set entry = acl.GetnextEntry(entry)
    roles = ""

Wend

maildoc.form="Memo"
maildoc.subject="ACL and database info for " & db.Title
Call maildoc.Send( False, session.UserName) ' use current name for to address

Messagebox "An email has been sent to " &  nam.Abbreviated , 0 , "Action Complete"


问:
How does Sort algorithm performance vary with repeated elements in data
Does the performance of a sorting algorithms(Merge,Quick) reduce with repeated elements for the same sized array.

can I say

```<code>var arr = [6,4,7,1,8,3,9,2,10,5]; --> Sorts faster because of unique elements
var arr = [1,1,3,3,3,2,4,4,5,10]; --> Slower because repeated elements
</code>```

I tried to write a simple quicksort implementation and it gives me the above mentioned behavior . Am I doing something wrong

```<code>var Quicksort = function(arr, si, ei) {

    if (si >= ei) return;

    var pivot = arr[ei];
    var pi = si;

    for (var i = si; i < ei; i++) {

        if (arr[i] < pivot) {
            Swap(arr, pi, i);
            pi++;
        }
    }

    Swap(arr, pi, ei);

    Quicksort(arr, 0, pi - 1);
    Quicksort(arr, pi + 1, ei);

    return arr;

}

function Swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

// Execute
var input = [];
for (var i = 0; i < 1000; i++) {
    input.push(Math.floor(Math.random() * 100000));
}
console.log(input);

var result = Quicksort(input, 0, input.length - 1);

console.log(result);
</code>```

Thanks

答:
The number of equal or different values does not affect the efficiency of either merge or quicksort.

what affects the efficiency of quicksort is how you choose the pivot value and if the array is already sorted.

read: http://www.geeksforgeeks.org/when-does-the-worst-case-of-quicksort-occur/

when it comes to mergesort, what affects its efficiency is how many comparisons your end up doing during the merge phase.

read: When will the worst case of Merge Sort occur?

Therefore, the frequency of numbers does not affect the sorting algorithms.

of course, assuming you have an array of size n, where all values are equal to x, quicksort will perform well, since the array will already be sorted.

like: [6,6,6,6,6], quicksort would performe in n².

I believe that there are other sorting algorithms that would do a better job for arrays where values repeat a lot, I would say counting sort (http://www.geeksforgeeks.org/counting-sort/) would be a good approach.

Body:
Does the performance of a sorting algorithms(Merge,Quick) reduce with repeated elements for the same sized array.

can I say

var arr = [6,4,7,1,8,3,9,2,10,5]; --> Sorts faster because of unique elements
var arr = [1,1,3,3,3,2,4,4,5,10]; --> Slower because repeated elements

I tried to write a simple quicksort implementation and it gives me the above mentioned behavior . Am I doing something wrong

var Quicksort = function(arr, si, ei) {

    if (si >= ei) return;

    var pivot = arr[ei];
    var pi = si;

    for (var i = si; i < ei; i++) {

        if (arr[i] < pivot) {
            Swap(arr, pi, i);
            pi++;
        }
    }

    Swap(arr, pi, ei);

    Quicksort(arr, 0, pi - 1);
    Quicksort(arr, pi + 1, ei);

    return arr;

}

function Swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

// Execute
var input = [];
for (var i = 0; i < 1000; i++) {
    input.push(Math.floor(Math.random() * 100000));
}
console.log(input);

var result = Quicksort(input, 0, input.length - 1);

console.log(result);

Thanks


问:
wpf dynamically add items to stackpanel with scrollbar
I am trying to create two columns of controls.  Let's say first column has 20 labels or buttons that user can interact with and second column has about 80 labels/buttons.   I'd like scrollbar as well.

when I add scrollview, my first column disappears.  How can I add scrollbar?

```<code>            InitializeComponent();
        Populate();
    }

    protected void Populate()
    {
        for (int i = 0; i <= (int) 20; i++)
        {
            Button l = new Button();
            l.Content = i;
            StyleSP.Children.Add(l);
        }

        for (int i = 100; i < 170; i++)
        {
            Button l = new Button();
            l.Content = i;
            IndustrySP.Children.Add(l);
        }
    }
</code>```

WPF

```<code><UserControl x:Class="Factor.Control.FactorList"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="700" d:DesignWidth="300" >
<Grid Height="300">

    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ScrollViewer>
    <StackPanel Name="StyleSP" Background="Chocolate"  Grid.Column ="0" Height="300">

        </StackPanel>
        </ScrollViewer>
    <ScrollViewer>
        <StackPanel  Name="IndustrySP" Background="AliceBlue" Grid.Column="1" Height="300">

        </StackPanel>
    </ScrollViewer>
</Grid>
</code>```

答: my problem was that i neglected to move up 'Grid.Column' from StackPanel to ScrollViewer.</p>

Body:
I am trying to create two columns of controls.  Let's say first column has 20 labels or buttons that user can interact with and second column has about 80 labels/buttons.   I'd like scrollbar as well.

when I add scrollview, my first column disappears.  How can I add scrollbar?

            InitializeComponent();
        Populate();
    }

    protected void Populate()
    {
        for (int i = 0; i <= (int) 20; i++)
        {
            Button l = new Button();
            l.Content = i;
            StyleSP.Children.Add(l);
        }

        for (int i = 100; i < 170; i++)
        {
            Button l = new Button();
            l.Content = i;
            IndustrySP.Children.Add(l);
        }
    }

WPF

<UserControl x:Class="Factor.Control.FactorList"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         d:DesignHeight="700" d:DesignWidth="300" >
<Grid Height="300">

    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ScrollViewer>
    <StackPanel Name="StyleSP" Background="Chocolate"  Grid.Column ="0" Height="300">

        </StackPanel>
        </ScrollViewer>
    <ScrollViewer>
        <StackPanel  Name="IndustrySP" Background="AliceBlue" Grid.Column="1" Height="300">

        </StackPanel>
    </ScrollViewer>
</Grid>


问:
get input from keyboard while displaying an avi with matlab
Hi all

I wrote a short program that displays an avi file. I need the program to get input from the keyboard while the movie is running (and not after it ends):
this is my code:

figure('MenuBar','none')

    set(gcf,'Color', 'white')

    set(gca,'Color','white');

    set(gca,'XColor','white');

    set(gca,'YColor','white');

    m=aviread('c:/t1.avi')

    a=30:1:100;

    b=100:-1:30;

    c=[a b a b a b a b a b] %to run the movie back and forth

    movie(m,c) %runs the movie

Thank you for any help

Ariel

答:
Unless movie() has been designed to watch for input I think you will have to multithread, which from one of the other answers sounds a bit complicated.

You could play a short section of the video, then run come code to check for inputs and then play the next bit of the video. I'm not sure if you can count on things that the user types whilst the video plays going into the input buffer though.


问:
Get minX, maxX, minY, maxY from multidimensional array
I have an array like this

```<code>var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]
</code>```

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

```<code>var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}
</code>```

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

```<code>var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}
</code>```

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)```

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

答:
var my_array = [
    [3, 9],
    [1, 5],
    [7, 2],
    [5, 4]
];
let extreme_result={};
extreme_result.MinX=my_array.reduce(function(a,b){
    if(a[0]<b[0]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MinY=my_array.reduce(function(a,b){
    if(a[1]b[0]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MaxY=my_array.reduce(function(a,b){
    if(a[1]>b[1]){
        return a;
    }
    else{
        return b;
    }
});
console.log(extreme_result);```

Body:
I have an array like this

var my_array = [
  [3,9],
  [1,5],
  [7,2],
  [5,4]
 ]

As you can see my_array is a multidimensional array that includes in this case 4 different arrays.

All of the arrays are x/y-coordinates ([3,9] ---> X: 3, Y: 9) and I'd like to move the arrays of the array with ...

the biggest X value,

the biggest Y value,

the smallest X value,

the smallest Y value

... to an object like this:

var my_object = {
  "minX": [1,5],
  "maxX": [7,2],
  "minY": [7,2],
  "maxY": [3,9]
}

The function I've created you can find below, but my function is just returning the listed values from above instead of returning the full array. So my current (wrong) result looks like this:

var wrong_object = {
  "minX": 1, // missing 5
  "maxX": 7, // missing 2
  "minY": 2, // missing 7
  "maxY": 9  // missing 3
}

var my_array = [
  [3, 9],
  [1, 5],
  [7, 2],
  [5, 4]
]

var extreme_result = {}
extreme_result.minX = Math.min.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.maxX = Math.max.apply(Math, my_array.map(function(i) {
  return i[0]
}));
extreme_result.minY = Math.min.apply(Math, my_array.map(function(i) {
  return i[1]
}));
extreme_result.maxY = Math.max.apply(Math, my_array.map(function(i) {
  return i[1]
}));

console.log(extreme_result)

I hope somebody can help me with this problem.

Thanks in advance, Greetings Pete

Body:
var my_array = [
    [3, 9],
    [1, 5],
    [7, 2],
    [5, 4]
];
let extreme_result={};
extreme_result.MinX=my_array.reduce(function(a,b){
    if(a[0]<b[0]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MinY=my_array.reduce(function(a,b){
    if(a[1]<b[1]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MaxX=my_array.reduce(function(a,b){
    if(a[0]>b[0]){
        return a;
    }
    else{
        return b;
    }
});
extreme_result.MaxY=my_array.reduce(function(a,b){
    if(a[1]>b[1]){
        return a;
    }
    else{
        return b;
    }
});
console.log(extreme_result);


问:
Clicking using Python and Selenium
I have these following elements in a page and I need to select the element with the value 18 inside using Python and selenium script. That is the second link. Here is the HTML code of the page

```<code><a class="ui-state-default ui-state-highlight ui-state-active" href="#">17</a>
<a class="ui-state-default ui-state-highlight ui-state-active" href="#">18</a>
<a class="ui-state-default ui-state-highlight ui-state-active" href="#">19</a>
</code>```

I am trying to use the following Python and Selenium code to click

```<code>elem = driver.find_element_by_xpath('//a[@class="ui-state-default"]').click()
</code>```

But that does not work. How do I fix it?

答:
```<code>elem = driver.find_element_by_link_text("18")
elem.click()
</code>```

Title: Clicking using Python and Selenium

Body:
I have these following elements in a page and I need to select the element with the value 18 inside using Python and selenium script. That is the second link. Here is the HTML code of the page

17
18
19

I am trying to use the following Python and Selenium code to click

elem = driver.find_element_by_xpath('//a[@class="ui-state-default"]').click()

But that does not work. How do I fix it?


问:
Python on Windows. Why is reading text 8x slower than binary?
I am running python 3.6 on Windows 10 (both 64 bit) with a fast SSD, 32GB RAM and a very fast processor (AMD Threadripper). I also get similar results running on an Intel i7. I am opening XML text files about 5MB in size and noticed very slow performance even using lxml. I boiled the problem down to disk read performance. If I load as binary, it is over 8x faster. The following tests were performed with the file already in disk cache. The disk was never hit during these runs. Similar results were obtained with a cold read.

```<code>%%timeit
with open(xmlpath + fn, 'rb') as f:
    r = f.read()
1.66 ms ± 31.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
with open(xmlpath + fn, 'r', encoding='UTF-8') as f:
    r = f.read()
13.7 ms ± 32.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

I understand the encoding has to be processed for the text version, but 8x slower seems excessive running on a fast processor. Also, 1.6ms seems slow to me to read such a small file already in cache. Disk performance measured with Passmark is as expected at > 2GB/s.

Any advice/suggestions would be appreciated. Thanks.

答:
When you're using rb, the file can be read with an unlimited/very big block size directly in the final buffer memory (r).

When you're using r, the file must be read with a smaller block size in order to be able to post-process the blocks & remove the \r chars before the \n chars (if it's not done char by char, which would be the easiest but the slowest way)

if you can afford to duplicate the memory (which r mode doesn't do), I would suggest:

```<code>with open(xmlpath + fn, 'rb') as f:
    r = f.read().decode('UTF-8').replace('\r','')
</code>```

also to save decoding & replacing as comments stated:

```<code>with open(xmlpath + fn, 'r', newline="") as f:
    r = f.read()
</code>```

Body:
I am running python 3.6 on Windows 10 (both 64 bit) with a fast SSD, 32GB RAM and a very fast processor (AMD Threadripper). I also get similar results running on an Intel i7. I am opening XML text files about 5MB in size and noticed very slow performance even using lxml. I boiled the problem down to disk read performance. If I load as binary, it is over 8x faster. The following tests were performed with the file already in disk cache. The disk was never hit during these runs. Similar results were obtained with a cold read.

%%timeit
with open(xmlpath + fn, 'rb') as f:
    r = f.read()
1.66 ms ± 31.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
with open(xmlpath + fn, 'r', encoding='UTF-8') as f:
    r = f.read()
13.7 ms ± 32.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

I understand the encoding has to be processed for the text version, but 8x slower seems excessive running on a fast processor. Also, 1.6ms seems slow to me to read such a small file already in cache. Disk performance measured with Passmark is as expected at > 2GB/s.

Any advice/suggestions would be appreciated. Thanks.

Body:
When you're using rb, the file can be read with an unlimited/very big block size directly in the final buffer memory (r).

When you're using r, the file must be read with a smaller block size in order to be able to post-process the blocks & remove the \r chars before the \n chars (if it's not done char by char, which would be the easiest but the slowest way)

if you can afford to duplicate the memory (which r mode doesn't do), I would suggest:

with open(xmlpath + fn, 'rb') as f:
    r = f.read().decode('UTF-8').replace('\r','')

also to save decoding & replacing as comments stated:

with open(xmlpath + fn, 'r', newline="") as f:
    r = f.read()


问:
How to set a form readonly (how to avoid the stay - leave popup)
We have the requirement that users, after terminating the input of a form, can only see the data; only authorized users can modify the data, see question
intermediate save and readonly after termination.

The first idea was to use the permission: owner can read the data.

This works  smootly : afer saving, in the summary page the form is marked as readonly.

But there was also the requirement: users must be able to interrupt the input of the form and resume it later.

So in the permissions we had to set that the owner can read and update the data, and we use a field of the form to set the section to readonly.

The save-final button sets this field.

We have renamed this button to FINISH, and the save-draft button to intermediate save.

Clicking save-final also makes invisible the save buttons, so the user after clicking this button cannot change anymore the data.

Before clicking FINISH:

After clicking FINISH:

Selecting  the form in the summary page and choosing review  works smootly: the form is opened in view mode.

But clicking in the created  or modified field  opens the form in edit. And although all form fields are readonly, clicking at the summary button a window "Leave page Stay on page" is shown. I suppose, because of the vars of the database service the form results as a modified page.

After clicking leave Page, in the summary page a new draft form is shown. This draft form only an Administrator can delete. Because the user haven't the permission to delete.

So the question is:

 is there a possibility to set the form read-only when the user clicks the FINISH button? So that in the summary page the form is marked as read only?

 Or as another option: is there a possibility to disable the columns Created  and Modified"  in the summary page, so that only the first column in the summary page is clickable?

Link to the test code

Many thanks

答:
I found as a possibility:

Inhibit the edit in the summary page

add an edit button to the detail page and associate it with the edit
action

Change the description of the Review button to Review/Edit

to 1)   I inserted in the custom summary css the lines:

.orbeon .fr-summary-table-div td a,

.orbeon .fr-summary-table-div th a {

  pointer-events: none;

}

to 2)   Lines added in the properties-local.xml:

    Add an edit button to the buttons of the detail page

    <property as="xs:string" name="oxf.fr.detail.buttons.view.*.*"   value="summary edit pdf"/>

    Add the edit process to the edit button

    <property as="xs:string" name="oxf.fr.detail.process.edit.apptest.*"     value="edit"/>

    Add descriptions to the edit key

    <property as="xs:string" name="oxf.fr.resource.apptest.*.en.buttons.edit" value="EDIT"/>

    <property as="xs:string" name="oxf.fr.resource.apptest.*.de.buttons.edit" value="Ändern"/>

    <property as="xs:string" name="oxf.fr.resource.apptest.*.it.buttons.edit" value="Aggiorna"/>

    Show the edit button only if the input phase isn't terminated

    <property as="xs:string" name="oxf.fr.detail.button.edit.visible.apptest.*">

          //datenOK = false()

 </property>

Summary page with review/edit button

Detail page with edit button (because the input phase isn't yet terminated)

Detail page without edit button (the input phase is already terminated)


问:
Find x value in function if I know returned value
I have javascript function like this:

```<code>   function(x) {
       return x + 2;
   };
</code>```

How can I find the value of x when returned value is for example 10 ?
I need to find formula so I can apply it on other different functions.

答:
You are asking to define the inverse of a function. In general a solution to this does not exist. Suppose your function was

```<code>function(x) {
    return x*x;
};
</code>```

When you ask for the value of x that returns 9, do you want 3 or -3? In general, you cannot do this if your function is not one-to-one (injective). But even if your function is one-to-one, you can't really make a general rule for what the inverse would be. You'd just have to do it on a case-by-case basis.

Body:
I have javascript function like this:

   function(x) {
       return x + 2;
   };

How can I find the value of x when returned value is for example 10 ?
I need to find formula so I can apply it on other different functions.

Body:
You are asking to define the inverse of a function. In general a solution to this does not exist. Suppose your function was

function(x) {
    return x*x;
};

When you ask for the value of x that returns 9, do you want 3 or -3? In general, you cannot do this if your function is not one-to-one (injective). But even if your function is one-to-one, you can't really make a general rule for what the inverse would be. You'd just have to do it on a case-by-case basis.


问:
How do I access the pixels of an image using OpenCV-Python?
I want to know how to loop through all pixels of an image. I tried this:

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

x = np.random.randint(0,5,(500,500))
img = cv2.imread('D:\Project\Capture1.jpg',0)
p = img.shape
print p
rows,cols = img.shape

for i in range(rows):
    for j in range(cols):
        k = x[i,j]
        print k
</code>```

It prints a vertical set of numbers which is not in the form of an array. I am also getting an array out of bounds exception. Please suggest a method.

答:
import cv2
import numpy as np

image = cv2.imread('/path/to/test.jpg', cv2.IMREAD_COLOR)

for x in range (1,480):
    for y in range (1,640):
        pixel = image[x,y]
        print(pixel)
```

ContentLicense: CC BY-SA 4.0

Body:
I want to know how to loop through all pixels of an image. I tried this:

import cv2
import numpy as np

x = np.random.randint(0,5,(500,500))
img = cv2.imread('D:\Project\Capture1.jpg',0)
p = img.shape
print p
rows,cols = img.shape

for i in range(rows):
    for j in range(cols):
        k = x[i,j]
        print k

It prints a vertical set of numbers which is not in the form of an array. I am also getting an array out of bounds exception. Please suggest a method.


问:
Include argument in NAnt executable call if property is not null or empty
For a build script, part of my process is to deploy files using an in-house executable.  We call this with a number of parameters.

On an application I'm working on, it turns out we need to add a parameter.  This isn't something that retroactively applies to anything else I've previously worked on, so the idea is that I would only include the new argument if the corresponding property is not null or empty.

Relevant NAnt Call:

```<code><property name="deploy.NewArg" value="" />
<echo message="deploy.NewArg = ${deploy.NewArg}" />

<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
    <arg value="AppTitle=${deploy.AppTitle}" />
    <arg value="Environment=${deploy.Environment}" />
    <!-- Here's the problem argument... -->
    <arg value="MyNewProperty=${deploy.NewArg}" if="${deploy.NewArg}" />
</exec>
</code>```

The reason what I have is not working, is because of the if clause on the new <arg> tag - the deploy.NewArg string doesn't convert to a boolean statement.

Question: In what way can I perform an "Is Null or Empty" check on an <arg if> parameter?  As noted above, I want the MyNewProperty=... argument added if deploy.NewArg is anything but nothing or an empty string.

I checked a number of other StackOverflow questions, as well as the official NAnt arg tag documentation, but could not find how to do this.

答:
It turns out, I needed to get back to the basics, and check out some of my fundamentals and functions.  The way to do an 'is empty' check on a property is as below:

```<code><exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
    <!-- Other args... -->
    <arg value="MyNewProperty=${deploy.NewArg}" if=${string::get-length(deploy.NewArg) > 0}" />
</exec>
</code>```

For someone who hasn't yet done the research, if only works with a boolean.  That being said, booleans can be generated in one of two ways: either an explicit true or false, or by using an expression.  Expressions are always contained in ${} brackets.  The use of string::get-length() should be obvious.

Bring it all together, and you only include an argument if it's specified.

Body:
For a build script, part of my process is to deploy files using an in-house executable.  We call this with a number of parameters.

On an application I'm working on, it turns out we need to add a parameter.  This isn't something that retroactively applies to anything else I've previously worked on, so the idea is that I would only include the new argument if the corresponding property is not null or empty.

Relevant NAnt Call:

<property name="deploy.NewArg" value="" />
<echo message="deploy.NewArg = ${deploy.NewArg}" />

<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
    <arg value="AppTitle=${deploy.AppTitle}" />
    <arg value="Environment=${deploy.Environment}" />

    <arg value="MyNewProperty=${deploy.NewArg}" if="${deploy.NewArg}" />
</exec>

The reason what I have is not working, is because of the if clause on the new <arg> tag - the deploy.NewArg string doesn't convert to a boolean statement.

Question: In what way can I perform an "Is Null or Empty" check on an <arg if> parameter?  As noted above, I want the MyNewProperty=... argument added if deploy.NewArg is anything but nothing or an empty string.

I checked a number of other StackOverflow questions, as well as the official NAnt arg tag documentation, but could not find how to do this.

Body:
It turns out, I needed to get back to the basics, and check out some of my fundamentals and functions.  The way to do an 'is empty' check on a property is as below:

<exec program="C:\Deploy\MyAwesomeDeployProgram.exe">
    <!-- Other args... -->
    <arg value="MyNewProperty=${deploy.NewArg}" if=${string::get-length(deploy.NewArg) > 0}" />
</exec>

For someone who hasn't yet done the research, if only works with a boolean.  That being said, booleans can be generated in one of two ways: either an explicit true or false, or by using an expression.  Expressions are always contained in ${} brackets.  The use of string::get-length() should be obvious.

Bring it all together, and you only include an argument if it's specified.


问:
How to get a value from a selected row in jfxtreetableview
I have searched all over the internet but couldn't find any easy way to get selected value from a jfxtreetableview like good old jtable anyone knows about it?

I have created a jfxtreetableview and populated data.

```<code>JFXTreeTableColumn<Person, String> address = new JFXTreeTableColumn("Address");
address.setPrefWidth(100);
address.impl_setReorderable(false);
address.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Person, String>, ObservableValue<String>>()
{
@Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Person, String> param)
{
return param.getValue().getValue().address;
}
});
</code>```

答:
You can get selected item by doing this :</p>

```<code>yourTreeTableView.getSelectionModel().getSelectedItem();
</code>```

Body:
I have searched all over the internet but couldn't find any easy way to get selected value from a jfxtreetableview like good old jtable anyone knows about it?

I have created a jfxtreetableview and populated data.

JFXTreeTableColumn<Person, String> address = new JFXTreeTableColumn("Address");
address.setPrefWidth(100);
address.impl_setReorderable(false);
address.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<Person, String>, ObservableValue<String>>()
{
@Override public ObservableValue<String> call(TreeTableColumn.CellDataFeatures<Person, String> param)
{
return param.getValue().getValue().address;
}
});

Body:
You can get selected item by doing this :

yourTreeTableView.getSelectionModel().getSelectedItem();


问:
Pentaho Kettle insert Error Handling of step
I am new to GeoKettle (Spoon) of Pentaho and I am currently rows from an Excel-file into my database. Now I want to avoid duplicates in my databasetable. That is why I want to insert only those rows into my database table which aren't there yet (to have only unique records in my database table).

And as far as I know, there are two ways to realize that. The first way I tried was with the Insert/Update step (I have disabled the Update functionality) and defined all the columns which have to be equal in order to insert the record or not. But it does not work. All records are still inserted into the database.

That is why I am trying to do the (according to pentaho) much faster option which is a "Table Output" with an "Update" error handling step as shown in the picture.

As shown in the picture, the arrow which is pointing from "table output" to "update" is black. But I need a red dotted one for error handling of step . But I do not know how to create this. In tutorials I often see that there pops up a little window with 2 options like in the picture:

But I do not get that popup. If I want to create a hop, I will have to mark both steps and do a right-click on one of them.
So in which possible ways can I create such a red dotted arrow? In the end, it has to look like this:

Thank you so much in advance!!

答:
You have a problem with your setup. Or with your version of the PDI. The functionality of an error step was introduced in V4 but fully implemented for all steps around V6.

Download a fresh PDI from SourceForge. V7.1 is really a robust and stable edition. Unzip and test.

By the way, what you want to achieve is know as the CRUD pattern. CRUD for Create, Read, Update, Delete. The step doing this the Merge Rows (diff) (in the Joins family). You tell the steps which columns to check, and it produce a new column with the value identical, changed, new, or deleted. You can them redirect the flow in a Switch / Case to do the appropriate action. Further information here (V4).


问:
Openstack All-In-One Single Machine Networking
I'm having a hard time configuring an Openstack environment based on the All-In-One Single Machine installer for bridged networking in my LAN.

My objective is to SSH into the instances created in Openstack from my LAN.

The server is an Ubuntu 16.04 LTS with minimal installation and OpenSSH. The network configuration of the server is:

auto enp3s0
iface enp3s0 inet static
address 10.4.4.1
netmask 255.255.255.0
gateway 10.4.4.254
broadcast 10.4.4.255
network 10.4.4.0
dns-nameservers 10.4.1.12 10.4.1.10```
</div>
</div>
</p>

<p>Basically my network details are the following:</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-html lang-html prettyprint-override"><code>LAN 10.4.4.0
MASK 255.255.255.0
Gateway/DHCP Server  10.4.4.254</code>```

The local.conf file I've used for deploying the devstack is the following:

# Sample ``local.conf`` for user-configurable variables in ``stack.sh``

# NOTE: Copy this file to the root DevStack directory for it to work properly.

# ``local.conf`` is a user-maintained settings file that is sourced from ``stackrc``.
# This gives it the ability to override any variables set in ``stackrc``.
# Also, most of the settings in ``stack.sh`` are written to only be set if no
# value has already been set; this lets ``local.conf`` effectively override the
# default values.

# This is a collection of some of the settings we have found to be useful
# in our DevStack development environments. Additional settings are described
# in https://docs.openstack.org/devstack/latest/configuration.html#local-conf
# These should be considered as samples and are unsupported DevStack code.

# The ``localrc`` section replaces the old ``localrc`` configuration file.
# Note that if ``localrc`` is present it will be used in favor of this section.
[[local|localrc]]

# Minimal Contents
# ----------------

# While ``stack.sh`` is happy to run without ``localrc``, devlife is better when
# there are a few minimal variables set:

# If the ``*_PASSWORD`` variables are not set here you will be prompted to enter
# values for them by ``stack.sh``and they will be added to ``local.conf``.
FLOATING_RANGE=10.4.4.192/27
FIXED_RANGE=192.168.0.0/24
FIXED_NETWORK_SIZE=256
FLAT_INTERFACE=enp3s0
ADMIN_PASSWORD=nomoresecret
DATABASE_PASSWORD=stackdb
RABBIT_PASSWORD=stackqueue
SERVICE_PASSWORD=$ADMIN_PASSWORD

# ``HOST_IP`` and ``HOST_IPV6`` should be set manually for best results if
# the NIC configuration of the host is unusual, i.e. ``eth1`` has the default
# route but ``eth0`` is the public interface.  They are auto-detected in
# ``stack.sh`` but often is indeterminate on later runs due to the IP moving
# from an Ethernet interface to a bridge on the host. Setting it here also
# makes it available for ``openrc`` to include when setting ``OS_AUTH_URL``.
# Neither is set by default.
HOST_IP=10.4.4.1
#HOST_IPV6=2001:db8::7

# Logging
# -------

# By default ``stack.sh`` output only goes to the terminal where it runs.  It can
# be configured to additionally log to a file by setting ``LOGFILE`` to the full
# path of the destination log file.  A timestamp will be appended to the given name.
LOGFILE=$DEST/logs/stack.sh.log

# Old log files are automatically removed after 7 days to keep things neat.  Change
# the number of days by setting ``LOGDAYS``.
LOGDAYS=2

# Nova logs will be colorized if ``SYSLOG`` is not set; turn this off by setting
# ``LOG_COLOR`` false.
#LOG_COLOR=False

# Using milestone-proposed branches
# ---------------------------------

# Uncomment these to grab the milestone-proposed branches from the
# repos:
#CINDER_BRANCH=milestone-proposed
#GLANCE_BRANCH=milestone-proposed
#HORIZON_BRANCH=milestone-proposed
#KEYSTONE_BRANCH=milestone-proposed
#KEYSTONECLIENT_BRANCH=milestone-proposed
#NOVA_BRANCH=milestone-proposed
#NOVACLIENT_BRANCH=milestone-proposed
#NEUTRON_BRANCH=milestone-proposed
#SWIFT_BRANCH=milestone-proposed

# Using git versions of clients
# -----------------------------
# By default clients are installed from pip.  See LIBS_FROM_GIT in
# stackrc for details on getting clients from specific branches or
# revisions.  e.g.
# LIBS_FROM_GIT="python-ironicclient"
# IRONICCLIENT_BRANCH=refs/changes/44/2.../1

# Swift
# -----

# Swift is now used as the back-end for the S3-like object store. Setting the
# hash value is required and you will be prompted for it if Swift is enabled
# so just set it to something already:
SWIFT_HASH=66a3d6b56c1f479c8b4e70ab5c2000f5

# For development purposes the default of 3 replicas is usually not required.
# Set this to 1 to save some resources:
SWIFT_REPLICAS=1

# The data for Swift is stored by default in (``$DEST/data/swift``),
# or (``$DATA_DIR/swift``) if ``DATA_DIR`` has been set, and can be
# moved by setting ``SWIFT_DATA_DIR``. The directory will be created
# if it does not exist.
SWIFT_DATA_DIR=$DEST/data```
</div>
</div>
</p>

<p>At the end of the deployment I'm able to ping from the instance to my LAN and do nslookup on google.com for example, but I can't do it backwards, ping/ssh/telnet the instance in Openstack.
The security group permits all traffic, all ICMP ingress/egress, SSH from everywhere.</p>

<p>I've tried to telnet on my local computer from the Openstack instance and it's showing the IP of the Openstack host, not the host. So I'm missing something in the network topology.</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-html lang-html prettyprint-override"><code>netstat -ant | grep 1716
tcp6       0      0 :::1716                 :::*                    LISTEN
tcp6       0      0 10.4.3.34:1716          10.4.4.1:42992          ESTABLISHED</code>```

Is there any type of network deployment I'm missing?
Any advice would be much appreciated!

答: If you are trying to access your instances from the "outside", you will need to create a floating IP pool and assign a floating IP to one of your instances.</p>

Body:
I'm having a hard time configuring an Openstack environment based on the All-In-One Single Machine installer for bridged networking in my LAN.

My objective is to SSH into the instances created in Openstack from my LAN.

The server is an Ubuntu 16.04 LTS with minimal installation and OpenSSH. The network configuration of the server is:

auto enp3s0
iface enp3s0 inet static
address 10.4.4.1
netmask 255.255.255.0
gateway 10.4.4.254
broadcast 10.4.4.255
network 10.4.4.0
dns-nameservers 10.4.1.12 10.4.1.10

Basically my network details are the following:

LAN 10.4.4.0
MASK 255.255.255.0
Gateway/DHCP Server  10.4.4.254

The local.conf file I've used for deploying the devstack is the following:

# Sample ``local.conf`` for user-configurable variables in ``stack.sh``

# NOTE: Copy this file to the root DevStack directory for it to work properly.

# ``local.conf`` is a user-maintained settings file that is sourced from ``stackrc``.
# This gives it the ability to override any variables set in ``stackrc``.
# Also, most of the settings in ``stack.sh`` are written to only be set if no
# value has already been set; this lets ``local.conf`` effectively override the
# default values.

# This is a collection of some of the settings we have found to be useful
# in our DevStack development environments. Additional settings are described
# in https://docs.openstack.org/devstack/latest/configuration.html#local-conf
# These should be considered as samples and are unsupported DevStack code.

# The ``localrc`` section replaces the old ``localrc`` configuration file.
# Note that if ``localrc`` is present it will be used in favor of this section.
[[local|localrc]]

# Minimal Contents
# ----------------

# While ``stack.sh`` is happy to run without ``localrc``, devlife is better when
# there are a few minimal variables set:

# If the ``*_PASSWORD`` variables are not set here you will be prompted to enter
# values for them by ``stack.sh``and they will be added to ``local.conf``.
FLOATING_RANGE=10.4.4.192/27
FIXED_RANGE=192.168.0.0/24
FIXED_NETWORK_SIZE=256
FLAT_INTERFACE=enp3s0
ADMIN_PASSWORD=nomoresecret
DATABASE_PASSWORD=stackdb
RABBIT_PASSWORD=stackqueue
SERVICE_PASSWORD=$ADMIN_PASSWORD

# ``HOST_IP`` and ``HOST_IPV6`` should be set manually for best results if
# the NIC configuration of the host is unusual, i.e. ``eth1`` has the default
# route but ``eth0`` is the public interface.  They are auto-detected in
# ``stack.sh`` but often is indeterminate on later runs due to the IP moving
# from an Ethernet interface to a bridge on the host. Setting it here also
# makes it available for ``openrc`` to include when setting ``OS_AUTH_URL``.
# Neither is set by default.
HOST_IP=10.4.4.1
#HOST_IPV6=2001:db8::7

# Logging
# -------

# By default ``stack.sh`` output only goes to the terminal where it runs.  It can
# be configured to additionally log to a file by setting ``LOGFILE`` to the full
# path of the destination log file.  A timestamp will be appended to the given name.
LOGFILE=$DEST/logs/stack.sh.log

# Old log files are automatically removed after 7 days to keep things neat.  Change
# the number of days by setting ``LOGDAYS``.
LOGDAYS=2

# Nova logs will be colorized if ``SYSLOG`` is not set; turn this off by setting
# ``LOG_COLOR`` false.
#LOG_COLOR=False

# Using milestone-proposed branches
# ---------------------------------

# Uncomment these to grab the milestone-proposed branches from the
# repos:
#CINDER_BRANCH=milestone-proposed
#GLANCE_BRANCH=milestone-proposed
#HORIZON_BRANCH=milestone-proposed
#KEYSTONE_BRANCH=milestone-proposed
#KEYSTONECLIENT_BRANCH=milestone-proposed
#NOVA_BRANCH=milestone-proposed
#NOVACLIENT_BRANCH=milestone-proposed
#NEUTRON_BRANCH=milestone-proposed
#SWIFT_BRANCH=milestone-proposed

# Using git versions of clients
# -----------------------------
# By default clients are installed from pip.  See LIBS_FROM_GIT in
# stackrc for details on getting clients from specific branches or
# revisions.  e.g.
# LIBS_FROM_GIT="python-ironicclient"
# IRONICCLIENT_BRANCH=refs/changes/44/2.../1

# Swift
# -----

# Swift is now used as the back-end for the S3-like object store. Setting the
# hash value is required and you will be prompted for it if Swift is enabled
# so just set it to something already:
SWIFT_HASH=66a3d6b56c1f479c8b4e70ab5c2000f5

# For development purposes the default of 3 replicas is usually not required.
# Set this to 1 to save some resources:
SWIFT_REPLICAS=1

# The data for Swift is stored by default in (``$DEST/data/swift``),
# or (``$DATA_DIR/swift``) if ``DATA_DIR`` has been set, and can be
# moved by setting ``SWIFT_DATA_DIR``. The directory will be created
# if it does not exist.
SWIFT_DATA_DIR=$DEST/data

At the end of the deployment I'm able to ping from the instance to my LAN and do nslookup on google.com for example, but I can't do it backwards, ping/ssh/telnet the instance in Openstack.
The security group permits all traffic, all ICMP ingress/egress, SSH from everywhere.

I've tried to telnet on my local computer from the Openstack instance and it's showing the IP of the Openstack host, not the host. So I'm missing something in the network topology.

netstat -ant | grep 1716
tcp6       0      0 :::1716                 :::*                    LISTEN
tcp6       0      0 10.4.3.34:1716          10.4.4.1:42992          ESTABLISHED

Is there any type of network deployment I'm missing?
Any advice would be much appreciated!


答:
That will find the first element matching that XPath, which is the one with the value 17. To select the element whose value is 18, try this:

```<code>driver.find_element_by_link_text('18').click()
</code>```

PS: You don't need to set the click event to a variable. Only do this if you need to multiple actions on the element (send_keys(), click(), text, etc.)

Title: Clicking using Python and Selenium

Body:
That will find the first element matching that XPath, which is the one with the value 17. To select the element whose value is 18, try this:

driver.find_element_by_link_text('18').click()

PS: You don't need to set the click event to a variable. Only do this if you need to multiple actions on the element (send_keys(), click(), text, etc.)


问:
Await.result on HttpService
I've a scala project with http4s 0.15.16a and slick 3.2.1 with these steps:

Receive a ID by rest call

passing ID to MySlickDAO  that responds with a Future

Call Await.result(res, Duration.Inf) on Future returned by MySlickDAO

Create the json

The problem is that I use a Await.result and this is bad practices
is there a better solution ?

Here the code:

```<code>  val service = HttpService {

//http://localhost:8080/rest/id/9008E75A-F112-396B-E050-A8C08D26075F
case GET -> Root / "rest" / "id" / id =>

  val res = MySlickDAO.load(id)

  Await.result(res, Duration.Inf)

  val ll = res.value.get.get
  ll match {
    case Failure(x) =>
      InternalServerError(x)
    case Success(record) =>
      val r = record.map(x => MyEntity(x._1, x._2, x._3))
      jsonOK(r.asJson)
  }
 case ....
</code>```

}

答:
The issue is that http4s 0.15 uses the Scalaz concurrency constructs, while Slick uses the native Scala ones, and the two aren't designed to work with each other. My understanding is that http4s 0.17+ has switched from Scalaz to Cats, which might entail using native Scala Futures, so if you can upgrade that might be worth a shot. If not, you can handle the conversion by manually creating a Task that wraps your future:

```<code>def scalaFutureRes = MySlickDAO.load(id)
val scalazTaskRes = Task.async { register =>
  scalaFutureRes.onComplete {
    case Success(success) => register(success.right)
    case Failure(ex)      => register(ex.left)
  }
}
</code>```

At this point you've got a Task[ResultType] from the Future[ResultType] which you can map/flatMap with the rest of your logic like in Levi's answer.

You can also use the delorean library for this which has this logic and the opposite direction defined on the classes in question via implicit conversions, so that you can just call .toTask on a Future to get it in a compatible form. Their readme also has a lot of useful information on the conversion and what pitfalls there are.

Title: Await.result on HttpService

Body:
I've a scala project with http4s 0.15.16a and slick 3.2.1 with these steps:

Receive a ID by rest call

passing ID to MySlickDAO  that responds with a Future

Call Await.result(res, Duration.Inf) on Future returned by MySlickDAO

Create the json

The problem is that I use a Await.result and this is bad practices
is there a better solution ?

Here the code:

  val service = HttpService {

//http://localhost:8080/rest/id/9008E75A-F112-396B-E050-A8C08D26075F
case GET -> Root / "rest" / "id" / id =>

  val res = MySlickDAO.load(id)

  Await.result(res, Duration.Inf)

  val ll = res.value.get.get
  ll match {
    case Failure(x) =>
      InternalServerError(x)
    case Success(record) =>
      val r = record.map(x => MyEntity(x._1, x._2, x._3))
      jsonOK(r.asJson)
  }
 case ....

}

Body:
The issue is that http4s 0.15 uses the Scalaz concurrency constructs, while Slick uses the native Scala ones, and the two aren't designed to work with each other. My understanding is that http4s 0.17+ has switched from Scalaz to Cats, which might entail using native Scala Futures, so if you can upgrade that might be worth a shot. If not, you can handle the conversion by manually creating a Task that wraps your future:

def scalaFutureRes = MySlickDAO.load(id)
val scalazTaskRes = Task.async { register =>
  scalaFutureRes.onComplete {
    case Success(success) => register(success.right)
    case Failure(ex)      => register(ex.left)
  }
}

At this point you've got a Task[ResultType] from the Future[ResultType] which you can map/flatMap with the rest of your logic like in Levi's answer.

You can also use the delorean library for this which has this logic and the opposite direction defined on the classes in question via implicit conversions, so that you can just call .toTask on a Future to get it in a compatible form. Their readme also has a lot of useful information on the conversion and what pitfalls there are.


问:
Mocking a @Bean defined in a @ConfigurationProperties Class
I have a @ConfigurationProperties class like this:

```<code>@ConfigurationProperties(prefix = "myprops", ignoreUnknownFields = false)
@Configuration
public class MyProperties {

   private Long mySchedulerRate;

   @Bean
   public Long mySchedulerRate() {
       return this.mySchedulerRate;
   }

}
</code>```

I'm registering it as a bean so I can refer to it in an annotation for a Spring scheduler:

```<code>@Scheduled(fixedRateString = "#{@mySchedulerRate}")
public void runScheduledUpdate() {
   ...
{
</code>```

However, I now want to write a unit test where I want to be able to set a different value for the bean 'mySchedulerRate'. Mocking/Spying on the @ConfigurationProperties class doesnt seem to work since the scheduler gets set up before the stubbing has been set to return my desired value.

What is the easiest way to achieve what I am trying to do?

答:
Managed to fix this now. I was running a @SpringBootTest and I realise you can override properties here within the annotation for a particular test class.

This worked for me:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class, properties = "myprops.my-scheduler-rate=1000")
public class MyTest {
</code>```

So no need to try and override the bean, I was overcomplicating this far too much.

Body:
I have a @ConfigurationProperties class like this:

@ConfigurationProperties(prefix = "myprops", ignoreUnknownFields = false)
@Configuration
public class MyProperties {

   private Long mySchedulerRate;

   @Bean
   public Long mySchedulerRate() {
       return this.mySchedulerRate;
   }

}

I'm registering it as a bean so I can refer to it in an annotation for a Spring scheduler:

@Scheduled(fixedRateString = "#{@mySchedulerRate}")
public void runScheduledUpdate() {
   ...
{

However, I now want to write a unit test where I want to be able to set a different value for the bean 'mySchedulerRate'. Mocking/Spying on the @ConfigurationProperties class doesnt seem to work since the scheduler gets set up before the stubbing has been set to return my desired value.

What is the easiest way to achieve what I am trying to do?

Body:
Managed to fix this now. I was running a @SpringBootTest and I realise you can override properties here within the annotation for a particular test class.

This worked for me:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class, properties = "myprops.my-scheduler-rate=1000")
public class MyTest {

So no need to try and override the bean, I was overcomplicating this far too much.


问:
INNO Setup: How to implement file update based on different versions of the application
I have an application written in Delphi that has several versions that contain binaries and database (MDB) with catalog data.

During the product life cycle fixes/enhancements are either in database file or in some binary files.

Version are preserved in Registry.

Users might have different versions of the program when new patch is available.

Now users have different versions how to implement following scenario in Inno Setup:

If user have version A prevent installation.

If user have version B copy db over and file1, file2, file3.

If user have version C just update file1.

What is the correct way to implement this in Inno setup?

答:
You can create functions for checking the version.

See this website for more details
(http://agiletracksoftware.com/blog.html?id=4)

```<code>[Code]
; Each data file contains a single value and can be loaded after extracted.
; The filename and DestDir from the [Files] section must match the names
; and locations used here
function GetAppMajorVersion(param: String): String;
     var
          AppVersion: String;
     begin
          ExtractTemporaryFile('major.dat');
          LoadStringFromFile(ExpandConstant('{tmp}\major.dat'), AppVersion);
          Result := AppVersion;
     end;

function GetAppMinorVersion(param: String): String;
     var
          AppMinorVersion: String;
     begin
          ExtractTemporaryFile('minor.dat');
          LoadStringFromFile(ExpandConstant('{tmp}\minor.dat'), AppMinorVersion);
          Result := AppMinorVersion;
     end;

function GetAppCurrentVersion(param: String): String;
     var
          BuildVersion: String;
     begin
          ExtractTemporaryFile('build.dat');
          LoadStringFromFile(ExpandConstant('{tmp}\build.dat'), BuildVersion);
          Result := BuildVersion;
     end;
</code>```

Code extract from AgileTrack Blog:
Using Inno Setup to Create a Versioned Installer

OwnerDisplayName: Irfan Mulic

Body:
You can create functions for checking the version.

See this website for more details
(http://agiletracksoftware.com/blog.html?id=4)

[Code]
; Each data file contains a single value and can be loaded after extracted.
; The filename and DestDir from the [Files] section must match the names
; and locations used here
function GetAppMajorVersion(param: String): String;
     var
          AppVersion: String;
     begin
          ExtractTemporaryFile('major.dat');
          LoadStringFromFile(ExpandConstant('{tmp}\major.dat'), AppVersion);
          Result := AppVersion;
     end;

function GetAppMinorVersion(param: String): String;
     var
          AppMinorVersion: String;
     begin
          ExtractTemporaryFile('minor.dat');
          LoadStringFromFile(ExpandConstant('{tmp}\minor.dat'), AppMinorVersion);
          Result := AppMinorVersion;
     end;

function GetAppCurrentVersion(param: String): String;
     var
          BuildVersion: String;
     begin
          ExtractTemporaryFile('build.dat');
          LoadStringFromFile(ExpandConstant('{tmp}\build.dat'), BuildVersion);
          Result := BuildVersion;
     end;

Code extract from AgileTrack Blog:
Using Inno Setup to Create a Versioned Installer

OwnerDisplayName: golimpio

LastEditorDisplayName: golimpio


问:
Renaming Multiple Files on macOS Terminal
Is it possible to rename multiple files that share a similar name but are different types of files all at once?

Example:

apple.png

apple.pdf

apple.jpg

Can I substitute the apple for something else, for example "pear"? If this is possible, what would the command be? Many thanks for your time!

答:
You can do this in bash natively by looping over the files beginning apple and renaming each one in turn using bash parameter expansion

```<code>$ for f in apple*; do mv "$f" "${f/apple/pear}"; done
</code>```

The for f in apple* finds all files matching the wildcard. Each filename is then assigned to the variable f
For each assignment to f bash calls the command mv to move (rename) the file from it's existing name to one where apple is replaced by pear

You could also install rename using a package manager like Homebrew and call

```<code>rename -e 's/apple/pear/' apple*
</code>```

Body:
You can do this in bash natively by looping over the files beginning apple and renaming each one in turn using bash parameter expansion

$ for f in apple*; do mv "$f" "${f/apple/pear}"; done

The for f in apple* finds all files matching the wildcard. Each filename is then assigned to the variable f
For each assignment to f bash calls the command mv to move (rename) the file from it's existing name to one where apple is replaced by pear

You could also install rename using a package manager like Homebrew and call

rename -e 's/apple/pear/' apple*


问:
How to overwrite version of transitive dependency Groovy from Thymeleaf 1.5.8.RELEASE in Spring Boot using Gradle
I'm kinda new in the Gradle world. As part of a security audit we are having, we were told the following dependency in one of your Gradle projects:

```<code>compile(group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '1.5.8.RELEASE')
</code>```

is using the transitive dependency for Groovy 2.4.7, but since that version has some security vulnerabilities (https://nvd.nist.gov/vuln/detail/CVE-2016-6497), we need to override the Groovy version for a newer one.

This is the dependency tree for that section:

```<code>org.springframework.boot.spring-boot-starter-thymeleaf-1.4.1.RELEASE ( /opt/whitehat/satellite/applications/9400/src/10280/pom.xml [line 36, column 15] )
    - nz.net.ultraq.thymeleaf.thymeleaf-layout-dialect-1.4.0 ( /opt/whitehat/satellite/applications/9400/src/10280/pom.xml [line 36, column 15] )
        - org.codehaus.groovy.groovy-2.4.7
</code>```

How to override the Groovy version from 2.4.7 to a higher version?

I have tried the following but it's not working:

```<code>compile(group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '1.5.8.RELEASE') {
    exclude(module: 'groovy')
}

compile group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.12'
</code>```

答:
If it is because of security concerns, I'd use a resolution strategy to make sure noone accidentally adds this version to any configuration like this:</p>

```<code>configurations.all {
    resolutionStrategy {
        dependencySubstitution {
            substitute module('org.codehaus.groovy:groovy:2.4.7') with module('org.codehaus.groovy:groovy:2.4.12')
        }
    }
}
</code>```

Body:
I'm kinda new in the Gradle world. As part of a security audit we are having, we were told the following dependency in one of your Gradle projects:

compile(group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '1.5.8.RELEASE')

is using the transitive dependency for Groovy 2.4.7, but since that version has some security vulnerabilities (https://nvd.nist.gov/vuln/detail/CVE-2016-6497), we need to override the Groovy version for a newer one.

This is the dependency tree for that section:

org.springframework.boot.spring-boot-starter-thymeleaf-1.4.1.RELEASE ( /opt/whitehat/satellite/applications/9400/src/10280/pom.xml [line 36, column 15] )
    - nz.net.ultraq.thymeleaf.thymeleaf-layout-dialect-1.4.0 ( /opt/whitehat/satellite/applications/9400/src/10280/pom.xml [line 36, column 15] )
        - org.codehaus.groovy.groovy-2.4.7

How to override the Groovy version from 2.4.7 to a higher version?

I have tried the following but it's not working:

compile(group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version: '1.5.8.RELEASE') {
    exclude(module: 'groovy')
}

compile group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.12'

Body:
If it is because of security concerns, I'd use a resolution strategy to make sure noone accidentally adds this version to any configuration like this:

configurations.all {
    resolutionStrategy {
        dependencySubstitution {
            substitute module('org.codehaus.groovy:groovy:2.4.7') with module('org.codehaus.groovy:groovy:2.4.12')
        }
    }
}


问:
"No module named scipy" on Windows
In sklearn\base.py, I have the statement from scipy import sparse.
I am getting this error "no module named scipy".

I tried to install using pip install scipy, but I get so many errors:

```<code>libraries mkl_rt not found
openblas not found
lapack not found
no lapacl/blas resources found
</code>```

etc.

What should I do on Windows?

答:
numpy should be installed before installing scipy. I face this issue when I was running only with numpy. First install numpy and then install scipy. It worked for me.

```<code>pip install numpy

pip install scipy
</code>```

It will display a message like this.

Requirement already satisfied: numpy>=1.8.2 in
   (from scipy)

Hope this would be helpful. :)

Title: "No module named scipy" on Windows

Body:
In sklearn\base.py, I have the statement from scipy import sparse.
I am getting this error "no module named scipy".

I tried to install using pip install scipy, but I get so many errors:

libraries mkl_rt not found
openblas not found
lapack not found
no lapacl/blas resources found

etc.

What should I do on Windows?

Body:
numpy should be installed before installing scipy. I face this issue when I was running only with numpy. First install numpy and then install scipy. It worked for me.

pip install numpy

pip install scipy

It will display a message like this.

Requirement already satisfied: numpy>=1.8.2 in
   (from scipy)

Hope this would be helpful. :)


问:
Is there a keyboard shortcut (hotkey) to open Terminal in macOS?
One of my primary tools used for programming is my Terminal. It makes my programming process more efficient when I'm able to quickly open a Terminal window.

In Ubuntu, I was using (window+Alt+T) to open Terminal. But now I use a Macbook at my programming job.

Sometimes I use Spotlight to search "Terminal", and press Enter.

I'd like to know if I can assign a keyboard hotkey to do it.

答:
As programmers we want the quickest, most fool-proof way to get our tools in order so we can start hacking. Here are how I got it to work in macOS 10.13.1 (High Sierra):

Option 1: Go to System Preferences | Keyboard | Shortcut | Services.
Under Files and Folders section, enable New Terminal at Folder
and/or New Terminal Tab at Folder and assign a shortcut key to it.

Option 2: If you want the shortcut key to work anywhere, create a new Service using Automator, then go to the Keyboard Shortcut to assign a shortcut key to it. Known limitation: not work from the desktop

Notes:

If the shortcut doesn't work, it might be in conflict with another
key binding (and the OS wouldn't warn you), try something else, e.g.
if ⇧⌥T doesn't work, try ⇧⌘T.


问:
Checking for null value with DataTable.Select
I'm using a DataTable select like this:

```<code>DataRow[] rows = employees.Select("Name LIKE '%" + TB_Search.Text + "%'");

LV_Employees.DataSource = rows;
LV_Employees.DataBind();
</code>```

I have a listview where I'm checking a value that is contained in the datarows that I'm using in the list and I'm checking a value like this:

```<code><%# Eval("Title") == DBNull.Value ? "" : Eval("Title") %>
</code>```

But when I do this I still get this error:

Unable to cast object of type 'System.DBNull' to type 'System.String'.

I tried checking Eval("Title") == null as well and got the same error. I'm not sure how else to check for the null values that would fix this issue.

Things I've also tried that still gave the same error:

(Eval("Title") as string) ?? ""

Convert.IsDBNull(Eval("Title")) ? "" : "test"

string.IsNullOrEmpty(Eval("Title").ToString()) ? "" : "test"

Eval("Title").ToString().IsNullOrEmpty() ? "" : "test"

答:
Doing this in the codebehind worked, but seems weird that I can't just do the inline check in the markup code.</p>

```<code>foreach (DataRow r in rows)
{
    if (r["Title"] == DBNull.Value)
        r["Title"] = "";
}
</code>```

Body:
I'm using a DataTable select like this:

DataRow[] rows = employees.Select("Name LIKE '%" + TB_Search.Text + "%'");

LV_Employees.DataSource = rows;
LV_Employees.DataBind();

I have a listview where I'm checking a value that is contained in the datarows that I'm using in the list and I'm checking a value like this:

<%# Eval("Title") == DBNull.Value ? "" : Eval("Title") %>

But when I do this I still get this error:

Unable to cast object of type 'System.DBNull' to type 'System.String'.

I tried checking Eval("Title") == null as well and got the same error. I'm not sure how else to check for the null values that would fix this issue.

Things I've also tried that still gave the same error:

(Eval("Title") as string) ?? ""

Convert.IsDBNull(Eval("Title")) ? "" : "test"

string.IsNullOrEmpty(Eval("Title").ToString()) ? "" : "test"

Eval("Title").ToString().IsNullOrEmpty() ? "" : "test"

Body:
Doing this in the codebehind worked, but seems weird that I can't just do the inline check in the markup code.

foreach (DataRow r in rows)
{
    if (r["Title"] == DBNull.Value)
        r["Title"] = "";
}


问:
JavaScript Error...Not creating elements when the button is clicked
My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:

```<code>submitButton.addEventListener("click", () => {
        var newTable = document.createElement("table");
        for(let i = 0; i < parseInt(numOfStudents); i++){
            var newRow = document.createElement("tr");
            var newInput = document.createElement("td");
            var newInput2 = document.createElement("td");
            document.newRow.appendChild(newInput);
            document.newRow.appendChild(newInput2);
            document.newTable.appendChild(newRow);
            document.body.appendChild(newTable);
        }
    });
</code>```

答:
U just need to add some text into it..otherwise you won't see it (unless you open the dev console).

Here is an example:

// Helpers
const createElement = el => document.createElement(el)
const createText = text => document.createTextNode(text)

// Create rows
const addStudentRows = students => {
  const $body = document.querySelector('body')

  const $table = createElement('table')

  for (let i = 0; i < students;i++ ) {
    let $td1 = createElement('td')
    let $td2 = createElement('td')

    $td1.appendChild(createText('Hello'))
    $td2.appendChild(createText('World'))

    let $tr = createElement('tr')
    $tr.appendChild($td1)
    $tr.appendChild($td2)

    $table.appendChild($tr)
  }

  $body.appendChild($table)
}

// Event listener
document.querySelector('button')
  .addEventListener('click', e => addStudentRows(1))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
  margin-bottom: 10px;
}

table tr td {
  padding: 10px;
  border-right:1px solid #f0f0f0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

table tr td:first-child {
  border-left:1px solid #f0f0f0;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

  <button>Click here</button>

```

Body:
My code look like this, It should have created a table when the "submitButton" was clicked but it doesn't do so. Here is my code:

submitButton.addEventListener("click", () => {
        var newTable = document.createElement("table");
        for(let i = 0; i < parseInt(numOfStudents); i++){
            var newRow = document.createElement("tr");
            var newInput = document.createElement("td");
            var newInput2 = document.createElement("td");
            document.newRow.appendChild(newInput);
            document.newRow.appendChild(newInput2);
            document.newTable.appendChild(newRow);
            document.body.appendChild(newTable);
        }
    });

Body:
U just need to add some text into it..otherwise you won't see it (unless you open the dev console).

Here is an example:

// Helpers
const createElement = el => document.createElement(el)
const createText = text => document.createTextNode(text)

// Create rows
const addStudentRows = students => {
  const $body = document.querySelector('body')

  const $table = createElement('table')

  for (let i = 0; i < students;i++ ) {
    let $td1 = createElement('td')
    let $td2 = createElement('td')

    $td1.appendChild(createText('Hello'))
    $td2.appendChild(createText('World'))

    let $tr = createElement('tr')
    $tr.appendChild($td1)
    $tr.appendChild($td2)

    $table.appendChild($tr)
  }

  $body.appendChild($table)
}

// Event listener
document.querySelector('button')
  .addEventListener('click', e => addStudentRows(1))

table {
  margin-bottom: 10px;
}

table tr td {
  padding: 10px;
  border-right:1px solid #f0f0f0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

table tr td:first-child {
  border-left:1px solid #f0f0f0;
}

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <button>Click here</button>
</body>
</html>


问:
tables export into to csv files
In laravel 5.5 project I want some my tables export into to csv files and I get this http://www.maatwebsite.nl/laravel-excel/docs/export#export library
with code like:

```<code>$path = $directoriesArray[count($directoriesArray)-1];
Excel::create($filename, function($excel) use($dataArray) {
    $excel->sheet('file', function($sheet)  use($dataArray) {
        $sheet->fromArray( $dataArray );
    });
})->store('csv', $path)->export('csv');
</code>```

I upload 1 file ok, but as I need to upload several tables any
to the relative file I run the exporting function in a circle
and only the first file is uploaded. Is it restriction of the
browser(I tried in chromium, firefox) or if is the way to upload all files?

1) If there is a way just to write this csv file to disk without uploading?

2) If there is some way to make kind of buffering ( like ob_start ) of output data and write them to the files manually?

3) If there is some other tools that could do this?

Thanks!

答:
The decision was :

```<code>})->store('csv', $path);
</code>```

without

```<code>->export('csv')
</code>```

:)

Title: tables export into to csv files

Body:
In laravel 5.5 project I want some my tables export into to csv files and I get this http://www.maatwebsite.nl/laravel-excel/docs/export#export library
with code like:

$path = $directoriesArray[count($directoriesArray)-1];
Excel::create($filename, function($excel) use($dataArray) {
    $excel->sheet('file', function($sheet)  use($dataArray) {
        $sheet->fromArray( $dataArray );
    });
})->store('csv', $path)->export('csv');

I upload 1 file ok, but as I need to upload several tables any
to the relative file I run the exporting function in a circle
and only the first file is uploaded. Is it restriction of the
browser(I tried in chromium, firefox) or if is the way to upload all files?

1) If there is a way just to write this csv file to disk without uploading?

2) If there is some way to make kind of buffering ( like ob_start ) of output data and write them to the files manually?

3) If there is some other tools that could do this?

Thanks!

Body:
The decision was :

})->store('csv', $path);

without

->export('csv')

:)


问:
Recordset Not Iterating
I am sure this is strictly user error, but for the life of me, I can not discover how to iterate a table, and write the records to Excel.  I have the below code, but it hangs on the first Manager ID and just repeats the write for that one constantly in a loop.  I want to iterate all the Manager ID in the table and write them to the same workbook.

How should I tweak this code in order to do such?

```<code>  Set xlR = xlWb.Worksheets(1).Range("$R$2")
  i=0
  Set rs2 = Db.OpenRecordset("SELECT * FROM TestTable ORDER BY [Manager ID] ASC", dbOpenDynaset)
  managerName = CLng(rs2.Fields(3).Value)
  Debug.Print managerName
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1 + (i * 2)).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2 + (i * 2)).Value = "ENTATH01"
        i = i + 1
        .MoveNext
     Loop
     .Close
  End With
  xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
  xlWb.Close SaveChanges:=True
  rs2.MoveNext
</code>```

答:
You're not changing your offset, so you're continuously assigning the  same cell.

Try the following:

```<code>    xlR.Offset(ColumnOffset:=i * 3).Value
    xlR.Offset(ColumnOffset:=1+(i*3)).Value = .Fields(2).Value
    xlR.Offset(ColumnOffset:=2+(i*3)).Value = "ENTATH01"
</code>```

I assume you're initializing i to 0

Title: Recordset Not Iterating

Body:
I am sure this is strictly user error, but for the life of me, I can not discover how to iterate a table, and write the records to Excel.  I have the below code, but it hangs on the first Manager ID and just repeats the write for that one constantly in a loop.  I want to iterate all the Manager ID in the table and write them to the same workbook.

How should I tweak this code in order to do such?

  Set xlR = xlWb.Worksheets(1).Range("$R$2")
  i=0
  Set rs2 = Db.OpenRecordset("SELECT * FROM TestTable ORDER BY [Manager ID] ASC", dbOpenDynaset)
  managerName = CLng(rs2.Fields(3).Value)
  Debug.Print managerName
  With rs2
     .MoveLast
     .MoveFirst
     Do While Not .EOF
        xlR.Value = .Fields(0).Value
        xlR.Offset(ColumnOffset:=1 + (i * 2)).Value = .Fields(2).Value
        xlR.Offset(ColumnOffset:=2 + (i * 2)).Value = "ENTATH01"
        i = i + 1
        .MoveNext
     Loop
     .Close
  End With
  xlWb.SaveAs FileName:=sPath & sFile, FileFormat:=xlOpenXMLWorkbook
  xlWb.Close SaveChanges:=True
  rs2.MoveNext

Body:
You're not changing your offset, so you're continuously assigning the  same cell.

Try the following:

    xlR.Offset(ColumnOffset:=i * 3).Value
    xlR.Offset(ColumnOffset:=1+(i*3)).Value = .Fields(2).Value
    xlR.Offset(ColumnOffset:=2+(i*3)).Value = "ENTATH01"

I assume you're initializing i to 0