问:
Pandas to_csv how to format both int and float variables with comma as thousands separator
All the data I crunch needs to be reported with comma as thousands separator. I'm only interested in values with comma as thousands separator after the data is written to a .csv file. Internally within my pandas dataframe, I want to keep them as int or float.

floats

I can output the floats to zero decimal with:

```<code> df.to_csv('c:\Awesome\Groovy.csv', float_format = '%.0f')
</code>```

but whenever I try to put a comma in the float it doesn't work.

```<code> df.to_csv('c:\Awesome\Groovy.csv', float_format = ':,.0f') ## WRONG
 df.to_csv('c:\Awesome\Groovy.csv', float_format = {:,.0f}'.format) ## WRONG
</code>```

ints

And my plan for the ints, is first to convert them to float in the dataframe and then format them with the .to_csv function. Any thoughts?

答:
This is the code I ended up with based on bernie's answer above. I wanted to post it here for other folks.

```<code>import re
def thous(x, sep=',', dot='.'):
   y = round(x)
   num, _, frac = str(y).partition(dot)
   num = re.sub(r'(\d{3})(?=\d)', r'\1'+sep, num[::-1])[::-1]
   #  comment out for no 0    if frac:
   #  comment out for no 0   num += dot + frac
   return num

num = df.select_dtypes(include=[np.number]) #selects only numeric dtypes
for x in num:
     df[x] = df[x].apply(lambda x: thous(x))
</code>```

run it just before you use the to_csv command and you're golden. Cheers!

Body:
All the data I crunch needs to be reported with comma as thousands separator. I'm only interested in values with comma as thousands separator after the data is written to a .csv file. Internally within my pandas dataframe, I want to keep them as int or float.

floats

I can output the floats to zero decimal with:

 df.to_csv('c:\Awesome\Groovy.csv', float_format = '%.0f')

but whenever I try to put a comma in the float it doesn't work.

 df.to_csv('c:\Awesome\Groovy.csv', float_format = ':,.0f') ## WRONG
 df.to_csv('c:\Awesome\Groovy.csv', float_format = {:,.0f}'.format) ## WRONG

ints

And my plan for the ints, is first to convert them to float in the dataframe and then format them with the .to_csv function. Any thoughts?

Body:
This is the code I ended up with based on bernie's answer above. I wanted to post it here for other folks.

import re
def thous(x, sep=',', dot='.'):
   y = round(x)
   num, _, frac = str(y).partition(dot)
   num = re.sub(r'(\d{3})(?=\d)', r'\1'+sep, num[::-1])[::-1]
   #  comment out for no 0    if frac:
   #  comment out for no 0   num += dot + frac
   return num

num = df.select_dtypes(include=[np.number]) #selects only numeric dtypes
for x in num:
     df[x] = df[x].apply(lambda x: thous(x))

run it just before you use the to_csv command and you're golden. Cheers!


来源: stackexchange

问:
How to load a html file into div tabs using javascript
I have created nav-tabs using bootstrap. Now I want to load html files into tab content on tab click. Can someone help me with java script.

This is my html:

```<code><body>
<div class="container-fluid">
  <div class="row">
    <div class="col-sm-3">
     <ul class="nav nav-pills nav-stacked">
       <li class="active"><a data-toggle="pill" id="Home" href="#home">Home</a></li>
       <li><a data-toggle="pill" id="Menu1" href="#menu1">Menu 1</a></li>
       <li><a data-toggle="pill" id="Menu2" href="#menu2">Menu 2</a></li>
     </ul>
    </div>
    <div class="col-sm-9">
      <div class="tab-content">
         <div id="home" class="tab-pane fade in active">
         </div>
         <div id="menu1" class="tab-pane fade">    <h3>Menu 1</h3>
         </div>
         <div id="menu2" class="tab-pane fade"> <h3>Menu 2</h3>
         </div>
      </div>
    </div>
  </div>
 </div>
 </body>
</code>```

In the above code, when i click on the home tab i want to load an external html(x.html) file into home div under tab-content div. I want the same functionality when i click on the menu1 tab(y.html). When I load (y.html) i need to hide (x.html).  Someone please help me...!!!

I used the below javascript. But it is not working.:

```<code>$('a#Home').click(function(){
    $("#home").load("x.html");
});
$('a#Menu1').click(function(){
   $("#menu1").load("y.html");
});
</code>```

答:
You can use .hide(), .show()

```<code>$('a#Home').click(function(e) {
    e.preventDefault();
    $("#home").load("x.html", function() {
      $("#menu1").hide();
      $(this).show();
    });
});

$('a#Menu1').click(function(e) {
   e.preventDefault();
   $("#menu1").load("y.html", function() {
     $("#home").hide();
     $(this).show();
   })
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have created nav-tabs using bootstrap. Now I want to load html files into tab content on tab click. Can someone help me with java script.

This is my html:

Home

Menu 1

Menu 2

Menu 1

Menu 2

In the above code, when i click on the home tab i want to load an external html(x.html) file into home div under tab-content div. I want the same functionality when i click on the menu1 tab(y.html). When I load (y.html) i need to hide (x.html).  Someone please help me...!!!

I used the below javascript. But it is not working.:

$('a#Home').click(function(){
    $("#home").load("x.html");
});
$('a#Menu1').click(function(){
   $("#menu1").load("y.html");
});

Body:
You can use .hide(), .show()

$('a#Home').click(function(e) {
    e.preventDefault();
    $("#home").load("x.html", function() {
      $("#menu1").hide();
      $(this).show();
    });
});

$('a#Menu1').click(function(e) {
   e.preventDefault();
   $("#menu1").load("y.html", function() {
     $("#home").hide();
     $(this).show();
   })
});


问:
How to use an interface with methods that has in input or return type the reference of the interface?
I have an interface like that:

```<code>public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}
</code>```

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

```<code>public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);
</code>```

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

```<code>public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}
</code>```

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

答:
When you define an inteface it means that you are defining all methods that you will use in the class implementation.

In your interface you have the following methods:

```<code>public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path) throws NoSuchTreeException;
    public void visit ();
    public void printIntTree ();
}
</code>```

These methods must be overwritten in MyTree class, for example:

```<code>public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }

    public IntTree followPath(int[] path) throws NoSuchTreeException {
        for (int i = 0; i < path.length; i++) {
            path[i] = path[i] - 1;
        }

        MyTree oggetto = this;
        for (int i = 0; i < path.length; i++) {
            int index = path[i];
            if (index >= oggetto.getChildren().size() || oggetto.getChildren().isEmpty()) {
                throw new NoSuchTreeException();
            }
            oggetto = oggetto.getChildren().get(i);
        }

        return oggetto;
    }

    @Override
    public int getValue() {
        return 0; //Implement the logic for this method
    }

    @Override
    public int childrenNumber() {
        return 0; //Implement the logic for this method
    }

    @Override
    public int nodes() {
        return 0; //Implement the logic for this method
    }

    @Override
    public int height() {
        return 0; //Implement the logic for this method
    }

    @Override
    public boolean equals(IntTree t) {
        return false; //Implement the logic for this method
    }

    public void addChild(IntTree child) {
        this.children.addFirst((MyTree) child);
    }

    public LinkedList<MyTree> getChildren() {
        return this.children;
    }

    @Override
    public void visit() {
        //Implement the logic for this method
    }

    @Override
    public void printIntTree() {
        //Implement the logic for this method
    }
}
</code>```

Body:
I have an interface like that:

public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path);
    public void visit ();
    public void printIntTree ();
}

And I don't know how to implement MyTree because there are a lot of references on the interface: for example:

public void addChild (IntTree child);
public IntTree followPath(int[] path);
public boolean equals (IntTree t);

So I don't understand how to use IntTree reference. I did all my methods with a cast for example:

public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }
    public void addChild(IntTree child){
        this.children.addFirst((MyTree) child);
    }
    public LinkedList<MyTree> getChildren() {
        return this.children;
    }
}

But my teacher said that is wrong to do that, how can I get access for example to my children list etc if I can't cast it to MyTree object? how can I do a method public IntTree followPath(int[] path); if MyTree object = this and it's != from IntTree? Please explain me, I am getting mad:

And for the other methods that have nothing in input and not return a reference of the Interface I can implement it with the constructor of MyTree?

Body:
When you define an inteface it means that you are defining all methods that you will use in the class implementation.

In your interface you have the following methods:

public interface IntTree {
    public int getValue();
    public int childrenNumber();
    public int nodes ();
    public int height ();
    public boolean equals (IntTree t);
    public void addChild (IntTree child);
    public IntTree followPath(int[] path) throws NoSuchTreeException;
    public void visit ();
    public void printIntTree ();
}

These methods must be overwritten in MyTree class, for example:

public class MyTree implements IntTree {
    private int data;
    private LinkedList<MyTree> children; //I have to declare it IntTree or MyTree?

    public MyTree(int data) {
        this.data = data;
        this.children = new LinkedList<>();
    }

    public IntTree followPath(int[] path) throws NoSuchTreeException {
        for (int i = 0; i < path.length; i++) {
            path[i] = path[i] - 1;
        }

        MyTree oggetto = this;
        for (int i = 0; i < path.length; i++) {
            int index = path[i];
            if (index >= oggetto.getChildren().size() || oggetto.getChildren().isEmpty()) {
                throw new NoSuchTreeException();
            }
            oggetto = oggetto.getChildren().get(i);
        }

        return oggetto;
    }

    @Override
    public int getValue() {
        return 0; //Implement the logic for this method
    }

    @Override
    public int childrenNumber() {
        return 0; //Implement the logic for this method
    }

    @Override
    public int nodes() {
        return 0; //Implement the logic for this method
    }

    @Override
    public int height() {
        return 0; //Implement the logic for this method
    }

    @Override
    public boolean equals(IntTree t) {
        return false; //Implement the logic for this method
    }

    public void addChild(IntTree child) {
        this.children.addFirst((MyTree) child);
    }

    public LinkedList<MyTree> getChildren() {
        return this.children;
    }

    @Override
    public void visit() {
        //Implement the logic for this method
    }

    @Override
    public void printIntTree() {
        //Implement the logic for this method
    }
}


问:
Rails post model for news and blog view
I have a post model and posts controller with an attribute format so id like to split the views out based on this attribute i.e. foo.com/blog/xxx if the format is blog and foo.com/news/xxx if the format is news.

resources :posts

```<code>def index
  @posts = Post.where(draft: 'false').order(publish_date: :desc)
end

def show
  @post = Post.find_by!(slug: params[:id])
end
</code>```

I can easily so something like this for the index view but im unsure about the show route

get '/new', to: 'posts#news'

```<code>def news
  @posts = Post.where(draft: 'false', format: 'news').order(publish_date: :desc)
end
</code>```

答:
To indicate a show route, you need to pass id as a parameter in your route.

```<code>get '/blog/:id' => 'posts#blogs'
</code>```

I guess this is what you are looking for.

Title: Rails post model for news and blog view

Body:
I have a post model and posts controller with an attribute format so id like to split the views out based on this attribute i.e. foo.com/blog/xxx if the format is blog and foo.com/news/xxx if the format is news.

resources :posts

def index
  @posts = Post.where(draft: 'false').order(publish_date: :desc)
end

def show
  @post = Post.find_by!(slug: params[:id])
end

I can easily so something like this for the index view but im unsure about the show route

get '/new', to: 'posts#news'

def news
  @posts = Post.where(draft: 'false', format: 'news').order(publish_date: :desc)
end

Body:
To indicate a show route, you need to pass id as a parameter in your route.

get '/blog/:id' => 'posts#blogs'

I guess this is what you are looking for.


问:
How to get all data in the table with hibernate?
```<code>public Service getServiceData(){
    return (Service)ServiceDaoImpl.getSession().get(Service.class, new Integer(1));
}
</code>```

The get method is getting one.
I want to get all data for the jsp page.

答:
```<code>public List<Service> getServiceAll(){
     return ServiceDaoImpl.getSession().createCriteria(Service.class).list();
}
</code>```

Body:
public Service getServiceData(){
    return (Service)ServiceDaoImpl.getSession().get(Service.class, new Integer(1));
}

The get method is getting one.
I want to get all data for the jsp page.


问:
Mergesort in python - too slow?
I'm trying to learn merge sort but I'm not sure I got this quite right. It works and I've tried optimizing this e.g. with deques for leftpop but I still get times that are roughly 4 times slower than the builtin sorted() function. Is this supposed to happen? Or am I missing some obvious bottlenecks?

```<code>import random
from time import time
from collections import deque

unsorted = [random.randint(0, 1000) for r in xrange(101101)]

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []
    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new.append(left_sorted.popleft())
            if not left_sorted:
                new += right_sorted
        else:
            new.append(right_sorted.popleft())
            if not right_sorted:
                new += left_sorted
    return new

s = time()
print merge_sort(unsorted)
e = time()
print e - s

s = time()
print sorted(unsorted)
e = time()
print e - s
</code>```

Edit: A somewhat optimized version below:

```<code>def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []

    new_append = new.append
    left_pop = left_sorted.popleft
    right_pop = right_sorted.popleft

    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new_append(left_pop())
        else:
            new_append(right_pop())

    if not left_sorted:
        new += right_sorted
    if not right_sorted:
        new += left_sorted

    return new
</code>```

答:
There are some name lookups you could cache. I see you doing .append and .popleft a lot. Try storing those in local variables:

```<code>new_append = new.append
left_pop = left_sorted.popleft
right_pop = right_sorted.popleft

 ...

new_append(left_pop())

...

new_append(right_pop())
</code>```

That should knock out some opcodes.

Also, your if not left_sorted: and right_sorted logic could be moved outside the loop.

You might not need to use a dequeue if you use index variables - left[li] and right[ri] instead of left[0] and right[0] all the time. Destroying the sublists one at a time isn't useful. (I don't know if this will speed things up, however. The dequeue might cache the start-index and do it this way.)

And the if statements at the end should be positive, not negative. It's possible (likely, even) to run out of both at the same time.

Title: Mergesort in python - too slow?

Body:
I'm trying to learn merge sort but I'm not sure I got this quite right. It works and I've tried optimizing this e.g. with deques for leftpop but I still get times that are roughly 4 times slower than the builtin sorted() function. Is this supposed to happen? Or am I missing some obvious bottlenecks?

import random
from time import time
from collections import deque

unsorted = [random.randint(0, 1000) for r in xrange(101101)]

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []
    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new.append(left_sorted.popleft())
            if not left_sorted:
                new += right_sorted
        else:
            new.append(right_sorted.popleft())
            if not right_sorted:
                new += left_sorted
    return new

s = time()
print merge_sort(unsorted)
e = time()
print e - s

s = time()
print sorted(unsorted)
e = time()
print e - s

Edit: A somewhat optimized version below:

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []

    new_append = new.append
    left_pop = left_sorted.popleft
    right_pop = right_sorted.popleft

    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new_append(left_pop())
        else:
            new_append(right_pop())

    if not left_sorted:
        new += right_sorted
    if not right_sorted:
        new += left_sorted

    return new

Body:
There are some name lookups you could cache. I see you doing .append and .popleft a lot. Try storing those in local variables:

new_append = new.append
left_pop = left_sorted.popleft
right_pop = right_sorted.popleft

 ...

new_append(left_pop())

...

new_append(right_pop())

That should knock out some opcodes.

Also, your if not left_sorted: and right_sorted logic could be moved outside the loop.

You might not need to use a dequeue if you use index variables - left[li] and right[ri] instead of left[0] and right[0] all the time. Destroying the sublists one at a time isn't useful. (I don't know if this will speed things up, however. The dequeue might cache the start-index and do it this way.)

And the if statements at the end should be positive, not negative. It's possible (likely, even) to run out of both at the same time.


问:
java script call back function
For accessing React element or component, 'ref' is the best possible method?
Do we have any other options for the same in ReactJS</p>

```<code><TextField
    ref={(elem) => this.textField = elem}
    value={value}
    {...restProps}
/>
</code>```

答:
If you want to access the actual DOM node, then ref is the only option.  Generally refs are used to create uncontrolled components, where we let the DOM keep charge of the input's value, and get the value from our reference to the DOM node when we need it.  You can't use value as a prop on these components, but you can use defaultValue to set their initial value:

```<code>class WithUncontrolledTextInput extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(`The input value is ${this.textField.value}`);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input ref={input => this.textField = input} defaultValue='hello' />
        <input type='submit' value='Submit' />
      </form>
    );
  }
}
</code>```

The alternative approach is to use a controlled component, where the current value of the input is stored within the component's state, and updated whenever the input value is updated.

```<code>class WithControlledTextInput extends React.Component {
  constructor() {
    super();
    this.state = {
      textField: 'hello'
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(`The input value is ${this.state.textField}`);
  }

  handleInput(e) {
    this.setState({
      textField: e.target.value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input value={this.state.textField} onChange={this.handleInput} />
        <input type='submit' value='Submit' />
      </form>
    );
  }
}
</code>```

Title: java script call back function

Body:
For accessing React element or component, 'ref' is the best possible method?
Do we have any other options for the same in ReactJS

<TextField
    ref={(elem) => this.textField = elem}
    value={value}
    {...restProps}
/>

Body:
If you want to access the actual DOM node, then ref is the only option.  Generally refs are used to create uncontrolled components, where we let the DOM keep charge of the input's value, and get the value from our reference to the DOM node when we need it.  You can't use value as a prop on these components, but you can use defaultValue to set their initial value:

class WithUncontrolledTextInput extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(`The input value is ${this.textField.value}`);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input ref={input => this.textField = input} defaultValue='hello' />
        <input type='submit' value='Submit' />
      </form>
    );
  }
}

The alternative approach is to use a controlled component, where the current value of the input is stored within the component's state, and updated whenever the input value is updated.

class WithControlledTextInput extends React.Component {
  constructor() {
    super();
    this.state = {
      textField: 'hello'
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(`The input value is ${this.state.textField}`);
  }

  handleInput(e) {
    this.setState({
      textField: e.target.value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input value={this.state.textField} onChange={this.handleInput} />
        <input type='submit' value='Submit' />
      </form>
    );
  }
}


问:
How to Hibernate Batch Insert with real time data? Use @Transactional or not?
I am trying to perform batch inserts with data that is currently being inserted to DB one statement per transaction. Transaction code statement looks similar to below. Currently, addHolding() method is being called for each quote that comes in from an external feed, and each of these quote updates happens about 150 times per second.

```<code>public class HoldingServiceImpl {

    @Autowired
    private HoldingDAO holdingDao;

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void addHolding(Quote quote) {
        Holding holding = transformQuote(quote);
        holdingDao.addHolding(holding);
    }

}
</code>```

And DAO is getting current session from Hibernate SessionFactory and calling save on object.

```<code>public class HoldingDAOImpl {

    @Autowired
    private SessionFactory sessionFactory;

    public void addHolding(Holding holding) {
        sessionFactory.getCurrentSession().save(holding);
    }

}
</code>```

I have looked at Hibernate batching documentation, but it is not clear from document how I would organize code for batch inserting in this case, since I don't have the full list of data at hand, but rather am waiting for it to stream.

Does merely setting Hibernate batching properties in properties file (e.g. hibernate.jdbc.batch_size=20) "magically" batch insert these? Or will I need to, say, capture each quote update in a synchronized list, and then insert list load and clear list when batch size limit reached?

Also, the whole purpose of implementing batching is to see if performance improves. If there is better way to handle inserts in this scenario, let me know.

答:
Setting the property hibernate.jdbc.batch_size=20 is an indication for the hibernate to Flush the objects after 20. In your case hibernate automatically calls sessionfactory.flush() after 20 records saved.

When u call a sessionFactory.save(), the insert command is only fired to in-memory hibernate cache. Only once the Flush is called hibernate synchronizes these changes with the Database. Hence setting hibernate batch size is enough to do batch inserts. Fine tune the Batch size according to your needs.

Also make sure your transactions are handled properly. If you commit a transaction also forces hibernate to flush the session.

Body:
I am trying to perform batch inserts with data that is currently being inserted to DB one statement per transaction. Transaction code statement looks similar to below. Currently, addHolding() method is being called for each quote that comes in from an external feed, and each of these quote updates happens about 150 times per second.

public class HoldingServiceImpl {

    @Autowired
    private HoldingDAO holdingDao;

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void addHolding(Quote quote) {
        Holding holding = transformQuote(quote);
        holdingDao.addHolding(holding);
    }

}

And DAO is getting current session from Hibernate SessionFactory and calling save on object.

public class HoldingDAOImpl {

    @Autowired
    private SessionFactory sessionFactory;

    public void addHolding(Holding holding) {
        sessionFactory.getCurrentSession().save(holding);
    }

}

I have looked at Hibernate batching documentation, but it is not clear from document how I would organize code for batch inserting in this case, since I don't have the full list of data at hand, but rather am waiting for it to stream.

Does merely setting Hibernate batching properties in properties file (e.g. hibernate.jdbc.batch_size=20) "magically" batch insert these? Or will I need to, say, capture each quote update in a synchronized list, and then insert list load and clear list when batch size limit reached?

Also, the whole purpose of implementing batching is to see if performance improves. If there is better way to handle inserts in this scenario, let me know.


问:
(Excel add-in) When setting a large number to Range.value, the resulting number in the spreadsheet is different
When setting a large number as the value for a Range (cell), the number that is written to the spreadsheet is different than the original number. E.g.

If I set 42300000000, the number in excel becomes -649672960. This doesn't happen with smaller numbers

I tested it with the basic project sample from Visual Studio. Just replaced the original loadSampleData function with:

```<code>function loadSampleData() {

     var values = [
                    [4230, 42300, 423000],
                    [4230000, 42300000, 423000000],
                    [4230000000, 42300000000, 423000000000]
    ];

    // Run a batch operation against the Excel object model
    Excel.run(function (ctx) {
        // Create a proxy object for the active sheet
        var sheet = ctx.workbook.worksheets.getActiveWorksheet();
        // Queue a command to write the sample data to the worksheet
        sheet.getRange("B3:D5").values = values;

        // Run the queued-up commands, and return a promise to indicate task completion
        return ctx.sync();
    })
    .catch(errorHandler);
}
</code>```

When I run the add-in, I get this in Excel:

```<code>4230         42300      423000
4230000      42300000   423000000
-64967296   -649672960  2093204992
</code>```

Is this some kind of overflow? Am I doing something wrong?

Thanks!

答:
Thanks for reporting this bug.

The problem seems to be in the JSON parser that we are using to deserialize the incoming request. It incorrectly assumes that any integer number fits in int32_t. The correct behavior would be to parse such large values as double despite of the fact that they are integers.

Since this isn't Excel code, a fix may take a long time.

Unfortunately, appending .0 or E0 at the end of these literals, doesn't drive the parser to parse these literals as double. As Charles Williams pointed out, enclosing the literals in single or double quotes serves your purpose [for some unknown reason].

I haven't been able to find a more deterministic work around. Other suggestions will be welcome.

Zlatko

Body:
When setting a large number as the value for a Range (cell), the number that is written to the spreadsheet is different than the original number. E.g.

If I set 42300000000, the number in excel becomes -649672960. This doesn't happen with smaller numbers

I tested it with the basic project sample from Visual Studio. Just replaced the original loadSampleData function with:

function loadSampleData() {

     var values = [
                    [4230, 42300, 423000],
                    [4230000, 42300000, 423000000],
                    [4230000000, 42300000000, 423000000000]
    ];

    // Run a batch operation against the Excel object model
    Excel.run(function (ctx) {
        // Create a proxy object for the active sheet
        var sheet = ctx.workbook.worksheets.getActiveWorksheet();
        // Queue a command to write the sample data to the worksheet
        sheet.getRange("B3:D5").values = values;

        // Run the queued-up commands, and return a promise to indicate task completion
        return ctx.sync();
    })
    .catch(errorHandler);
}

When I run the add-in, I get this in Excel:

4230         42300      423000
4230000      42300000   423000000
-64967296   -649672960  2093204992

Is this some kind of overflow? Am I doing something wrong?

Thanks!


问:
Sort an ArrayList base on multiple attributes
I have an ArrayList of object. The object contain attributes date and value. So I want to sort the objects on the date, and for all objects in the same date I want to sort them on value. How can I do that?

答:
```<code>public static <T> void sort(List<T> list, final List<Comparator<T>> comparatorList) {
       if (comparatorList.isEmpty()) {//Always equals, if no Comparator.
            throw new IllegalArgumentException("comparatorList is empty.");
       }
       Comparator<T> comparator = new Comparator<T>() {
       public int compare(T o1, T o2) {
               for (Comparator<T> c:comparatorList) {
                   if (c.compare(o1, o2) > 0) {
                     return 1;
                   } else if (c.compare(o1, o2) < 0) {
                     return -1;
                   }
               }
               return 0;
         }
       };
       Collections.sort(list, comparator);
  }
</code>```

ContentLicense: CC BY-SA 2.5


问:
Python: writing to CSV in a for-loop, conditionally adding value in particular column
Here's an example of the contents of my CSV file:

```<code>Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,
</code>```

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

```<code>Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,
</code>```

My current code looks like this:

```<code>csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.
</code>```

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

答:
If you want to create a new CSV file

```<code>csv_data = csv.reader(open('./Desktop/fruit_data.csv', 'r'))
csv_new = csv.writer(open('./Desktop/fruit_new_data.csv', 'w'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
        row.append("ripe")
        csv_new.writerow(row)
    else:
        csv_new.writerow(row)
</code>```

Basically the only thing missing in your previous question is the last statment, which is to write, else is add in case the criteria does not match.

Another possibility could be to use linestartswith

Body:
Here's an example of the contents of my CSV file:

Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,

My current code looks like this:

csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

Body:
If you want to create a new CSV file

csv_data = csv.reader(open('./Desktop/fruit_data.csv', 'r'))
csv_new = csv.writer(open('./Desktop/fruit_new_data.csv', 'w'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
        row.append("ripe")
        csv_new.writerow(row)
    else:
        csv_new.writerow(row)

Basically the only thing missing in your previous question is the last statment, which is to write, else is add in case the criteria does not match.

Another possibility could be to use linestartswith


问:
MySQL - Figuring out what indexes to use, AND not working as expected
I have two problems here I'm trying to solve. First of all, the query, with values replaced with ? since I'm using a prepared statement:

```<code>SELECT  *
    FROM  Messages t
    WHERE  perspective_user=?
      and  timestamp BETWEEN ? AND ?
      AND  timestamp_added =
        ( SELECT  max(timestamp_added)
            from  Messages t2
            where  t2.author = t.author
              AND  t2.body = t.body
              AND  t2.timestamp = t.timestamp
              AND  t2.timestamp_added <= ?  )
      AND  convo_id IN (
        SELECT  convo_id
            FROM  Conversations
            WHERE  perspective_user=?
              AND  identity=?
              AND  timestamp_added=? );
</code>```

The code is incredibly slow but works without the following line. With it included, it returns 0 results:

```<code>      AND  convo_id IN (
        SELECT  convo_id
            FROM  Conversations
            WHERE  perspective_user=?
              AND  identity=?
              AND  timestamp_added=? );
</code>```

That line works fine on its own, and there are rows that satisfy the above requirements as well as that line. I'm wondering why it's behaving so odd.

The other thing I'm wondering about is what indexes to add. My first thought was three indexes: One on perspective_user, timestamp, timestamp_added, and convo_id, a second index on author, body, timestamp, and timestamp_added, and a final index on perspective_user, identity, and timestamp_added.

I don't really understand MySQL so I'm not sure how to proceed.

答:
IN ( SELECT ... ) is a very inefficient construct in MySQL.  Instead JOIN Conversations ON convo_id = ... WHERE ....

The added game appears to be a "groupwise max".  See this for discussion of efficient ways to do that.

Please provide SHOW CREATE TABLE.  If body is not TEXT, then you need INDEX(author, body, timestamp, timestamp_added).  If that won't work, then we need to better understand the structure of Messages.

Body:
I have two problems here I'm trying to solve. First of all, the query, with values replaced with ? since I'm using a prepared statement:

SELECT  *
    FROM  Messages t
    WHERE  perspective_user=?
      and  timestamp BETWEEN ? AND ?
      AND  timestamp_added =
        ( SELECT  max(timestamp_added)
            from  Messages t2
            where  t2.author = t.author
              AND  t2.body = t.body
              AND  t2.timestamp = t.timestamp
              AND  t2.timestamp_added <= ?  )
      AND  convo_id IN (
        SELECT  convo_id
            FROM  Conversations
            WHERE  perspective_user=?
              AND  identity=?
              AND  timestamp_added=? );

The code is incredibly slow but works without the following line. With it included, it returns 0 results:

      AND  convo_id IN (
        SELECT  convo_id
            FROM  Conversations
            WHERE  perspective_user=?
              AND  identity=?
              AND  timestamp_added=? );

That line works fine on its own, and there are rows that satisfy the above requirements as well as that line. I'm wondering why it's behaving so odd.

The other thing I'm wondering about is what indexes to add. My first thought was three indexes: One on perspective_user, timestamp, timestamp_added, and convo_id, a second index on author, body, timestamp, and timestamp_added, and a final index on perspective_user, identity, and timestamp_added.

I don't really understand MySQL so I'm not sure how to proceed.


问:
Get position/offset of element relative to a parent container?
How can I retrieve the offset of a container relative to a parent with pure JS?</p>

答:
Sure is easy with pure JS, just do this, work for fixed and animated HTML 5 panels too, i made and try this code and it works for any brower (include IE 8):</p>

```<code><script type="text/javascript">
    function fGetCSSProperty(s, e) {
        try { return s.currentStyle ? s.currentStyle[e] : window.getComputedStyle(s)[e]; }
        catch (x) { return null; }
    }
    function fGetOffSetParent(s) {
        var a = s.offsetParent || document.body;

        while (a && a.tagName && a != document.body && fGetCSSProperty(a, 'position') == 'static')
            a = a.offsetParent;
        return a;
    }
    function GetPosition(s) {
        var b = fGetOffSetParent(s);

        return { Left: (b.offsetLeft + s.offsetLeft), Top: (b.offsetTop + s.offsetTop) };
    }
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sure is easy with pure JS, just do this, work for fixed and animated HTML 5 panels too, i made and try this code and it works for any brower (include IE 8):

<script type="text/javascript">
    function fGetCSSProperty(s, e) {
        try { return s.currentStyle ? s.currentStyle[e] : window.getComputedStyle(s)[e]; }
        catch (x) { return null; }
    }
    function fGetOffSetParent(s) {
        var a = s.offsetParent || document.body;

        while (a && a.tagName && a != document.body && fGetCSSProperty(a, 'position') == 'static')
            a = a.offsetParent;
        return a;
    }
    function GetPosition(s) {
        var b = fGetOffSetParent(s);

        return { Left: (b.offsetLeft + s.offsetLeft), Top: (b.offsetTop + s.offsetTop) };
    }
</script>


问:
I need a format of code that only counts odd lines
test_title.bat

```<code>:GET_DOWNLOADS
set Counter=-1
for /f "DELIMS=" %%i in ('type version.txt') do (
set /a Counter+=2
set "Line_!Counter!=%%i"
)
if exist version.txt del version.txt
exit /b

:list_files
call :GET_DOWNLOADS
For /L %%C in (1,2,%Counter%) Do (
:: removing this part makes it work fine
set line=%%C
set /a line+=1
set /a line/=2
:: alternate way doesnt work either
REM set /a line=%line% / 2
:: this part without the math part would be %%C instead of %Line%
echo %line%. !Line_%%C!
)
pause
</code>```

(made an edit)
the second part isnt working for some reason
it just crashes
if i remove the line that does the math it works fine but instead display 1. 3. 5. 7.

version.txt

```<code>everything
0
minecraft
0
steam
0
obs
0
</code>```

fixed test_list.bat :D

```<code>@echo off
setlocal enabledelayedexpansion
set "num=1"
set "counter=0"
for /f "DELIMS=" %%i in (version.txt) do (
set /a num+=1
if "!num!"=="2" (set /a counter+=1&set "line_!counter!=%%i"&set num=0)
)

echo.

For /L %%C in (1,1,%Counter%) Do (echo %%C. !Line_%%C!)

pause
</code>```

答:
```<code>@echo off
setlocal enabledelayedexpansion
set "num=1"
set "counter=0"
for /f "DELIMS=" %%i in (version.txt) do (
    set /a num+=1
    if "!num!"=="2" (set /a counter+=1&set "line_!counter!=%%i"&echo %%i&set num=0)
)

echo.
set line_1
set line_2
set line_3

pause
</code>```

Would output:

everything

  minecraft

  steam

  obs

  line_1=everything

  line_2=minecraft

  line_3=steam

Body:
test_title.bat

:GET_DOWNLOADS
set Counter=-1
for /f "DELIMS=" %%i in ('type version.txt') do (
set /a Counter+=2
set "Line_!Counter!=%%i"
)
if exist version.txt del version.txt
exit /b

:list_files
call :GET_DOWNLOADS
For /L %%C in (1,2,%Counter%) Do (
:: removing this part makes it work fine
set line=%%C
set /a line+=1
set /a line/=2
:: alternate way doesnt work either
REM set /a line=%line% / 2
:: this part without the math part would be %%C instead of %Line%
echo %line%. !Line_%%C!
)
pause

(made an edit)
the second part isnt working for some reason
it just crashes
if i remove the line that does the math it works fine but instead display 1. 3. 5. 7.

version.txt

everything
0
minecraft
0
steam
0
obs
0

fixed test_list.bat :D

@echo off
setlocal enabledelayedexpansion
set "num=1"
set "counter=0"
for /f "DELIMS=" %%i in (version.txt) do (
set /a num+=1
if "!num!"=="2" (set /a counter+=1&set "line_!counter!=%%i"&set num=0)
)

echo.

For /L %%C in (1,1,%Counter%) Do (echo %%C. !Line_%%C!)

pause

Body:
@echo off
setlocal enabledelayedexpansion
set "num=1"
set "counter=0"
for /f "DELIMS=" %%i in (version.txt) do (
    set /a num+=1
    if "!num!"=="2" (set /a counter+=1&set "line_!counter!=%%i"&echo %%i&set num=0)
)

echo.
set line_1
set line_2
set line_3

pause

Would output:

everything

  minecraft

  steam

  obs

  line_1=everything

  line_2=minecraft

  line_3=steam


问:
bootstrap carousel - when the carousel slides, auto update active nav-item
I would need your help:
here (click to see jsfiddle) I've got an auto-sliding bootstrap-carousel including a navigation to navigate manually.

I can navigate the carousel via the buttons. If I click one, its active. But if the carousel auto-slides, it does not change the active navigation-item. I tried the following code, without success. Do you know where the failure is? Thanks! :-)

```<code>$('#myCarousel').on('slid', function (e) {
  var id = $('.item.active').data('slide-number');
  id = parseInt(id);
  $('[id^=carousel-selector-]').removeClass('selected');
  $('[id=carousel-selector-'+id+']').addClass('selected');
});
</code>```

答:
Hi your on slide function isnt getting triggered. Thats why it did not work. heres a working fiddle https://jsfiddle.net/xgkzf25p/12/ . it worked for me after this change.

the changes made :

```<code>$('#myCarousel').on('slid', function (e) {}
</code>```

changed to :

```<code>$('#myCarousel').on('slide.bs.carousel', function (e) {}
</code>```

Body:
I would need your help:
here (click to see jsfiddle) I've got an auto-sliding bootstrap-carousel including a navigation to navigate manually.

I can navigate the carousel via the buttons. If I click one, its active. But if the carousel auto-slides, it does not change the active navigation-item. I tried the following code, without success. Do you know where the failure is? Thanks! :-)

$('#myCarousel').on('slid', function (e) {
  var id = $('.item.active').data('slide-number');
  id = parseInt(id);
  $('[id^=carousel-selector-]').removeClass('selected');
  $('[id=carousel-selector-'+id+']').addClass('selected');
});

Body:
Hi your on slide function isnt getting triggered. Thats why it did not work. heres a working fiddle https://jsfiddle.net/xgkzf25p/12/ . it worked for me after this change.

the changes made :

$('#myCarousel').on('slid', function (e) {}

changed to :

$('#myCarousel').on('slide.bs.carousel', function (e) {}


问:
Finding the maximum value of a linked list recursively
I need to write a Java method called findMax within a class called Node, which has two instance variables: int value and Node next. The method takes no parameters, and must return the greatest value of a linked list. Within the context of the program, the method will always be called by the first Node of a linked list (except for the recursive calls). I was struggling to complete the method when I accidentally found a working solution:

```<code>public int findMax(){
    int max = value;
    if(next == null){
        return max;
    }
    else{
        if(max <= next.findMax()){
           max = next.value;
        }
        else return max;
    }
    return next.findMax();
}
</code>```

This method properly returned the largest value of each linked list I tested it for. However, since I found this solution by trying random arrangements of code, I don't really feel like I understand what's going on here. Can anyone explain to me how/why this works? Also, if there is a more efficient solution, how would it be implemented?

答:
You can imagine a linked list looking something like this:

val1 -> val2 -> val3 -> null

Recursion works on the principle that eventually, the input you pass into the function can be handled without recursing further. In your case, node.findMax() can be handled if the next pointer is null. That is, the max of a linked list of size 1 is simply the value (base case of the recursion), the max of any other linked list is the max of the value of that node or the max of the remaining elements.

ie) for the Node n3 with value val3, n3.findMax() simply returns the value

For any other node n, n.findMax() returns the maximum of the node's value or n.next.findMax()

The way this looks in the example at the start is:

```<code>n1.findMax()
  = Max(n1.value, n2.findMax())
  = Max(val1, Max(n2.value, n3.findMax())
  = Max(val1, Max(val2, n3.value)) // Since n3.next == null
  = Max(val1, Max(val2, val3))
</code>```

which is simply the maximum over the whole list

Edit: Based on the discussion above, although what you said might work, there is a simpler way of writing the program:

```<code>int findMax() {
    if (this.next == null) {
        return this.value;
    } else {
        return Math.max(this.value, this.next.findMax());
    }
}
</code>```

Edit 2: A break down of why your code works (and why it's bad):

```<code>public int findMax(){
    // This variable doesn't serve much purpose
    int max = value;
    if(next == null){
        return max;
    }
    else{
        // This if condition simply prevents us from following
        // the else block below but the stuff inside does nothing.
        if(max <= next.findMax()){
           // max is never used again if you are here.
           max = next.value;
        }
        else return max;
    }
    // We now compute findMax() again, leading to serious inefficiency
    return next.findMax();
}
</code>```

Why is this inefficient? Because each call to findMax() on a node makes two subsequent calls to findMax() on the next node. Each of those calls will generate two more calls, etc.

The way to fix this up is by storing the result of next.findMax() like so:

```<code>public int findMax() {
    if (next == null) {
        return value;
    }
    else {
        int maxOfRest = next.findMax();
        if(value <= maxOfRest) {
            return maxOfRest;
        }
        else return value;
    }
}
</code>```

Body:
I need to write a Java method called findMax within a class called Node, which has two instance variables: int value and Node next. The method takes no parameters, and must return the greatest value of a linked list. Within the context of the program, the method will always be called by the first Node of a linked list (except for the recursive calls). I was struggling to complete the method when I accidentally found a working solution:

public int findMax(){
    int max = value;
    if(next == null){
        return max;
    }
    else{
        if(max <= next.findMax()){
           max = next.value;
        }
        else return max;
    }
    return next.findMax();
}

This method properly returned the largest value of each linked list I tested it for. However, since I found this solution by trying random arrangements of code, I don't really feel like I understand what's going on here. Can anyone explain to me how/why this works? Also, if there is a more efficient solution, how would it be implemented?

Body:
You can imagine a linked list looking something like this:

val1 -> val2 -> val3 -> null

Recursion works on the principle that eventually, the input you pass into the function can be handled without recursing further. In your case, node.findMax() can be handled if the next pointer is null. That is, the max of a linked list of size 1 is simply the value (base case of the recursion), the max of any other linked list is the max of the value of that node or the max of the remaining elements.

ie) for the Node n3 with value val3, n3.findMax() simply returns the value

For any other node n, n.findMax() returns the maximum of the node's value or n.next.findMax()

The way this looks in the example at the start is:

n1.findMax()
  = Max(n1.value, n2.findMax())
  = Max(val1, Max(n2.value, n3.findMax())
  = Max(val1, Max(val2, n3.value)) // Since n3.next == null
  = Max(val1, Max(val2, val3))

which is simply the maximum over the whole list

Edit: Based on the discussion above, although what you said might work, there is a simpler way of writing the program:

int findMax() {
    if (this.next == null) {
        return this.value;
    } else {
        return Math.max(this.value, this.next.findMax());
    }
}

Edit 2: A break down of why your code works (and why it's bad):

public int findMax(){
    // This variable doesn't serve much purpose
    int max = value;
    if(next == null){
        return max;
    }
    else{
        // This if condition simply prevents us from following
        // the else block below but the stuff inside does nothing.
        if(max <= next.findMax()){
           // max is never used again if you are here.
           max = next.value;
        }
        else return max;
    }
    // We now compute findMax() again, leading to serious inefficiency
    return next.findMax();
}

Why is this inefficient? Because each call to findMax() on a node makes two subsequent calls to findMax() on the next node. Each of those calls will generate two more calls, etc.

The way to fix this up is by storing the result of next.findMax() like so:

public int findMax() {
    if (next == null) {
        return value;
    }
    else {
        int maxOfRest = next.findMax();
        if(value <= maxOfRest) {
            return maxOfRest;
        }
        else return value;
    }
}


问:
Issue mounting docker volume with docker-compose

My Scenario

I am trying to build docker swarm with docker-compose.yml file

```<code>version: '3'

services:
  myapp-nginx:
    image: nginx:1.10
    volumes:
     - ./nginx/certs:/etc/nginx/certs
    ports:
      - 80:80
      - 443:443
</code>```

using build command as below

```<code>$ docker stack deploy --compose-file docker-compose.yml myapp

Creating network myapp_default
Creating service myapp_myapp-nginx
</code>```

My system have Docker Version 17.03.1-ce-mac5 (16048)

Problem

Volumes mounts are not working, If I comment out volumes:  - ./nginx/certs:/etc/nginx/certs then everything works fine.

Otherwise nginx doesn't work at all, I see

```<code>CAGTAM1059934:docker iskumar$ docker stack ps myapp
ID            NAME                  IMAGE       NODE      DESIRED STATE  CURRENT STATE            ERROR                             PORTS
efjia8b7y6jd  myapp_myapp-nginx.1      nginx:1.10  manager1  Ready          Rejected 5 seconds ago   "invalid mount config for type…"
c9c6ogh11osi   \_ myapp_myapp-nginx.1  nginx:1.10  worker2   Shutdown       Rejected 10 seconds ago  "invalid mount config for type…"
iveikxpnbq6x   \_ myapp_myapp-nginx.1  nginx:1.10  worker1   Shutdown       Rejected 15 seconds ago  "invalid mount config for type…"
</code>```

Is there any special way to mount volumes in docker-compose v3?

答:
You must use absolute paths when mounting volumes, also with docker run.

```<code>$ docker run --rm -it -v ./eos:/eos:ro ubuntu
docker: Error response from daemon: create ./eos: "./eos" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intented to pass a host directory, use absolute path.
See 'docker run --help'
</code>```

Body:
My Scenario

I am trying to build docker swarm with docker-compose.yml file

version: '3'

services:
  myapp-nginx:
    image: nginx:1.10
    volumes:
     - ./nginx/certs:/etc/nginx/certs
    ports:
      - 80:80
      - 443:443

using build command as below

$ docker stack deploy --compose-file docker-compose.yml myapp

Creating network myapp_default
Creating service myapp_myapp-nginx

My system have Docker Version 17.03.1-ce-mac5 (16048)

Problem

Volumes mounts are not working, If I comment out volumes:  - ./nginx/certs:/etc/nginx/certs then everything works fine.

Otherwise nginx doesn't work at all, I see

CAGTAM1059934:docker iskumar$ docker stack ps myapp
ID            NAME                  IMAGE       NODE      DESIRED STATE  CURRENT STATE            ERROR                             PORTS
efjia8b7y6jd  myapp_myapp-nginx.1      nginx:1.10  manager1  Ready          Rejected 5 seconds ago   "invalid mount config for type…"
c9c6ogh11osi   \_ myapp_myapp-nginx.1  nginx:1.10  worker2   Shutdown       Rejected 10 seconds ago  "invalid mount config for type…"
iveikxpnbq6x   \_ myapp_myapp-nginx.1  nginx:1.10  worker1   Shutdown       Rejected 15 seconds ago  "invalid mount config for type…"

Is there any special way to mount volumes in docker-compose v3?

Body:
You must use absolute paths when mounting volumes, also with docker run.

$ docker run --rm -it -v ./eos:/eos:ro ubuntu
docker: Error response from daemon: create ./eos: "./eos" includes invalid characters for a local volume name, only "[a-zA-Z0-9][a-zA-Z0-9_.-]" are allowed. If you intented to pass a host directory, use absolute path.
See 'docker run --help'


问:
How to set default date of format 'MM/dd/yyyy'
Here is my code for creating calendar by using Bootstrap datetimepicker:

```<code>$('#datetimepicker12').datetimepicker({
    inline: true,
    format: 'MM/dd/yyyy',
    minDate: new Date(moment(new Date()).add(0, 'days').toDate()),
    maxDate: new Date(moment(new Date()).add(7, 'days').toDate()),
});
</code>```

Now I want to set default date of calendar to be my custom date, its format is like this '2017-03-30'

How can I convert that to be the same format as format of datetimepicker that I have set before?

答:
Bootstrap datetimepicker uses momentjs to manage dates, so:

You don't need new Date(...) and toDate() in your minDate and maxDate option.

The format option should be compliant to moment tokens, in your case change it into uppercase MM/DD/YYYY.

The picker has a defaultDate option, you can use it to set 2017-03-30 as default date, you simply have to parse it using moment (moment('2017-03-30') will be enough since you input is in supported ISO 8601 format).

Note the the datimepicker has useCurrent option if you have to default to the current date.

Here a working example:

$('#datetimepicker12').datetimepicker({
  inline: true,
  format: 'MM/DD/YYYY',
  minDate: moment().startOf('day'),
  maxDate: moment().add(7, 'days').endOf('day'),
  defaultDate: moment('2017-03-30')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group">
  <div class="row">
    <div class="col-md-8">
      <div id="datetimepicker12"></div>
    </div>
  </div>
</div></code>```

The snippet will not work after the 2017-30-17 beacuse the default date will be not included between minDate and maxDate.

Body:
Here is my code for creating calendar by using Bootstrap datetimepicker:

$('#datetimepicker12').datetimepicker({
    inline: true,
    format: 'MM/dd/yyyy',
    minDate: new Date(moment(new Date()).add(0, 'days').toDate()),
    maxDate: new Date(moment(new Date()).add(7, 'days').toDate()),
});

Now I want to set default date of calendar to be my custom date, its format is like this '2017-03-30'

How can I convert that to be the same format as format of datetimepicker that I have set before?

Body:
Bootstrap datetimepicker uses momentjs to manage dates, so:

You don't need new Date(...) and toDate() in your minDate and maxDate option.

The format option should be compliant to moment tokens, in your case change it into uppercase MM/DD/YYYY.

The picker has a defaultDate option, you can use it to set 2017-03-30 as default date, you simply have to parse it using moment (moment('2017-03-30') will be enough since you input is in supported ISO 8601 format).

Note the the datimepicker has useCurrent option if you have to default to the current date.

Here a working example:

$('#datetimepicker12').datetimepicker({
  inline: true,
  format: 'MM/DD/YYYY',
  minDate: moment().startOf('day'),
  maxDate: moment().add(7, 'days').endOf('day'),
  defaultDate: moment('2017-03-30')
});

<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group">
  <div class="row">
    <div class="col-md-8">
      <div id="datetimepicker12"></div>
    </div>
  </div>
</div>

The snippet will not work after the 2017-30-17 beacuse the default date will be not included between minDate and maxDate.


问:
IOS swift TableView is there a way I can reuse them
I am new to IOS development and am using swift 3.0 . I have 2 custom TableViews that have identical layout. The only difference is the data coming back via Json URL . One TableView is called HomePageC and the other UserProfileC . How can I use what I have in Prototype HomePageC and reuse it in UserProfileC ? It is like having a homepage of data then seeing individual users data hence userProfile but same layout because I think it's redundant doing 2 TableViews that are identical .

This is the HomePageC code

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomePageTVC", for: indexPath) as! HomePageTVC

   cell.post.text = Posts[indexPath.row]
   cell.fullname.setTitle(FullName[indexPath.row],for: UIControlState.normal)
   cell.fullname.tag = indexPath.row
   cell.fullname.addTarget(self, action: #selector(HomePageC.Fullname_Click(sender:)), for: .touchUpInside)
   cell.comments.setTitle(Comments[indexPath.row],for: UIControlState.normal)
   cell.comments.tag = indexPath.row
   cell.votes.setTitle(Votes[indexPath.row],for: UIControlState.normal)
   cell.votes.tag = indexPath.row
   cell.time.text = Times[indexPath.row]
  cell.shares.setTitle(Shares[indexPath.row],for: UIControlState.normal)
   cell.shares.tag = indexPath.row
  cell.location.text = Locations[indexPath.row]

        return cell
    }
</code>```

UserProfileC code

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTVC", for: indexPath) as! HomePageTVC

        cell.post.text = Posts[indexPath.row]
        cell.fullname.setTitle(FullName[indexPath.row],for: UIControlState.normal)
        cell.fullname.tag = indexPath.row
        cell.fullname.addTarget(self, action: #selector(HomePageC.Fullname_Click(sender:)), for: .touchUpInside)
        cell.comments.setTitle(Comments[indexPath.row],for: UIControlState.normal)
        cell.comments.tag = indexPath.row
        cell.votes.setTitle(Votes[indexPath.row],for: UIControlState.normal)
        cell.votes.tag = indexPath.row
        cell.time.text = Times[indexPath.row]
        cell.shares.setTitle(Shares[indexPath.row],for: UIControlState.normal)
        cell.shares.tag = indexPath.row
        cell.location.text = Locations[indexPath.row]
        cell.vote_status.text = Votes[indexPath.row]

        return cell
    }
</code>```

I tried to cast it to HomePage but it gives an error any help would be great as i'm quite lost .

答:
One possible way to have reusable table is to create a single separated UITableViewController in Storyboard and design your prototype cell there. Instead of having two different reuse identifiers — "HomePageTVC" and "UserProfileTVC" — you can now have a single one (just leave "UserProfileTVC"). Don't forget to set dataSource and delegate of the table view controller to itself.

Next step: add a container view to any view controller you want to reuse this table in (both HomePageC and UserProfileC controllers in your case).

Now just Control+Drag cursor from the created container views to your reusable table view controller in Storyboard to establish a container relationship.

Now you have a single UITableViewController class to put all cells management logic to, and you can easily load different data based on current parentViewController property — just check what type of controller your table is currently embedded in:

```<code>if parentViewController is HomePageC {
    // Load user data for Home page controller
} else if parentViewController is UserProfileC {
    // Load user data for user profile controller
}
</code>```

Body:
I am new to IOS development and am using swift 3.0 . I have 2 custom TableViews that have identical layout. The only difference is the data coming back via Json URL . One TableView is called HomePageC and the other UserProfileC . How can I use what I have in Prototype HomePageC and reuse it in UserProfileC ? It is like having a homepage of data then seeing individual users data hence userProfile but same layout because I think it's redundant doing 2 TableViews that are identical .

This is the HomePageC code

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomePageTVC", for: indexPath) as! HomePageTVC

   cell.post.text = Posts[indexPath.row]
   cell.fullname.setTitle(FullName[indexPath.row],for: UIControlState.normal)
   cell.fullname.tag = indexPath.row
   cell.fullname.addTarget(self, action: #selector(HomePageC.Fullname_Click(sender:)), for: .touchUpInside)
   cell.comments.setTitle(Comments[indexPath.row],for: UIControlState.normal)
   cell.comments.tag = indexPath.row
   cell.votes.setTitle(Votes[indexPath.row],for: UIControlState.normal)
   cell.votes.tag = indexPath.row
   cell.time.text = Times[indexPath.row]
  cell.shares.setTitle(Shares[indexPath.row],for: UIControlState.normal)
   cell.shares.tag = indexPath.row
  cell.location.text = Locations[indexPath.row]

        return cell
    }

UserProfileC code

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserProfileTVC", for: indexPath) as! HomePageTVC

        cell.post.text = Posts[indexPath.row]
        cell.fullname.setTitle(FullName[indexPath.row],for: UIControlState.normal)
        cell.fullname.tag = indexPath.row
        cell.fullname.addTarget(self, action: #selector(HomePageC.Fullname_Click(sender:)), for: .touchUpInside)
        cell.comments.setTitle(Comments[indexPath.row],for: UIControlState.normal)
        cell.comments.tag = indexPath.row
        cell.votes.setTitle(Votes[indexPath.row],for: UIControlState.normal)
        cell.votes.tag = indexPath.row
        cell.time.text = Times[indexPath.row]
        cell.shares.setTitle(Shares[indexPath.row],for: UIControlState.normal)
        cell.shares.tag = indexPath.row
        cell.location.text = Locations[indexPath.row]
        cell.vote_status.text = Votes[indexPath.row]

        return cell
    }

I tried to cast it to HomePage but it gives an error any help would be great as i'm quite lost .

Body:
One possible way to have reusable table is to create a single separated UITableViewController in Storyboard and design your prototype cell there. Instead of having two different reuse identifiers — "HomePageTVC" and "UserProfileTVC" — you can now have a single one (just leave "UserProfileTVC"). Don't forget to set dataSource and delegate of the table view controller to itself.

Next step: add a container view to any view controller you want to reuse this table in (both HomePageC and UserProfileC controllers in your case).

Now just Control+Drag cursor from the created container views to your reusable table view controller in Storyboard to establish a container relationship.

Now you have a single UITableViewController class to put all cells management logic to, and you can easily load different data based on current parentViewController property — just check what type of controller your table is currently embedded in:

if parentViewController is HomePageC {
    // Load user data for Home page controller
} else if parentViewController is UserProfileC {
    // Load user data for user profile controller
}


问:
Stored proc - union query syntax error
I have an issue with a dynamic query inside a sproc I have in mysql.

Now this query executes fine when I execute it directly in phpmyadmin however this seems to spring up a syntax error upon execution.

```<code>BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
</code>```

I really need this to work somehow as I need to change some field names with params I pass through.

The execution error I get is ...

```<code>MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_c' at line 2
</code>```

I presume this is a limitation with a prep query if I can execute it outside of this environment with no problems.

Thanks

答:
Put the variables setup into the query. see was @Shadow has written.</p>

```<code>    SET @sql = 'select * from (
        (
         select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
         union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
        ) `list_content`
    CROSS JOIN (SELECT @my_id:=24, @rank:=0) as init
    WHERE `listId` = 15 limit 4';
</code>```

Title: Stored proc - union query syntax error

Body:
I have an issue with a dynamic query inside a sproc I have in mysql.

Now this query executes fine when I execute it directly in phpmyadmin however this seems to spring up a syntax error upon execution.

BEGIN
SET @sql = 'set @my_id=24;
set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
     union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
    ) `list_content` WHERE `listId` = 15 limit 4';

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

I really need this to work somehow as I need to change some field names with params I pass through.

The execution error I get is ...

MySQL said: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @rank=0;
select * from (
    (
     select *, @rank:=@rank+1 as x from `list_c' at line 2

I presume this is a limitation with a prep query if I can execute it outside of this environment with no problems.

Thanks

Body:
Put the variables setup into the query. see was @Shadow has written.

    SET @sql = 'select * from (
        (
         select *, @rank:=@rank+1 as x from `list_content` where `id` > @my_id order by `id`)
         union (select *, @rank:=@rank+1 as x from `list_content` where `id` < @my_id order by `id`)
        ) `list_content`
    CROSS JOIN (SELECT @my_id:=24, @rank:=0) as init
    WHERE `listId` = 15 limit 4';


问:
Finding characters within a string in C
I'm writing an algorithm in C with netbeans to find asterisks in a string.

```<code>int main() {
    int M=0, i, j;
    scanf("%i",&M);
    int pos[M];
    char c[M];
    scanf("%s", c);

    i=0;
    j=1;

    while(c[i] != '\0'){
        if(c[i]=='*'){
            pos[j] = i;
            j++;
        }
        i++;
    }

    printf("Asterisks in positions: \n\n");

    for(j=1; j<=i; j++){
        printf("%i", pos[j]);
    }
    return 0;
}
</code>```

But it doesn't work, it prints a lot of numbers even if M is a small number.

答:
After your while loop completes, j holds the total number of positions recorded, so you should be printing from pos[1] to pos[j]. Your current loop prints from pos[1] to pos[i]. Just invert the variables in your final loop:

```<code>for(i=1; i<=j; i++){
    printf("%i", pos[i]);
}
</code>```

Title: Finding characters within a string in C

Body:
I'm writing an algorithm in C with netbeans to find asterisks in a string.

int main() {
    int M=0, i, j;
    scanf("%i",&M);
    int pos[M];
    char c[M];
    scanf("%s", c);

    i=0;
    j=1;

    while(c[i] != '\0'){
        if(c[i]=='*'){
            pos[j] = i;
            j++;
        }
        i++;
    }

    printf("Asterisks in positions: \n\n");

    for(j=1; j<=i; j++){
        printf("%i", pos[j]);
    }
    return 0;
}

But it doesn't work, it prints a lot of numbers even if M is a small number.

Body:
After your while loop completes, j holds the total number of positions recorded, so you should be printing from pos[1] to pos[j]. Your current loop prints from pos[1] to pos[i]. Just invert the variables in your final loop:

for(i=1; i<=j; i++){
    printf("%i", pos[i]);
}


问:
Running some Cucumber steps without invoking Webdriver
Scenario

```<code>Step1 Run 1 webservice
Step2 Validate stepService
Step3 initiate browser/visit url
</code>```

Is there a possibility to have Step 1 and 2 not to call for Webdriver?
My understanding if I do not force step to call anything like visit url, then I should be fine
Reason for asking I have Cucumber JVM framework and trying to implement some web service calls before.

答: Yes, in the step definitions for Step 1 and Step 2, you can perform non-Webdriver/non-UI tasks as well. Let me know, if you have any further queries.</p>

Body:
Scenario

Step1 Run 1 webservice
Step2 Validate stepService
Step3 initiate browser/visit url

Is there a possibility to have Step 1 and 2 not to call for Webdriver?
My understanding if I do not force step to call anything like visit url, then I should be fine
Reason for asking I have Cucumber JVM framework and trying to implement some web service calls before.


问:
Angular2: how to add validator and exclude required
I created a custom validator to check email addresses filled by users. Anyway the email field is not required, but if I add my validator it includes required as well.

Here is my form in the constructor of my component class:

```<code>    this.myForm = fb.group({
        'name': [''],
        'surname': [''],
        'username': ['', Validators.required],
        'email': ['', validateEmail]
    });
</code>```

Email field is not required, but if users doesn't fill it, the form doesn't get validated. At the same time if users fill it, I want that the email validation is applied.

Here is my email validator:

```<code>export function validateEmail(c: FormControl) {
    var EMAIL_REGEXP = /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})*$/i;

    return EMAIL_REGEXP.test(c.value) ? null : {
        validateEmail: {
            valid: false
        }
    };
}
</code>```

I could edit my custom validator to accept empty strings, but I think this is not the right way to solve my problem.

Do you have a better idea?

答:
Allow an empty string for control value, as follows:

```<code>static emailValidator(control: any) {
  // RFC 2822 compliant regex
  var EMAIL_REGXP = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

  if ( control.value === '' || control.value.match(EMAIL_REGXP) ) {
    return null;
  } else {
    return { 'invalidEmailAddress': true };
  }
};
</code>```

I don't think this could be seen as a side-effect as the purpose of the function is to find invalid strings that should conform to an email format.

Body:
I created a custom validator to check email addresses filled by users. Anyway the email field is not required, but if I add my validator it includes required as well.

Here is my form in the constructor of my component class:

    this.myForm = fb.group({
        'name': [''],
        'surname': [''],
        'username': ['', Validators.required],
        'email': ['', validateEmail]
    });

Email field is not required, but if users doesn't fill it, the form doesn't get validated. At the same time if users fill it, I want that the email validation is applied.

Here is my email validator:

export function validateEmail(c: FormControl) {
    var EMAIL_REGEXP = /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})*$/i;

    return EMAIL_REGEXP.test(c.value) ? null : {
        validateEmail: {
            valid: false
        }
    };
}

I could edit my custom validator to accept empty strings, but I think this is not the right way to solve my problem.

Do you have a better idea?

Body:
Allow an empty string for control value, as follows:

static emailValidator(control: any) {
  // RFC 2822 compliant regex
  var EMAIL_REGXP = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;

  if ( control.value === '' || control.value.match(EMAIL_REGXP) ) {
    return null;
  } else {
    return { 'invalidEmailAddress': true };
  }
};

I don't think this could be seen as a side-effect as the purpose of the function is to find invalid strings that should conform to an email format.


问:
Windows Azure Client with IP address 'XXX.XXX.XXX.XX' is not allowed to access the server
I have setup Sever, database and Firewall Setting (Rule) In windows Azure. I Have added The IP In firewall setting which is populating under the Windows Azure Firewall Tab.

When I am trying connect with Database using Manage from Azure Platform I am getting this error message.

Firewall check failed. Cannot open server 'XXXXXXXXX' requested by the login. Client with IP address 'XXXXXXXXX' is not allowed to access the server.  To enable access, use the SQL Azure Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range.  It may take up to five minutes for this change to take effect.

And I am also Not able to connect via Sql Server Management Studio. Getting Same connection issue Error for My IP Address.

I am not using static IP but my IP haven't change during this process. I have tried lot Example but all are saying To add firewall rule That I had already done.

I have Added Firewall exception for port Number 1433.

But still this is not working Please let me know that what type of setting is still missing.

答:
As Azure keeps changing, so do the ways to get to the firewall.

Click your SQL server (not the database, but the server) -> click firewall -> add the IP range you want to allow.

Dont forget to click save!


问:
how to call IBM Watson services from javascript
I am implementing a virtual agent using IBM Watson services. My application is developed using Jquery, Angular JS & Java.Currently i am calling the watson services from middle layer that is java. But i want to avoid that and call directly from javascript.When i call from javascript using XML Http request, i am getting CORS error.How to solve this?

Below is my code:

```<code>var username = "uid";
var password = "pwd";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
//xhr.withCredentials = true;
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type, application/json, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xhr.setRequestHeader('Content-Type', undefined);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
xhr.send('"query":"hi"');
</code>```

答:
take a look at this tutorial on IBM developerWorks on using Watson's Question and Answer service -
http://www.ibm.com/developerworks/cloud/library/cl-watson-qaapi-app/index.html#N10229</p>

Body:
I am implementing a virtual agent using IBM Watson services. My application is developed using Jquery, Angular JS & Java.Currently i am calling the watson services from middle layer that is java. But i want to avoid that and call directly from javascript.When i call from javascript using XML Http request, i am getting CORS error.How to solve this?

Below is my code:

var username = "uid";
var password = "pwd";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'url');
//xhr.withCredentials = true;
xhr.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type, application/json, Authorization");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
xhr.setRequestHeader('Content-Type', undefined);
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
xhr.send('"query":"hi"');


问:
pure opengl zoom camera to mouse pos
Im trying to edit my mouse zoom function to zoom towards the mouse pos in 3d world, I can get the 3d cords of the mouse if i need that just not sure how to do it.

At the moment my zoom just zooms towards the screen center.

```<code>void CCamera::OnMouseWheel(float zDelta)
{
    Position -= Reference;

    if(zDelta < 0 && length(Position) < 500.0f)
    {
        Position += Position * 0.1f;
    }

    if(zDelta > 0 && length(Position) > 0.05f)
    {
        Position -= Position * 0.1f;
    }

    Position += Reference;

    CalculateViewMatrix();
}

void CCamera::CalculateViewMatrix()
{
    ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
    ViewMatrixInverse = inverse(ViewMatrix);
    ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
    ViewProjectionMatrixInverse = ViewMatrixInverse * ProjectionMatrixInverse;
}
</code>```

答:
Let's suppose you have the 3D coordinates of the mouse cursor. Undoing the viewport transformation you get these coordinates in NDC space, and also by matrix inversion you can get View space or Model space coordinates. Now, you have a vector from camera to these mouse coordinates (in whatever space you like). The last step is moving the camera following that vector by an amount depending on mouse wheel-rotation.

If you don't have those 3D mouse coordinates... you have a big problem, due to it's not possible to get 3D information from a 2D data. You lack the "depth in the screen", Z value in NDC space.

Title: pure opengl zoom camera to mouse pos

Body:
Im trying to edit my mouse zoom function to zoom towards the mouse pos in 3d world, I can get the 3d cords of the mouse if i need that just not sure how to do it.

At the moment my zoom just zooms towards the screen center.

void CCamera::OnMouseWheel(float zDelta)
{
    Position -= Reference;

    if(zDelta < 0 && length(Position) < 500.0f)
    {
        Position += Position * 0.1f;
    }

    if(zDelta > 0 && length(Position) > 0.05f)
    {
        Position -= Position * 0.1f;
    }

    Position += Reference;

    CalculateViewMatrix();
}

void CCamera::CalculateViewMatrix()
{
    ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
    ViewMatrixInverse = inverse(ViewMatrix);
    ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
    ViewProjectionMatrixInverse = ViewMatrixInverse * ProjectionMatrixInverse;
}


问:
Concatenate column headers if value in rows below is non-blank
I have table with data in the format below.

Data

I want the finished table to have the blank column to be populated like the highlighted one below.

Finished Table

So, I need a formula or VBA that will return and concatenate the headers of non-blank cells in each row.

答:
Use¹ the following as an array formula.

```<code>=TEXTJOIN("-->", TRUE, IF(LEN(C3:I3), C$2:I$2, ""))
</code>```

Pre-Excel 2016 versions

While you could just string together a series of IF statements, a cleaner alternate might be to write a user defined function (aka UDF).

In a standard VBA module code sheet:

```<code>Function udf_Stitch_Together(r As Range, _
                             h As Range, _
                             Optional d As String = "-->", _
                             Optional blnks As Boolean = False) As String
    Dim s As String, c As Long
    For c = 1 To r.Cells.Count
        If CBool(Len(r.Cells(c).Text)) Then _
            s = s & IIf(Len(s), d, vbNullString) & h.Cells(c).Text
    Next c
    udf_Stitch_Together = s
End Function
</code>```

¹ The TEXTJOIN was introduced with Excel 2016 in the following versions:Excel for Android phones, Excel Mobile, Excel 2016 with Office 365, Excel 2016 for Mac, Excel Online, Excel for iPad, Excel for iPhone and Excel for Android tablet.

Body:
Use¹ the following as an array formula.

=TEXTJOIN("-->", TRUE, IF(LEN(C3:I3), C$2:I$2, ""))

Pre-Excel 2016 versions

While you could just string together a series of IF statements, a cleaner alternate might be to write a user defined function (aka UDF).

In a standard VBA module code sheet:

Function udf_Stitch_Together(r As Range, _
                             h As Range, _
                             Optional d As String = "-->", _
                             Optional blnks As Boolean = False) As String
    Dim s As String, c As Long
    For c = 1 To r.Cells.Count
        If CBool(Len(r.Cells(c).Text)) Then _
            s = s & IIf(Len(s), d, vbNullString) & h.Cells(c).Text
    Next c
    udf_Stitch_Together = s
End Function

¹ The TEXTJOIN was introduced with Excel 2016 in the following versions:Excel for Android phones, Excel Mobile, Excel 2016 with Office 365, Excel 2016 for Mac, Excel Online, Excel for iPad, Excel for iPhone and Excel for Android tablet.


问:
Common libraries in a large team
Assume you have five products, and all of them use one or more of the company's internal libraries, written by individual developers.

It sounds simple but in practice, I found it to be very difficult to maintain.

How do you deal with the following scenarios:

A developer unintentionally introduces a bug and breaks everything in production.

Every library has to mature, That means the API needs to evolve, so how do you deploy the updated version to production if every developer needs to update/test their code while they are extremely busy on other projects? Is this a resource and time issue?

Version control, deployment,and usage. Would you store this in one global location or force each project to use, say, svn:externals to "tie" a library?

I've found that it is extremely hard to come up with a good strategy. My own pet theory is this:

Each common library has to have a super-thorough set of tests or else it should never be common, even if it means someone else duplicates the effort. Duplicate untested code is better than common untested code (you break only one project).

Each common library has to have a dedicated maintainer (can be offset by a really good test suite in a smaller team).

Each project should check out the version of the library that is known to work with it. This means a developer does not have to get pulled away to update API usage, as the common code gets updated. Which it will be. Every non-trivial piece of code evolves over months and years.

Thank you for your thoughts on this!

答:
Treat the development of the libraries like any other product. Each library has its own repository, its own releases and version numbers. The compiled and officially tested versions of the library are also kept in the repository. Document features and changes from version to version.

Then use the libraries like you would using third party libraries. Your product uses only fixed versions of the compiled libraries. Switch to a new version when you really need to and be aware that this involves more testing. Add the versions you use to your version control.

When you find a bug or require a new feature in a library, a new version or sub-version is created. Using a version control system like svn makes this easy. When you need the source code for debugging purposes, export it and include it in your projects, but do not change it there, but fix problems in the libraries' repositories.

This way, every team can contribute to the libraries without endangering the work of the other teams. Switching versions is done deliberately and not by accident.

OwnerDisplayName: Andrei

Title: Common libraries in a large team

LastEditorDisplayName: Roger Lipscombe

OwnerDisplayName: Sebastian Dietz


问:
Android: advanced text drawing (columns, fixed height, paging). How?
I'm porting application from iPad to Galaxy Tab and, since I hadn't had much experience with programming for Android devices I'd like to know some "general" things.

I've used CoreText for all my ipad text drawing needs, what can I use in Android? How can I break large text apart dividing it in to frames/paths and then layout them on screen (think, columns in news application articles). It looks like that Paint class does some things related to what I need, but I don't know if that's the proper way to go.

Please, enlighten me :)

答:
Personally I would wait for Honeycomb, maybe Gingerbread if you're lucky. Currently Android is not optimized for tablets, plain and simple (can you imagine developing on the iPad with just the standard iPhone SDK?)

Gingerbread is going to be announced before the new year and we might get some tablet goodies, but Honeycomb (release soonish?) is when full tablet support will be available.

For the timebeing maybe develop for the standard phone size, but keep it modular enough so the upgrade for tablets is painless.


问:
Entity Framework, deleting from a collection results in foreign key exception
I have a code-first EF database solution. The following are my model classes:

```<code>public class HolidayAllowance
{
    private decimal _taken;

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public int EmployeeId { get; set; }
    public decimal Allowance { get; set; }
    public virtual ObservableCollection<Holiday>  Holidays { get; set; }

    public decimal Taken
    {
        get { return Holidays?.Sum(x => x.Duration) ?? 0; }
        set { _taken = value; }
    }

    public decimal Remaining => Allowance - Taken;
}

public class Holiday
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public DateTime HolidayStartDay { get; set; }
    public HolidayType HolidayStartDayType { get; set; }
    public decimal Duration { get; set; }
    public int HolidayAllowanceId { get; set; }
}
</code>```

My DbContext:

```<code>public class StaffAndInvoiceManagerDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<HolidayAllowance> HolidayAllowances { get; set; }
    public DbSet<Note> Notes { get; set; }
    public DbSet<Termination> Terminations { get; set; }
}
</code>```

The method from my DataService that tries to delete a holiday from the holidayAllowance:

```<code>public void DeleteHoliday(Holiday selectedHoliday)
{
   var allowance = _dbContext
       .HolidayAllowances
        .FirstOrDefault(x => x.Id == selectedHoliday.HolidayAllowanceId);

    allowance?
      .Holidays
      .Remove(selectedHoliday);

   _dbContext.SaveChanges();
}
</code>```

The method on my ViewModel that calls that:

```<code>private void DeleteHoliday()
{
    if (!_messageBoxService.AskYesNoQuestion("Delete Holiday?", "Do you want to delete this holiday?")) return;

    _staffDataService.DeleteHoliday(SelectedHoliday);
    HolidayAllowance.Holidays.Remove(SelectedHoliday);
    RaisePropertyChanged(nameof(HolidayAllowance));
}
</code>```

The problem is, when I try to delete a Holiday from the HolidayAllowance.Holidays collection I get the following error:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value.

  If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

I don't understand why that would be a FK violation? I'm just trying to delete from a collection.

My DB tables that EF is generating.

I can execute the following SQL and it works without throwing a FK exception.

```<code>delete from dbo.Holidays
where Id = 2
</code>```

The Foreign Key its generating looks like this, If I script to Create in SSMS

```<code>ALTER TABLE [dbo].[Holidays]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Holidays_dbo.HolidayAllowances_HolidayAllowanceId]
FOREIGN KEY([HolidayAllowanceId])
REFERENCES [dbo].[HolidayAllowances] ([Id])
GO

ALTER TABLE [dbo].[Holidays] CHECK CONSTRAINT [FK_dbo.Holidays_dbo.HolidayAllowances_HolidayAllowanceId]
GO
</code>```

I've tried the following in my DBContext after reading @Fals comment below.

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    base.OnModelCreating(modelBuilder);
}
</code>```

I would have thought EF was doing similar ? Still no luck.

答:
I've found a fix for this, but I'm not sure why it works or if it's the correct way to do it. Anyway,

```<code>_dbContext.Entry(selectedHoliday).State = EntityState.Deleted;
_dbContext.SaveChanges();
</code>```

And the item is deleted. I have no idea why I have to do this and not just delete it from it's parent, but it works.

Body:
I have a code-first EF database solution. The following are my model classes:

public class HolidayAllowance
{
    private decimal _taken;

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public int EmployeeId { get; set; }
    public decimal Allowance { get; set; }
    public virtual ObservableCollection<Holiday>  Holidays { get; set; }

    public decimal Taken
    {
        get { return Holidays?.Sum(x => x.Duration) ?? 0; }
        set { _taken = value; }
    }

    public decimal Remaining => Allowance - Taken;
}

public class Holiday
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public DateTime HolidayStartDay { get; set; }
    public HolidayType HolidayStartDayType { get; set; }
    public decimal Duration { get; set; }
    public int HolidayAllowanceId { get; set; }
}

My DbContext:

public class StaffAndInvoiceManagerDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Employee> Employees { get; set; }
    public DbSet<HolidayAllowance> HolidayAllowances { get; set; }
    public DbSet<Note> Notes { get; set; }
    public DbSet<Termination> Terminations { get; set; }
}

The method from my DataService that tries to delete a holiday from the holidayAllowance:

public void DeleteHoliday(Holiday selectedHoliday)
{
   var allowance = _dbContext
       .HolidayAllowances
        .FirstOrDefault(x => x.Id == selectedHoliday.HolidayAllowanceId);

    allowance?
      .Holidays
      .Remove(selectedHoliday);

   _dbContext.SaveChanges();
}

The method on my ViewModel that calls that:

private void DeleteHoliday()
{
    if (!_messageBoxService.AskYesNoQuestion("Delete Holiday?", "Do you want to delete this holiday?")) return;

    _staffDataService.DeleteHoliday(SelectedHoliday);
    HolidayAllowance.Holidays.Remove(SelectedHoliday);
    RaisePropertyChanged(nameof(HolidayAllowance));
}

The problem is, when I try to delete a Holiday from the HolidayAllowance.Holidays collection I get the following error:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value.

  If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

I don't understand why that would be a FK violation? I'm just trying to delete from a collection.

My DB tables that EF is generating.

I can execute the following SQL and it works without throwing a FK exception.

delete from dbo.Holidays
where Id = 2

The Foreign Key its generating looks like this, If I script to Create in SSMS

ALTER TABLE [dbo].[Holidays]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Holidays_dbo.HolidayAllowances_HolidayAllowanceId]
FOREIGN KEY([HolidayAllowanceId])
REFERENCES [dbo].[HolidayAllowances] ([Id])
GO

ALTER TABLE [dbo].[Holidays] CHECK CONSTRAINT [FK_dbo.Holidays_dbo.HolidayAllowances_HolidayAllowanceId]
GO

I've tried the following in my DBContext after reading @Fals comment below.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    base.OnModelCreating(modelBuilder);
}

I would have thought EF was doing similar ? Still no luck.

Body:
I've found a fix for this, but I'm not sure why it works or if it's the correct way to do it. Anyway,

_dbContext.Entry(selectedHoliday).State = EntityState.Deleted;
_dbContext.SaveChanges();

And the item is deleted. I have no idea why I have to do this and not just delete it from it's parent, but it works.