答:
It is the expected behavior.
The local storage is a key-value storage, when you write a data in an already existing key, it is overridden.

In order to add a value, you need to parse the existing value, add an item and write it again.

```<code>var storedFavs = JSON.parse(localStorage.get('favourites') || '[]');
storedFavs.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
localStorage.setItem('favourites', JSON.stringify(storedFavs));
</code>```

Title: Adding to local storage

Body:
It is the expected behavior.
The local storage is a key-value storage, when you write a data in an already existing key, it is overridden.

In order to add a value, you need to parse the existing value, add an item and write it again.

var storedFavs = JSON.parse(localStorage.get('favourites') || '[]');
storedFavs.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
localStorage.setItem('favourites', JSON.stringify(storedFavs));


来源: stackexchange

问:
Adding to local storage
I am using local storage to add json data as favorites. for some reason when i add more that one favorite it removes the one already in local storage. </p>

```<code> $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));
</code>```

答:
You are writting an array of one element, first you need to read in your favourites, add your new element to it then save it back. Try something like this, though your porbably want to add some checks to handle the case where there is no favourties already and use an empty array then etc.</p>

```<code>    var storedbar = JSON.parse(localStorage.getItem('storedBar'));
    var favArray = JSON.parse(localStorage.getItem('favourites'));
    favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
    localStorage.setItem('favourites', JSON.stringify(favArray));
    console.log(localStorage.getItem('favourites'));
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding to local storage

Body:
I am using local storage to add json data as favorites. for some reason when i add more that one favorite it removes the one already in local storage.

 $('.favoritesbtn').click(function() {
        var storedbar = JSON.parse(localStorage.getItem('storedBar'));
        var favArray = [];
        favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
        localStorage.setItem('favourites', JSON.stringify(favArray));
        console.log(localStorage.getItem('favourites'));

Body:
You are writting an array of one element, first you need to read in your favourites, add your new element to it then save it back. Try something like this, though your porbably want to add some checks to handle the case where there is no favourties already and use an empty array then etc.

    var storedbar = JSON.parse(localStorage.getItem('storedBar'));
    var favArray = JSON.parse(localStorage.getItem('favourites'));
    favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
    localStorage.setItem('favourites', JSON.stringify(favArray));
    console.log(localStorage.getItem('favourites'));


问:
Extract time series of a point ( lon, lat) from netCDF in R
I am relatively new on R.
I am trying to get time series of different points ( lat, lon) of temperature data from a netCDF file.
My sample data file is here and here is the small file .  I have tried netCDF package and the code i have used so far

```<code>library(ncdf)
obsdata = open.ncdf("obs.nc")

print.ncdf(obsdata)

obsdatadates = obsdata$dim$time$vals
obsdatadates = as.Date(obsdatadates,origin = '1950-01-01')
obsdatadates
obsoutput = get.var.ncdf(obsdata, varid = 'tasmin', start = c(1,1,1),
                         count = c(1,1,22280))
dim(obsoutput)
datafinal=merge(obsdatadates,obsoutput)
</code>```

Can anyone help me to get a dataframe of timeseries ( first column) and value of data in another for a particular points( lat, lon) of that data.
In this case I am looking for time series ( 1950-01-01 to 2010-12-31  for which the data is ) for a particular lat lon point ( and repeat for many points of interests) and for given variable(in this case tasmin).
Your help would be appreciated.
Thank you,
aseem

答:
the 'ncdf'-package is deprecated: http://cirrus.ucsd.edu/~pierce/ncdf/

update with the ncdf4 package:

```<code>library(ncdf4)
obsdata <- nc_open("obs1.nc")
print(obsdata) # check that dims are lon-lat-time

# location of interest
lon <- 6  # longitude of location
lat <- 51 # latitude  of location

# get dates
obsdatadates <- as.Date(obsdata$dim$time$vals, origin = '1950-01-01')

# get values at location lonlat
obsoutput <- ncvar_get(obsdata, varid = 'tasmin',
                  start= c(which.min(abs(obsdata$dim$longitude$vals - lon)), # look for closest long
                           which.min(abs(obsdata$dim$latitude$vals - lat)),  # look for closest lat
                           1),
                  count = c(1,1,-1)) #count '-1' means 'all values along that dimension'that dimension'
# create dataframe
datafinal <- data.frame(dates= obsdatadates, obs = obsoutput)
</code>```

Body:
I am relatively new on R.
I am trying to get time series of different points ( lat, lon) of temperature data from a netCDF file.
My sample data file is here and here is the small file .  I have tried netCDF package and the code i have used so far

library(ncdf)
obsdata = open.ncdf("obs.nc")

print.ncdf(obsdata)

obsdatadates = obsdata$dim$time$vals
obsdatadates = as.Date(obsdatadates,origin = '1950-01-01')
obsdatadates
obsoutput = get.var.ncdf(obsdata, varid = 'tasmin', start = c(1,1,1),
                         count = c(1,1,22280))
dim(obsoutput)
datafinal=merge(obsdatadates,obsoutput)

Can anyone help me to get a dataframe of timeseries ( first column) and value of data in another for a particular points( lat, lon) of that data.
In this case I am looking for time series ( 1950-01-01 to 2010-12-31  for which the data is ) for a particular lat lon point ( and repeat for many points of interests) and for given variable(in this case tasmin).
Your help would be appreciated.
Thank you,
aseem

Body:
the 'ncdf'-package is deprecated: http://cirrus.ucsd.edu/~pierce/ncdf/

update with the ncdf4 package:

library(ncdf4)
obsdata <- nc_open("obs1.nc")
print(obsdata) # check that dims are lon-lat-time

# location of interest
lon <- 6  # longitude of location
lat <- 51 # latitude  of location

# get dates
obsdatadates <- as.Date(obsdata$dim$time$vals, origin = '1950-01-01')

# get values at location lonlat
obsoutput <- ncvar_get(obsdata, varid = 'tasmin',
                  start= c(which.min(abs(obsdata$dim$longitude$vals - lon)), # look for closest long
                           which.min(abs(obsdata$dim$latitude$vals - lat)),  # look for closest lat
                           1),
                  count = c(1,1,-1)) #count '-1' means 'all values along that dimension'that dimension'
# create dataframe
datafinal <- data.frame(dates= obsdatadates, obs = obsoutput)


问:
Transaction on two tables at the same time in two different databases
I have spring-boot app with mybatis as my ORM. I also use sqlserver 2012.

I consider following scenario:

```<code>void foo () {
    set current datasource as Datasource D1 (connected to database D1)
    do some insert on table T1 in database D1
    set current datasource as Datasource D2 (connected to database D2)
    do some insert on table T1 (the same name) in database D2
}
</code>```

I would like to be able to ensure that it always succees both queries. Otherwise (when at least one of them fails) transaction will be rollback (I mean no changes) in both databases (even if one of them query succeed).

I think that @Transactional above foo() is not sufficient.

Is it possible to gain this effect ?

答:
SQL Server provides the ability to manage transactions distributed across databases and/or servers. You start the distributed transaction with BEGIN DISTRIBUTED TRANSACTION

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/begin-distributed-transaction-transact-sql

Body:
I have spring-boot app with mybatis as my ORM. I also use sqlserver 2012.

I consider following scenario:

void foo () {
    set current datasource as Datasource D1 (connected to database D1)
    do some insert on table T1 in database D1
    set current datasource as Datasource D2 (connected to database D2)
    do some insert on table T1 (the same name) in database D2
}

I would like to be able to ensure that it always succees both queries. Otherwise (when at least one of them fails) transaction will be rollback (I mean no changes) in both databases (even if one of them query succeed).

I think that @Transactional above foo() is not sufficient.

Is it possible to gain this effect ?


问:
How do I modify a JSON Object in a JSON list?
My JSON list looks like this,(Where Type 3 is the CommandType.Welcome):

```<code>[
  {
    "Keyword": "Hello",
    "Type": 0,
    "Message": "World"
  },
  {
    "Keyword": "Hi",
    "Type": 0,
    "Message": "There"
  },
  {
    "Keyword": "Test",
    "Type": 0,
    "Message": "test"
  },
  {
    "Keyword": "Greeting",
    "Type": 3,
    "Message": "Welcome"
  }
]
</code>```

My current method will pull the correct Object from the list and modify the object but it isn't modify the List Object. For Example, command.message = message but when I serialize the list it doesn't merge the changes.

```<code>    public void SetGreetMessage(string message)
    {
        var leaveGreet = new LeaveGreetService();
        foreach (var command in leaveGreet.CommandList.Where(x => x.Type == CommandType.Welcome))
        {
            command.Message = message;
            dynamic jsonData = JsonConvert.SerializeObject(CommandList, Formatting.Indented);

            File.WriteAllText("Commands.txt", jsonData);
        }
    }
</code>```

I have looked online at a few resources and most parse into a string and modify it with the string. But I was wondering if it was possible to do it like this somehow. I know I can add a new object to it with this method but modifying seems to be a great feat.

Edit:

```<code>using System;

namespace vVvBot.Model
{
    public class CustomCommand
    {
        public string Keyword { get; set; }
        public CommandType Type { get; set; }
        public string Message { get; set; }
    }

    public enum CommandType
    {
        Message,
        Faq,
        Action,
        Welcome,
        Leaving
    }
}
</code>```

CommandList is the list of the command Object from the file

答:
I think you're passing command parameter incorrectly and json isn't being generated. I have changed serializeObject parameter from CommandList to command.

```<code>public void SetGreetMessage(string message)
    {
        var leaveGreet = new LeaveGreetService();
        foreach (var command in leaveGreet.CommandList.Where(x => x.Type == CommandType.Welcome))
        {
            command.Message = message;
            dynamic jsonData = JsonConvert.SerializeObject(command, Formatting.Indented);

            File.WriteAllText("Commands.txt", jsonData);
        }
    }
</code>```

Body:
My JSON list looks like this,(Where Type 3 is the CommandType.Welcome):

[
  {
    "Keyword": "Hello",
    "Type": 0,
    "Message": "World"
  },
  {
    "Keyword": "Hi",
    "Type": 0,
    "Message": "There"
  },
  {
    "Keyword": "Test",
    "Type": 0,
    "Message": "test"
  },
  {
    "Keyword": "Greeting",
    "Type": 3,
    "Message": "Welcome"
  }
]

My current method will pull the correct Object from the list and modify the object but it isn't modify the List Object. For Example, command.message = message but when I serialize the list it doesn't merge the changes.

    public void SetGreetMessage(string message)
    {
        var leaveGreet = new LeaveGreetService();
        foreach (var command in leaveGreet.CommandList.Where(x => x.Type == CommandType.Welcome))
        {
            command.Message = message;
            dynamic jsonData = JsonConvert.SerializeObject(CommandList, Formatting.Indented);

            File.WriteAllText("Commands.txt", jsonData);
        }
    }

I have looked online at a few resources and most parse into a string and modify it with the string. But I was wondering if it was possible to do it like this somehow. I know I can add a new object to it with this method but modifying seems to be a great feat.

Edit:

using System;

namespace vVvBot.Model
{
    public class CustomCommand
    {
        public string Keyword { get; set; }
        public CommandType Type { get; set; }
        public string Message { get; set; }
    }

    public enum CommandType
    {
        Message,
        Faq,
        Action,
        Welcome,
        Leaving
    }
}

CommandList is the list of the command Object from the file

Body:
I think you're passing command parameter incorrectly and json isn't being generated. I have changed serializeObject parameter from CommandList to command.

public void SetGreetMessage(string message)
    {
        var leaveGreet = new LeaveGreetService();
        foreach (var command in leaveGreet.CommandList.Where(x => x.Type == CommandType.Welcome))
        {
            command.Message = message;
            dynamic jsonData = JsonConvert.SerializeObject(command, Formatting.Indented);

            File.WriteAllText("Commands.txt", jsonData);
        }
    }


问:
Parsing XML file and coverting it to array of objects
I'm trying to get the XML contents and organize it as objects to retreive them in json file.

XML structure:

```<code><lorem date="2017-01-01">
    <ipsum key="a">0001</ipsum>
    <ipsum key="b">0002</ipsum>
    <ipsum key="c">0003</ipsum>
    <ipsum key="d">0004</ipsum>
</lorem>
</code>```

and PHP

```<code><?php
    $URL = simplexml_load_file("http://www.example.com");
    foreach($URL -> lorem -> ipsum as $item){
        $arr = array($item["key"] => $item["value"]);
    }
    echo json_encode($arr);
?>
</code>```

At the end i would like to get json returned with the following structure:

```<code>{
"a": "0001",
"b": "0002",
"c": "0003",
"d": "0004",
}
</code>```

But i'm stuck on how to retrieve values between the ipsum tags. And also the code above doesn't work as expected.

答:
Change your code like this

```<code><?php
    $URL = simplexml_load_file("http://www.example.com");
    foreach($URL->ipsum as $item){
        $arr[] = array((string)$item["key"] => (string)$item);
    }
    echo json_encode($arr);

    //for the format you show above
    $URL = simplexml_load_file("http://www.example.com");
    $arr = new stdClass();
    foreach($URL->ipsum as $item){
        $key = (string)$item["key"];
        $arr->{$key} = (string)$item;
    }
    echo json_encode([$arr]);
?>
</code>```

via (string)$item["key"] you access always a node attribute

via $item->subnode you get the child node(s)

via (string)$item you get the content of the current node

Body:
I'm trying to get the XML contents and organize it as objects to retreive them in json file.

XML structure:

<lorem date="2017-01-01">
    <ipsum key="a">0001</ipsum>
    <ipsum key="b">0002</ipsum>
    <ipsum key="c">0003</ipsum>
    <ipsum key="d">0004</ipsum>
</lorem>

and PHP

<?php
    $URL = simplexml_load_file("http://www.example.com");
    foreach($URL -> lorem -> ipsum as $item){
        $arr = array($item["key"] => $item["value"]);
    }
    echo json_encode($arr);
?>

At the end i would like to get json returned with the following structure:

{
"a": "0001",
"b": "0002",
"c": "0003",
"d": "0004",
}

But i'm stuck on how to retrieve values between the ipsum tags. And also the code above doesn't work as expected.

Body:
Change your code like this

<?php
    $URL = simplexml_load_file("http://www.example.com");
    foreach($URL->ipsum as $item){
        $arr[] = array((string)$item["key"] => (string)$item);
    }
    echo json_encode($arr);

    //for the format you show above
    $URL = simplexml_load_file("http://www.example.com");
    $arr = new stdClass();
    foreach($URL->ipsum as $item){
        $key = (string)$item["key"];
        $arr->{$key} = (string)$item;
    }
    echo json_encode([$arr]);
?>

via (string)$item["key"] you access always a node attribute

via $item->subnode you get the child node(s)

via (string)$item you get the content of the current node


问:
jsf selectOneMenu value does not change
I have a selectOneMenu that have the correct values (a list of string) however when I select a value it does not trigger the setSelectedValue from the bean.

```<code><h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}">
    <f:selectItems value="#{Bean.values}"/>
</h:selectOneMenu>
</code>```

Bean:

```<code>private String selectedValue = "";
private List<String> values = new LinkedList<String>();

...

public String getSelectedValue() {
    return this.selectedValue;
}

public void setSelectedValue(String selectedValue) {
    LOGGER.debug("Try to set selected value" + selectedValue);
    if (!selectedValue.isEmpty()){
        this.selectedValue = selectedValue ;
    }
}
</code>```

There is nothing in the logs.

I've tried to add a listener:

```<code><h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}" valueChangeListener="#{dwrBean.statusChanged}" >
    <f:selectItems value="#{dwrBean.values}"/>
</h:selectOneMenu>
</code>```

Here the statusChanged is triggered but the newValue is null, the oldValue is correct, but it is always the same.

```<code>public void statusChanged(ValueChangeEvent event) {
    LOGGER.debug("new" + event.getNewValue());
    LOGGER.debug("old" + event.getOldValue());

    if (event.getNewValue() != null &&
            !((String) event.getNewValue()).isEmpty()) {

            LOGGER.debug("OK");
        }
}
</code>```

I really don't understand.

Actually the selectOneMenu is within a popup.

I've moved the selectOneMenu outside of the popup and it works. Do I have to change the scope of the Bean ?

Non-working configuration:

```<code><h:form>
     <rich:popupPanel>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>
<h:form>
</code>```

Working configuration:

```<code><h:form>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>

     <rich:popupPanel>
<h:form>
</code>```

答:
You need to use AJAX to do a partial form submission when the value changes. The valueChangeListener is a hook that provides your code with notification when the value has changed and the form has been submitted.

The code below will register an AJAX event for the onchange event for selectOneMenu. The value changes it will then execute the menu (submit the value to the bean).

```<code><h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}">
   <f:selectItems value="#{dwrBean.values}"/>
   <f:ajax/>
</h:selectOneMenu>
</code>```

Title: jsf selectOneMenu value does not change

Body:
I have a selectOneMenu that have the correct values (a list of string) however when I select a value it does not trigger the setSelectedValue from the bean.

<h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}">
    <f:selectItems value="#{Bean.values}"/>
</h:selectOneMenu>

Bean:

private String selectedValue = "";
private List<String> values = new LinkedList<String>();

...

public String getSelectedValue() {
    return this.selectedValue;
}

public void setSelectedValue(String selectedValue) {
    LOGGER.debug("Try to set selected value" + selectedValue);
    if (!selectedValue.isEmpty()){
        this.selectedValue = selectedValue ;
    }
}

There is nothing in the logs.

I've tried to add a listener:

<h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}" valueChangeListener="#{dwrBean.statusChanged}" >
    <f:selectItems value="#{dwrBean.values}"/>
</h:selectOneMenu>

Here the statusChanged is triggered but the newValue is null, the oldValue is correct, but it is always the same.

public void statusChanged(ValueChangeEvent event) {
    LOGGER.debug("new" + event.getNewValue());
    LOGGER.debug("old" + event.getOldValue());

    if (event.getNewValue() != null &&
            !((String) event.getNewValue()).isEmpty()) {

            LOGGER.debug("OK");
        }
}

I really don't understand.

Actually the selectOneMenu is within a popup.

I've moved the selectOneMenu outside of the popup and it works. Do I have to change the scope of the Bean ?

Non-working configuration:

<h:form>
     <rich:popupPanel>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>
<h:form>

Working configuration:

<h:form>
          <h:selectOneMenu>
               ...
          </h:selectOneMenu>
     <rich:popupPanel>

     <rich:popupPanel>
<h:form>

Body:
You need to use AJAX to do a partial form submission when the value changes. The valueChangeListener is a hook that provides your code with notification when the value has changed and the form has been submitted.

The code below will register an AJAX event for the onchange event for selectOneMenu. The value changes it will then execute the menu (submit the value to the bean).

<h:selectOneMenu layout="lineDirection" id="myMenu" value="#{dwrBean.selectedValue}">
   <f:selectItems value="#{dwrBean.values}"/>
   <f:ajax/>
</h:selectOneMenu>


问:
Get year, month or day from numpy datetime64
I have an array of datetime64 type:

```<code>dates = np.datetime64(['2010-10-17', '2011-05-13', "2012-01-15"])
</code>```

Is there a better way than looping through each element just to get np.array of years:

```<code>years = f(dates)
#output:
array([2010, 2011, 2012], dtype=int8) #or dtype = string
</code>```

I'm using stable numpy version 1.6.2.

答:
Using numpy version 1.10.4 and pandas version 0.17.1,

```<code>dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype=np.datetime64)
pd.to_datetime(dates).year
</code>```

I get what you're looking for:

```<code>array([2010, 2011, 2012], dtype=int32)
</code>```

Body:
I have an array of datetime64 type:

dates = np.datetime64(['2010-10-17', '2011-05-13', "2012-01-15"])

Is there a better way than looping through each element just to get np.array of years:

years = f(dates)
#output:
array([2010, 2011, 2012], dtype=int8) #or dtype = string

I'm using stable numpy version 1.6.2.

Body:
Using numpy version 1.10.4 and pandas version 0.17.1,

dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype=np.datetime64)
pd.to_datetime(dates).year

I get what you're looking for:

array([2010, 2011, 2012], dtype=int32)


问:
Jquery each and visible - Unknown Pseudoclass or Pseudoelement 'visible'

i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

```<code>$('.fse:visible').each(function (i)
</code>```

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

```<code>$('.fse').is(':visible').each(function (i)
</code>```

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter

答:
$('.fse').is(':visible') checks if the element is visible or not and returns true or false. Appending ".each" is the same as you would typing "false.each(...)" or "true.each(...)". And "true" or "false" does not have a method called "each".

You can try it using the find-selector: $.find('.fse:visible').each(...) or jQuery.find('.fse.visible').

ContentLicense: CC BY-SA 2.5

Body:
i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

$('.fse:visible').each(function (i)

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

$('.fse').is(':visible').each(function (i)

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter


问:
Ansible - Reading output of remote scripts into variable for processing by another play
I'm writing a playbook that will run a script on a number of remote boxes. The stdout_lines of running these remotes needs to be collated into one single array that can be passed to another play in the book that is run locally, where this big collated array is then passed to a module.

I can't seem to find a way to do this. Some code kind-of stuff (that doesn't work) is below:

```<code>---

- name: Gather information from hosts
  hosts: remote-hosts
  become: yes
  become_method: sudo

  vars:
    information: |
      {%- set o=[] %}
      {%- for i in play_hosts %}
        {%- for line in hostvars[i].info_script_output_lines %}
          {%- if o.append(hostvars[i].info_script_output_lines[line]) %}
          {%- endif %}
        {%- endfor %}
      {%- endfor %}
      {{ o }}

  tasks:
    - name: Run info retrieval script
      script: /script_folder/script_that_outputs_lines.sh
      register: info_script_output

    - set_fact:
        info_script_output_lines: "{{ info_script_output.stdout_lines }}"

    - set_fact:
        final_info: "{{ info_script_output_lines }}"
        run_once: true
        delegate_to: 127.0.0.1
        delegate_facts: true

- name: Output result
  hosts: localhost

  tasks:
    - debug:
        msg: Output = {{ hostvars['localhost']['final_info'] }}
</code>```

hostvars['localhost']['final_info'] doesn't exist in the second play.

Can anyone explain whether I'm (a) constructing my array correctly with the output facts from each remote and (b) how to get that final consolidated array into another play so I can use it?

答:
Here you go:

```<code>---
- hosts: mygroup
  gather_facts: no
  tasks:
    - shell: echo begin; echo {{ inventory_hostname }}; echo end;
      register: cmd_output
    - set_fact:
        my_lines: "{{ cmd_output.stdout_lines }}"

- hosts: localhost
  gather_facts: no
  vars:
    combined_lines: "{{ groups['mygroup'] | map('extract',hostvars,'my_lines') | sum(start=[]) }}"
  tasks:
    - debug:
        msg: "{{ combined_lines }}"
</code>```

Use extract filter and then sum(start=[]) to flatten the list into long list of lines.

Body:
I'm writing a playbook that will run a script on a number of remote boxes. The stdout_lines of running these remotes needs to be collated into one single array that can be passed to another play in the book that is run locally, where this big collated array is then passed to a module.

I can't seem to find a way to do this. Some code kind-of stuff (that doesn't work) is below:

---

- name: Gather information from hosts
  hosts: remote-hosts
  become: yes
  become_method: sudo

  vars:
    information: |
      {%- set o=[] %}
      {%- for i in play_hosts %}
        {%- for line in hostvars[i].info_script_output_lines %}
          {%- if o.append(hostvars[i].info_script_output_lines[line]) %}
          {%- endif %}
        {%- endfor %}
      {%- endfor %}
      {{ o }}

  tasks:
    - name: Run info retrieval script
      script: /script_folder/script_that_outputs_lines.sh
      register: info_script_output

    - set_fact:
        info_script_output_lines: "{{ info_script_output.stdout_lines }}"

    - set_fact:
        final_info: "{{ info_script_output_lines }}"
        run_once: true
        delegate_to: 127.0.0.1
        delegate_facts: true

- name: Output result
  hosts: localhost

  tasks:
    - debug:
        msg: Output = {{ hostvars['localhost']['final_info'] }}

hostvars['localhost']['final_info'] doesn't exist in the second play.

Can anyone explain whether I'm (a) constructing my array correctly with the output facts from each remote and (b) how to get that final consolidated array into another play so I can use it?

Body:
Here you go:

---
- hosts: mygroup
  gather_facts: no
  tasks:
    - shell: echo begin; echo {{ inventory_hostname }}; echo end;
      register: cmd_output
    - set_fact:
        my_lines: "{{ cmd_output.stdout_lines }}"

- hosts: localhost
  gather_facts: no
  vars:
    combined_lines: "{{ groups['mygroup'] | map('extract',hostvars,'my_lines') | sum(start=[]) }}"
  tasks:
    - debug:
        msg: "{{ combined_lines }}"

Use extract filter and then sum(start=[]) to flatten the list into long list of lines.


问:
Why is this caterpillar algorithm O(n^2) not O(n^3)?
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

```<code>        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z < A.Length && A[x] + A[y] > A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }
</code>```

答: You should note that z is initialized inside x-loop, not y-loop. And on every x-iteration z could be incremented maximum A.length - x - 2 times.

Body:
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z  A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }


问:
Realloc resizing array
i'm having a doubt about the use of the realloc() function in C++. I need it to basically change the size of an array by removing the first item. This is what i've done

```<code>cell* Queue::pull() {
    cell* data = cellArray[0];
    arrayLen--;
    cell** temp = (cell**)realloc(cellArray+1, sizeof(cell*)* (arrayLen));
    if (temp == NULL) {
        return 0;
    }
    cellArray = temp;
    return data;
}
</code>```

arrayLen is and integer and it stores the current lenght of the queue and cellArray is a cell* array which is allocated and populated previously.

```<code>cell** cellArray;
int arrayLen = 0;
</code>```

My problem is: does this cause a memory leak? Does realloc free the space that was used by the first item of the array or is this basically the same as something like:

```<code>cell** temp = cellArray+1;
</code>```

Thank you in advance.

答:
If the allocated memory is expanded, the following is true:

If the current memory segment is required after the memory space, then directly expand this memory space, realloc () will return to the original pointer.

If the free bytes behind the current memory segment are not enough, then use the first memory block to meet this requirement, copy the current data to the new location, and release the original data block, Returns a new memory block location.

If the application fails, will return NULL, this time, the original pointer is still valid.

And you should note: If the call is successful, regardless of the current memory space behind the free space to meet the requirements, will release the original pointer, return to a pointer, although the return of the pointer and the original pointer is the same, that can not release the original pointer again

Title: Realloc resizing array

Body:
i'm having a doubt about the use of the realloc() function in C++. I need it to basically change the size of an array by removing the first item. This is what i've done

cell* Queue::pull() {
    cell* data = cellArray[0];
    arrayLen--;
    cell** temp = (cell**)realloc(cellArray+1, sizeof(cell*)* (arrayLen));
    if (temp == NULL) {
        return 0;
    }
    cellArray = temp;
    return data;
}

arrayLen is and integer and it stores the current lenght of the queue and cellArray is a cell* array which is allocated and populated previously.

cell** cellArray;
int arrayLen = 0;

My problem is: does this cause a memory leak? Does realloc free the space that was used by the first item of the array or is this basically the same as something like:

cell** temp = cellArray+1;

Thank you in advance.


问:
RVM is not working over SSH
RVM is not working over SSH.

At the command-line:

```<code>leifg@host:~$ which ruby
/usr/local/rvm/rubies/ruby-1.9.2-p290/bin/ruby
</code>```

Connected over SSH:

```<code>local:~$ ssh leifg@server 'which ruby'
/usr/bin/ruby
</code>```

I'm using Ubuntu 11.04.

How do I get SSH to use the same Ruby as it is on the system?

I already verified some prequisites:

Ruby was already installed using apt-get install ruby. Does that make any difference?

sshd_config has the option "PermitUserEnvironment yes", and I restarted the daemon.

The .bashrc on the server contains these lines, but I see the same behavior when I remove them:

```<code>if [ -s "$HOME/.rvm/scripts/rvm" ] ; then
  . "$HOME/.rvm/scripts/rvm"
elif [ -s "/usr/local/rvm/scripts/rvm" ] ; then
  . "/usr/local/rvm/scripts/rvm"
fi
</code>```

答:
zoomix's is the best solution. But when you change with "ruby rvm use system" in terminal or what else you get an error :
Warning! PATH is not properly set up, is not at first place.... To solve that put the snippet just before the return instead of at the top of the .bashrc file (Debian Jessie here)</p>

```<code>case $- in
*i*) ;;
  *)
  [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
  return;; esac
</code>```

Title: RVM is not working over SSH

Body:
RVM is not working over SSH.

At the command-line:

leifg@host:~$ which ruby
/usr/local/rvm/rubies/ruby-1.9.2-p290/bin/ruby

Connected over SSH:

local:~$ ssh leifg@server 'which ruby'
/usr/bin/ruby

I'm using Ubuntu 11.04.

How do I get SSH to use the same Ruby as it is on the system?

I already verified some prequisites:

Ruby was already installed using apt-get install ruby. Does that make any difference?

sshd_config has the option "PermitUserEnvironment yes", and I restarted the daemon.

The .bashrc on the server contains these lines, but I see the same behavior when I remove them:

if [ -s "$HOME/.rvm/scripts/rvm" ] ; then
  . "$HOME/.rvm/scripts/rvm"
elif [ -s "/usr/local/rvm/scripts/rvm" ] ; then
  . "/usr/local/rvm/scripts/rvm"
fi

Body:
zoomix's is the best solution. But when you change with "ruby rvm use system" in terminal or what else you get an error :
Warning! PATH is not properly set up, is not at first place.... To solve that put the snippet just before the return instead of at the top of the .bashrc file (Debian Jessie here)

case $- in
*i*) ;;
  *)
  [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
  return;; esac


问:
Wix - Remove files only when uninstall, when having REP after InstallInitialize
I have to accomplish the following: when the product gets completelly uninstalled (from add/remove programs, not during an update) I need to specifically delete 2 additional files.

For that I have the following code:

```<code><Component Id="RemoveLogosFile" Guid="PUT_MY_GUID" >
  <RemoveFile Id="RemoveLogosFile" Name="MyLogo.jpg" On="uninstall"/>
  <RemoveFile Id="RemoveBundleFile" Name="bundle" On="uninstall"/>
  <Condition>(NOT UPGRADINGPRODUCTCODE) AND (REMOVE=ALL)</Condition>
</Component>
</code>```

The above code works as expected if:

```<code><RemoveExistingProducts After="InstallFinalize"/>
</code>```

meaning the 2 files are deleted only during an uninstall from
add/remove programs and they don't get deleted during an update.

But in my installer I have:

```<code><RemoveExistingProducts After="InstallInitialize"/>
</code>```

and the behavior in this case is that the 2 files are always deleted regardless if it's an update or removal from add/remove programs.

Can somebody help me accomplish the deletion of those files only when uninstalling from add/remove programs and not during an update, when having

```<code><RemoveExistingProducts After="InstallInitialize"/>
</code>```

?

Thank you,
MeCoco

答:
I finally got the answer. Look here:
http://www.mail-archive.com/wix-users@lists.sourceforge.net/msg42579.html</p>

Body:
I have to accomplish the following: when the product gets completelly uninstalled (from add/remove programs, not during an update) I need to specifically delete 2 additional files.

For that I have the following code:

<Component Id="RemoveLogosFile" Guid="PUT_MY_GUID" >
  <RemoveFile Id="RemoveLogosFile" Name="MyLogo.jpg" On="uninstall"/>
  <RemoveFile Id="RemoveBundleFile" Name="bundle" On="uninstall"/>
  <Condition>(NOT UPGRADINGPRODUCTCODE) AND (REMOVE=ALL)</Condition>
</Component>

The above code works as expected if:

<RemoveExistingProducts After="InstallFinalize"/>

meaning the 2 files are deleted only during an uninstall from
add/remove programs and they don't get deleted during an update.

But in my installer I have:

<RemoveExistingProducts After="InstallInitialize"/>

and the behavior in this case is that the 2 files are always deleted regardless if it's an update or removal from add/remove programs.

Can somebody help me accomplish the deletion of those files only when uninstalling from add/remove programs and not during an update, when having

<RemoveExistingProducts After="InstallInitialize"/>

?

Thank you,
MeCoco


问:
Laravel - Master password / Log into other accounts?
I have developed a nutrition platform that I'm using with my clients. It's somewhat similar to MyFitnessPal.

Some of my clients need help refining their diets so I need to log into their account to make changes to their plan.

What's the best option to achieve this? I thought of maybe having a master password that lets me log into any clients account but I don't know how to implement this.

My postLogin() method in the LoginController doesn't seem to be doing anything.

答:
In our applications we have a route/controller method in the admin backend that does something like auth()->login($user); then redirects you to the route the usual user would go to when they first login.

Docs:
https://laravel.com/docs/5.4/authentication#other-authentication-methods


问:
Does Eclipse for Android developers is not compactable with Java projects ? It shows Null Pointer exceptions
Code****************************************************************************

```<code>import javax.swing.JFrame;

import javax.swing.JSlider;

//import com.fazecast.jSerialComm.*;

public class Main{// extends JFrame{

    public static void main(String[] args) {

        try{
            JFrame w = new JFrame();
            w.setBounds(100, 100, 200, 200);
            JSlider slider = new JSlider();
            slider.setMinimum(1023);
            w.add(slider);
            w.pack();
            w.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Error***************************************************************************

```<code>java.lang.NullPointerException
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at Main.main(Main.java:11)
</code>```

答: Yes.there is no JFrame in Android.</p>

Body:
Code****************************************************************************

import javax.swing.JFrame;

import javax.swing.JSlider;

//import com.fazecast.jSerialComm.*;

public class Main{// extends JFrame{

    public static void main(String[] args) {

        try{
            JFrame w = new JFrame();
            w.setBounds(100, 100, 200, 200);
            JSlider slider = new JSlider();
            slider.setMinimum(1023);
            w.add(slider);
            w.pack();
            w.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Error***************************************************************************

java.lang.NullPointerException
at java.awt.Window.init(Unknown Source)
at java.awt.Window.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at java.awt.Frame.<init>(Unknown Source)
at javax.swing.JFrame.<init>(Unknown Source)
at Main.main(Main.java:11)

Body: Yes.there is no JFrame in Android.


问:
C# Assigning Enum value to object
In some places of our code, we are assigning enum value to object variable (ex: object value = DayOfWeek.Sunday). I was thinking on the line that enum underlying type is int, so why not use (int) and then call .ToString() to avoid boxing. To my happiness, It seems to avoid boxing (I checked IL code) but to my surprise, that part of code took more time to execute and allocated more memory too. I used BenchmarkDotNet tool to test performance differences. Below are the code samples,

1) Returning enum value, boxing happens (IL code below)

```<code>public object AssingEnumToObject()
    {
        return DayOfWeek.Sunday;
    }

  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldc.i4.0
  IL_0001:  box        [mscorlib]System.DayOfWeek
  IL_0006:  ret
</code>```

2) Using (int), still boxing happens understandably.

```<code>public object AssingEnumIntToObject()
        {
            return (int)DayOfWeek.Sunday;
        }

// Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldc.i4.0
  IL_0001:  box        [mscorlib]System.Int32
  IL_0006:  ret
</code>```

3) Using (int) then ToString(). Now its string which is returned for method requiring object return type. No boxing in IL but call to Int32.ToString() method.

```<code>public object AssingEnumIntStringToObject()
        {
            return ((int)DayOfWeek.Sunday).ToString();
        }

  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] int32 V_0)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloca.s   V_0
  IL_0004:  call       instance string [mscorlib]System.Int32::ToString()
  IL_0009:  ret
</code>```

To my surprise, BenchmarkDotNet tool shows, method 3 (AssingEnumIntStringToObject) is taking longer and allocating more memory.

Results of BenchmarkDotNet tool
What am I missing here? Is it because of this rule in CSharp Language Specification "From any enum-type to the type System.Enum" ? If so, how this works?

Please explain me. Thanks.

Edit:

Thanks @JonSkeet and @Craig for the answers. I failed to take into account the cost of creating string reference. I understood now.

答:
Method 3 is taking longer because it is adding a function call to ToString and allocating and assigning a string, all of which takes extra time.

Method 3 is taking more memory because it is allocating a string.  Like with the boxing conversions, this is adding a reference (pointer-sized), but it is also adding the string itself.  The string will be at least the size of an int: at minimum, it has a counter for the size (four bytes, I believe) plus the buffer for the characters (minimum one character for your case).  Thus, this is taking more than double the additional memory vs the other two, which at most only add a reference (pointer-sized).

Title: C# Assigning Enum value to object

Body:
In some places of our code, we are assigning enum value to object variable (ex: object value = DayOfWeek.Sunday). I was thinking on the line that enum underlying type is int, so why not use (int) and then call .ToString() to avoid boxing. To my happiness, It seems to avoid boxing (I checked IL code) but to my surprise, that part of code took more time to execute and allocated more memory too. I used BenchmarkDotNet tool to test performance differences. Below are the code samples,

1) Returning enum value, boxing happens (IL code below)

public object AssingEnumToObject()
    {
        return DayOfWeek.Sunday;
    }

  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldc.i4.0
  IL_0001:  box        [mscorlib]System.DayOfWeek
  IL_0006:  ret

2) Using (int), still boxing happens understandably.

public object AssingEnumIntToObject()
        {
            return (int)DayOfWeek.Sunday;
        }

// Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldc.i4.0
  IL_0001:  box        [mscorlib]System.Int32
  IL_0006:  ret

3) Using (int) then ToString(). Now its string which is returned for method requiring object return type. No boxing in IL but call to Int32.ToString() method.

public object AssingEnumIntStringToObject()
        {
            return ((int)DayOfWeek.Sunday).ToString();
        }

  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] int32 V_0)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloca.s   V_0
  IL_0004:  call       instance string [mscorlib]System.Int32::ToString()
  IL_0009:  ret

To my surprise, BenchmarkDotNet tool shows, method 3 (AssingEnumIntStringToObject) is taking longer and allocating more memory.

Results of BenchmarkDotNet tool
What am I missing here? Is it because of this rule in CSharp Language Specification "From any enum-type to the type System.Enum" ? If so, how this works?

Please explain me. Thanks.

Edit:

Thanks @JonSkeet and @Craig for the answers. I failed to take into account the cost of creating string reference. I understood now.


问:
Loopback "Include" Filter Fails with hasManyThrough Relation
I have 3 models. 2 resource models, account(id, name) and widget(id, name), and 1 mapping model to map between the two widget_to_account(id, account_id, widget_id), to tell what widgets an account has access to, so to speak.

When stating the relationship between the models in their JSONs, using the guide in http://loopback.io/doc/en/lb3/HasManyThrough-relations.html, RESTful requests like "get widgets of account id=1" for example, works perfectly.

GET /accounts/1/widgets yields the widgets that account 1 has, yielding a widgets array:

```<code>[
    {
        "id": 1,
        "name": "wg_user_mgr"
    },
    {
        "id": 2,
        "name": "wg_desc"
    }
]
</code>```

That's all good.

However, say I wanted to append this widgets array result along with the account object returned by a GET to the account model?. Loopback documentation suggests that this is done using the include keyword with the request, like so:
GET /accounts/1?filter[include]=widgets, returning hopefully an account model with it's allowed widgets:

```<code>{
    "id": 1,
    "name": "Account1Name",
    "widgets": [
        {
            "id": 1,
            "name": "wg_user_mgr",
            "display_name": "User Manager"
        },
        {
            "id": 2,
            "name": "wg_desc",
            "display_name": "Description"
        }
    ]
}
</code>```

However, what is actually returned by loopback with that request, is:

```<code>{
    "id": 1,
    "name": "Account1Name",
    "widgets": []
}
</code>```

Empty widgets array! When I look at the loopback SQL debugs, I see that it does go to the widget_to_account table and selects the entries of account_id=1, but interestingly it stop there and just returns an empty widgets array.

Any clues? The hasManyThrough loopback docs doesn't actually show any examples of using include like this to bridge two models that are connected via a mapping model.

My guess is they just forgot to code it in ¯\_(ツ)_/¯

UPDATE:

Doing some more digging around, I found the answer at https://groups.google.com/forum/#!topic/loopbackjs/sH7bKoqzU5c.

Where you define the relationships in the 2 resource models, you have to specifically define the "keyThrough" value.

NOT THIS:

```<code>"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account"
    }
}
</code>```

BUT THIS:

```<code>"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account",
        "keyThrough": "account_id"
    }
}
</code>```

This is not made super clear, and is even stated incorrectly in the loopback api docs -.-

答:
UPDATE:

Doing some more digging around, I found the answer at https://groups.google.com/forum/#!topic/loopbackjs/sH7bKoqzU5c.

Where you define the relationships in the 2 resource models, you have to specifically define the "keyThrough" value.

NOT THIS:

```<code>"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account"
    }
}
</code>```

BUT THIS:

```<code>"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account",
        "keyThrough": "widget_id"
    }
}
</code>```

This is not made super clear, and is even stated incorrectly in the loopback api docs. I wish they'de stop this "auto-naming" paradigm they've been pushing around. Looking at loopback SO and the wider community, it's generally caused so much pain with models being named incorrectly, keys like this being set to totally arbitary names -.-

Body:
I have 3 models. 2 resource models, account(id, name) and widget(id, name), and 1 mapping model to map between the two widget_to_account(id, account_id, widget_id), to tell what widgets an account has access to, so to speak.

When stating the relationship between the models in their JSONs, using the guide in http://loopback.io/doc/en/lb3/HasManyThrough-relations.html, RESTful requests like "get widgets of account id=1" for example, works perfectly.

GET /accounts/1/widgets yields the widgets that account 1 has, yielding a widgets array:

[
    {
        "id": 1,
        "name": "wg_user_mgr"
    },
    {
        "id": 2,
        "name": "wg_desc"
    }
]

That's all good.

However, say I wanted to append this widgets array result along with the account object returned by a GET to the account model?. Loopback documentation suggests that this is done using the include keyword with the request, like so:
GET /accounts/1?filter[include]=widgets, returning hopefully an account model with it's allowed widgets:

{
    "id": 1,
    "name": "Account1Name",
    "widgets": [
        {
            "id": 1,
            "name": "wg_user_mgr",
            "display_name": "User Manager"
        },
        {
            "id": 2,
            "name": "wg_desc",
            "display_name": "Description"
        }
    ]
}

However, what is actually returned by loopback with that request, is:

{
    "id": 1,
    "name": "Account1Name",
    "widgets": []
}

Empty widgets array! When I look at the loopback SQL debugs, I see that it does go to the widget_to_account table and selects the entries of account_id=1, but interestingly it stop there and just returns an empty widgets array.

Any clues? The hasManyThrough loopback docs doesn't actually show any examples of using include like this to bridge two models that are connected via a mapping model.

My guess is they just forgot to code it in ¯\_(ツ)_/¯

UPDATE:

Doing some more digging around, I found the answer at https://groups.google.com/forum/#!topic/loopbackjs/sH7bKoqzU5c.

Where you define the relationships in the 2 resource models, you have to specifically define the "keyThrough" value.

NOT THIS:

"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account"
    }
}

BUT THIS:

"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account",
        "keyThrough": "account_id"
    }
}

This is not made super clear, and is even stated incorrectly in the loopback api docs -.-

Body:
UPDATE:

Doing some more digging around, I found the answer at https://groups.google.com/forum/#!topic/loopbackjs/sH7bKoqzU5c.

Where you define the relationships in the 2 resource models, you have to specifically define the "keyThrough" value.

NOT THIS:

"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account"
    }
}

BUT THIS:

"relations": {
    "widgets": {
        "type": "hasMany",
        "model": "widget",
        "foreignKey": "account_id",
        "through": "widget_to_account",
        "keyThrough": "widget_id"
    }
}

This is not made super clear, and is even stated incorrectly in the loopback api docs. I wish they'de stop this "auto-naming" paradigm they've been pushing around. Looking at loopback SO and the wider community, it's generally caused so much pain with models being named incorrectly, keys like this being set to totally arbitary names -.-

ContentLicense: CC BY-SA 4.0


问:
Searching for a word in a file & then printing the value next to it in Tcl
I have the following text file with me:

```
 ..............................................
 ..............................................
 ..............................................
 ..............................................
 xyz (MTU)                             301.2017
```

I tried the following :

```<code>set fd [open "textfile.file" r]
set data [read $fd]
set input_list [split $data "\n"]
set pattern [lsearch -all -inline $data "xyz (MTU)*"]
foreach elem $pattern{
    puts "[lindex $elem 3]"
}
</code>```

But it gives a blank output ?

答:
The problem is that there's a space at the start of the line. If I add a space at the start of the pattern, it works:</p>

```<code>% set pattern [lsearch -all -inline -glob $input_list " xyz (MTU)*"]
{ xyz (MTU)                             301.2017}
</code>```

Body:
I have the following text file with me:

 ..............................................
 ..............................................
 ..............................................
 ..............................................
 xyz (MTU)                             301.2017

I tried the following :

set fd [open "textfile.file" r]
set data [read $fd]
set input_list [split $data "\n"]
set pattern [lsearch -all -inline $data "xyz (MTU)*"]
foreach elem $pattern{
    puts "[lindex $elem 3]"
}

But it gives a blank output ?

Body:
The problem is that there's a space at the start of the line. If I add a space at the start of the pattern, it works:

% set pattern [lsearch -all -inline -glob $input_list " xyz (MTU)*"]
{ xyz (MTU)                             301.2017}


问:
Appending in middle of text in column data oracle sql
I need to append the text in middle of text .

1 EX :existing text is : "Monoclonal Anti-FLAG, Clone 6F7"

Result :"<HIDE>Monoclonal Anti-<HIDE>FLAG, Clone 6F7".

2 EX :existing text is : "Anti-100-KD subunit"

Result  : "<HIDE> Anti-</HIDE>100-KD subunit"

I want to append <HIDE> tag where ever Anti and Monoclonal term is coming.

```<code>select * from table where regexp_like(colnanme, '^(Monoclonal Anti|Anti)')
</code>```

Can you suggest how should i write this .for select i have written query .

答:
The predicted certain regular expression solution.</p>

```<code>-- Start test data
with test_data as
    (select 'Monoclonal Anti-FLAG, Clone 6F7' as test_string from dual union all
     select 'Anti-100-KD subunit' from dual)
-- End test data
select test_string,
       REGEXP_REPLACE(test_string,'(Monoclonal Anti-|Anti-)','<HIDE>\1</HIDE>')
from   test_data;

"TEST_STRING"                     "Result"
"Monoclonal Anti-FLAG, Clone 6F7" "<HIDE>Monoclonal Anti-</HIDE>FLAG, Clone 6F7"
"Anti-100-KD subunit"             "<HIDE>Anti-</HIDE>100-KD subunit"
</code>```

Body:
I need to append the text in middle of text .

1 EX :existing text is : "Monoclonal Anti-FLAG, Clone 6F7"

Result :"<HIDE>Monoclonal Anti-<HIDE>FLAG, Clone 6F7".

2 EX :existing text is : "Anti-100-KD subunit"

Result  : "<HIDE> Anti-</HIDE>100-KD subunit"

I want to append <HIDE> tag where ever Anti and Monoclonal term is coming.

select * from table where regexp_like(colnanme, '^(Monoclonal Anti|Anti)')

Can you suggest how should i write this .for select i have written query .

Body:
The predicted certain regular expression solution.

-- Start test data
with test_data as
    (select 'Monoclonal Anti-FLAG, Clone 6F7' as test_string from dual union all
     select 'Anti-100-KD subunit' from dual)
-- End test data
select test_string,
       REGEXP_REPLACE(test_string,'(Monoclonal Anti-|Anti-)','<HIDE>\1</HIDE>')
from   test_data;

"TEST_STRING"                     "Result"
"Monoclonal Anti-FLAG, Clone 6F7" "<HIDE>Monoclonal Anti-</HIDE>FLAG, Clone 6F7"
"Anti-100-KD subunit"             "<HIDE>Anti-</HIDE>100-KD subunit"


问:
Error during compilation
I downloaded a software framework from the Data Prefetching Championship website (http://www.jilp.org/dpc/) and installed on a computer with the Ubuntu OS, 64 bit.  I followed all of the instructions for unpacking the compressed file, and entered the "make" command to compile and this is what I received:

```<code>g++ -Wl,-u,main -g -shared -Wl,-Bsymbolic -Wl,--version-script=/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/source/include/pintool.ver -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/Lib/ -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/ExtLib/ -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/extras/xed2-intel64/lib -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/intel64/lib -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/intel64/lib-ext  -o bin/CMPsim.usetrace ./bin/libCMPsim64.a ./src/prefetch/sample_prefetcher.o -lpin  -lxed -ldwarf -lelf -ldl  /usr/lib/x86_64-linux-gnu/libz.a
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libz.a(gzio.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libz.a: could not read symbols: Bad value
collect2: ld returned 1 exit status
make: *** [CMPsimpref64] Error 1
</code>```

The problem, I believe, is with the libz.a file.  Help?

答: I also faced same problem mentions above but I am able to solved it with scientific linux 5.4 with gcc 4.1 configuration and I did one mistake when we have to set path up to prefetch kit. There was '$' sign which we have to remove while setting path for that PREF_KIT

Title: Error during compilation

Body:
I downloaded a software framework from the Data Prefetching Championship website (http://www.jilp.org/dpc/) and installed on a computer with the Ubuntu OS, 64 bit.  I followed all of the instructions for unpacking the compressed file, and entered the "make" command to compile and this is what I received:

g++ -Wl,-u,main -g -shared -Wl,-Bsymbolic -Wl,--version-script=/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/source/include/pintool.ver -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/Lib/ -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/ExtLib/ -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/extras/xed2-intel64/lib -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/intel64/lib -L/grads/hhoffman/Documents/ELE_591/PREF_KIT/pin-2.5-22247-gcc.4.0.0-ia32_intel64-linux/intel64/lib-ext  -o bin/CMPsim.usetrace ./bin/libCMPsim64.a ./src/prefetch/sample_prefetcher.o -lpin  -lxed -ldwarf -lelf -ldl  /usr/lib/x86_64-linux-gnu/libz.a
/usr/bin/ld: /usr/lib/x86_64-linux-gnu/libz.a(gzio.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/usr/lib/x86_64-linux-gnu/libz.a: could not read symbols: Bad value
collect2: ld returned 1 exit status
make: *** [CMPsimpref64] Error 1

The problem, I believe, is with the libz.a file.  Help?


答:
It sounds like you also have Prototype (or another library using $) included in the page, is that the case?

Try jQuery('.fse:visible').each(function (i) {... to verify that's the case.

Title: Jquery each and visible - Unknown Pseudoclass or Pseudoelement 'visible'

Body:
i have a problem with jquery/visible. Hope somebody can help me.

This code works, but i get an error in firebug

$('.fse:visible').each(function (i)

-> Unknown Pseudoclass or Pseudoelement 'visible'.

second try

$('.fse').is(':visible').each(function (i)

->  $(".fse").is(":visible").each is not a function

Whats wrong?

Thanks in advance!

Peter


问:
Way to update all Readme(s) of Guithub Repo with changed styling
As given here ,Github has changed the way to show smnallest heading from 3 Pound symbols to <s> Four </s> Six Pound symbols . I am looking for some way to update all my Readme(s) of the repos that I have.

Eg: https://github.com/HackersArena/python-backdoor (In the last part of the read-me)

Also reference linking has changed as you can see here:

Eg: https://github.com/TilakMaddy/gulp-template-backend-support (Broken page links)

I am looking for any sort of Git - command -built - in- Migration technique
to update all the readme(s) ?

答:
Well, to address your question: updating of the content isn't really in git's wheel house.  Depending on your environment, a combination of Unix (or git bash) tools can probably achieve that sort of edit with reasonable ease...

But are you sure you need to change anything?  The documentation you linked actually shows six hashes (not four) as the "smallest heading", but three hashes is still "heading smaller than you get with two hashes"...  unless you have more than three levels of heading, why not leave it be?


问:
Turn variable elements into string for json
How can I make a foreach in here to turn every $values_x array element into a string?

```<code>$values_x = '';
if ( isset( $chart_render_data['options']['xAxis']['categories'] ) ) {
    $values_x = $chart_render_data['options']['xAxis']['categories'];
}
</code>```

$values_x outputs this, in the current graph I have:

```<code>array(14) {
  [0]=>float(2002)
  [1]=>float(2003)
  [2]=>float(2004)
  [3]=>float(2005)
  [4]=>float(2006)
  [5]=>float(2007)
  [6]=>float(2008)
  [7]=>float(2009)
  [8]=>float(2010)
  [9]=>float(2011)
  [10]=>float(2012)
  [11]=>float(2013)
  [12]=>float(2014)
  [13]=>float(2015)
}
bool(true)
</code>```

And I need it to output "2002", etc.
Any help is greatly appreciated.

答:
Another version with the exact same logic - wrap each value in quotes.  When you declare $values_x access each element (either via array_map or foreach()) and wrap them with double quotes.  As stated in another answer, casting as (string) will also work.

Code: (Demo)

```<code>$chart_render_data['options']['xAxis']['categories']=array(
    array(2002),array(2003),array(2004),array(2005),array(2006),array(2007),
    array(2008),array(2009),array(2010),array(2011),array(2012),array(2013),
    array(2014),array(2015));

if(isset( $chart_render_data['options']['xAxis']['categories'])){
    $values_x=array_map(function($v){return "$v";},array_column($chart_render_data['options']['xAxis']['categories'],0));
}
foreach($values_x as $v){
    echo "$v is a ",gettype($v),"\n";
}
</code>```

Output:

```<code>2002 is a string
2003 is a string
2004 is a string
2005 is a string
2006 is a string
2007 is a string
2008 is a string
2009 is a string
2010 is a string
2011 is a string
2012 is a string
2013 is a string
2014 is a string
2015 is a string
</code>```

Body:
How can I make a foreach in here to turn every $values_x array element into a string?

$values_x = '';
if ( isset( $chart_render_data['options']['xAxis']['categories'] ) ) {
    $values_x = $chart_render_data['options']['xAxis']['categories'];
}

$values_x outputs this, in the current graph I have:

array(14) {
  [0]=>float(2002)
  [1]=>float(2003)
  [2]=>float(2004)
  [3]=>float(2005)
  [4]=>float(2006)
  [5]=>float(2007)
  [6]=>float(2008)
  [7]=>float(2009)
  [8]=>float(2010)
  [9]=>float(2011)
  [10]=>float(2012)
  [11]=>float(2013)
  [12]=>float(2014)
  [13]=>float(2015)
}
bool(true)

And I need it to output "2002", etc.
Any help is greatly appreciated.

Body:
Another version with the exact same logic - wrap each value in quotes.  When you declare $values_x access each element (either via array_map or foreach()) and wrap them with double quotes.  As stated in another answer, casting as (string) will also work.

Code: (Demo)

$chart_render_data['options']['xAxis']['categories']=array(
    array(2002),array(2003),array(2004),array(2005),array(2006),array(2007),
    array(2008),array(2009),array(2010),array(2011),array(2012),array(2013),
    array(2014),array(2015));

if(isset( $chart_render_data['options']['xAxis']['categories'])){
    $values_x=array_map(function($v){return "$v";},array_column($chart_render_data['options']['xAxis']['categories'],0));
}
foreach($values_x as $v){
    echo "$v is a ",gettype($v),"\n";
}

Output:

2002 is a string
2003 is a string
2004 is a string
2005 is a string
2006 is a string
2007 is a string
2008 is a string
2009 is a string
2010 is a string
2011 is a string
2012 is a string
2013 is a string
2014 is a string
2015 is a string


问:
How to store result of dynamically executed stored procedure into a variable?
I am trying to assign result of a stored procedure executed dynamically into a variable. However when i call them, sql throw me this error:

Could not find the stored procedure 'exec dbo.cont_com 3611,892;'

Below is the code snippet I am using:

```<code>declare @procedure_to_call varchar(max);
declare @procedure_result int;

set @procedure_to_call='exec dbo.cont_com 3611,892;'

exec @procedure_result=@procedure_to_call;
</code>```

When I put parenthesis and execute the stored procedure, it works fine:

```<code>exec (@procedure_to_call);
</code>```

But i need to save the return of the @procedure_to_call inside a variable.

This is the sample code for dbo.cont_com SP:

```<code>CREATE PROCEDURE dbo.cont_com
(
    @id_c int,
    @id_f int)
AS
BEGIN

    declare @porcent int;

    select @porcent=p.porcent
    from porcent_table p
    where p.id_c=@id_c
    and p.id_c=@id_f;

    select porcent=@porcent;
    return @porcent;

END
</code>```

Any help will be greatly appreciated.

答:
Try something like this.

```<code>DECLARE @procedure_to_call NVARCHAR(MAX) = 'EXEC @x = dbo.cont_com 3611,892'
DECLARE @procedure_result INT;
SET @procedure_result = 0;

EXEC sp_executesql @procedure_to_call, N'@x INT OUT', @procedure_result OUT;
SELECT @procedure_result
</code>```

It worked for me, hope it work for you.

Body:
I am trying to assign result of a stored procedure executed dynamically into a variable. However when i call them, sql throw me this error:

Could not find the stored procedure 'exec dbo.cont_com 3611,892;'

Below is the code snippet I am using:

declare @procedure_to_call varchar(max);
declare @procedure_result int;

set @procedure_to_call='exec dbo.cont_com 3611,892;'

exec @procedure_result=@procedure_to_call;

When I put parenthesis and execute the stored procedure, it works fine:

exec (@procedure_to_call);

But i need to save the return of the @procedure_to_call inside a variable.

This is the sample code for dbo.cont_com SP:

CREATE PROCEDURE dbo.cont_com
(
    @id_c int,
    @id_f int)
AS
BEGIN

    declare @porcent int;

    select @porcent=p.porcent
    from porcent_table p
    where p.id_c=@id_c
    and p.id_c=@id_f;

    select porcent=@porcent;
    return @porcent;

END

Any help will be greatly appreciated.

Body:
Try something like this.

DECLARE @procedure_to_call NVARCHAR(MAX) = 'EXEC @x = dbo.cont_com 3611,892'
DECLARE @procedure_result INT;
SET @procedure_result = 0;

EXEC sp_executesql @procedure_to_call, N'@x INT OUT', @procedure_result OUT;
SELECT @procedure_result

It worked for me, hope it work for you.


问:
how to get the document url to add custom fields using docusign api
I am trying to integrate docusign embedded signing into my hybrid app and i am loading the signing url in an iframe in my app, but is there any way to add some more custom fields on the fly using that signing url and make it in an unlocked state so that i can drag them where i want, and then make those fields locked at the time of sending to the sender for signing, also how to get the url of that document after he has signed it so that i can view it later.

Since i am a newbie in this please help me.

This is my code to get the signing url

```<code><?php
$min=100;
$max=300;
$random = rand($min,$max);
$recipientId=rand();
require_once('vendor/autoload.php');
//require_once('./docusign-php-client/autoload.php');
// DocuSign account credentials & Integrator Key
$username = "testmail@mail.com";
$password = "test1234";
$integrator_key = "[integrator-key]";
$host = "https://demo.docusign.net/restapi";
// create a new DocuSign configuration and assign host and header(s)
$config = new DocuSign\eSign\Configuration();
$config->setHost($host);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
/////////////////////////////////////////////////////////////////////////
// STEP 1:  Login() API
/////////////////////////////////////////////////////////////////////////
// instantiate a new docusign api client
$apiClient = new DocuSign\eSign\ApiClient($config);
// we will first make the Login() call which exists in the AuthenticationApi...
$authenticationApi = new DocuSign\eSign\Api\AuthenticationApi($apiClient);
// optional login parameters
$options = new \DocuSign\eSign\Api\AuthenticationApi\LoginOptions();
// call the login() API
$loginInformation = $authenticationApi->login($options);
// parse the login results
if(isset($loginInformation) && count($loginInformation) > 0)
{
    // note: defaulting to first account found, user might be a
    // member of multiple accounts
    $loginAccount = $loginInformation->getLoginAccounts()[0];
    if(isset($loginInformation))
    {
        $accountId = $loginAccount->getAccountId();
        if(!empty($accountId))
        {
            echo "<b>Account ID</b> = $accountId</br>";
        }
    }
}
/////////////////////////////////////////////////////////////////////////
// STEP 2:  Create & Send Envelope with Embedded Recipient
/////////////////////////////////////////////////////////////////////////
// set recipient information
$recipientName = "username";
$recipientEmail = "Test@email.com";
// configure the document we want signed
$documentFileName = "/abcd_test_01.pdf";
$documentName = "abcd_test.pdf";
// instantiate a new envelopeApi object
$envelopeApi = new DocuSign\eSign\Api\EnvelopesApi($apiClient);
// Add a document to the envelope
$document = new DocuSign\eSign\Model\Document();
$document->setDocumentBase64(base64_encode(file_get_contents(__DIR__ . $documentFileName)));
$document->setName($documentName);
$document->setDocumentId("1");
// Create a |SignHere| tab somewhere on the document for the recipient to sign
$signHere = new \DocuSign\eSign\Model\SignHere();
$signHere->setXPosition($random);
$signHere->setYPosition($random);
$signHere->setDocumentId("1");
$signHere->setPageNumber("1");
$signHere->setRecipientId("1");
// add the signature tab to the envelope's list of tabs
$tabs = new DocuSign\eSign\Model\Tabs();
$tabs->setSignHereTabs(array($signHere));
// add a signer to the envelope
$signer = new \DocuSign\eSign\Model\Signer();
$signer->setEmail($recipientEmail);
$signer->setName($recipientName);
$signer->setRecipientId("1");
$signer->setTabs($tabs);
$signer->setClientUserId($recipientId);  // must set this to embed the recipient!
// Add a recipient to sign the document
$recipients = new DocuSign\eSign\Model\Recipients();
$recipients->setSigners(array($signer));
$envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
$envelop_definition->setEmailSubject("[DocuSign PHP SDK] - Please sign this doc");
// set envelope status to "sent" to immediately send the signature request
$envelop_definition->setStatus("sent");
$envelop_definition->setRecipients($recipients);
$envelop_definition->setDocuments(array($document));
// create and send the envelope! (aka signature request)
$envelop_summary = $envelopeApi->createEnvelope($accountId, $envelop_definition, null);
echo "<b>Envelope Details: </b>```".$envelop_summary ."```</br>";

/////////////////////////////////////////////////////////////////////////
// STEP 3:  Request Recipient View (aka signing URL)
/////////////////////////////////////////////////////////////////////////
// instantiate a RecipientViewRequest object
$recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest();
// set where the recipient is re-directed once they are done signing
$recipient_view_request->setReturnUrl("https://www.docusign.com/develcenter");
// configure the embedded signer
$recipient_view_request->setUserName($recipientName);
$recipient_view_request->setEmail($recipientEmail);
// must reference the same clientUserId that was set for the recipient when they
// were added to the envelope in step 2
$recipient_view_request->setClientUserId($recipientId);
// used to indicate on the certificate of completion how the user authenticated
$recipient_view_request->setAuthenticationMethod("email");
// generate the recipient view! (aka embedded signing URL)
$signingView = $envelopeApi->createRecipientView($accountId, $envelop_summary->getEnvelopeId(), $recipient_view_request);
echo "</br> Signing URL = getUrl() . "' target='_blank'>".$signingView->getUrl()."</br>";

//MEthod for embedded sending view
$return_url="https://www.docusign.com/devcenter";
$senderView = $envelopeApi->createSenderView($accountId, $envelopeId,
$return_url);
var_dump($senderView->getUrl());
</code>```

答:
If you want to place additional fields on the document as a sender, you should use the Embedded Sending (or Sender View)

The Embedded Sending view of an envelope allows users to edit the tabs, documents, recipients, and other settings of draft envelopes before sending them out for approval. Similar to Embedded Signing, your app or website can generate a sending URL and integrate directly into your workflow using a Redirect, Webview, or an iFrame.

See here for the code sample.

Q : How to get the url of that document after he has signed it so that i can view it later.

See this answer.

Body:
I am trying to integrate docusign embedded signing into my hybrid app and i am loading the signing url in an iframe in my app, but is there any way to add some more custom fields on the fly using that signing url and make it in an unlocked state so that i can drag them where i want, and then make those fields locked at the time of sending to the sender for signing, also how to get the url of that document after he has signed it so that i can view it later.

Since i am a newbie in this please help me.

This is my code to get the signing url

<?php
$min=100;
$max=300;
$random = rand($min,$max);
$recipientId=rand();
require_once('vendor/autoload.php');
//require_once('./docusign-php-client/autoload.php');
// DocuSign account credentials & Integrator Key
$username = "testmail@mail.com";
$password = "test1234";
$integrator_key = "[integrator-key]";
$host = "https://demo.docusign.net/restapi";
// create a new DocuSign configuration and assign host and header(s)
$config = new DocuSign\eSign\Configuration();
$config->setHost($host);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
/////////////////////////////////////////////////////////////////////////
// STEP 1:  Login() API
/////////////////////////////////////////////////////////////////////////
// instantiate a new docusign api client
$apiClient = new DocuSign\eSign\ApiClient($config);
// we will first make the Login() call which exists in the AuthenticationApi...
$authenticationApi = new DocuSign\eSign\Api\AuthenticationApi($apiClient);
// optional login parameters
$options = new \DocuSign\eSign\Api\AuthenticationApi\LoginOptions();
// call the login() API
$loginInformation = $authenticationApi->login($options);
// parse the login results
if(isset($loginInformation) && count($loginInformation) > 0)
{
    // note: defaulting to first account found, user might be a
    // member of multiple accounts
    $loginAccount = $loginInformation->getLoginAccounts()[0];
    if(isset($loginInformation))
    {
        $accountId = $loginAccount->getAccountId();
        if(!empty($accountId))
        {
            echo "Account ID = $accountId
";
        }
    }
}
/////////////////////////////////////////////////////////////////////////
// STEP 2:  Create & Send Envelope with Embedded Recipient
/////////////////////////////////////////////////////////////////////////
// set recipient information
$recipientName = "username";
$recipientEmail = "Test@email.com";
// configure the document we want signed
$documentFileName = "/abcd_test_01.pdf";
$documentName = "abcd_test.pdf";
// instantiate a new envelopeApi object
$envelopeApi = new DocuSign\eSign\Api\EnvelopesApi($apiClient);
// Add a document to the envelope
$document = new DocuSign\eSign\Model\Document();
$document->setDocumentBase64(base64_encode(file_get_contents(__DIR__ . $documentFileName)));
$document->setName($documentName);
$document->setDocumentId("1");
// Create a |SignHere| tab somewhere on the document for the recipient to sign
$signHere = new \DocuSign\eSign\Model\SignHere();
$signHere->setXPosition($random);
$signHere->setYPosition($random);
$signHere->setDocumentId("1");
$signHere->setPageNumber("1");
$signHere->setRecipientId("1");
// add the signature tab to the envelope's list of tabs
$tabs = new DocuSign\eSign\Model\Tabs();
$tabs->setSignHereTabs(array($signHere));
// add a signer to the envelope
$signer = new \DocuSign\eSign\Model\Signer();
$signer->setEmail($recipientEmail);
$signer->setName($recipientName);
$signer->setRecipientId("1");
$signer->setTabs($tabs);
$signer->setClientUserId($recipientId);  // must set this to embed the recipient!
// Add a recipient to sign the document
$recipients = new DocuSign\eSign\Model\Recipients();
$recipients->setSigners(array($signer));
$envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
$envelop_definition->setEmailSubject("[DocuSign PHP SDK] - Please sign this doc");
// set envelope status to "sent" to immediately send the signature request
$envelop_definition->setStatus("sent");
$envelop_definition->setRecipients($recipients);
$envelop_definition->setDocuments(array($document));
// create and send the envelope! (aka signature request)
$envelop_summary = $envelopeApi->createEnvelope($accountId, $envelop_definition, null);
echo "Envelope Details:
".$envelop_summary ."

";

/////////////////////////////////////////////////////////////////////////
// STEP 3:  Request Recipient View (aka signing URL)
/////////////////////////////////////////////////////////////////////////
// instantiate a RecipientViewRequest object
$recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest();
// set where the recipient is re-directed once they are done signing
$recipient_view_request->setReturnUrl("https://www.docusign.com/develcenter");
// configure the embedded signer
$recipient_view_request->setUserName($recipientName);
$recipient_view_request->setEmail($recipientEmail);
// must reference the same clientUserId that was set for the recipient when they
// were added to the envelope in step 2
$recipient_view_request->setClientUserId($recipientId);
// used to indicate on the certificate of completion how the user authenticated
$recipient_view_request->setAuthenticationMethod("email");
// generate the recipient view! (aka embedded signing URL)
$signingView = $envelopeApi->createRecipientView($accountId, $envelop_summary->getEnvelopeId(), $recipient_view_request);
echo "
 Signing URL = getUrl() . "' target='_blank'>".$signingView->getUrl()."
";

//MEthod for embedded sending view
$return_url="https://www.docusign.com/devcenter";
$senderView = $envelopeApi->createSenderView($accountId, $envelopeId,
$return_url);
var_dump($senderView->getUrl());


问:
View differences of branches with meld?
I know that I can view the difference between HEAD and current state with meld .. But how can I view the differences between branches, for example master and devel with meld?

At the moment I do the following steps:

Rename folder of working copy

    For example mv /projectA /projectA_master)

Clone the project again

    git clone url

Switch to devel branch

    cd projectA && git -b devel origin/devel

View differences with meld

    meld /projectA_Master projectA

Isn't there an easier way to get the same result in meld? I only need it to review the changes and not primarily for merging.

答: I also found this issue annoying so I've made git meld which allows a more comfortable way of diffing arbitrary commits against the working tree or the staging area. You can find it at https://github.com/wmanley/git-meld .  It's a bit like Mark's script but works for comparing any arbitrary commit or the staging area or the working directory against any of the others.  If one of the things you are comparing against is the working tree then that is read-write also so you don't lose your changes.</p>

Title: View differences of branches with meld?


问:
Using AspNetCore.SignalR with net462
Apologies if this is a stupid question, I've been looking into this for hours and have gotten myself really confused by the different framework versions and by the current state of SignalR.

I've got an asp.net core 1.1 web application (.NET Framework) currently targetting net462, and I wish to add websocket functionality to this using SignalR. I've tried adding the MyGet feed (https://dotnet.myget.org/F/aspnetcore-master/api/v3/index.json) but can't add Microsoft.AspNetCore.SignalR, even though this seems to be the recommended course of action. I wondered if this was because of an incompatibility between SignalR and net462, but SignalR targets netstandard1.3 which as far as I can tell should be compatible with net462.

Can anyone point me in the right direction?

答:
I made two silly mistakes here, posting just in case it helps anyone else:

The correct feed url was: https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json

I didn't notice there was a 'Package source' dropdown

Title: Using AspNetCore.SignalR with net462


问:
Identify if an image is blurred (preferred without OpenCV)
Just completed building a camera using AVCaptureSession for scanning documents on iPhone, I am looking for away to determine if the captured image is in good quality and not blurred.
I saw many solutions using OpenCV and I am looking for an other options.

Any Help would be appreciated.

Thanks

答:
First of all, interesting question, made me do some research to figure out stuff myself. In general, Analysis of focus measure operators for shape-from-focus is a great research paper, talking about a few methods (36 to be precise) on how to get measure of blurriness in an image, from simple/straightforward ones to more complex ones.

I have done myself some basic laplacian operation on one channel of the image (essentially 2nd derivative of the pixels) to measure the blurriness, which worked quite well for me. Once you convolve the channel with the laplacian operator, the variance of this laplacian image is a good estimate of the blurriness. The assumption here is that if an image contains high variance then there is a wide spread of responses, both edge-like and non-edge like, representative of a normal, in-focus image. But if there is very low variance, then there is a tiny spread of responses, indicating there are very little edges in the image. As we know, the more an image is blurred, the less edges there are. The trick here is to find an apt threshold for the variance to be high/low, which I guess you can ascertain by running it on your dataset.

Courtesy: Blog

PS. Although the blog I reference here mentions "OpenCV", the methods can be implemented as you want if you understand the concept and hence I started the answer with the research paper.


问:
Why is this caterpillar algorithm O(n^2) not O(n^3)?
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

```<code>        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z < A.Length && A[x] + A[y] > A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }
</code>```

答:
The trick lies in the fact that z is increased in total up to A.Length:
E.g. if we get unlucky in the first iteration:

x=0, y=1 and we get z to go from 2 to A.Length, in the subsequent y-loops, z won't be incremented at all.

Body:
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z  A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }


问:
Hibernate or JPA?
With Spring 3.0 is it recommended to use hibernate or JPA.What are the advantages and disadvantages of both of them when used with Spring 3.0 ?

Note : We are also suppose to use it with Spring Data Access.

答:
To be precise, you should use the Java Persistence API, and then you can use Hibernate as an implementation.

JPA without an implementation isn't worth anything.

JPA is a standard, so if you only use it's API, you can substitute Hibernate with some other JPA implementation. If you use some of Hibernate's specific API because you need functionality not provided with plain JPA, you'll have a vendor lock-in scenario, so you'll have to be careful about this.

Title: Hibernate or JPA?


问:
Tracking duration of functions calls in vb.net
In our VB6 applications, we added a few utility functions for tracking the amount of time spent in a function.  We did this to track performance bottlenecks.

Basically, how it worked was there were two utility functions: StartTickCount() and EndTickCount().  You would pass the name of the function in each, and the functions would use a dictionary to get the tick count when StartTickCount() was called, and then subtract the tick count when EndTickCount() was called.  This wasn't perfect because it didn't of course take into consideration that calls to get tick count takes time, etc, but basically it worked for our purposes.  The pain in the butt part was making sure to call StartTickCount() at the beginning of each function and EndTickCount() at each exit point:

```<code>Private Function SomeFuction() as String
    ' indicate the function started
    StartTickCount("MyClass.SomeFunction")

    ' some logic that causes the function to end
    If (some logic) Then
        EndTickCount("MyClass.SomeFunction")
        Return "Hello!"
    End If

    ' final exit point
    EndTickCount("MyClass.SomeFunction")
    Return "World"
End Function
</code>```

Anyway, is there any functionality built in, either through the VS 2010 debugger or in the System.Reflection namespace, to do something similar in VB.NET?

Basically, what I want is to log the number of times each function is called, the total amount to time spent in that function, the average number of seconds spent in that function, and the maximum amount of time spent in a single call in that function.

I can certainly write this by hand (since we already did once in VB6), but if there are existing tools to make it easier, I'd rather use them.

答:
I ofently use this helper class. It basically does what @AndreaAntonangeli suggested but arranged to have a cleaner code:

```<code>Public Class TimeSpanHelper

    Dim caller_name As String
    Dim timer_start As DateTime
    Dim time_spent As System.TimeSpan
    Dim prev_time As DateTime
    Dim time_diff As System.TimeSpan

    Public Sub New(caller As String)
        caller_name = caller
    End Sub

    Public Sub startClock()
        timer_start = DateTime.Now
        Console.WriteLine(caller_name & " starts at:" & timer_start.ToString)
        prev_time = timer_start
    End Sub

    Public Sub getElapsedTime(Optional flag As String = "")
        time_spent = Now.Subtract(timer_start)
        time_diff = Now.Subtract(prev_time)
        prev_time = DateTime.Now
        Console.WriteLine(caller_name & "-" & flag & " " & time_spent.TotalSeconds & "s from start (" & time_diff.TotalSeconds & "s from previous flag)")
    End Sub

    Public Sub stopClock()
        Dim timer_stop As DateTime = DateTime.Now
        time_spent = Now.Subtract(timer_start)
        time_diff = Now.Subtract(prev_time)
        Console.WriteLine(caller_name & " ends at:" & timer_stop.ToString & " - " & time_spent.TotalSeconds & " seconds elapsed from start (" & time_diff.TotalSeconds & "s from previous flag)")
    End Sub

End Class
</code>```

Example of use:

```<code>'Put this wherever you want to start to count
Dim timer As TimeSpanHelper = New TimeSpanHelper("MyFunctionName")
timer.startClock()
'Do something ...
timer.getElapsedTime("flag1")
'Do something ...
timer.getElapsedTime("flag2")
'Do something ...
timer.stopClock()
</code>```

Your output should be something like:

```<code>MyFunctionName starts at 30/03/2017 16:57:21
MyFunctionName - flag1 Xs from start (Xs from previous flag)
MyFunctionName - flag2 Xs from start (Xs from previous flag)
MyFunctionName ends at 30/03/2017 16:59:14 - 120s elapsed from start (Xs from previous flag)
</code>```

Body:
In our VB6 applications, we added a few utility functions for tracking the amount of time spent in a function.  We did this to track performance bottlenecks.

Basically, how it worked was there were two utility functions: StartTickCount() and EndTickCount().  You would pass the name of the function in each, and the functions would use a dictionary to get the tick count when StartTickCount() was called, and then subtract the tick count when EndTickCount() was called.  This wasn't perfect because it didn't of course take into consideration that calls to get tick count takes time, etc, but basically it worked for our purposes.  The pain in the butt part was making sure to call StartTickCount() at the beginning of each function and EndTickCount() at each exit point:

Private Function SomeFuction() as String
    ' indicate the function started
    StartTickCount("MyClass.SomeFunction")

    ' some logic that causes the function to end
    If (some logic) Then
        EndTickCount("MyClass.SomeFunction")
        Return "Hello!"
    End If

    ' final exit point
    EndTickCount("MyClass.SomeFunction")
    Return "World"
End Function

Anyway, is there any functionality built in, either through the VS 2010 debugger or in the System.Reflection namespace, to do something similar in VB.NET?

Basically, what I want is to log the number of times each function is called, the total amount to time spent in that function, the average number of seconds spent in that function, and the maximum amount of time spent in a single call in that function.

I can certainly write this by hand (since we already did once in VB6), but if there are existing tools to make it easier, I'd rather use them.

Body:
I ofently use this helper class. It basically does what @AndreaAntonangeli suggested but arranged to have a cleaner code:

Public Class TimeSpanHelper

    Dim caller_name As String
    Dim timer_start As DateTime
    Dim time_spent As System.TimeSpan
    Dim prev_time As DateTime
    Dim time_diff As System.TimeSpan

    Public Sub New(caller As String)
        caller_name = caller
    End Sub

    Public Sub startClock()
        timer_start = DateTime.Now
        Console.WriteLine(caller_name & " starts at:" & timer_start.ToString)
        prev_time = timer_start
    End Sub

    Public Sub getElapsedTime(Optional flag As String = "")
        time_spent = Now.Subtract(timer_start)
        time_diff = Now.Subtract(prev_time)
        prev_time = DateTime.Now
        Console.WriteLine(caller_name & "-" & flag & " " & time_spent.TotalSeconds & "s from start (" & time_diff.TotalSeconds & "s from previous flag)")
    End Sub

    Public Sub stopClock()
        Dim timer_stop As DateTime = DateTime.Now
        time_spent = Now.Subtract(timer_start)
        time_diff = Now.Subtract(prev_time)
        Console.WriteLine(caller_name & " ends at:" & timer_stop.ToString & " - " & time_spent.TotalSeconds & " seconds elapsed from start (" & time_diff.TotalSeconds & "s from previous flag)")
    End Sub

End Class

Example of use:

'Put this wherever you want to start to count
Dim timer As TimeSpanHelper = New TimeSpanHelper("MyFunctionName")
timer.startClock()
'Do something ...
timer.getElapsedTime("flag1")
'Do something ...
timer.getElapsedTime("flag2")
'Do something ...
timer.stopClock()

Your output should be something like:

MyFunctionName starts at 30/03/2017 16:57:21
MyFunctionName - flag1 Xs from start (Xs from previous flag)
MyFunctionName - flag2 Xs from start (Xs from previous flag)
MyFunctionName ends at 30/03/2017 16:59:14 - 120s elapsed from start (Xs from previous flag)