问:
How to avoid module conflicts in Rails?
I have model in rails app named Benchmark, although ruby requires its Benchmark module by default when starting process.

Is there anyway I can unload Benchmark module in order to use my Benchmark model?

答:
It's generally possible to unbind Ruby constants from their original names using logic like this:

```<code>require "benchmark"

BM = Benchmark
Object.send(:remove_const, :Benchmark)

class Benchmark
  def initialize
    puts "Hey, I'm your custom Benchmark"
  end

  ...
end
</code>```

However, specifically for the original Benchmark implementation this won't work, as it's internally full of name references like this one:

```<code>@list << res = Benchmark.measure(label, &blk)
</code>```

The best practical solution is to pick a "free" synonym to name your model.

Title: How to avoid module conflicts in Rails?

Body:
It's generally possible to unbind Ruby constants from their original names using logic like this:

require "benchmark"

BM = Benchmark
Object.send(:remove_const, :Benchmark)

class Benchmark
  def initialize
    puts "Hey, I'm your custom Benchmark"
  end

  ...
end

However, specifically for the original Benchmark implementation this won't work, as it's internally full of name references like this one:

@list << res = Benchmark.measure(label, &blk)

The best practical solution is to pick a "free" synonym to name your model.


来源: stackexchange

问:
Should I commit yarn.lock and package-lock.json files?
We're using yarn for all our deterministic pkg installations but don't prevent the user from using npm - I'm guessing having both these files will cause issues however. Should one be added to your .gitignore dir?</p>

答:
Always commit dependency lock files in general

As is covered elsewhere, dependency lock files, which are supported by many package management systems (e.g.:
 composer and bundler), should be committed to the codebase in end-of-chain projects - so that each individual trying to run that project is doing so with exactly the tested set of dependencies.

It's less clear whether lock files should always be committed into packages that are intended to be included in other projects (where looser dependencies are desirable). However, both Yarn and NPM (as covered by @Cyrille) intelligently ignore yarn.lock and package-lock.json respectively where necessary, making it safe to always commit these lockfiles.

So you should always commit at least one of yarn.lock or package-lock.json depending on which package manager you're using.

Should you commit both yarn.lock and package-lock.json?

At present we have two different package management systems, which both install the same set of dependencies from package.json, but which generate and read from two different lockfiles. NPM 5 generates package-lock.json, whereas Yarn generates yarn.lock.

If you commit package-lock.json then you're building in support for people installing your dependencies with NPM 5. If you commit yarn.lock, you're building in support for people installing dependencies with Yarn.

Whether you choose to commit yarn.lock or package-lock.json or both depends on whether those developing on your project are only using Yarn or NPM 5 or both. If your project is open-source, the most community-friendly thing to do would probably be to commit both and have an automated process to ensure yarn.lock and package-lock.json always stay in sync.

Update: Yarn have now introduced an import command which will generate a yarn.lock file from a package-lock.json file. This could be useful for keeping the two files in sync. (Thanks @weakish)

This issues was discussed at length on the Yarn project in:

"Idea: support package-lock.json from npm 5"

"Competing lockfiles create poor UX"

Both are now closed.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
python error on npm package install Windows
On Windows, When I try to install wdio, I have a python error :
but python is installed and in the path.
the PYTHON variable is set to "C:\Program Files\Python36\python.exe", which is a correct path.
I don't know where the error is coming from, since it says it can find the executable, bit show the right path to the executable.</p>

```<code>PS C:\Users\admin> npm install wdio

> fibers@1.0.15 install C:\Users\admin\node_modules\fibers
> node build.js || nodejs build.js

C:\Users\admin\node_modules\fibers>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild --release )  else (node "" rebuild --release )
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "C:\Program Files\Python36\python.exe", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:483:19)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:508:16)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:152:21)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--release"
gyp ERR! cwd C:\Users\admin\node_modules\fibers
gyp ERR! node -v v8.0.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok
node-gyp exited with code: 1
Please make sure you are using a supported platform and node version. If you
would like to compile fibers on this machine please make sure you have setup your
build environment--
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\admin\package.json'
</code>```

答: You need to install Python 2.7 since node-gyp is not compatible with Python 3.x. See e.g. https://github.com/nodejs/node-gyp#on-windows</p>

Body:
On Windows, When I try to install wdio, I have a python error :
but python is installed and in the path.
the PYTHON variable is set to "C:\Program Files\Python36\python.exe", which is a correct path.
I don't know where the error is coming from, since it says it can find the executable, bit show the right path to the executable.

PS C:\Users\admin> npm install wdio

> fibers@1.0.15 install C:\Users\admin\node_modules\fibers
> node build.js || nodejs build.js

C:\Users\admin\node_modules\fibers>if not defined npm_config_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild --release )  else (node "" rebuild --release )
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "C:\Program Files\Python36\python.exe", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:483:19)
gyp ERR! stack     at PythonFinder.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:508:16)
gyp ERR! stack     at C:\Program Files\nodejs\node_modules\npm\node_modules\graceful-fs\polyfills.js:284:29
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:152:21)
gyp ERR! System Windows_NT 10.0.15063
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--release"
gyp ERR! cwd C:\Users\admin\node_modules\fibers
gyp ERR! node -v v8.0.0
gyp ERR! node-gyp -v v3.6.1
gyp ERR! not ok
node-gyp exited with code: 1
Please make sure you are using a supported platform and node version. If you
would like to compile fibers on this machine please make sure you have setup your
build environment--
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\admin\package.json'


问:
java.io.IOException: Server returned HTTP response code: 400 for URL? why am getting this exception
i have a method to send sms to bulk members
here is my java method

```<code>public void sendSMS(String mobilno,String msg)
{
    URLConnection myURLConnection=null;
    URL myURL=null;
    BufferedReader reader=null;
    String mainUrl="http://smsstreet.in/websms/sendsms.aspx?userid=id&password=pwd&sender=sender&mobileno="+mobilno+"&msg="+msg;
    StringBuilder sbPostData= new StringBuilder(mainUrl);
    mainUrl = sbPostData.toString();
    try
    {

        myURL = new URL(mainUrl);
        myURLConnection = myURL.openConnection();
        myURLConnection.connect();
        reader= new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
        String response;
        while ((response = reader.readLine()) != null)
        System.out.println(response);
        reader.close();
    }
    catch (IOException e)
    {
            e.printStackTrace();
    }
}
</code>```

here is my servlrt:

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    // TODO Auto-generated method stub
    String mobilnmbers=request.getParameter("mobName");
    System.out.println(mobilnmbers);
    String message=request.getParameter("comment");
    System.out.println(message);
    SMSMethod sms=new SMSMethod();
    sms.sendSMS(mobilnmbers, message);
}
</code>```

when i call it into servlet its giving following exception

```<code>java.io.IOException: Server returned HTTP response code: 400 for URL: http://smsstreet.in/websms/sendsms.aspx?userid=id&password=pwd&sender=sender&mobileno=9014780300,8309518663,9920221173,9849133273,9849656287,7013083104,8759197399,1234567890,8096613756,7075472796,8121104305,9182176200,9949327590,8309490418,9949913331,8125206381,9550371787,9502167674,9912193234,9912193234,9700237487,9246563935&msg=Have you started booking the train tickets
</code>```

i am new to this smsGatway can anyone help me?

答:
Add:
    String mainUrl = mainUrl.replaceAll(" ", "%20");

After this line:
    String mainUrl="http://smsstreet.in/..."

Body:
i have a method to send sms to bulk members
here is my java method

public void sendSMS(String mobilno,String msg)
{
    URLConnection myURLConnection=null;
    URL myURL=null;
    BufferedReader reader=null;
    String mainUrl="http://smsstreet.in/websms/sendsms.aspx?userid=id&password=pwd&sender=sender&mobileno="+mobilno+"&msg="+msg;
    StringBuilder sbPostData= new StringBuilder(mainUrl);
    mainUrl = sbPostData.toString();
    try
    {

        myURL = new URL(mainUrl);
        myURLConnection = myURL.openConnection();
        myURLConnection.connect();
        reader= new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
        String response;
        while ((response = reader.readLine()) != null)
        System.out.println(response);
        reader.close();
    }
    catch (IOException e)
    {
            e.printStackTrace();
    }
}

here is my servlrt:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    // TODO Auto-generated method stub
    String mobilnmbers=request.getParameter("mobName");
    System.out.println(mobilnmbers);
    String message=request.getParameter("comment");
    System.out.println(message);
    SMSMethod sms=new SMSMethod();
    sms.sendSMS(mobilnmbers, message);
}

when i call it into servlet its giving following exception

java.io.IOException: Server returned HTTP response code: 400 for URL: http://smsstreet.in/websms/sendsms.aspx?userid=id&password=pwd&sender=sender&mobileno=9014780300,8309518663,9920221173,9849133273,9849656287,7013083104,8759197399,1234567890,8096613756,7075472796,8121104305,9182176200,9949327590,8309490418,9949913331,8125206381,9550371787,9502167674,9912193234,9912193234,9700237487,9246563935&msg=Have you started booking the train tickets

i am new to this smsGatway can anyone help me?


问:
Drop Down in Selenium
I am automating one application and I have many drop downs in one of the webpage. All of the drop downs have a common class name also i can see no id associated with them.

I am able to select value from the first dropdown with no issues. Problem comes when i am trying to click second drop down. Due to common class name it is clicking first drop down only. Any solutions for that.

Code I have tried so far for first drop down:

driver.findElement(By.xpath("//div["class=Say class A']")).click();

TIA

答:
This should work:

driver.findElement(By.xpath("(//div["class=Say class A'])[2]")).click();

Title: Drop Down in Selenium


问:
Re Duplicates in Oracle query
I have a requirement to include Student details along with Postcode and Borough in my query.

Query gives correct results when I include the Postcode.

```<code>SELECT DISTINCT
 t1.StuID,
 t1.Forename,
 t1.Surname,
 t1.dob,
 t2.a_reference "Postcode",
  FROM
student t1, address t2
WHERE t1.s_address = t2.a_id

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU
</code>```

However, When I add the Borough field I see duplicates as below

```<code>    SELECT DISTINCT
     t1.StuID,
     t1.Forename,
     t1.Surname,
     t1.dob,
     t2.a_reference "Postcode",
     MAX(t.el_name) "Borough" -- Using Max so as to get most recent value for Borough
     FROM
    student t1, address t2, lookup t3
    WHERE
 WHERE t1.s_address = t2.a_id AND
    t2.a_reference (+) = t3.el_reference
     GROUP BY t1.StuID, t1.Forename, t1.Surname,
     t1.dob, t2.a_reference, t3.el_name

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Barnsbury
AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Islington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Tollington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Islington
</code>```

Any idea where am I going wrong?

Thanks
Ar

答:
MAX() does NOT give "most recent" value, it returns the maximum, which could be "Westminster" even if the person is currently addressed at "Barking".

Please stop using commas between table names in the FROM clause. Over 25 years ago (ANSI-92) better join syntax was adopted as standard.

If you are using GROUP BY then "select distinct" is 100% utterly useless and redundant. GROUP BY ensure the rows are unique by itself, it does not need "select distinct" as well (plus, GROUP BY is performed before the "select distinct").

To get the "most recent" address you need to reference the date field that we see in results shown in the question, but which isn't listed in ether query. Take that table and make it a subquery instead. In that subquery use ROW_NUMBER() OVER().

The following is a GUESS because the details of your tables aren't revealed in the question. I am not expecting this suggested query to work "as is" - it will need to be "interpreted".

```<code>SELECT
      t1.StuID
    , t2.a_reference "Postcode"
    , t.el_name "Borough"
FROM student t1
INNER JOIN (
      SELECT
            a_reference
          , date_of_address_change
          , ROW_NUMBER() OVER (PARTITION BY a_reference
                               ORDER BY date_of_address_change DESC) AS rn
      FROM address
      ) t2 ON t1.s_address = t2.a_id AND rn = 1
LEFT JOIN lookup t3 ON t2.a_reference = t3.el_reference
</code>```

Using order by inside the OVER() we can locate a "most recent" row and then return only that row by the "AND RN = 1" of the join to the subquery.

Title: Re Duplicates in Oracle query

Body:
I have a requirement to include Student details along with Postcode and Borough in my query.

Query gives correct results when I include the Postcode.

SELECT DISTINCT
 t1.StuID,
 t1.Forename,
 t1.Surname,
 t1.dob,
 t2.a_reference "Postcode",
  FROM
student t1, address t2
WHERE t1.s_address = t2.a_id

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU

However, When I add the Borough field I see duplicates as below

    SELECT DISTINCT
     t1.StuID,
     t1.Forename,
     t1.Surname,
     t1.dob,
     t2.a_reference "Postcode",
     MAX(t.el_name) "Borough" -- Using Max so as to get most recent value for Borough
     FROM
    student t1, address t2, lookup t3
    WHERE
 WHERE t1.s_address = t2.a_id AND
    t2.a_reference (+) = t3.el_reference
     GROUP BY t1.StuID, t1.Forename, t1.Surname,
     t1.dob, t2.a_reference, t3.el_name

O/P:

AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Barnsbury
AC24340 MITCHELL ACKERMAN     21-OCT-99    N1 1HH          Islington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Tollington
AB48765 KEANUE   SETTLE       17-JUL-97    N19 4EU         Islington

Any idea where am I going wrong?

Thanks
Ar

Body:
MAX() does NOT give "most recent" value, it returns the maximum, which could be "Westminster" even if the person is currently addressed at "Barking".

Please stop using commas between table names in the FROM clause. Over 25 years ago (ANSI-92) better join syntax was adopted as standard.

If you are using GROUP BY then "select distinct" is 100% utterly useless and redundant. GROUP BY ensure the rows are unique by itself, it does not need "select distinct" as well (plus, GROUP BY is performed before the "select distinct").

To get the "most recent" address you need to reference the date field that we see in results shown in the question, but which isn't listed in ether query. Take that table and make it a subquery instead. In that subquery use ROW_NUMBER() OVER().

The following is a GUESS because the details of your tables aren't revealed in the question. I am not expecting this suggested query to work "as is" - it will need to be "interpreted".

SELECT
      t1.StuID
    , t2.a_reference "Postcode"
    , t.el_name "Borough"
FROM student t1
INNER JOIN (
      SELECT
            a_reference
          , date_of_address_change
          , ROW_NUMBER() OVER (PARTITION BY a_reference
                               ORDER BY date_of_address_change DESC) AS rn
      FROM address
      ) t2 ON t1.s_address = t2.a_id AND rn = 1
LEFT JOIN lookup t3 ON t2.a_reference = t3.el_reference

Using order by inside the OVER() we can locate a "most recent" row and then return only that row by the "AND RN = 1" of the join to the subquery.


问:
SML functor expose a type without exposing implementation (implementing sets)
I'm writing a functor to implement sets in standard ML. Since sets don't allow duplicates and I don't want it to be constrained to equality types, it's declared like this:

```<code>signature SET = sig
    type t
    type 'a set

    val add : t -> t set -> t set
    ...
end

functor ListSet (EQ : sig type t val equal : t * t -> bool end) :> SET = struct
    type t = EQ.t
    type 'a set = 'a list

    fun add x s = ...
    ...
end
</code>```

I use :> so that list operations cannot be used on sets, hiding the internal implementation and allowing to change the representation (e.g. to a BST)

However, this also hides type t, therefore function add when used like this gives an error:

```<code>structure IntSet = ListSet (struct type t = int val equal = op= end);
val s0 = IntSet.empty
val s1 = IntSet.add 0 s0

Function: IntSet.add : IntSet.t -> IntSet.t IntSet.set -> IntSet.t IntSet.set
Argument: 0 : int
Reason:
  Can't unify int (*In Basis*) with
    IntSet.t (*Created from applying functor ListEqSet*)
    (Different type constructors)
</code>```

Is there a way to keep the implementation hidden but somehow expose the type t? Or is there a better approach to implementing sets?

P.S. The main reason I can't have equality types is to allow sets of sets, and while I can keep the lists sorted and define eqtype 'a set, it adds unnecessary complexity.

答:
You have to expose the type t using a type refinement:

```<code>functor ListSet (Eq : sig type t val equal : t * t -> bool end) :> SET where type t = Eq.t =
struct
  ...
end
</code>```

This is equivalent to an expansion of the signature SET where the type t is specified transparently as

```<code>type t = Eq.t
</code>```

Body:
I'm writing a functor to implement sets in standard ML. Since sets don't allow duplicates and I don't want it to be constrained to equality types, it's declared like this:

signature SET = sig
    type t
    type 'a set

    val add : t -> t set -> t set
    ...
end

functor ListSet (EQ : sig type t val equal : t * t -> bool end) :> SET = struct
    type t = EQ.t
    type 'a set = 'a list

    fun add x s = ...
    ...
end

I use :> so that list operations cannot be used on sets, hiding the internal implementation and allowing to change the representation (e.g. to a BST)

However, this also hides type t, therefore function add when used like this gives an error:

structure IntSet = ListSet (struct type t = int val equal = op= end);
val s0 = IntSet.empty
val s1 = IntSet.add 0 s0

Function: IntSet.add : IntSet.t -> IntSet.t IntSet.set -> IntSet.t IntSet.set
Argument: 0 : int
Reason:
  Can't unify int (*In Basis*) with
    IntSet.t (*Created from applying functor ListEqSet*)
    (Different type constructors)

Is there a way to keep the implementation hidden but somehow expose the type t? Or is there a better approach to implementing sets?

P.S. The main reason I can't have equality types is to allow sets of sets, and while I can keep the lists sorted and define eqtype 'a set, it adds unnecessary complexity.

Body:
You have to expose the type t using a type refinement:

functor ListSet (Eq : sig type t val equal : t * t -> bool end) :> SET where type t = Eq.t =
struct
  ...
end

This is equivalent to an expansion of the signature SET where the type t is specified transparently as

type t = Eq.t


问:
Update on double click of EA Element
We are opening the Customized Form in place of Properties view of EA Element on Double Click of an element in diagram or project browser i.e using EA_OnContextItemDoubleClicked Event (We are using show-dialog to open the customized form and returning false such that properties view should not open on double click). In the customized form we are trying to update the EA Element using the API element.Name and updating it. But the issue is when we update the element name it is getting reflected in project browser but if we open the EA properties view of the updated EA Element and click OK button the update will be reverted back to the old value (Old Name).
Please find the code below.</p>

```<code>public virtual bool EA_OnContextItemDoubleClicked(EA.Repository Repository,string GUID, EA.ObjectType ot)
        {
                  EA.Element ele=  Repository.GetElementByGuid(GUID);
                  ele.Name = "Test";
                  ele.Update();

 repository.AdviseElementChange(ele.ElementID);

            }
</code>```

答:
What you are doing is playing with unsecured weapons. NEVER use Execute unless it's unavoidable (if the API lacks functionality, if performance is a must). So in your code the Execute has no reason. Set the name in to "test" before the Update and remove the Execute statement.

Besides that: t_object.ea_guid=GUID will never do anything since you will not have any result set. Or maybe it will throw an exception since GUID is no field. I guess you meant

```<code>Repository.Execute("Update t_object set t_object.Name='test' where t_object.ea_guid='" + GUID + "'");
</code>```

But then again: see above!

Title: Update on double click of EA Element

Body:
We are opening the Customized Form in place of Properties view of EA Element on Double Click of an element in diagram or project browser i.e using EA_OnContextItemDoubleClicked Event (We are using show-dialog to open the customized form and returning false such that properties view should not open on double click). In the customized form we are trying to update the EA Element using the API element.Name and updating it. But the issue is when we update the element name it is getting reflected in project browser but if we open the EA properties view of the updated EA Element and click OK button the update will be reverted back to the old value (Old Name).
Please find the code below.

public virtual bool EA_OnContextItemDoubleClicked(EA.Repository Repository,string GUID, EA.ObjectType ot)
        {
                  EA.Element ele=  Repository.GetElementByGuid(GUID);
                  ele.Name = "Test";
                  ele.Update();

 repository.AdviseElementChange(ele.ElementID);

            }

Body:
What you are doing is playing with unsecured weapons. NEVER use Execute unless it's unavoidable (if the API lacks functionality, if performance is a must). So in your code the Execute has no reason. Set the name in to "test" before the Update and remove the Execute statement.

Besides that: t_object.ea_guid=GUID will never do anything since you will not have any result set. Or maybe it will throw an exception since GUID is no field. I guess you meant

Repository.Execute("Update t_object set t_object.Name='test' where t_object.ea_guid='" + GUID + "'");

But then again: see above!


问:
CollectionViewLayout Supplementary View height equal to content
I have a UICollectionViewLayout subclass with in it a Supplementary View that contains a multi-line UILabel. The problem is that not all the text is visible at a certain point, how can I give the Supplementary View the height equal to its content?

答:
You can find the height of text using below function:-

```<code>func labelHeight(width:CGFloat , font:UIFont , text:String)->CGFloat{
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
    return height:label.frame.height
}
</code>```

then add this UICollectionViewDelegateFlowLayout method into your controller and return size for your header

```<code>func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
   // Pass parameter into this function according to your requirement
  let height = labelHeight(width: collectionView.bounds.width , font:UIFont , text:"")
  return CGSize(width:collectionView.bounds.width , height: height + 10)

}
</code>```

Body:
You can find the height of text using below function:-

func labelHeight(width:CGFloat , font:UIFont , text:String)->CGFloat{
    let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()
    return height:label.frame.height
}

then add this UICollectionViewDelegateFlowLayout method into your controller and return size for your header

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
   // Pass parameter into this function according to your requirement
  let height = labelHeight(width: collectionView.bounds.width , font:UIFont , text:"")
  return CGSize(width:collectionView.bounds.width , height: height + 10)

}


问:
Grouping and remove from list
I have following type

```<code>public class Parameter
{
   public string Name {get;set;}
   public string PathType {get;set;}
}
</code>```

My parameter list like:

```<code>List<Parameter> params = new List<Parameter>();
params.Add(new Parameter{ Name ="A", PathType ="path" });
params.Add(new Parameter{ Name ="B", PathType ="query" });
params.Add(new Parameter{ Name ="C", PathType ="path" });
params.Add(new Parameter{ Name ="C", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="path" });
params.Add(new Parameter{ Name ="D", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="body" });
</code>```

I need to find parameters that have the same Name (like: C and D) where PathType equals path and query. Sorry for my English, it is a little bit difficult to explain. I want to find

```<code> Name ="C", PathType ="path"
 Name ="C", PathType ="query"
 Name ="D", PathType ="path"
 Name ="D", PathType ="query"
</code>```

Then remove all where PathType = "query". Finally result should be

```<code>Name ="A", PathType ="path"
Name ="B", PathType ="query"
Name ="C", PathType ="path"
Name ="D", PathType ="path"
Name ="D", PathType ="body"
</code>```

My code

```<code>var groupedParams = params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var parameter in params) {
    if (groupedParams.ContainsKey(parameter.Name)) {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1) {
            params.Remove(parameter);
        }
    }
}
</code>```

I need to group by name but remove only when there are path and query for that name.
Please suggest how can I do in in other way? Thanks

答:
It seems I found the solution. My code :</p>

```<code>var paramList = params.Where(x => x.PathType.Equals("path") || x.PathType.Equals("query"));
var groupedParams  = paramList.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var item in groupedParams) {
    var temp = item.Value.Count() > 1;
    if (temp) {
        var paramToDelete = operation.parameters.FirstOrDefault(x => x.Name.ToLower() == item.Key.ToLower() && x.PathType == "query");
        if (paramToDelete != null) {
            operation.parameters.Remove(paramToDelete);
        }
    }
}
</code>```

Title: Grouping and remove from list

Body:
I have following type

public class Parameter
{
   public string Name {get;set;}
   public string PathType {get;set;}
}

My parameter list like:

List<Parameter> params = new List<Parameter>();
params.Add(new Parameter{ Name ="A", PathType ="path" });
params.Add(new Parameter{ Name ="B", PathType ="query" });
params.Add(new Parameter{ Name ="C", PathType ="path" });
params.Add(new Parameter{ Name ="C", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="path" });
params.Add(new Parameter{ Name ="D", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="body" });

I need to find parameters that have the same Name (like: C and D) where PathType equals path and query. Sorry for my English, it is a little bit difficult to explain. I want to find

 Name ="C", PathType ="path"
 Name ="C", PathType ="query"
 Name ="D", PathType ="path"
 Name ="D", PathType ="query"

Then remove all where PathType = "query". Finally result should be

Name ="A", PathType ="path"
Name ="B", PathType ="query"
Name ="C", PathType ="path"
Name ="D", PathType ="path"
Name ="D", PathType ="body"

My code

var groupedParams = params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var parameter in params) {
    if (groupedParams.ContainsKey(parameter.Name)) {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1) {
            params.Remove(parameter);
        }
    }
}

I need to group by name but remove only when there are path and query for that name.
Please suggest how can I do in in other way? Thanks

Body:
It seems I found the solution. My code :

var paramList = params.Where(x => x.PathType.Equals("path") || x.PathType.Equals("query"));
var groupedParams  = paramList.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var item in groupedParams) {
    var temp = item.Value.Count() > 1;
    if (temp) {
        var paramToDelete = operation.parameters.FirstOrDefault(x => x.Name.ToLower() == item.Key.ToLower() && x.PathType == "query");
        if (paramToDelete != null) {
            operation.parameters.Remove(paramToDelete);
        }
    }
}


问:
trouble parsing multipart/form-data (not file upload) with spring-mvc 4.1
I need to parse a multipart request in a spring-mvc controller. Spring version is 4.1.6. Example of the request:

```<code>HEADER host: "localhost:8080"
HEADER accept: "*/*"
HEADER content-length: "539"
HEADER expect: "100-continue"
HEADER content-type: "multipart/form-data; boundary=------------------------2e2bf5fa2f7bbfbf"
BODY:
--------------------------2e2bf5fa2f7bbfbf
Content-Disposition: form-data; name="objectid"

160714.110239.GG
--------------------------2e2bf5fa2f7bbfbf--
Content-Disposition: form-data; name="geojson"

[a very long json string]
--------------------------2e2bf5fa2f7bbfbf
</code>```

The exact formatting of the request is not under my control.

As long as I use the whole @RequestBody, my RequestMapping is resolved:

```<code>@RequestMapping(value = "/coordinates", method = RequestMethod.POST)
public @ResponseStatus(value = HttpStatus.OK)
void coordinates(final HttpServletRequest request,
                 final @RequestBody String body) {
  final Enumeration<String> headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
    final String element = headerNames.nextElement();
    System.out.println("HEADER " + element + ": \"" + request.getHeader(element) + "\"" );
  }
  System.out.println("BODY:");
  System.out.println(body);
}
</code>```

But when I change the signature in order to get the parts directly, the client gets an error message, saying "Required String parameter 'objectid' is not present", and my mapping is not resolved anymore (tested with a breakpoint). This is the failing code:

```<code>@RequestMapping(value = "/coordinates", method = RequestMethod.POST)
public @ResponseStatus(value = HttpStatus.OK)
void coordinates(final HttpServletRequest request,
                 final @RequestParam("objectid") String objectid,
                 final @RequestParam("geojson") String geojson) {
  final String remoteAddr = request.getRemoteAddr();
  System.out.println("coordinates from " + remoteAddr
      + ":\nobjectid=" + objectid
      + "\ngeojson=" + geojson);
}
</code>```

What am I doing wrong ?

答:
Resolved.

There was one thing missing in my spring configuration:

```<code><bean id="multipartResolver"
      class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
  <property name="maxUploadSize" value="100000"/>
</bean>
</code>```

And with that resolver, the @RequestParam annotation (as in my second java source example) works. Yes, it's @RequestParam although the values are not part of the URL.

Body:
I need to parse a multipart request in a spring-mvc controller. Spring version is 4.1.6. Example of the request:

HEADER host: "localhost:8080"
HEADER accept: "*/*"
HEADER content-length: "539"
HEADER expect: "100-continue"
HEADER content-type: "multipart/form-data; boundary=------------------------2e2bf5fa2f7bbfbf"
BODY:
--------------------------2e2bf5fa2f7bbfbf
Content-Disposition: form-data; name="objectid"

160714.110239.GG
--------------------------2e2bf5fa2f7bbfbf--
Content-Disposition: form-data; name="geojson"

[a very long json string]
--------------------------2e2bf5fa2f7bbfbf

The exact formatting of the request is not under my control.

As long as I use the whole @RequestBody, my RequestMapping is resolved:

@RequestMapping(value = "/coordinates", method = RequestMethod.POST)
public @ResponseStatus(value = HttpStatus.OK)
void coordinates(final HttpServletRequest request,
                 final @RequestBody String body) {
  final Enumeration<String> headerNames = request.getHeaderNames();
  while (headerNames.hasMoreElements()) {
    final String element = headerNames.nextElement();
    System.out.println("HEADER " + element + ": \"" + request.getHeader(element) + "\"" );
  }
  System.out.println("BODY:");
  System.out.println(body);
}

But when I change the signature in order to get the parts directly, the client gets an error message, saying "Required String parameter 'objectid' is not present", and my mapping is not resolved anymore (tested with a breakpoint). This is the failing code:

@RequestMapping(value = "/coordinates", method = RequestMethod.POST)
public @ResponseStatus(value = HttpStatus.OK)
void coordinates(final HttpServletRequest request,
                 final @RequestParam("objectid") String objectid,
                 final @RequestParam("geojson") String geojson) {
  final String remoteAddr = request.getRemoteAddr();
  System.out.println("coordinates from " + remoteAddr
      + ":\nobjectid=" + objectid
      + "\ngeojson=" + geojson);
}

What am I doing wrong ?

Body:
Resolved.

There was one thing missing in my spring configuration:

<bean id="multipartResolver"
      class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
  <property name="maxUploadSize" value="100000"/>
</bean>

And with that resolver, the @RequestParam annotation (as in my second java source example) works. Yes, it's @RequestParam although the values are not part of the URL.


问:
Rails Strong Parameters - Allow parameter to be an Array or String
Using Strong Parameters in my Rails Controller, how can I state that a permitted parameter can be a String or an Array?

My strong params:

```<code>class SiteSearchController < ApplicationController
    [...abbreviated for brevity...]

    private
    def search_params
        params.fetch(:search, {}).permit(:strings)
    end
end
</code>```

I'm wanting to POST string(s) to search as a String or as an Array:

To search for 1 thing:

```<code>{
    "strings": "search for this"
}
</code>```

OR, to search for multiple things:

```<code>{
    "strings": [
        "search for this",
        "and for this",
        "and search for this string too"
    ]
}
</code>```

Update:

Purpose: I'm creating an API where my users can "batch" requests (getting responses via web-hooks), or make a one-off request (getting an immediate response) all on the same endpoint. This question is only 1 small part of my requirement.

The next piece will be doing this same logic, where I'll allow the search to happen on multiple pages, i.e.:

```<code>[
    {
        "page": "/section/look-at-this-page",
        "strings": "search for this"
    },
    {
        "page": "/this-page",
        "strings": [
            "search for this",
            "and for this",
            "and search for this string too"
        ]
    }
]
</code>```

OR on a single page:

```<code>{
    "page": "/section/look-at-this-page",
    "strings": "search for this"
}
</code>```

(which will make me need to have Strong Params allow an Object or an Array to be sent.

This seems like a basic thing, but I'm not seeing anything out there.

I know that I could just make the strings param an array, and then require searching for 1 thing to just have 1 value in the array... but I want to have this parameter be more robust than that.

答:
You can just permit the parameter twice - once for an array and once for a scalar value.</p>

```<code>def search_params
    params.fetch(:search, {}).permit(:strings, strings: [])
end
</code>```

Body:
Using Strong Parameters in my Rails Controller, how can I state that a permitted parameter can be a String or an Array?

My strong params:

class SiteSearchController < ApplicationController
    [...abbreviated for brevity...]

    private
    def search_params
        params.fetch(:search, {}).permit(:strings)
    end
end

I'm wanting to POST string(s) to search as a String or as an Array:

To search for 1 thing:

{
    "strings": "search for this"
}

OR, to search for multiple things:

{
    "strings": [
        "search for this",
        "and for this",
        "and search for this string too"
    ]
}

Update:

Purpose: I'm creating an API where my users can "batch" requests (getting responses via web-hooks), or make a one-off request (getting an immediate response) all on the same endpoint. This question is only 1 small part of my requirement.

The next piece will be doing this same logic, where I'll allow the search to happen on multiple pages, i.e.:

[
    {
        "page": "/section/look-at-this-page",
        "strings": "search for this"
    },
    {
        "page": "/this-page",
        "strings": [
            "search for this",
            "and for this",
            "and search for this string too"
        ]
    }
]

OR on a single page:

{
    "page": "/section/look-at-this-page",
    "strings": "search for this"
}

(which will make me need to have Strong Params allow an Object or an Array to be sent.

This seems like a basic thing, but I'm not seeing anything out there.

I know that I could just make the strings param an array, and then require searching for 1 thing to just have 1 value in the array... but I want to have this parameter be more robust than that.

Body:
You can just permit the parameter twice - once for an array and once for a scalar value.

def search_params
    params.fetch(:search, {}).permit(:strings, strings: [])
end


答:
Your mistake is from logic. You want to select the df2 date that are df1. So you should write

```<code>df2[df2.Date.isin(df1.Date)]
</code>```

not the contrary of the boolean where comparison/inclusion in df1 is true

You could also obtain the same result with

```<code>set(b.Date)-(set(b.Date)-set(a.Date))
</code>```

Which should then be used through:

```<code>pd.DataFrame(sorted((set(b.Date)-(set(b.Date)-set(a.Date)))), columns=["Date"] )
</code>```

While the sorting is not optimal and you may change it in pandas by better logic.

```<code> df = pd.DataFrame(list((set(b.Date)-(set(b.Date)-set(a.Date)))), columns=["Date"] )
 df.Date = [date.date() for date in df.Date]
</code>```

or
     df.Date.dt.date

(see How do I convert dates in a Pandas data frame to a 'date' data type?)

Title: Compare two dataframes and delete not same dates

Body:
I have two dataframes and want to compare them and delete the days in the df2 which are not the same as in df1. I tried to use:

df2[~df2.Date.isin(df1.Date)]

but this does not work and getting an empty dataframe. df2 should look like df1. The dataframe's looks like the following:

df1
        Date
0    20-12-16
1    21-12-16
2    22-12-16
3    23-12-16
4    27-12-16
5    28-12-16
6    29-12-16
7    30-12-16
8    02-01-17
9    03-01-17
10   04-01-17
11   05-01-17
12   06-01-17

df2

         Date
0    20-12-16
1    21-12-16
2    22-12-16
3    23-12-16
4    24-12-16
5    25-12-16
6    26-12-16
7    27-12-16
8    28-12-16
9    29-12-16
10   30-12-16
11   31-12-16
12   01-01-17
13   02-01-17
14   03-01-17
15   04-01-17
16   05-01-17
17   06-01-17

Body:
Your mistake is from logic. You want to select the df2 date that are df1. So you should write

df2[df2.Date.isin(df1.Date)]

not the contrary of the boolean where comparison/inclusion in df1 is true

You could also obtain the same result with

set(b.Date)-(set(b.Date)-set(a.Date))

Which should then be used through:

pd.DataFrame(sorted((set(b.Date)-(set(b.Date)-set(a.Date)))), columns=["Date"] )

While the sorting is not optimal and you may change it in pandas by better logic.

 df = pd.DataFrame(list((set(b.Date)-(set(b.Date)-set(a.Date)))), columns=["Date"] )
 df.Date = [date.date() for date in df.Date]

or
     df.Date.dt.date

(see How do I convert dates in a Pandas data frame to a 'date' data type?)


问:
Delete Method in PHP 7 not recieving parameters
we are programming a Restful API to be called from an ionic app. We are sending from angular service with this code:

```<code>      .service('ServiceName', function($http) {
       return {
           borrarAlumno: function(par) {
               var link = "http://localhost/ws/index.php";
               return $http.delete(link, {
                   id: par.id
               })
           }
       }
   })
</code>```

When we try to read id parameter from php we dont get anything. This is the code we are using:

```<code>    if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

$input = file_get_contents('php://input');
print_r($_SERVER['REQUEST_METHOD']);
exit();
</code>```

We have tried with similar code to get parameters with PUT, GET and POST methods and it worked.

Any help would be appreciated.

Edit:

This php is called form another PHP:

```<code>class AlumnosAPI
{
    public function API()
    {
        header('Content-Type: application/JSON');
        $method = $_SERVER['REQUEST_METHOD'];

        switch ($method)
        {
          case 'GET':
              include('get.php');
              break;
          case 'POST':
              include('post.php');
              break;
          case 'PUT':
              include('put.php');
              break;
          case 'DELETE':
              include('delete.php');
              break;
          default:
              echo 'NOT SUPPORTED';
              break;
        }
    }

}
</code>```

Edit 2: full code of delete.php

```<code>  if (isset($_SERVER['HTTP_ORIGIN']))
  {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }

    // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
  {

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

      exit(0);
  }

  $valor['borrado'] = 0;

  include('conexion.php');

  $id = "";

  //parse_str(file_get_contents('php://input'), $delete);
  $input = file_get_contents('php://input');
  print_r($input);
  exit();

  foreach (array_keys($delete) as $key)
  {
    $$key = $delete[$key];
  }

  if ($id != "")
  {
    //PREPARAMOS LA SENTENCIA SQL
    $sql = "DELETE FROM Alumnado WHERE `ID`=?";

    $resultado1=$conexion->prepare($sql);

    $resultado1->bind_param('i', $id);

    $resultado1->execute();

    $valor['borrado'] = $resultado1->affected_rows;
  }

  $datos=json_encode($valor);

  echo $datos;
</code>```

答:
Angular doesn't send a request body for DELETE so you're going to have to read id from the URL.

```<code>.service('ServiceName', function($http) {
       return {
           borrarAlumno: function(par) {
               var link = "http://localhost/ws/index.php";
               return $http.delete(link, {
                   params : {id: par.id}
               })
           }
       }
   })
</code>```

get the id via $_GET['id'] instead of file_get_contents('php://input');

Body:
we are programming a Restful API to be called from an ionic app. We are sending from angular service with this code:

      .service('ServiceName', function($http) {
       return {
           borrarAlumno: function(par) {
               var link = "http://localhost/ws/index.php";
               return $http.delete(link, {
                   id: par.id
               })
           }
       }
   })

When we try to read id parameter from php we dont get anything. This is the code we are using:

    if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

$input = file_get_contents('php://input');
print_r($_SERVER['REQUEST_METHOD']);
exit();

We have tried with similar code to get parameters with PUT, GET and POST methods and it worked.

Any help would be appreciated.

Edit:

This php is called form another PHP:

class AlumnosAPI
{
    public function API()
    {
        header('Content-Type: application/JSON');
        $method = $_SERVER['REQUEST_METHOD'];

        switch ($method)
        {
          case 'GET':
              include('get.php');
              break;
          case 'POST':
              include('post.php');
              break;
          case 'PUT':
              include('put.php');
              break;
          case 'DELETE':
              include('delete.php');
              break;
          default:
              echo 'NOT SUPPORTED';
              break;
        }
    }

}

Edit 2: full code of delete.php

  if (isset($_SERVER['HTTP_ORIGIN']))
  {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
  }

    // Access-Control headers are received during OPTIONS requests
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
  {

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
          header("Access-Control-Allow-Methods: GET, POST, DELETE, PUT, OPTIONS");

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
          header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

      exit(0);
  }

  $valor['borrado'] = 0;

  include('conexion.php');

  $id = "";

  //parse_str(file_get_contents('php://input'), $delete);
  $input = file_get_contents('php://input');
  print_r($input);
  exit();

  foreach (array_keys($delete) as $key)
  {
    $$key = $delete[$key];
  }

  if ($id != "")
  {
    //PREPARAMOS LA SENTENCIA SQL
    $sql = "DELETE FROM Alumnado WHERE `ID`=?";

    $resultado1=$conexion->prepare($sql);

    $resultado1->bind_param('i', $id);

    $resultado1->execute();

    $valor['borrado'] = $resultado1->affected_rows;
  }

  $datos=json_encode($valor);

  echo $datos;

Body:
Angular doesn't send a request body for DELETE so you're going to have to read id from the URL.

.service('ServiceName', function($http) {
       return {
           borrarAlumno: function(par) {
               var link = "http://localhost/ws/index.php";
               return $http.delete(link, {
                   params : {id: par.id}
               })
           }
       }
   })

get the id via $_GET['id'] instead of file_get_contents('php://input');


问:
gradle jacocoTestReport is not working?
I have tried to get code coverage in a spring-gradle project using gradle jacoco plugin.

The build.gradle contains the following

```<code>apply plugin: "jacoco"

    jacoco {
        toolVersion = "0.7.1.201405082137"
        reportsDir = file("$buildDir/customJacocoReportDir")
    }

    jacocoTestReport {
    reports {
        xml.enabled false
        csv.enabled false
        html.destination "${buildDir}/jacocoHtml"
    }
}
</code>```

I then ran

```<code>gradle test jacocoTestReport
</code>```

Where after only the file test.exec is generated in build/reports folder.

Other than that nothing happens.

How can I get the HTML report?

答:
You don't have to configure reportsDir/destinationFile

Because jacoco has default values for them.

build.gradle:

```<code>plugins {
    id 'java'
    id 'jacoco'
}

jacocoTestReport {
    reports {
        xml.enabled true
        html.enabled true
        csv.enabled true
    }
}

repositories {
    jcenter()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}
</code>```

Run gradle test jacocoTestReport

You can find the test report in ./build/reports/jacoco/test directory.

HTML output is in ./build/reports/jacoco/test/html directory.

Title: gradle jacocoTestReport is not working?

Body:
I have tried to get code coverage in a spring-gradle project using gradle jacoco plugin.

The build.gradle contains the following

apply plugin: "jacoco"

    jacoco {
        toolVersion = "0.7.1.201405082137"
        reportsDir = file("$buildDir/customJacocoReportDir")
    }

    jacocoTestReport {
    reports {
        xml.enabled false
        csv.enabled false
        html.destination "${buildDir}/jacocoHtml"
    }
}

I then ran

gradle test jacocoTestReport

Where after only the file test.exec is generated in build/reports folder.

Other than that nothing happens.

How can I get the HTML report?

Body:
You don't have to configure reportsDir/destinationFile

Because jacoco has default values for them.

build.gradle:

plugins {
    id 'java'
    id 'jacoco'
}

jacocoTestReport {
    reports {
        xml.enabled true
        html.enabled true
        csv.enabled true
    }
}

repositories {
    jcenter()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

Run gradle test jacocoTestReport

You can find the test report in ./build/reports/jacoco/test directory.

HTML output is in ./build/reports/jacoco/test/html directory.


问:
How to update artists in scrollable, matplotlib and multiplot
I'm trying to create a scrollable multiplot based on the answer to this question:
Creating a scrollable multiplot with python's pylab

Lines created using ax.plot() are updating correctly, however I'm unable to figure out how to update artists created using xvlines() and fill_between().

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider

#create dataframes
dfs={}
for x in range(100):
    col1=np.random.normal(10,0.5,30)
    col2=(np.repeat([5,8,7],np.round(np.random.dirichlet(np.ones(3),size=1)*31)[0].tolist()))[:30]
    col3=np.random.randint(4,size=30)
    dfs[x]=pd.DataFrame({'col1':col1,'col2':col2,'col3':col3})

#create figure,axis,subplot
fig = plt.figure()
gs = gridspec.GridSpec(1,1,hspace=0,wspace=0,left=0.1,bottom=0.1)
ax = plt.subplot(gs[0])
ax.set_ylim([0,12])

#slider
frame=0
axframe = plt.axes([0.13, 0.02, 0.75, 0.03])
sframe = Slider(axframe, 'frame', 0, 99, valinit=0,valfmt='%d')

#plots
ln1,=ax.plot(dfs[0].index,dfs[0]['col1'])
ln2,=ax.plot(dfs[0].index,dfs[0]['col2'],c='black')

#artists
ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==5,facecolor='r',edgecolors='none',alpha=0.5)
ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==8,facecolor='b',edgecolors='none',alpha=0.5)
ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==7,facecolor='g',edgecolors='none',alpha=0.5)
ax.vlines(x=dfs[0]['col3'].index,ymin=0,ymax=dfs[0]['col3'],color='black')

#update plots
def update(val):
    frame = np.floor(sframe.val)
    ln1.set_ydata(dfs[frame]['col1'])
    ln2.set_ydata(dfs[frame]['col2'])
    ax.set_title('Frame ' + str(int(frame)))
    plt.draw()

#connect callback to slider
sframe.on_changed(update)
plt.show()
</code>```

This is what it looks like at the moment

I can't apply the same approach as for plot(), since the following produces an error message:

```<code>ln3,=ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==5,facecolor='r',edgecolors='none',alpha=0.5)
TypeError: 'PolyCollection' object is not iterable
</code>```

This is what it's meant to look like on each frame

答:
fill_between returns a PolyCollection, which expects a list (or several lists) of vertices upon creation. Unfortunately I haven't found a way to retrieve the vertices that where used to create the given PolyCollection, but in your case it is easy enough to create the PolyCollection directly (thereby avoiding the use of fill_between) and then update its vertices upon frame change.

Below a version of your code that does what you are after:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider

from matplotlib.collections import PolyCollection

#create dataframes
dfs={}
for x in range(100):
    col1=np.random.normal(10,0.5,30)
    col2=(np.repeat([5,8,7],np.round(np.random.dirichlet(np.ones(3),size=1)*31)[0].tolist()))[:30]
    col3=np.random.randint(4,size=30)
    dfs[x]=pd.DataFrame({'col1':col1,'col2':col2,'col3':col3})

#create figure,axis,subplot
fig = plt.figure()
gs = gridspec.GridSpec(1,1,hspace=0,wspace=0,left=0.1,bottom=0.1)
ax = plt.subplot(gs[0])
ax.set_ylim([0,12])

#slider
frame=0
axframe = plt.axes([0.13, 0.02, 0.75, 0.03])
sframe = Slider(axframe, 'frame', 0, 99, valinit=0,valfmt='%d')

#plots
ln1,=ax.plot(dfs[0].index,dfs[0]['col1'])
ln2,=ax.plot(dfs[0].index,dfs[0]['col2'],c='black')

##additional code to update the PolyCollections
val_r = 5
val_b = 8
val_g = 7

def update_collection(collection, value, frame = 0):
    xs = np.array(dfs[frame].index)
    ys = np.array(dfs[frame]['col2'])

    ##we need to catch the case where no points with y == value exist:
    try:
        minx = np.min(xs[ys == value])
        maxx = np.max(xs[ys == value])
        miny = value-0.5
        maxy = value+0.5
        verts = np.array([[minx,miny],[maxx,miny],[maxx,maxy],[minx,maxy]])
    except ValueError:
        verts = np.zeros((0,2))
    finally:
        collection.set_verts([verts])

#artists

##ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==5,facecolor='r',edgecolors='none',alpha=0.5)
reds = PolyCollection([],facecolors = ['r'], alpha = 0.5)
ax.add_collection(reds)
update_collection(reds,val_r)

##ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==8,facecolor='b',edgecolors='none',alpha=0.5)
blues = PolyCollection([],facecolors = ['b'], alpha = 0.5)
ax.add_collection(blues)
update_collection(blues, val_b)

##ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==7,facecolor='g',edgecolors='none',alpha=0.5)
greens = PolyCollection([],facecolors = ['g'], alpha = 0.5)
ax.add_collection(greens)
update_collection(greens, val_g)

ax.vlines(x=dfs[0]['col3'].index,ymin=0,ymax=dfs[0]['col3'],color='black')

#update plots
def update(val):
    frame = np.floor(sframe.val)
    ln1.set_ydata(dfs[frame]['col1'])
    ln2.set_ydata(dfs[frame]['col2'])
    ax.set_title('Frame ' + str(int(frame)))

    ##updating the PolyCollections:
    update_collection(reds,val_r, frame)
    update_collection(blues,val_b, frame)
    update_collection(greens,val_g, frame)

    plt.draw()

#connect callback to slider
sframe.on_changed(update)
plt.show()
</code>```

Each of the three PolyCollections (reds, blues, and greens) has only four vertices (the edges of the rectangles), which are determined based on the given data (which is done in update_collections). The result looks like this:

Tested in Python 3.5

Body:
I'm trying to create a scrollable multiplot based on the answer to this question:
Creating a scrollable multiplot with python's pylab

Lines created using ax.plot() are updating correctly, however I'm unable to figure out how to update artists created using xvlines() and fill_between().

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider

#create dataframes
dfs={}
for x in range(100):
    col1=np.random.normal(10,0.5,30)
    col2=(np.repeat([5,8,7],np.round(np.random.dirichlet(np.ones(3),size=1)*31)[0].tolist()))[:30]
    col3=np.random.randint(4,size=30)
    dfs[x]=pd.DataFrame({'col1':col1,'col2':col2,'col3':col3})

#create figure,axis,subplot
fig = plt.figure()
gs = gridspec.GridSpec(1,1,hspace=0,wspace=0,left=0.1,bottom=0.1)
ax = plt.subplot(gs[0])
ax.set_ylim([0,12])

#slider
frame=0
axframe = plt.axes([0.13, 0.02, 0.75, 0.03])
sframe = Slider(axframe, 'frame', 0, 99, valinit=0,valfmt='%d')

#plots
ln1,=ax.plot(dfs[0].index,dfs[0]['col1'])
ln2,=ax.plot(dfs[0].index,dfs[0]['col2'],c='black')

#artists
ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==5,facecolor='r',edgecolors='none',alpha=0.5)
ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==8,facecolor='b',edgecolors='none',alpha=0.5)
ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==7,facecolor='g',edgecolors='none',alpha=0.5)
ax.vlines(x=dfs[0]['col3'].index,ymin=0,ymax=dfs[0]['col3'],color='black')

#update plots
def update(val):
    frame = np.floor(sframe.val)
    ln1.set_ydata(dfs[frame]['col1'])
    ln2.set_ydata(dfs[frame]['col2'])
    ax.set_title('Frame ' + str(int(frame)))
    plt.draw()

#connect callback to slider
sframe.on_changed(update)
plt.show()

This is what it looks like at the moment

I can't apply the same approach as for plot(), since the following produces an error message:

ln3,=ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==5,facecolor='r',edgecolors='none',alpha=0.5)
TypeError: 'PolyCollection' object is not iterable

This is what it's meant to look like on each frame

Body:
fill_between returns a PolyCollection, which expects a list (or several lists) of vertices upon creation. Unfortunately I haven't found a way to retrieve the vertices that where used to create the given PolyCollection, but in your case it is easy enough to create the PolyCollection directly (thereby avoiding the use of fill_between) and then update its vertices upon frame change.

Below a version of your code that does what you are after:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.widgets import Slider

from matplotlib.collections import PolyCollection

#create dataframes
dfs={}
for x in range(100):
    col1=np.random.normal(10,0.5,30)
    col2=(np.repeat([5,8,7],np.round(np.random.dirichlet(np.ones(3),size=1)*31)[0].tolist()))[:30]
    col3=np.random.randint(4,size=30)
    dfs[x]=pd.DataFrame({'col1':col1,'col2':col2,'col3':col3})

#create figure,axis,subplot
fig = plt.figure()
gs = gridspec.GridSpec(1,1,hspace=0,wspace=0,left=0.1,bottom=0.1)
ax = plt.subplot(gs[0])
ax.set_ylim([0,12])

#slider
frame=0
axframe = plt.axes([0.13, 0.02, 0.75, 0.03])
sframe = Slider(axframe, 'frame', 0, 99, valinit=0,valfmt='%d')

#plots
ln1,=ax.plot(dfs[0].index,dfs[0]['col1'])
ln2,=ax.plot(dfs[0].index,dfs[0]['col2'],c='black')

##additional code to update the PolyCollections
val_r = 5
val_b = 8
val_g = 7

def update_collection(collection, value, frame = 0):
    xs = np.array(dfs[frame].index)
    ys = np.array(dfs[frame]['col2'])

    ##we need to catch the case where no points with y == value exist:
    try:
        minx = np.min(xs[ys == value])
        maxx = np.max(xs[ys == value])
        miny = value-0.5
        maxy = value+0.5
        verts = np.array([[minx,miny],[maxx,miny],[maxx,maxy],[minx,maxy]])
    except ValueError:
        verts = np.zeros((0,2))
    finally:
        collection.set_verts([verts])

#artists

##ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==5,facecolor='r',edgecolors='none',alpha=0.5)
reds = PolyCollection([],facecolors = ['r'], alpha = 0.5)
ax.add_collection(reds)
update_collection(reds,val_r)

##ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==8,facecolor='b',edgecolors='none',alpha=0.5)
blues = PolyCollection([],facecolors = ['b'], alpha = 0.5)
ax.add_collection(blues)
update_collection(blues, val_b)

##ax.fill_between(dfs[0].index,y1=dfs[0]['col2']-0.5,y2=dfs[0]['col2']+0.5,where=dfs[0]['col2']==7,facecolor='g',edgecolors='none',alpha=0.5)
greens = PolyCollection([],facecolors = ['g'], alpha = 0.5)
ax.add_collection(greens)
update_collection(greens, val_g)

ax.vlines(x=dfs[0]['col3'].index,ymin=0,ymax=dfs[0]['col3'],color='black')

#update plots
def update(val):
    frame = np.floor(sframe.val)
    ln1.set_ydata(dfs[frame]['col1'])
    ln2.set_ydata(dfs[frame]['col2'])
    ax.set_title('Frame ' + str(int(frame)))

    ##updating the PolyCollections:
    update_collection(reds,val_r, frame)
    update_collection(blues,val_b, frame)
    update_collection(greens,val_g, frame)

    plt.draw()

#connect callback to slider
sframe.on_changed(update)
plt.show()

Each of the three PolyCollections (reds, blues, and greens) has only four vertices (the edges of the rectangles), which are determined based on the given data (which is done in update_collections). The result looks like this:

Tested in Python 3.5


问:
How to use ldap3 generator for pagination?
I want to paginate the results of an ldap query so that I get 50 users per query for each page. The documentation here http://ldap3.readthedocs.io/searches.html?highlight=generator suggests that using a generator is the simplest way to do this, however it doesn't provide any detail as to how to use it to achieve pagination. When I iterate through the generator object, it prints out every user entry, even though I specified 'paged_size=5' in my search query. Can anyone explain to me what's going on here? Thanks!!</p>

答:
This is a similar system that I used:

```<code># Set up your ldap connection
conn = Connection(*args)

# create a generator
entry_generator = conn.extend.standard.paged_search(
        search_base=self.dc, search_filter=query[0],
        search_scope=SUBTREE, attributes=self.user_attributes,
        paged_size=1, generator=True)

# Then get your results:
results = []
for entry in entry_generator:
    total_entries += 1
    results.append(entry)
    if total_entries % 50 == 0:
        # do something with results
</code>```

Otherwise try setting the page_size to 50 and get results like that.

Body:
This is a similar system that I used:

# Set up your ldap connection
conn = Connection(*args)

# create a generator
entry_generator = conn.extend.standard.paged_search(
        search_base=self.dc, search_filter=query[0],
        search_scope=SUBTREE, attributes=self.user_attributes,
        paged_size=1, generator=True)

# Then get your results:
results = []
for entry in entry_generator:
    total_entries += 1
    results.append(entry)
    if total_entries % 50 == 0:
        # do something with results

Otherwise try setting the page_size to 50 and get results like that.


问:
system.string[] /value of type 'String' cannot be converted to 'String()' in selected Index in listbox vb.net
This is a program that I created in Visual Basic Window Form Application that uses two listboxes, one for Months and the other for Birthstones. When the user clicks a Birthstone a corresponding month is displayed in the lblDescription control, or when the user clicks a Month in the _strMonths listbox a corresponding Birthstone is displayed in the lblDescription. The program was working but I accidentally deleted it and now I don't remember the exact code anymore. I've been at it for a week now to recreate it but to no avail. I've researched SelectedIndex Property but everything I've seen so far is about the SelectedIndex Property being an integer but mine is a string. So I'm coming to the forum for help. The code is simple. I added a MsgBox(_intFill) which shows all the birthstones. I'm almost there, but no cigar yet.</p>

```<code>Option Strict On

Public Class frmBirthstones
    'Declare class variables
    Private _strStones(11) As String
    Private _strMonths(11) As String
    Public Shared _intFill As String
    Public Shared _selectedIndex As String

    Private Sub frmBirthstones_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Array items for Brith Stones
        _strStones(0) = "Garnet"
        _strStones(1) = "Amethyst"
        _strStones(2) = "Aquamarine"
        _strStones(3) = "Diamond"
        _strStones(4) = "Emerald"
        _strStones(5) = "Pearl"
        _strStones(6) = "Ruby"
        _strStones(7) = "Peridot"
        _strStones(8) = "Sapphire"
        _strStones(9) = "Opal"
        _strStones(10) = "Topaz"
        _strStones(11) = "Turquoise"
        'Array items for Months
        _strMonths(0) = "January"
        _strMonths(1) = "February"
        _strMonths(2) = "March"
        _strMonths(3) = "April"
        _strMonths(4) = "May"
        _strMonths(5) = "June"
        _strMonths(6) = "July"
        _strMonths(7) = "August"
        _strMonths(8) = "September"
        _strMonths(9) = "October"
        _strMonths(10) = "November"
        _strMonths(11) = "December"

        'Makes label Description visible
        lblDescription.Visible = True

        For Each _intFill In _strStones
            'fills listbox with Birthstones
            lstStones.Items.Add(_intFill)
         MsgBox(_intFill)

        Next
        For Each _intFill In _strMonths
            'fills listbox with Months
            lstMonths.Items.Add(_intFill)
        Next

    End Sub

    Private Sub lstStones_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstStones.SelectedIndexChanged
        'When user click or selects a Birthstone in this listbox a corresponding Month for the Birthstone is selected

        '_strStones = _intFill
        'Doesn't work
        lblDescription.Text = _strStones.ToString() & "is the Birthstone for the month of " & _strMonths.ToString()

    End Sub

    Private Sub lstMonths_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstMonths.SelectedIndexChanged
        'When user click or selects a Month in this listbox a corresponding Birthstone for that Month is selected

        '_strMonths =
        lblDescription.Text = _strMonths.ToString() & "is the Month for the Birthstone " & _strStones.ToString()
    End Sub
End Class
</code>```

答:
```<code>Option Strict On

Public Class frmBirthstones
    Private _strStones(11) As String
    Private _strMonths(11) As String

    Private Sub frmBirthstones_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        'Array items for Brith Stones
        _strStones(0) = "Garnet"
        _strStones(1) = "Amethyst"
        _strStones(2) = "Aquamarine"
        _strStones(3) = "Diamond"
        _strStones(4) = "Emerald"
        _strStones(5) = "Pearl"
        _strStones(6) = "Ruby"
        _strStones(7) = "Peridot"
        _strStones(8) = "Sapphire"
        _strStones(9) = "Opal"
        _strStones(10) = "Topaz"
        _strStones(11) = "Turquoise"
        'Array items for Months
        _strMonths(0) = "January"
        _strMonths(1) = "February"
        _strMonths(2) = "March"
        _strMonths(3) = "April"
        _strMonths(4) = "May"
        _strMonths(5) = "June"
        _strMonths(6) = "July"
        _strMonths(7) = "August"
        _strMonths(8) = "September"
        _strMonths(9) = "October"
        _strMonths(10) = "November"
        _strMonths(11) = "December"

        'Makes label Description visible
        lblDescription.Visible = True

        'fills listbox with Birthstones
        lstStones.Items.AddRange(_strStones)

        'fills listbox with Months
        lstMonths.Items.AddRange(_strMonths)

    End Sub

    Private Sub lstStones_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstStones.SelectedIndexChanged
        lblDescription.Text = _strStones(lstStones.SelectedIndex).ToString() & " is the Birthstone for the month of " & _strMonths(lstStones.SelectedIndex).ToString()
    End Sub

    Private Sub lstMonths_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstMonths.SelectedIndexChanged
        lblDescription.Text = _strMonths(lstMonths.SelectedIndex).ToString() & " is the Month for the Birthstone " & _strStones(lstMonths.SelectedIndex).ToString()
    End Sub
End Class
</code>```

Maybe this is what you want to do.

Body:
This is a program that I created in Visual Basic Window Form Application that uses two listboxes, one for Months and the other for Birthstones. When the user clicks a Birthstone a corresponding month is displayed in the lblDescription control, or when the user clicks a Month in the _strMonths listbox a corresponding Birthstone is displayed in the lblDescription. The program was working but I accidentally deleted it and now I don't remember the exact code anymore. I've been at it for a week now to recreate it but to no avail. I've researched SelectedIndex Property but everything I've seen so far is about the SelectedIndex Property being an integer but mine is a string. So I'm coming to the forum for help. The code is simple. I added a MsgBox(_intFill) which shows all the birthstones. I'm almost there, but no cigar yet.

Option Strict On

Public Class frmBirthstones
    'Declare class variables
    Private _strStones(11) As String
    Private _strMonths(11) As String
    Public Shared _intFill As String
    Public Shared _selectedIndex As String

    Private Sub frmBirthstones_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Array items for Brith Stones
        _strStones(0) = "Garnet"
        _strStones(1) = "Amethyst"
        _strStones(2) = "Aquamarine"
        _strStones(3) = "Diamond"
        _strStones(4) = "Emerald"
        _strStones(5) = "Pearl"
        _strStones(6) = "Ruby"
        _strStones(7) = "Peridot"
        _strStones(8) = "Sapphire"
        _strStones(9) = "Opal"
        _strStones(10) = "Topaz"
        _strStones(11) = "Turquoise"
        'Array items for Months
        _strMonths(0) = "January"
        _strMonths(1) = "February"
        _strMonths(2) = "March"
        _strMonths(3) = "April"
        _strMonths(4) = "May"
        _strMonths(5) = "June"
        _strMonths(6) = "July"
        _strMonths(7) = "August"
        _strMonths(8) = "September"
        _strMonths(9) = "October"
        _strMonths(10) = "November"
        _strMonths(11) = "December"

        'Makes label Description visible
        lblDescription.Visible = True

        For Each _intFill In _strStones
            'fills listbox with Birthstones
            lstStones.Items.Add(_intFill)
         MsgBox(_intFill)

        Next
        For Each _intFill In _strMonths
            'fills listbox with Months
            lstMonths.Items.Add(_intFill)
        Next

    End Sub

    Private Sub lstStones_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstStones.SelectedIndexChanged
        'When user click or selects a Birthstone in this listbox a corresponding Month for the Birthstone is selected

        '_strStones = _intFill
        'Doesn't work
        lblDescription.Text = _strStones.ToString() & "is the Birthstone for the month of " & _strMonths.ToString()

    End Sub

    Private Sub lstMonths_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstMonths.SelectedIndexChanged
        'When user click or selects a Month in this listbox a corresponding Birthstone for that Month is selected

        '_strMonths =
        lblDescription.Text = _strMonths.ToString() & "is the Month for the Birthstone " & _strStones.ToString()
    End Sub
End Class

Body:
Option Strict On

Public Class frmBirthstones
    Private _strStones(11) As String
    Private _strMonths(11) As String

    Private Sub frmBirthstones_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        'Array items for Brith Stones
        _strStones(0) = "Garnet"
        _strStones(1) = "Amethyst"
        _strStones(2) = "Aquamarine"
        _strStones(3) = "Diamond"
        _strStones(4) = "Emerald"
        _strStones(5) = "Pearl"
        _strStones(6) = "Ruby"
        _strStones(7) = "Peridot"
        _strStones(8) = "Sapphire"
        _strStones(9) = "Opal"
        _strStones(10) = "Topaz"
        _strStones(11) = "Turquoise"
        'Array items for Months
        _strMonths(0) = "January"
        _strMonths(1) = "February"
        _strMonths(2) = "March"
        _strMonths(3) = "April"
        _strMonths(4) = "May"
        _strMonths(5) = "June"
        _strMonths(6) = "July"
        _strMonths(7) = "August"
        _strMonths(8) = "September"
        _strMonths(9) = "October"
        _strMonths(10) = "November"
        _strMonths(11) = "December"

        'Makes label Description visible
        lblDescription.Visible = True

        'fills listbox with Birthstones
        lstStones.Items.AddRange(_strStones)

        'fills listbox with Months
        lstMonths.Items.AddRange(_strMonths)

    End Sub

    Private Sub lstStones_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstStones.SelectedIndexChanged
        lblDescription.Text = _strStones(lstStones.SelectedIndex).ToString() & " is the Birthstone for the month of " & _strMonths(lstStones.SelectedIndex).ToString()
    End Sub

    Private Sub lstMonths_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstMonths.SelectedIndexChanged
        lblDescription.Text = _strMonths(lstMonths.SelectedIndex).ToString() & " is the Month for the Birthstone " & _strStones(lstMonths.SelectedIndex).ToString()
    End Sub
End Class

Maybe this is what you want to do.


问:
angular.js:14642 TypeError: Cannot read property 'then' of undefined when calling back-end service from angular
I am calling a back-end service using angular and I am encountering an error. the response comes to my service but from there I cannot get the response to my angular controller due to the above promise error.

angular service

```<code>function userRegister(data) {
  $http.post('/api/user/register',data).then(function(response) {
    console.log(response); //the success response comes here
    return response;
  });
}
</code>```

angular controller

```<code>vm.register = function register() {
  console.log(vm.user);

  commonService.userRegister(vm.user).then(function (response) {
    console.log(response); //the promise error comes here
  });
}
</code>```

Can someone please help me solve this?

答:
you should return your service also

```<code>function userRegister(data) {
 return $http.post('/api/user/register',data).then(function(response) {
    console.log(response); //the success response comes here
    return response;
  });
}
</code>```

Body:
I am calling a back-end service using angular and I am encountering an error. the response comes to my service but from there I cannot get the response to my angular controller due to the above promise error.

angular service

function userRegister(data) {
  $http.post('/api/user/register',data).then(function(response) {
    console.log(response); //the success response comes here
    return response;
  });
}

angular controller

vm.register = function register() {
  console.log(vm.user);

  commonService.userRegister(vm.user).then(function (response) {
    console.log(response); //the promise error comes here
  });
}

Can someone please help me solve this?

Body:
you should return your service also

function userRegister(data) {
 return $http.post('/api/user/register',data).then(function(response) {
    console.log(response); //the success response comes here
    return response;
  });
}


问:
Skip certain calculated values (not cells themselves) in an AVERAGE or STDEV Excel formula based on a criterion
I have a series of paired measurements (two for each sample). I need to calculate the mean for each pair and then the general mean based on those pairwise averaged values, but I can only include those pairwise means that don't exceed a certain threshold.

I'm trying to work out an excel formula for the general mean that takes into account all of the above, without having to create additional rows/columns.

Now, the formula

```<code>=AVERAGE(IF(ABS(A1-A2)<$C$1,AVERAGE(A1,A2)),IF(ABS(A7-A8)<$C$1,AVERAGE(A7,A8)), ... )
</code>```

... doesn't do the job because it replaces with zeros those pairwise means that exceed the threshold (value of $C$1), while they just need to be skipped. "AVERAGEIF" doesn't work because it doesn't accept non-contiguous ranges (at least when they are entered as such), using "INDIRECT" to build non-contiguous ranges doesn't help either because it doesn't accept formulas. Any help appreciated.

答:
Not using helper column here is making formula look ugly but will give you the desired result. Have a try.

```<code>=AVERAGE(IF(CHOOSE({1;2;3},A1-A2,A4-A5,A7-A8)<C1,CHOOSE({1;2;3},AVERAGE(A1,A2),AVERAGE(A4,A5),AVERAGE(A7,A8))))
</code>```

This is an array formula so commit it by pressing Ctrl+Shift+Enter.

See image to see the difference in the result from above formula and formula in question that is yielding incorrect result as you mentioned.

Body:
I have a series of paired measurements (two for each sample). I need to calculate the mean for each pair and then the general mean based on those pairwise averaged values, but I can only include those pairwise means that don't exceed a certain threshold.

I'm trying to work out an excel formula for the general mean that takes into account all of the above, without having to create additional rows/columns.

Now, the formula

=AVERAGE(IF(ABS(A1-A2)<$C$1,AVERAGE(A1,A2)),IF(ABS(A7-A8)<$C$1,AVERAGE(A7,A8)), ... )

... doesn't do the job because it replaces with zeros those pairwise means that exceed the threshold (value of $C$1), while they just need to be skipped. "AVERAGEIF" doesn't work because it doesn't accept non-contiguous ranges (at least when they are entered as such), using "INDIRECT" to build non-contiguous ranges doesn't help either because it doesn't accept formulas. Any help appreciated.

Body:
Not using helper column here is making formula look ugly but will give you the desired result. Have a try.

=AVERAGE(IF(CHOOSE({1;2;3},A1-A2,A4-A5,A7-A8)<C1,CHOOSE({1;2;3},AVERAGE(A1,A2),AVERAGE(A4,A5),AVERAGE(A7,A8))))

This is an array formula so commit it by pressing Ctrl+Shift+Enter.

See image to see the difference in the result from above formula and formula in question that is yielding incorrect result as you mentioned.


问:
Can I Use JWT(JSON Web Token) authentication to our new REST API?
My authentication calls an API of the other server, I don't have a database table(The username and password does not exist on my server).How do I use JWT authentication in this case?
Thanks.</p>

答:
When You try to implement your own authentication server, you have to have a database with the username and passwords.

But after the user has its JWT Token, it can authenticate itself with it to your API Server, as long as the expiration time has not passed and the signature secret is shared between your auth and API Server, since you need to check if an attacker might have modified it.

After the expiration time has passed your client needs to issue a new token. You would usually use a second refreshToken which has a longer expiration time, and is checked against a DB to issue a new accessToken.

You could implement this yourself, but I would highly advise you to use technologies like OAuth2 since OAuth is used across all major brands like Google, Twitter, Github etc and is well tested against vulnerabilities.


问:
Remove a string that start with
 and with
 from a column in a table
I have a table called op_description, in this table a column called description.

I want to strip HTML code from that column that start with
 to the end

答:
Can you try the below?

```<code>UPDATE op_description SET description=IF(POSITION('<div class='XXX'>' IN
description)=0,description,CONCAT(LEFT(description,POSITION('<div
class='XXX'>' IN description)),"</div>"));
</code>```

Example:

Input:

```<code>Test <html> <div class="XXX"> Test</div>
</code>```

Output:

```<code>Test <html> </div>
</code>```

Body:
Can you try the below?

UPDATE op_description SET description=IF(POSITION('<div class='XXX'>' IN
description)=0,description,CONCAT(LEFT(description,POSITION('<div
class='XXX'>' IN description)),"</div>"));

Example:

Input:

Test <html> <div class="XXX"> Test</div>

Output:

Test <html> </div>


问:
Scheduled task PHP alternatives
I'm working on an existing custom eCommerce PHP application which is currently running a very resource intensive CRON every 15 minutes.

The gist of it is: Customers can set up complex filters for products they are interested in, and receive emails based on these filters. The CRON which runs every 15 minutes, checks for all new products that have been listed since it last ran, and compares them with each customers filters. If the products match a customers filters they are send an email via amazon SES.

Up until now, this method has been working ok, but as the number of active customers is rising very quickly the CRON is starting to make a noticable performance drop on the application every 15 minutes which lasts for a minute or two while it runs.

I have been toying with other ideas to help spread out the load on the server, such as performing the task each time a product is listed, so the server doesn't need to catch up on multiple products at a time.

What is usually the best practise when approaching something like this?

答:
The message queues fit perfectly well and you can easily make use of them with enqueue library. Just a few words on why should you choose it:

It supports a lot of transports from the simplest one (filesystem) to enterprise ones (RabbitMQ or Amazon SQS).

It comes with a very powerful bundle.

It has a top level abstraction which could be used with the greatest of ease.

There are a lot more which might come in handy.

Instead of defining cron tasks you need a supervisord (or any other process manager). It must be configured to run a consume command. More on this in the doc.

Whenever a message is published it is delivered to a consumer (by a broker) and is being processed.

I suggest using RabbitMQ broker.

Title: Scheduled task PHP alternatives


问:
Crontab does not run on CentOS 7
I'm using CentOS 7, and installed "cronie"

```<code>yum install cronie
</code>```

I have a shell to backup my home folder, shell's content (of course, backup.sh is 775)

```<code>#!/bin/bash
#START
TIME=`date +%Y-%m-%d_%Hh%M`
FILENAME=backupHome_123.30.150.29_$TIME.tar.gz
SRCDIR=/home
DESDIR=/backup
tar -cpvzf $DESDIR/$FILENAME $SRCDIR
#END
</code>```

And add to crontab -e

```<code>00 2 * * * /bin/bash /backup/backup.sh
</code>```

But crontab does nothing. When I check log at /var/log/cron only, something like that and no more error or processing log

```<code>May  1 00:26:08 app crontab[12041]: (root) END EDIT (root)
May  1 00:33:21 app crontab[12086]: (root) BEGIN EDIT (root)
May  1 00:34:25 app crontab[12086]: (root) END EDIT (root)
</code>```

Anyone can give me some advises to make crontab work?
Thank you.

答:
You want to make sure cron is started & that it is started if your server reboots so you need two commands on CentOS 7 to make sure of this:

```<code>systemctl enable crond && systemctl restart crond
</code>```

If you are used to using sudo, you can add sudo in front of above command. like this:

```<code>sudo systemctl enable crond && systemctl restart crond
</code>```

YOU WILL get confirmation from system, something like:

Created symlink from /etc/systemd/system/multi-user.target.wants/crond.service to /usr/lib/systemd/system/crond.service.

Then lastly check cron is running
pgrep cron

Title: Crontab does not run on CentOS 7

Body:
I'm using CentOS 7, and installed "cronie"

yum install cronie

I have a shell to backup my home folder, shell's content (of course, backup.sh is 775)

#!/bin/bash
#START
TIME=`date +%Y-%m-%d_%Hh%M`
FILENAME=backupHome_123.30.150.29_$TIME.tar.gz
SRCDIR=/home
DESDIR=/backup
tar -cpvzf $DESDIR/$FILENAME $SRCDIR
#END

And add to crontab -e

00 2 * * * /bin/bash /backup/backup.sh

But crontab does nothing. When I check log at /var/log/cron only, something like that and no more error or processing log

May  1 00:26:08 app crontab[12041]: (root) END EDIT (root)
May  1 00:33:21 app crontab[12086]: (root) BEGIN EDIT (root)
May  1 00:34:25 app crontab[12086]: (root) END EDIT (root)

Anyone can give me some advises to make crontab work?
Thank you.

Body:
You want to make sure cron is started & that it is started if your server reboots so you need two commands on CentOS 7 to make sure of this:

systemctl enable crond && systemctl restart crond

If you are used to using sudo, you can add sudo in front of above command. like this:

sudo systemctl enable crond && systemctl restart crond

YOU WILL get confirmation from system, something like:

Created symlink from /etc/systemd/system/multi-user.target.wants/crond.service to /usr/lib/systemd/system/crond.service.

Then lastly check cron is running
pgrep cron


问:
HTML & CSS progress bar does not stop at the end
I have created this progress bar and I just can't make it stop at the end. Currently its stopping at 70% and gets cleared. Any ideas? Is there any kind of animation setting to stop it at 100%?

.wrap {
  background-color: #f2f2f2;
  height: 10px;
  width: 400px;
  margin: 0 auto;
  position: relative;
  top: 20px;
  margin-bottom: 20px;
}

.bar {
  background: #ffcc00;
  height: 10px;
  width: 0%;
}

.animating {
  -webkit-animation: progress 3s ;
}

@-webkit-keyframes progress {
  0% {
    width: 0%;
  }
  100% {
    width: 70%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="bar animating"></div>
</div></code>```

答:
Try to use 100% in:</p>

```<code>@-webkit-keyframes progress {
  0% {
    width: 0%;
  }
  100% {
    width: 70%; /* edit to 100% */
  }
}
</code>```

Body:
Try to use 100% in:

@-webkit-keyframes progress {
  0% {
    width: 0%;
  }
  100% {
    width: 70%; /* edit to 100% */
  }
}


答:
I need to group by name but remove only when there are path and query for that name. Please suggest how can I do in in other way?

If I were to assume that phrase is equal to this:

How do I remove a parameter with PathType="query" from a collection, if and only if there's another parameter with the same Name AND PathType="path"?

Then you could do it with this statement:

```<code>params.RemoveAll(o => o.PathType == "query" && params.Any(p => p.Name == o.Name && p.PathType == "path"));
</code>```

Update:

For case insensitive comparison (on PathType):

```<code>params.RemoveAll(o => o.PathType.Equals("query", StringComparison.OrdinalIgnoreCase) && params.Any(p => p.Name == o.Name && p.PathType.Equals("path", StringComparison.OrdinalIgnoreCase)));
</code>```

Title: Grouping and remove from list

Body:
I have following type

public class Parameter
{
   public string Name {get;set;}
   public string PathType {get;set;}
}

My parameter list like:

List<Parameter> params = new List<Parameter>();
params.Add(new Parameter{ Name ="A", PathType ="path" });
params.Add(new Parameter{ Name ="B", PathType ="query" });
params.Add(new Parameter{ Name ="C", PathType ="path" });
params.Add(new Parameter{ Name ="C", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="path" });
params.Add(new Parameter{ Name ="D", PathType ="query" });
params.Add(new Parameter{ Name ="D", PathType ="body" });

I need to find parameters that have the same Name (like: C and D) where PathType equals path and query. Sorry for my English, it is a little bit difficult to explain. I want to find

 Name ="C", PathType ="path"
 Name ="C", PathType ="query"
 Name ="D", PathType ="path"
 Name ="D", PathType ="query"

Then remove all where PathType = "query". Finally result should be

Name ="A", PathType ="path"
Name ="B", PathType ="query"
Name ="C", PathType ="path"
Name ="D", PathType ="path"
Name ="D", PathType ="body"

My code

var groupedParams = params.GroupBy(a => a.Name, StringComparer.InvariantCultureIgnoreCase).ToDictionary(t => t.Key);
foreach (var parameter in params) {
    if (groupedParams.ContainsKey(parameter.Name)) {
        var temp = groupedParams[parameter.Name];
        if (temp.Count(x => x.PathType.ToLower() == "path") == 1 && temp.Count(x => x.PathType.ToLower() == "query") == 1) {
            params.Remove(parameter);
        }
    }
}

I need to group by name but remove only when there are path and query for that name.
Please suggest how can I do in in other way? Thanks

Body:
I need to group by name but remove only when there are path and query for that name. Please suggest how can I do in in other way?

If I were to assume that phrase is equal to this:

How do I remove a parameter with PathType="query" from a collection, if and only if there's another parameter with the same Name AND PathType="path"?

Then you could do it with this statement:

params.RemoveAll(o => o.PathType == "query" && params.Any(p => p.Name == o.Name && p.PathType == "path"));

Update:

For case insensitive comparison (on PathType):

params.RemoveAll(o => o.PathType.Equals("query", StringComparison.OrdinalIgnoreCase) && params.Any(p => p.Name == o.Name && p.PathType.Equals("path", StringComparison.OrdinalIgnoreCase)));


问:
Why would you set `null: false, default: ""` on a required DB column?
I'm building a Rails app with Devise for authentication, and its default DB migration sets the following columns:

```<code>## Database authenticatable
t.string :email,              null: false, default: ""
t.string :encrypted_password, null: false, default: ""
</code>```

What is the purpose of setting null: false and default: "" at the same time?

My understanding is that null: false effectively makes a value required: i.e., trying to save a record with a NULL value in that column will fail on the database level, without depending any validations on the model.

But then default: "" basically undoes that by simply converting NULL values to empty strings before saving.

I understand that for an optional column, you want to reject NULL values just to make sure that all data within that column is of the same type. However, in this case, email and password are decidedly not optional attributes on a user authentication model. I'm sure there are validations in the model to make sure you can't create a user with an empty email address, but why would you set default: "" here in the first place? Does it serve some benefit or prevent some edge case that I haven't considered?

答:
Some application software gacks on NULL values but not on zero-length text strings. In Oracle, they're the same thing, but not in MySQL.

Things get interesting upon altering tables to add columns. In that case a default value is mandatory, so the DBMS can populate the new column.

Body:
I'm building a Rails app with Devise for authentication, and its default DB migration sets the following columns:

## Database authenticatable
t.string :email,              null: false, default: ""
t.string :encrypted_password, null: false, default: ""

What is the purpose of setting null: false and default: "" at the same time?

My understanding is that null: false effectively makes a value required: i.e., trying to save a record with a NULL value in that column will fail on the database level, without depending any validations on the model.

But then default: "" basically undoes that by simply converting NULL values to empty strings before saving.

I understand that for an optional column, you want to reject NULL values just to make sure that all data within that column is of the same type. However, in this case, email and password are decidedly not optional attributes on a user authentication model. I'm sure there are validations in the model to make sure you can't create a user with an empty email address, but why would you set default: "" here in the first place? Does it serve some benefit or prevent some edge case that I haven't considered?


问:
Simplify User.IsInRole() check asp.net mvc
In our asp.net mvc project in .cshtml views often you can find:

if (User.IsInRole("Admin") || User.IsInRole("Supervisor"))

I'd like to simplify current syntax like this:
if (IsAdminOrSupervisor(User))

So, I need to make a html-helper, or some backend helper. Could you help me how can I do this? Thank you!

答:
Create an extension to your identity for checking multiple roles:

```<code>public static bool IsAdminOrSupervisor(this IPrincipal user, List<string> roles)
{
    var userRoles = Roles.GetRolesForUser(user.Identity.Name);

    return userRoles.Any(u => roles.Contains(u));
}
</code>```

Then you can use this like:

```<code>var roles = new List<string> { "Admin", "Supervisor" };

if (User.IsAdminOrSupervisor(roles))
{
   //Action
}
</code>```

Tips: You need to reference the class that holds this method to your Razor:

```<code>@Using NameSpace.ClassName
</code>```

Body:
Create an extension to your identity for checking multiple roles:

public static bool IsAdminOrSupervisor(this IPrincipal user, List<string> roles)
{
    var userRoles = Roles.GetRolesForUser(user.Identity.Name);

    return userRoles.Any(u => roles.Contains(u));
}

Then you can use this like:

var roles = new List<string> { "Admin", "Supervisor" };

if (User.IsAdminOrSupervisor(roles))
{
   //Action
}

Tips: You need to reference the class that holds this method to your Razor:

@Using NameSpace.ClassName


问:
How to execute a Java method multiply in same second?
I want to limit access my server per second by ip,  How can I  execute a Java method in same second to test my code?</p>

答:
You can't ever guarantee that a particular line of code will run within a certain amount of time of another, because you don't know what else is likely to be happening on the machine that you run it on.  But you can wrap your test in a loop that checks the time before and after it runs, and simply repeats if the test finished in a different second from when it started.

```<code>do {
    // record the start time

    // run the test

    //  record the end time

} while (start time and end time are in different seconds);

// If you get to here the test has failed.
</code>```

Of course, this test has to be expecting to throw whatever kind of exception you've organised to be thrown if the same IP address makes two calls in the same second; and to pass if that exception is thrown.

Body:
You can't ever guarantee that a particular line of code will run within a certain amount of time of another, because you don't know what else is likely to be happening on the machine that you run it on.  But you can wrap your test in a loop that checks the time before and after it runs, and simply repeats if the test finished in a different second from when it started.

do {
    // record the start time

    // run the test

    //  record the end time

} while (start time and end time are in different seconds);

// If you get to here the test has failed.

Of course, this test has to be expecting to throw whatever kind of exception you've organised to be thrown if the same IP address makes two calls in the same second; and to pass if that exception is thrown.