问:
Deleting multiple rows throws 'there is no row position at 2' IndexOutOfRangeException
```<code>Console.WriteLine("Enter how many rows you want to delete:");
del = Convert.ToInt16(Console.ReadLine());
try
{

    for (int i = 0; i <del; i++)
    {
        dt.Rows[i].Delete();
        dt.AcceptChanges();
    }

    Console.WriteLine("\n************************************\n");
}
</code>```

答:
The problem you're having is that each time you delete a row, the rows "move up" so when you delete dt.Rows[0], what was dt.Rows[1] becomes dt.Rows[0], because you're accessing each row by its index rather than by a unique identifier for it. The below is a worked example that will show this if you run it (I've based it on your code so that you've got some context to it):

```<code>var dt = new DataTable();
dt.Columns.Add("IdColumn", typeof(int));
for (int i = 0; i < 10; i++)
{
    dt.Rows.Add(new object[] { i } );
}

var del = 3;

for (int i = 0; i < del; i++)
{
    dt.Rows[i].Delete();
    dt.AcceptChanges();
    Console.WriteLine("Deleted row number {0}, rows remaining in table are {1}, IdColumn for Rows[i] is {2}", i, dt.Rows.Count, dt.Rows[i]["IdColumn"]);
}

Console.WriteLine("\n************************************\n");
</code>```

One option available to you is to use LINQ and replace the above with something along the lines of:

```<code>var dt = new DataTable();
dt.Columns.Add("IdColumn", typeof(int));
for (int i = 0; i < 10; i++)
{
    dt.Rows.Add(new object[] { i } );
}

var del = 3;

dt = dt.AsEnumerable().Skip(del).CopyToDataTable();
</code>```

If you look at the contents of dt after running the second code snippet, you should see that the rows with a value of {0, 1, 2} for IdColumn have been removed, which looks like the outcome you're after.

Body:
The problem you're having is that each time you delete a row, the rows "move up" so when you delete dt.Rows[0], what was dt.Rows[1] becomes dt.Rows[0], because you're accessing each row by its index rather than by a unique identifier for it. The below is a worked example that will show this if you run it (I've based it on your code so that you've got some context to it):

var dt = new DataTable();
dt.Columns.Add("IdColumn", typeof(int));
for (int i = 0; i < 10; i++)
{
    dt.Rows.Add(new object[] { i } );
}

var del = 3;

for (int i = 0; i < del; i++)
{
    dt.Rows[i].Delete();
    dt.AcceptChanges();
    Console.WriteLine("Deleted row number {0}, rows remaining in table are {1}, IdColumn for Rows[i] is {2}", i, dt.Rows.Count, dt.Rows[i]["IdColumn"]);
}

Console.WriteLine("\n************************************\n");

One option available to you is to use LINQ and replace the above with something along the lines of:

var dt = new DataTable();
dt.Columns.Add("IdColumn", typeof(int));
for (int i = 0; i < 10; i++)
{
    dt.Rows.Add(new object[] { i } );
}

var del = 3;

dt = dt.AsEnumerable().Skip(del).CopyToDataTable();

If you look at the contents of dt after running the second code snippet, you should see that the rows with a value of {0, 1, 2} for IdColumn have been removed, which looks like the outcome you're after.


来源: stackexchange

问:
python numpy: iterate for different conditions without using a loop
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

```<code>min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])
</code>```

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

答:
The solution is</p>

```<code>    import numpy as np
    min1=3
    max1=1
    a1=np.array([1,2,5,3,4])
    a2=np.array([5,2,6,2,1])

    output=np.zeros(5)
    diff = a1-a2

    output[np.where(diff < max1)] = diff[np.where(diff < max1)]*5
    output[np.where(diff > min1)] = diff[np.where(diff > min1)]*3
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to iterate over numpy arrays and generate an output, which has conditions similar to that described below:

min1 = 3
max1 = 1
a1 = np.array([1, 2, 5, 3, 4])
a2 = np.array([5, 2, 6, 2, 1])
output = np.zeros(5)
for i in range(0, 5):
  if((a1[i] - a2[i]) > min1):
    output[i] = 3 * (a1[i] - a2[i])

  if((a1[i] - a2[i]) < max1):
    output = 5 * (a1[i] - a2[i])

I need to optimize the above code, so that I utilize the numpy functionalities as the best and also avoid using a loop. How should I do it?

Body:
The solution is

    import numpy as np
    min1=3
    max1=1
    a1=np.array([1,2,5,3,4])
    a2=np.array([5,2,6,2,1])

    output=np.zeros(5)
    diff = a1-a2

    output[np.where(diff < max1)] = diff[np.where(diff < max1)]*5
    output[np.where(diff > min1)] = diff[np.where(diff > min1)]*3


问:
UICollctionView didSelectItemAt problems
I am trying to change an UIImage in the collectionviewcell with the help of on didSelectItemAt. It is working when I select cell on the beginning but when I scroll down and scroll back up the images are back to what they were and changed images shift to different cells.

First cell selected Image

Scrolled down then came up Image

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
        let tempString = "\(NSLocalizedString("base_url", comment: ""))\(itemImageLink[indexPath.row])"
        let urlnew:String = tempString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
        let url = URL(string: urlnew)
        cell.rateCardImage.kf.setImage(with: url,placeholder: UIImage(named: "Junkart_Bin.png"))
        cell.label.text = itemName[indexPath.row]
        cell.itemRate.text = itemRate[indexPath.row]
        cell.layer.cornerRadius = 3
        cell.card.backgroundColor = UIColor.white
        cell.card.layer.masksToBounds = false
        cell.card.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
        cell.card.layer.shadowOffset = CGSize(width: 0, height: 0)
        cell.card.layer.shadowOpacity = 1   //0.8
        return cell
    }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! RateCardCollectionViewCell
        if self.selectedRate == nil {
            cell.changeImagetoSelected()
            self.selectedRate = [Int]()
            self.selectedRate.append(indexPath.row)
        }
        else {

        }
    }
</code>```

Following is the UICollectionViewCell Class

```<code>class RateCardCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var rateCardImage: UIImageView!
    @IBOutlet weak var card: UIView!
    @IBOutlet weak var itemRate: UILabel!
    @IBOutlet weak var selected_rate_image: UIImageView!
    func changeImagetounSelected() {
        selected_rate_image.image = UIImage(named: "unselected_rate")
    }
    func changeImagetoSelected() {
        selected_rate_image.image = UIImage(named: "selected_rate")
    }
}
</code>```

Please Help!!

答:
This happened because collection view dequeue his cells. So you need to persist your selection in dataModel and get if cell is selected or no from it. So persist your selectedIndex in your viewController and in your cellForItemAt method call:

```<code>if(self.selectedIndex == indexPath.row){
    cell.changeImageToSelected()
}
else{
    cell.changeImageTounselected()
}
</code>```

This will persist your selection when scroll

Body:
I am trying to change an UIImage in the collectionviewcell with the help of on didSelectItemAt. It is working when I select cell on the beginning but when I scroll down and scroll back up the images are back to what they were and changed images shift to different cells.

First cell selected Image

Scrolled down then came up Image

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
        let tempString = "\(NSLocalizedString("base_url", comment: ""))\(itemImageLink[indexPath.row])"
        let urlnew:String = tempString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
        let url = URL(string: urlnew)
        cell.rateCardImage.kf.setImage(with: url,placeholder: UIImage(named: "Junkart_Bin.png"))
        cell.label.text = itemName[indexPath.row]
        cell.itemRate.text = itemRate[indexPath.row]
        cell.layer.cornerRadius = 3
        cell.card.backgroundColor = UIColor.white
        cell.card.layer.masksToBounds = false
        cell.card.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
        cell.card.layer.shadowOffset = CGSize(width: 0, height: 0)
        cell.card.layer.shadowOpacity = 1   //0.8
        return cell
    }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! RateCardCollectionViewCell
        if self.selectedRate == nil {
            cell.changeImagetoSelected()
            self.selectedRate = [Int]()
            self.selectedRate.append(indexPath.row)
        }
        else {

        }
    }

Following is the UICollectionViewCell Class

class RateCardCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var rateCardImage: UIImageView!
    @IBOutlet weak var card: UIView!
    @IBOutlet weak var itemRate: UILabel!
    @IBOutlet weak var selected_rate_image: UIImageView!
    func changeImagetounSelected() {
        selected_rate_image.image = UIImage(named: "unselected_rate")
    }
    func changeImagetoSelected() {
        selected_rate_image.image = UIImage(named: "selected_rate")
    }
}

Please Help!!

Body:
This happened because collection view dequeue his cells. So you need to persist your selection in dataModel and get if cell is selected or no from it. So persist your selectedIndex in your viewController and in your cellForItemAt method call:

if(self.selectedIndex == indexPath.row){
    cell.changeImageToSelected()
}
else{
    cell.changeImageTounselected()
}

This will persist your selection when scroll


问:
A gap between a Canvas object and its parent Toplevel object right side in a Tkinter GUI program
I'm developing a GUI program with Tkinter. It will work on 7" touch screen, full screen.
First, I made the main title.

```<code>import Tkinter as tk

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 480

class Application(tk.Toplevel):
  def __init__(self, *args, **kwargs):
    tk.Toplevel.__init__(self, *args, **kwargs)
    self.overrideredirect(True)
    self.wm_geometry("800x480")
    self.cnvs = None
    self.showTitle()

  def showTitle(self):
    self.config(bg = 'white', borderwidth = 0)
    self.cnvs = TitleCanvas(self)
    self.cnvs.grid(sticky = tk.N + tk.E + tk.W + tk.S)

class TitleCanvas(tk.Canvas):
  def __init__(self, parent):
    tk.Canvas.__init__(self, parent, width = SCREEN_WIDTH, height = SCREEN_HEIGHT)
    self.widgets = {}
    self.init_ui()

  def init_ui(self):
    # BG Color: White
    self.config(bg = 'white', borderwidth = 0)

    # Blank Area
    # Row: 0
    self.lblBlank = tk.Label(self, background = 'white', borderwidth = 0, text = '')
    self.lblBlank.grid(pady = 20, row = 0)

    # Title Image
    # Row: 1
    self.photoLogo = tk.PhotoImage(file = 'samplelogo.gif')
    self.lblLogo = tk.Label(self, image = self.photoLogo)
    self.lblLogo.grid(padx = 100, pady = 40, row = 10, sticky = tk.E + tk.W)

    # Text1
    # Row: 2
    self.lblLoad = tk.Label(self, background = 'white',
                      font = ("Helvetica", -30), text = "Loading...")
    self.lblLoad.grid(pady = 60, row = 2, sticky = tk.E + tk.W)

    # Text2
    # Row: 3
    self.lblVer = tk.Label(self, background = 'white',
                     font = ("Helvetica", -30), text = "Company and Version")
    self.lblVer.grid(pady = 30, row = 3, sticky = tk.E + tk.W)

app = Application()
app.mainloop()
</code>```

The Canvas object should fill the whole screen. But it doesn't reach to the edge of the right side.
To remove the gap, what should I do?

答:
I solved this problem with create_image() and create_text(). these methods are able to set the position of widgets.

TitleCanvas.init_ui() method can be revised like this;

```<code>def init_ui(self):
  #BG Color: White
  self.config(bg = 'white', borderwidth = 0)

  # Background
  self.create_rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), fill = 'white')

  # Title Image
  #Center Point: (400, 160)
  self.photoLogo = tk.PhotoImage(file = 'samplelogo.gif')
  self.create_image(400, 160, anchor = tk.CENTER, image = self.photoLogo)

  # Text1
  self.create_text((400, 315), text = 'Loading...')

  # Text2
  self.create_text((400, 435), text = 'Company and Version')
</code>```

Body:
I'm developing a GUI program with Tkinter. It will work on 7" touch screen, full screen.
First, I made the main title.

import Tkinter as tk

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 480

class Application(tk.Toplevel):
  def __init__(self, *args, **kwargs):
    tk.Toplevel.__init__(self, *args, **kwargs)
    self.overrideredirect(True)
    self.wm_geometry("800x480")
    self.cnvs = None
    self.showTitle()

  def showTitle(self):
    self.config(bg = 'white', borderwidth = 0)
    self.cnvs = TitleCanvas(self)
    self.cnvs.grid(sticky = tk.N + tk.E + tk.W + tk.S)

class TitleCanvas(tk.Canvas):
  def __init__(self, parent):
    tk.Canvas.__init__(self, parent, width = SCREEN_WIDTH, height = SCREEN_HEIGHT)
    self.widgets = {}
    self.init_ui()

  def init_ui(self):
    # BG Color: White
    self.config(bg = 'white', borderwidth = 0)

    # Blank Area
    # Row: 0
    self.lblBlank = tk.Label(self, background = 'white', borderwidth = 0, text = '')
    self.lblBlank.grid(pady = 20, row = 0)

    # Title Image
    # Row: 1
    self.photoLogo = tk.PhotoImage(file = 'samplelogo.gif')
    self.lblLogo = tk.Label(self, image = self.photoLogo)
    self.lblLogo.grid(padx = 100, pady = 40, row = 10, sticky = tk.E + tk.W)

    # Text1
    # Row: 2
    self.lblLoad = tk.Label(self, background = 'white',
                      font = ("Helvetica", -30), text = "Loading...")
    self.lblLoad.grid(pady = 60, row = 2, sticky = tk.E + tk.W)

    # Text2
    # Row: 3
    self.lblVer = tk.Label(self, background = 'white',
                     font = ("Helvetica", -30), text = "Company and Version")
    self.lblVer.grid(pady = 30, row = 3, sticky = tk.E + tk.W)

app = Application()
app.mainloop()

The Canvas object should fill the whole screen. But it doesn't reach to the edge of the right side.
To remove the gap, what should I do?

Body:
I solved this problem with create_image() and create_text(). these methods are able to set the position of widgets.

TitleCanvas.init_ui() method can be revised like this;

def init_ui(self):
  #BG Color: White
  self.config(bg = 'white', borderwidth = 0)

  # Background
  self.create_rectangle((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), fill = 'white')

  # Title Image
  #Center Point: (400, 160)
  self.photoLogo = tk.PhotoImage(file = 'samplelogo.gif')
  self.create_image(400, 160, anchor = tk.CENTER, image = self.photoLogo)

  # Text1
  self.create_text((400, 315), text = 'Loading...')

  # Text2
  self.create_text((400, 435), text = 'Company and Version')


问:
ASP.NET DataList - defining "columns/rows" when repeating horizontal and using flow layout
Here is my DataList:

```<code><asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>
</code>```

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

```<code><div>
 <span>Item 1</span>
 <span>Item 2</span>
 <span>Item 3</span>
</div>
<div>
 <span>Item 4</span>
 <span>Item 5</span>
 <span>Item 6</span>
</div>
[etc]
</code>```

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.

```<code> <span>Item 1</span>
 <span>Item 2</span>
 <span>Item 3</span>
<br>
 <span>Item 4</span>
 <span>Item 5</span>
 <span>Item 6</span>
<br>
</code>```

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.

Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

答:
If you really needed to use a datalist for some reason instead of implementing this as a repeater, you can try doing something like this:

```<code><asp:DataList ID="dataList" runat="server" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" OnItemDataBound="dataList_ItemDataBound">
    <HeaderTemplate>
        <div>
    </HeaderTemplate>
    <SeparatorTemplate>
        </div><div>
    </SeparatorTemplate>
    <ItemTemplate>
        <%# Container.DataItem %></ItemTemplate>
    <FooterTemplate>
        </div></FooterTemplate>
</asp:DataList>
</code>```

```<code>protected void dataList_ItemDataBound(object sender, DataListItemEventArgs e) {
    if (e.Item.ItemType == ListItemType.Separator) {
        if ((e.Item.ItemIndex + 1) % 3 != 0) {
            e.Item.Controls.Clear();
        }
    }
}
</code>```

OwnerDisplayName: irobinson

ContentLicense: CC BY-SA 2.5

Body:
Here is my DataList:

<asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

[etc]

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.

Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

LastEditorDisplayName: bdukes

Body:
If you really needed to use a datalist for some reason instead of implementing this as a repeater, you can try doing something like this:

<asp:DataList ID="dataList" runat="server" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" OnItemDataBound="dataList_ItemDataBound">
    <HeaderTemplate>
        <div>
    </HeaderTemplate>
    <SeparatorTemplate>
        </div><div>
    </SeparatorTemplate>
    <ItemTemplate>
        <%# Container.DataItem %></ItemTemplate>
    <FooterTemplate>
        </div></FooterTemplate>
</asp:DataList>

protected void dataList_ItemDataBound(object sender, DataListItemEventArgs e) {
    if (e.Item.ItemType == ListItemType.Separator) {
        if ((e.Item.ItemIndex + 1) % 3 != 0) {
            e.Item.Controls.Clear();
        }
    }
}

OwnerDisplayName: David Thomas Garcia


问:
Change html  letters length on resolution change?
I have an HTML code: My Text - Loooong Text

Output: My Text - Loooong Text

When screen resolution goes to width lower than 445px, I want Loooong Text as: L. Text, and if it increases, text returns to original size.

Any help? Thanks.

答:
You can split the text into more  elements, and then use @media query in your CSS to decide which to show and which to hide.

HTML:

```<code><a>
    <span>My Text -</span>
    <span id='long'>Loooong Text</span>
    <span id='short'>L. Text</span>
</a>
</code>```

CSS:

```<code>@media screen and (max-width: 445px) {
   #short { display: inline; }
   #long { display: none; }
}
@media screen and (min-width: 446px) {
   #short { display: none; }
   #long { display: inline; }
}
</code>```

Title: Change html <a> letters length on resolution change?

Body:
You can split the text into more  elements, and then use @media query in your CSS to decide which to show and which to hide.

HTML:

<a>
    <span>My Text -</span>
    <span id='long'>Loooong Text</span>
    <span id='short'>L. Text</span>
</a>

CSS:

@media screen and (max-width: 445px) {
   #short { display: inline; }
   #long { display: none; }
}
@media screen and (min-width: 446px) {
   #short { display: none; }
   #long { display: inline; }
}


问:
How to render openFrameworks app to host on browser
I'm new to both openFrameworks and this compiler called Emscripten.
After struggling for a few days, I was able to compile my openFrameworks/C++ code into js but Emscripten gives me an html file with a lot of junk included (For example, there is a header and footer -
 http://openframeworks.cc/setup/emscripten/)

I'm trying to host the video/animation itself like it is on this page (http://www.syedrezaali.com/#/great-scott/) but I have no idea how to go about it. Can anyone help me out?

Thank you

答:
If you follow OF's guidelines Emscripten generates not only the html file but also some other files (I think it's 4 files in total). You need to copy all of those into your site, then link to the html file.

Notice that while developing you can use

emrun --browser chrome bin/yourSample.html

To open the file, but you cannot just open the .html file (not sure why). See this guidelines as well, which are linked in the OF tutorial.

Update

I haven't tested this, but it looks like OF loads a site template. See this makefile for emscripten, you may specify your own via PROJECT_EMSCRIPTEN_TEMPLATE or you could just change the template OF uses.


问:
Scala tuple function composition
Let's say we have a 3 functions with Tuple3 result:

```<code>def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}
</code>```

And I can compose them like this:

```<code>val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)
</code>```

But I want something like this:

```<code>val (x, y, z) = foo(bar(buz("1", "2", "3")))
</code>```

How can I achieve this?

答:
```<code>def foo(arg: (String, String, String)): (String, String, String) = {
  (s"foo_${arg._1}", s"foo_${arg._2}", s"foo_${arg._3}")
}

def bar(arg: (String, String, String)): (String, String, String) = {
  (s"bar_${arg._1}", s"bar_${arg._2}", s"bar_${arg._3}")
}

def buz(arg: (String, String, String)): (String, String, String) = {
  (s"buz_${arg._1}", s"buz_${arg._2}", s"buz_${arg._3}")
}

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

val newFunc = foo _ andThen bar andThen buz
newFunc("1", "2", "3")
</code>```

There are two functions, andThen and compose that do this. They are only defined on Function1, which you can create by passing tuples to your methods.

Title: Scala tuple function composition

Body:
Let's say we have a 3 functions with Tuple3 result:

def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}

And I can compose them like this:

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

But I want something like this:

val (x, y, z) = foo(bar(buz("1", "2", "3")))

How can I achieve this?

Body:
def foo(arg: (String, String, String)): (String, String, String) = {
  (s"foo_${arg._1}", s"foo_${arg._2}", s"foo_${arg._3}")
}

def bar(arg: (String, String, String)): (String, String, String) = {
  (s"bar_${arg._1}", s"bar_${arg._2}", s"bar_${arg._3}")
}

def buz(arg: (String, String, String)): (String, String, String) = {
  (s"buz_${arg._1}", s"buz_${arg._2}", s"buz_${arg._3}")
}

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

val newFunc = foo _ andThen bar andThen buz
newFunc("1", "2", "3")

There are two functions, andThen and compose that do this. They are only defined on Function1, which you can create by passing tuples to your methods.


问:
Select values from multiple dictionaries into list of objects with LINQ
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

```<code>var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}
</code>```

Anyone have a good idea how to solve this?

答:
You could first select the orders and then the occording rows like so.</p>

```<code>var orderFieldName = "OrderId";
var orders = listOfDictionaries.Select(dict => dict[orderFieldName]).Distinct();
var grouped = orders.Select(order => new Order
{
    OrderId = order,
    OrderRows = listOfDictionaries.Where(dict => dict[orderFieldName] == order)
        .Select(item => new OrderRow {OrderRowId = item["Row"]}).ToList()
});
</code>```

Body:
I want to select OrderId & Row from multiple dictionaries and create a list of Orders which contains a list of Rows.

The code I'm struggling with this far is:

var listOfDictionaries = new List<Dictionary<string, string>>();

var dict1 = new Dictionary<string, string>();
dict1.Add("OrderId", "12345");
dict1.Add("Row", "1");
listOfDictionaries.Add(dict1);

var dict2 = new Dictionary<string, string>();
dict2.Add("OrderId", "97845");
dict2.Add("Row", "10");
listOfDictionaries.Add(dict2);

var dict3 = new Dictionary<string, string>();
dict3.Add("OrderId", "12345");
dict3.Add("Row", "2");
listOfDictionaries.Add(dict3);

var grouped = listOfDictionaries.SelectMany(d =>
                 d.Where(kvp =>
                    kvp.Key.ToLower().Contains("orderid") || kvp.Key.ToLower().Contains("row")))
              .GroupBy(a => a.Key).ToList();

public class Order
{
    public Order()
    {
       OrderRows = new List<OrderRow>();
    }

    public string OrderId { get; set; }
    public List<OrderRow> OrderRows { get; set; }
}

public class OrderRow
{
    public string OrderRowId { get; set; }
}

Anyone have a good idea how to solve this?

Body:
You could first select the orders and then the occording rows like so.

var orderFieldName = "OrderId";
var orders = listOfDictionaries.Select(dict => dict[orderFieldName]).Distinct();
var grouped = orders.Select(order => new Order
{
    OrderId = order,
    OrderRows = listOfDictionaries.Where(dict => dict[orderFieldName] == order)
        .Select(item => new OrderRow {OrderRowId = item["Row"]}).ToList()
});


问:
Method local inner class hides method fields
Given the following class definition

```<code>public class MethodLocalAccess {

    int m = 10;

    String show(){
        final int m = 20;
        final int n = 30;
        class MyClass{
            int m = 40;
            String someOtherMethod(){
                return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
            }
        }

        MyClass object = new MyClass();
        return object.someOtherMethod();
    }

    public static void main(String[] args) {
        System.out.println(new MethodLocalAccess().show());
    }

}
</code>```

Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.

Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.

答:
In your case I don't think you can access the local variable m defined in the show method since you already have it declared in your inner class, therefore shadowing it.

Using constructs like ClassName.this.varName allows you to access only the members of that enclosing class. This means you can't use that type of expression to access shadowed local varibles defined in the method since they aren't members of that class.

Body:
Given the following class definition

public class MethodLocalAccess {

    int m = 10;

    String show(){
        final int m = 20;
        final int n = 30;
        class MyClass{
            int m = 40;
            String someOtherMethod(){
                return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
            }
        }

        MyClass object = new MyClass();
        return object.someOtherMethod();
    }

    public static void main(String[] args) {
        System.out.println(new MethodLocalAccess().show());
    }

}

Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.

Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.


问:
Fetching first records of sets matching a where condition in Rails
I want to create a method for my Activity model that has many Practices called month_days_not_practiced which gives a count of the days in the current month that the Activity does not have any practices recorded for (note: days_in_month is a helper method):

```<code>  def month_days_not_practiced(date = Date.today)
    p = practices.where(:created_at => date.at_beginning_of_month..date.at_end_of_month).count
    days_in_month - p
  end
</code>```

However, I want to return only one record per month day.

Can someone help me with my custom SQL (I think) please? I'm drawing a blank at the moment..

TIA!

Andy

答:
Put this on the end of your query:</p>

```<code>.group("DATE(created_at)")
</code>```

Body:
I want to create a method for my Activity model that has many Practices called month_days_not_practiced which gives a count of the days in the current month that the Activity does not have any practices recorded for (note: days_in_month is a helper method):

  def month_days_not_practiced(date = Date.today)
    p = practices.where(:created_at => date.at_beginning_of_month..date.at_end_of_month).count
    days_in_month - p
  end

However, I want to return only one record per month day.

Can someone help me with my custom SQL (I think) please? I'm drawing a blank at the moment..

TIA!

Andy

Body:
Put this on the end of your query:

.group("DATE(created_at)")


问:
Spring-Batch without persisting metadata to database?
I want to create a spring-batch job, but I want to run it without any database persistence. Unfortunately spring-batch requires to write metadata ob the job cycles to a database somehow, thus procing me to provide at least some kind of db with transactionmanager and entitymanager.

It it possible to prevent the metadata and run independently from txmanagers and databases?

Update:

```<code>ERROR org.springframework.batch.core.job.AbstractJob: Encountered fatal error executing job
java.lang.NullPointerException
    at org.springframework.batch.core.repository.dao.MapJobExecutionDao.synchronizeStatus(MapJobExecutionDao.java:158) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.batch.core.repository.support.SimpleJobRepository.update(SimpleJobRepository.java:161) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy134.update(Unknown Source) ~[?:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy134.update(Unknown Source) ~[?:?]
    at org.springframework.batch.core.job.AbstractJob.updateStatus(AbstractJob.java:416) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:299) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy50.run(Unknown Source) [?:?]
</code>```

答:
If you don't want to store job's metadata in the database, configuration looks as follows

```<code>@Configuration
public class InMemoryJobRepositoryConfiguration {
@Bean
public ResourcelessTransactionManager transactionManager() {
    return new ResourcelessTransactionManager();
}

@Bean
public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager transactionManager)
        throws Exception {
    MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(transactionManager);
    factory.afterPropertiesSet();
    return factory;
}

@Bean
public JobRepository jobRepository(MapJobRepositoryFactoryBean repositoryFactory) throws Exception {
    return repositoryFactory.getObject();
}

@Bean
public JobExplorer jobExplorer(MapJobRepositoryFactoryBean repositoryFactory) {
    return new SimpleJobExplorer(repositoryFactory.getJobInstanceDao(), repositoryFactory.getJobExecutionDao(),
            repositoryFactory.getStepExecutionDao(), repositoryFactory.getExecutionContextDao());
}

@Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
    SimpleJobLauncher launcher = new SimpleJobLauncher();
    launcher.setJobRepository(jobRepository);
    return launcher;
}
}
</code>```

If job needs to read/write business data to the database and the datasource is configured as follows.

```<code>@Autowired
private DataSource dataSource;
</code>```

spring batch creates internal schema (BATCH_* tables and sequences) using that datasource. To prevent this from happening set flag spring.batch.initializer.enabled=false in application.properties.

Body:
I want to create a spring-batch job, but I want to run it without any database persistence. Unfortunately spring-batch requires to write metadata ob the job cycles to a database somehow, thus procing me to provide at least some kind of db with transactionmanager and entitymanager.

It it possible to prevent the metadata and run independently from txmanagers and databases?

Update:

ERROR org.springframework.batch.core.job.AbstractJob: Encountered fatal error executing job
java.lang.NullPointerException
    at org.springframework.batch.core.repository.dao.MapJobExecutionDao.synchronizeStatus(MapJobExecutionDao.java:158) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.batch.core.repository.support.SimpleJobRepository.update(SimpleJobRepository.java:161) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) ~[spring-tx-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy134.update(Unknown Source) ~[?:?]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) ~[spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy134.update(Unknown Source) ~[?:?]
    at org.springframework.batch.core.job.AbstractJob.updateStatus(AbstractJob.java:416) ~[spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:299) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50) [spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.7.0_51]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[?:1.7.0_51]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.7.0_51]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[?:1.7.0_51]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.batch.core.configuration.annotation.SimpleBatchConfiguration$PassthruAdvice.invoke(SimpleBatchConfiguration.java:127) [spring-batch-core-3.0.1.RELEASE.jar:3.0.1.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207) [spring-aop-4.0.6.RELEASE.jar:4.0.6.RELEASE]
    at com.sun.proxy.$Proxy50.run(Unknown Source) [?:?]

Body:
If you don't want to store job's metadata in the database, configuration looks as follows

@Configuration
public class InMemoryJobRepositoryConfiguration {
@Bean
public ResourcelessTransactionManager transactionManager() {
    return new ResourcelessTransactionManager();
}

@Bean
public MapJobRepositoryFactoryBean mapJobRepositoryFactory(ResourcelessTransactionManager transactionManager)
        throws Exception {
    MapJobRepositoryFactoryBean factory = new MapJobRepositoryFactoryBean(transactionManager);
    factory.afterPropertiesSet();
    return factory;
}

@Bean
public JobRepository jobRepository(MapJobRepositoryFactoryBean repositoryFactory) throws Exception {
    return repositoryFactory.getObject();
}

@Bean
public JobExplorer jobExplorer(MapJobRepositoryFactoryBean repositoryFactory) {
    return new SimpleJobExplorer(repositoryFactory.getJobInstanceDao(), repositoryFactory.getJobExecutionDao(),
            repositoryFactory.getStepExecutionDao(), repositoryFactory.getExecutionContextDao());
}

@Bean
public SimpleJobLauncher jobLauncher(JobRepository jobRepository) {
    SimpleJobLauncher launcher = new SimpleJobLauncher();
    launcher.setJobRepository(jobRepository);
    return launcher;
}
}

If job needs to read/write business data to the database and the datasource is configured as follows.

@Autowired
private DataSource dataSource;

spring batch creates internal schema (BATCH_* tables and sequences) using that datasource. To prevent this from happening set flag spring.batch.initializer.enabled=false in application.properties.


问:
How to get value width from input field using jQuery?
In this example i want to show an alert when input value width or cursor cross the input width. How to get value width from input field but not value length using jQuery?

$('.value_width').text($('.input').val().length); //this is just length of value but not value width
$('.input_width').text($('.input').width());

$('.input').keyup(function(){
    $('.value_width').text($(this).val().length); //this is just length of value but not value width
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" name="" value="Example Text" />
<p/>
Value width : <span class="value_width"></span>
<br/>
Input width : <span class="input_width"></span></code>```

答:
You can check like this

$('.value_width').text($('.input').val().length);
$('.input_width').text($('.input').width());

$('.input').keyup(function(){
    $('.value_width').text($(this).val().length);
     if(22<=$(this).val().length){
      alert('length filled');
     }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" name="" value="Example Text" />
<p/>
Value width : <span class="value_width"></span>
<br/>
Input width : <span class="input_width"></span></code>```

Body:
In this example i want to show an alert when input value width or cursor cross the input width. How to get value width from input field but not value length using jQuery?

$('.value_width').text($('.input').val().length); //this is just length of value but not value width
$('.input_width').text($('.input').width());

$('.input').keyup(function(){
    $('.value_width').text($(this).val().length); //this is just length of value but not value width
});

<input type="text" class="input" name="" value="Example Text" />

Value width :

Input width :

Body:
You can check like this

$('.value_width').text($('.input').val().length);
$('.input_width').text($('.input').width());

$('.input').keyup(function(){
    $('.value_width').text($(this).val().length);
     if(22<=$(this).val().length){
      alert('length filled');
     }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="input" name="" value="Example Text" />
<p/>
Value width : <span class="value_width"></span>
<br/>
Input width : <span class="input_width"></span>


问:
Can't maximize chrome window using Selenium
I've tried to maximize the window onPreapre by the command below:

```<code>browser.driver.manage().window().maximize();
</code>```

But it doesn't maxmize the window and there's no error on selenium webdriver logs, actually it seems like the execute has been succeed -

```<code>Starting ChromeDriver 2.26.436421 (6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6) on port 5814
Only local connections are allowed.
17:14:28.898 INFO - Done: [new session: Capabilities [{count=1, browserName=chrome, chromeOptions={args=[--no-sandbox, --test-type, --memory-metrics, --console, --crash-on-failure], prefs={download={directory_upgrade=true, default_directory=./Users/Idan/automation/tests/downloaded/, prompt_for_download=false}}}}]]
17:14:28.909 INFO - Executing: [set script timeout: 90000])
17:14:28.910 INFO - Done: [set script timeout: 90000]
17:14:28.969 INFO - Executing: [maximise window])
17:14:29.236 INFO - Done: [maximise window]
17:14:29.244 INFO - Executing: [maximise window])
17:14:29.250 INFO - Done: [maximise window]
</code>```

答:
The best way to maximize a chrome app is through JavaScript. Try this:

```<code>//Maximizing Chrome App Window.
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("window.resizeTo(1366, 768);");
</code>```

Change the parameters 1366, 768 according to your monitor settings/setup.

Body:
I've tried to maximize the window onPreapre by the command below:

browser.driver.manage().window().maximize();

But it doesn't maxmize the window and there's no error on selenium webdriver logs, actually it seems like the execute has been succeed -

Starting ChromeDriver 2.26.436421 (6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6) on port 5814
Only local connections are allowed.
17:14:28.898 INFO - Done: [new session: Capabilities [{count=1, browserName=chrome, chromeOptions={args=[--no-sandbox, --test-type, --memory-metrics, --console, --crash-on-failure], prefs={download={directory_upgrade=true, default_directory=./Users/Idan/automation/tests/downloaded/, prompt_for_download=false}}}}]]
17:14:28.909 INFO - Executing: [set script timeout: 90000])
17:14:28.910 INFO - Done: [set script timeout: 90000]
17:14:28.969 INFO - Executing: [maximise window])
17:14:29.236 INFO - Done: [maximise window]
17:14:29.244 INFO - Executing: [maximise window])
17:14:29.250 INFO - Done: [maximise window]

Body:
The best way to maximize a chrome app is through JavaScript. Try this:

//Maximizing Chrome App Window.
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("window.resizeTo(1366, 768);");

Change the parameters 1366, 768 according to your monitor settings/setup.


问:
How to edit row of cell?
I can not turn on editing mode in the first row of the cell. I tried this code but it didn't help.

```<code>   public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            if indexPath.row == 1{
                return true
            }
            return false
        }
</code>```

Can someone help me?

答:
If you want to edit first row then replace

```<code>if indexPath.row == 1
</code>```

with

```<code>if indexPath.row == 0
</code>```

Because indexPath.row starts from 0 not from 1.

Hope that will help.

EDIT:

Since you didn't show your complete code I am adding example code here.

check below code:

```<code>import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tbl: UITableView!

    let arr = ["1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tbl.dataSource = self
        tbl.delegate = self
    }

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

        cell.textLabel?.text = self.arr[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

        //set 0 for first cell
        if indexPath.row == 0 {
            return true
        }
        return false
    }

    //Need this method for delete cell
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == UITableViewCellEditingStyle.delete {
            tbl.reloadData()
        }
    }
}
</code>```

Title: How to edit row of cell?

Body:
I can not turn on editing mode in the first row of the cell. I tried this code but it didn't help.

   public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            if indexPath.row == 1{
                return true
            }
            return false
        }

Can someone help me?

Body:
If you want to edit first row then replace

if indexPath.row == 1

with

if indexPath.row == 0

Because indexPath.row starts from 0 not from 1.

Hope that will help.

EDIT:

Since you didn't show your complete code I am adding example code here.

check below code:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tbl: UITableView!

    let arr = ["1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tbl.dataSource = self
        tbl.delegate = self
    }

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

        cell.textLabel?.text = self.arr[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

        //set 0 for first cell
        if indexPath.row == 0 {
            return true
        }
        return false
    }

    //Need this method for delete cell
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if editingStyle == UITableViewCellEditingStyle.delete {
            tbl.reloadData()
        }
    }
}


问:
Prevent universal links from opening in `WKWebView`/`UIWebView`
When user tap on a universal link in WKWebView, the corresponding app will be opened (if installed).

This is described in Apple Search Programming Guide

If you instantiate a SFSafariViewController, WKWebView, or UIWebView object to handle a universal link, iOS opens your website in Safari instead of opening your app. However, if the user taps a universal link from within an embedded SFSafariViewController, WKWebView, or UIWebView object, iOS opens your app.

In my app, I have a WKWebView, but I don't want the user to go out of my app. I want to handle the link within my WKWebView.

How do I prevent universal link from opening? Or can I know if a URL could be handle by other apps?

答:
sourcecode for WebKit:

static const WKNavigationActionPolicy WK_API_AVAILABLE(macosx(10.11), ios(9.0)) _WKNavigationActionPolicyAllowWithoutTryingAppLink = (WKNavigationActionPolicy)(WKNavigationActionPolicyAllow + 2);

if you are using WKWebView, just use WKNavigationActionPolicyAllow + 2 instead of WKNavigationActionPolicyAllow


问:
Extract a function name inside a macro
In C, we often have to run such code

```<code>if (! somefun(x, y, z)) {
    perror("somefun")
}
</code>```

Is it possible to create a macro which, used as follows:

```<code>#define chkerr ...
chkerr(somefun(x, y, z));
</code>```

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

```<code>chkerr(somefun, x, y, z)
</code>```

答:
C11 6.4.2.2 Predefined identifiers

The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

```<code>static const char __func__[] = "function-name";
</code>```

appeared, where function-name is the name of the lexically-enclosing function.

You can used it this way:

```<code>#define chkErr(exp)  do { if (!(exp)) perror(__func__); } while (0)

chkerr(somefun(x, y, z));
</code>```

Unfortunately, this would produce an error message with the name of the calling function, not somefun.  Here is a simple variant that should work and even produce more informative error messages:

```<code>#define chkErr(exp)  do { if (!(exp)) perror(#exp); } while (0)

chkerr(somefun(x, y, z));
</code>```

In case somefun(x, y, z) returns a non zero value, the error message will contain the string "somefun(x, y, z)".

You can combine both techniques to give both the offending call and the location:

```<code>#include <errno.h>
#include <stdio.h>
#include <string.h>

#define chkErr(exp)  \
    do { if (!(exp)) \
        fprintf(stderr, "%s:%d: in function %s, %s failed: %s\n",\
                __FILE__, __LINE__, __func__, #exp, strerror(errno)); \
    } while (0)

chkerr(somefun(x, y, z));
</code>```

This assumes somefun() returns 0 or NULL in case of error and set errno accordingly. Note however that most system calls return non zero in case of error.

Title: Extract a function name inside a macro

Body:
In C, we often have to run such code

if (! somefun(x, y, z)) {
    perror("somefun")
}

Is it possible to create a macro which, used as follows:

#define chkerr ...
chkerr(somefun(x, y, z));

would compile to the above?

I already know I can use __VA_ARGS__ macro, but this would require me to call it like

chkerr(somefun, x, y, z)

Body:
C11 6.4.2.2 Predefined identifiers

The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function.

You can used it this way:

#define chkErr(exp)  do { if (!(exp)) perror(__func__); } while (0)

chkerr(somefun(x, y, z));

Unfortunately, this would produce an error message with the name of the calling function, not somefun.  Here is a simple variant that should work and even produce more informative error messages:

#define chkErr(exp)  do { if (!(exp)) perror(#exp); } while (0)

chkerr(somefun(x, y, z));

In case somefun(x, y, z) returns a non zero value, the error message will contain the string "somefun(x, y, z)".

You can combine both techniques to give both the offending call and the location:

#include <errno.h>
#include <stdio.h>
#include <string.h>

#define chkErr(exp)  \
    do { if (!(exp)) \
        fprintf(stderr, "%s:%d: in function %s, %s failed: %s\n",\
                __FILE__, __LINE__, __func__, #exp, strerror(errno)); \
    } while (0)

chkerr(somefun(x, y, z));

This assumes somefun() returns 0 or NULL in case of error and set errno accordingly. Note however that most system calls return non zero in case of error.


问:
AuthorizeAttribute adal signout MVC
I have created a custom Authorize attribute based on AAD groups in MVC. If I return false in the attribute the applications goes into an infinite loop on the login page. How do you signoff the user from an custom authorize attribute when using adal in an MVC application?</p>

答:
When the user is authenticated but does not have the role(false returned in custom attribute) the authorize attribute will change the response to 401. It is only when the user is authenticated and have the role (true returned in custom attribute) that the authorize attribute won’t change the response.

If you are using FormsAuthentication or the OWIN Cookie Authentication Middleware and the user is already logged in , he will be redirected to the login page again, which is kind of weird if you thing about it. "I've already logged in, and now I'm back do the log in page just because I clicked some link, and no one told me why this just happened."

AuthorizeAttribute provides a protected virtual method named HandleUnauthorizedRequest that you can override, checking whether user is authenticated and show an erro page . For example :

```<code>protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }
</code>```

You could also  redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

```<code>protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        {
                            controller = "Error",
                            action = "Unauthorised"
                        })
                );
}
</code>```

Please read here for more details .

Title: AuthorizeAttribute adal signout MVC

Body:
When the user is authenticated but does not have the role(false returned in custom attribute) the authorize attribute will change the response to 401. It is only when the user is authenticated and have the role (true returned in custom attribute) that the authorize attribute won’t change the response.

If you are using FormsAuthentication or the OWIN Cookie Authentication Middleware and the user is already logged in , he will be redirected to the login page again, which is kind of weird if you thing about it. "I've already logged in, and now I'm back do the log in page just because I clicked some link, and no one told me why this just happened."

AuthorizeAttribute provides a protected virtual method named HandleUnauthorizedRequest that you can override, checking whether user is authenticated and show an erro page . For example :

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }
        }

You could also  redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        {
                            controller = "Error",
                            action = "Unauthorised"
                        })
                );
}

Please read here for more details .


问:
C# XAML MVVM Treeview control Data Binding
I can not display the item list.
What am I doing wrong?

XAML(View):

```<code><Grid.DataContext>
     <vm:MainViewModel />
</Grid.DataContext>

<Grid.Resources>
     <DataTemplate x:Key="Remedy">
       <TextBlock Text="{Binding Titulo}" />
     </DataTemplate>

     <HierarchicalDataTemplate x:Key="Laboratorio"
                              ItemTemplate="{StaticResource Remedy}"
                              ItemsSource="{Binding Items}">
         <TextBlock Text="{Binding Titulo}" />
     </HierarchicalDataTemplate>
     <HierarchicalDataTemplate x:Key="Root"
                               ItemTemplate="{StaticResource Laboratorio}"
                               ItemsSource="{Binding Items}">
         <TextBlock Text="{Binding Titulo}" />
     </HierarchicalDataTemplate>

</Grid.Resources>

<TreeView x:Name="dirR"
          ItemsSource="{Binding Path=Arbol}"
          ItemTemplate="{StaticResource Root}">
</TreeView>
</code>```

C# (ViewModel):

```<code>class MainViewModel:INotifyPropertyChanged
{
   private TreeItem _arbol = new TreeItem("Remedys");
   public TreeItem Arbol
   {
      set
      {
         _arbol = value;
         OnPropertyChanged("Arbol");
      }
         get { return _arbol; }
   }

   public MainViewModel()
   {
       //Populate Arbol
       ...
    }
}
</code>```

C# (Model):

```<code>public class TreeItem:INotifyPropertyChanged
{
    private String _titulo;
    private ObservableCollection<TreeItem> _items;
    public String Titulo
    {
        get { return _titulo; }
        set
        {
            _titulo = value;
            OnPropertyChanged("Titulo");
        }
    }
    public ObservableCollection<TreeItem> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            OnPropertyChanged("Items");
        }
    }
    public TreeItem(String __titulo)
    {
        Titulo = __titulo;
    }
</code>```

C# (MainWindow v1):

```<code>public MainWindow()
{
    InitializeComponent();

}
</code>```

C# (MainWindow v2) This version works ok but I do not like it because there is code dependency between View and Viewmodel

```<code>public MainWindow()
{
    InitializeComponent();

    MainViewModel vm = new MainViewModel();
    dirR.Items.Add(vm.Arbol);
}
</code>```

答:
Set DataContext in MainWindow code:

From XAML:

```<code><Window.DataContext>
  <vm:MainWindowViewModel/>
</Window.DataContext>
</code>```

From code:

```<code>public MainWindow()
{
   InitializeComponent();

  DataContext = new MainViewModel();
}
</code>```

Body:
I can not display the item list.
What am I doing wrong?

XAML(View):

<Grid.DataContext>
     <vm:MainViewModel />
</Grid.DataContext>

<Grid.Resources>
     <DataTemplate x:Key="Remedy">
       <TextBlock Text="{Binding Titulo}" />
     </DataTemplate>

     <HierarchicalDataTemplate x:Key="Laboratorio"
                              ItemTemplate="{StaticResource Remedy}"
                              ItemsSource="{Binding Items}">
         <TextBlock Text="{Binding Titulo}" />
     </HierarchicalDataTemplate>
     <HierarchicalDataTemplate x:Key="Root"
                               ItemTemplate="{StaticResource Laboratorio}"
                               ItemsSource="{Binding Items}">
         <TextBlock Text="{Binding Titulo}" />
     </HierarchicalDataTemplate>

</Grid.Resources>

<TreeView x:Name="dirR"
          ItemsSource="{Binding Path=Arbol}"
          ItemTemplate="{StaticResource Root}">
</TreeView>

C# (ViewModel):

class MainViewModel:INotifyPropertyChanged
{
   private TreeItem _arbol = new TreeItem("Remedys");
   public TreeItem Arbol
   {
      set
      {
         _arbol = value;
         OnPropertyChanged("Arbol");
      }
         get { return _arbol; }
   }

   public MainViewModel()
   {
       //Populate Arbol
       ...
    }
}

C# (Model):

public class TreeItem:INotifyPropertyChanged
{
    private String _titulo;
    private ObservableCollection<TreeItem> _items;
    public String Titulo
    {
        get { return _titulo; }
        set
        {
            _titulo = value;
            OnPropertyChanged("Titulo");
        }
    }
    public ObservableCollection<TreeItem> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            OnPropertyChanged("Items");
        }
    }
    public TreeItem(String __titulo)
    {
        Titulo = __titulo;
    }

C# (MainWindow v1):

public MainWindow()
{
    InitializeComponent();

}

C# (MainWindow v2) This version works ok but I do not like it because there is code dependency between View and Viewmodel

public MainWindow()
{
    InitializeComponent();

    MainViewModel vm = new MainViewModel();
    dirR.Items.Add(vm.Arbol);
}

Body:
Set DataContext in MainWindow code:

From XAML:

<Window.DataContext>
  <vm:MainWindowViewModel/>
</Window.DataContext>

From code:

public MainWindow()
{
   InitializeComponent();

  DataContext = new MainViewModel();
}


问:
Java Filter a List of Model by a Property and Return the Filter Out List
I have a list of Model class. It contains two field:

```<code>Class Model {
    String id;
    String type;
}
</code>```

I have a Map structure:
Map<String, List<Model>> each String represents a Name that maps to the List<Model>.

Now I want to check if the Name has a distinct List<Model>. The List will only consider distinct only if each Model has different type. If there is Modal A ("abc", "green"), and next if I see Modal B ("dbc", "green"), Modal C("drrt", "green"), then Modal B, Modal C are not distinctive and I want to store the Name and Modal B, Modal C, and returnMap<String, List<Modal>>, which represents the Name that with the list of non-distinctive List<Model>;

I thought about building a Map<String, Set<String>> structure, type as the key, and a Set<id> as value, when I iterate the List<Model>, I check if the Map contains the key I have seen, if it is, add the id toSet, if it add successfully, means it is non-distinctive, I will add them to the result Map<String, List<Modal>>.

But, is there another way, or a more elegant/simple/efficient way to do it, using Java library, or Lambda etc? Please help~~~

答:
How about

```<code>public class Main {

    public static void main(String[] args) {
        Map<String, List<Model>> map = Stream.of(
                new Model("1", "type1"),
                new Model("2", "type2"),
                new Model("3", "type2")
        )
                .collect(groupingBy(m -> "name"));

        Map<String, List<Model>> dupes = map.entrySet().stream()
                .flatMap(e -> e.getValue().stream()
                        .collect(groupingBy(Model::getType))
                        .entrySet().stream()
                        .filter(e1 -> e1.getValue().size() > 1)
                        .map(e1 -> new SimpleImmutableEntry<>(e.getKey(), e1.getValue())))
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(dupes);

    }

    private static class Model {
        private final String id;
        private final String type;

        public Model(String id, String type) {
            this.id = id;
            this.type = type;
        }

        public String getId() {
            return id;
        }

        public String getType() {
            return type;
        }

        @Override
        public String toString() {
            return "Model{" +
                    "id='" + id + '\'' +
                    ", type='" + type + '\'' +
                    '}';
        }
    }
}
</code>```

Prints {name=[Model{id='2', type='type2'}, Model{id='3', type='type2'}]}

Body:
I have a list of Model class. It contains two field:

Class Model {
    String id;
    String type;
}

I have a Map structure:
Map<String, List<Model>> each String represents a Name that maps to the List<Model>.

Now I want to check if the Name has a distinct List<Model>. The List will only consider distinct only if each Model has different type. If there is Modal A ("abc", "green"), and next if I see Modal B ("dbc", "green"), Modal C("drrt", "green"), then Modal B, Modal C are not distinctive and I want to store the Name and Modal B, Modal C, and returnMap<String, List<Modal>>, which represents the Name that with the list of non-distinctive List<Model>;

I thought about building a Map<String, Set<String>> structure, type as the key, and a Set<id> as value, when I iterate the List<Model>, I check if the Map contains the key I have seen, if it is, add the id toSet, if it add successfully, means it is non-distinctive, I will add them to the result Map<String, List<Modal>>.

But, is there another way, or a more elegant/simple/efficient way to do it, using Java library, or Lambda etc? Please help~~~

Body:
How about

public class Main {

    public static void main(String[] args) {
        Map<String, List<Model>> map = Stream.of(
                new Model("1", "type1"),
                new Model("2", "type2"),
                new Model("3", "type2")
        )
                .collect(groupingBy(m -> "name"));

        Map<String, List<Model>> dupes = map.entrySet().stream()
                .flatMap(e -> e.getValue().stream()
                        .collect(groupingBy(Model::getType))
                        .entrySet().stream()
                        .filter(e1 -> e1.getValue().size() > 1)
                        .map(e1 -> new SimpleImmutableEntry<>(e.getKey(), e1.getValue())))
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(dupes);

    }

    private static class Model {
        private final String id;
        private final String type;

        public Model(String id, String type) {
            this.id = id;
            this.type = type;
        }

        public String getId() {
            return id;
        }

        public String getType() {
            return type;
        }

        @Override
        public String toString() {
            return "Model{" +
                    "id='" + id + '\'' +
                    ", type='" + type + '\'' +
                    '}';
        }
    }
}

Prints {name=[Model{id='2', type='type2'}, Model{id='3', type='type2'}]}


问:
if else condition using sql query
I have problem to generate SQL query for below table.
Here is my table:

```<code>County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter
</code>```

I want to be result like this

```<code>County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter
</code>```

The Scenario is if Designation is Promoter, use both Display and Stock data.
If Designation is from Merchandiser, use data from Promoter for Stock data
How can i achieve this?

答:
```<code>Select a.Country, a.Store
, Stock = CASE WHEN a.Designation = "Merchendiser" THEN b.Stock ELSE a.Stock
, Display = CASE WHEN a.Designation = "Merchendiser" THEN b.Display ELSE a.Display
, a.Designation
FROM YourTable a LEFT JOIN YourTable b WHERE b.Designation = "Promoter"
</code>```

may do the trick. Unable to test at the moment.

Edit: I see that you havent stated which SQL you use (i.e. SQL server, MySQL, PostgreSQL etc., so depending on that this solution may not be able to run).

Title: if else condition using sql query

Body:
I have problem to generate SQL query for below table.
Here is my table:

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 1     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

I want to be result like this

County          | Store     | Stock | Display | Designation
--------------- | --------- | ----- | ------- | ------------
USA             | USD       | 2     | Yes     | Merchandiser
USA             | USD       | 2     | Yes     | Promoter

The Scenario is if Designation is Promoter, use both Display and Stock data.
If Designation is from Merchandiser, use data from Promoter for Stock data
How can i achieve this?

Body:
Select a.Country, a.Store
, Stock = CASE WHEN a.Designation = "Merchendiser" THEN b.Stock ELSE a.Stock
, Display = CASE WHEN a.Designation = "Merchendiser" THEN b.Display ELSE a.Display
, a.Designation
FROM YourTable a LEFT JOIN YourTable b WHERE b.Designation = "Promoter"

may do the trick. Unable to test at the moment.

Edit: I see that you havent stated which SQL you use (i.e. SQL server, MySQL, PostgreSQL etc., so depending on that this solution may not be able to run).


问:
Consuming BlockingCollection with multiple consumers
I have a program as follows

```<code> class Program
    {
        public static int TaskCount { get; set; }
        public static BlockingCollection<string> queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
        static void Main(string[] args)
        {
            TaskCount = 3;
            Task.Factory.StartNew(() => Producer());

            for (int i = 0; i < TaskCount; i++)
                Task.Factory.StartNew(() => Consumer());
            Console.ReadKey();
        }

        private static void Producer()
        {
            using (StreamWriter sw = File.AppendText(@"C:\pcadder.txt"))
            {
                for (int i = 0; i < 15; i++)
                {
                    queue.Add("Item: " + (i+1).ToString());
                    var message = string.Format("{2}.Item added: Item {0} at {1}", (i+1).ToString(), DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),i+1);
                    Console.WriteLine(message);
                    sw.WriteLine(message);

                }
                queue.CompleteAdding();
            }
        }
        private static void Consumer()
        {
            int count = 1;
            foreach (var item in queue.GetConsumingEnumerable())
            {
                var message = string.Format("{3}.Item taken: {0} at {1} by thread {2}.", item, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),
                        Thread.CurrentThread.ManagedThreadId,count);
                Console.WriteLine(message);

                using (StreamWriter sw = File.AppendText(@"C:\pctaker.txt"))
                    sw.WriteLine(message);
                count += 1;
            }
        }
    }
</code>```

The Output

```<code>1.Item added: Item 1 at 2017.07.06 09:58:49.784734
2.Item added: Item 2 at 2017.07.06 09:58:49.784734
3.Item added: Item 3 at 2017.07.06 09:58:49.784734
4.Item added: Item 4 at 2017.07.06 09:58:49.784734
5.Item added: Item 5 at 2017.07.06 09:58:49.784734
6.Item added: Item 6 at 2017.07.06 09:58:49.784734
7.Item added: Item 7 at 2017.07.06 09:58:49.784734
8.Item added: Item 8 at 2017.07.06 09:58:49.784734
9.Item added: Item 9 at 2017.07.06 09:58:49.784734
10.Item added: Item 10 at 2017.07.06 09:58:49.784734
11.Item added: Item 11 at 2017.07.06 09:58:49.784734
12.Item added: Item 12 at 2017.07.06 09:58:49.784734
13.Item added: Item 13 at 2017.07.06 09:58:49.784734
14.Item added: Item 14 at 2017.07.06 09:58:49.784734
15.Item added: Item 15 at 2017.07.06 09:58:49.784734

1.Item taken: Item: 3 at 2017.07.06 09:58:49.784734 by thread 7.
1.Item taken: Item: 2 at 2017.07.06 09:58:49.784734 by thread 4.
1.Item taken: Item: 1 at 2017.07.06 09:58:49.784734 by thread 5.
2.Item taken: Item: 5 at 2017.07.06 09:58:49.784734 by thread 4.
2.Item taken: Item: 4 at 2017.07.06 09:58:49.784734 by thread 7.
2.Item taken: Item: 6 at 2017.07.06 09:58:49.784734 by thread 5.
3.Item taken: Item: 7 at 2017.07.06 09:58:49.784734 by thread 4.
3.Item taken: Item: 8 at 2017.07.06 09:58:49.784734 by thread 7.
3.Item taken: Item: 9 at 2017.07.06 09:58:49.784734 by thread 5.
4.Item taken: Item: 11 at 2017.07.06 09:58:49.784734 by thread 7.
4.Item taken: Item: 12 at 2017.07.06 09:58:49.784734 by thread 5.
5.Item taken: Item: 13 at 2017.07.06 09:58:49.784734 by thread 7.
5.Item taken: Item: 14 at 2017.07.06 09:58:49.784734 by thread 5.
6.Item taken: Item: 15 at 2017.07.06 09:58:49.784734 by thread 7.
</code>```

After almost every running the program, I have one item missing in consumer logs.(Here, Item 10 is missing). I could't catch why this is happening.

How does not this item processed?

While using multiple tasks as consumer, is processing items in order (FIFO) being spoiled? If I want to keep/force processing in FIFO order inside the consumer method, should I avoid using multiple tasks? (Processing may include I/O,Networking operations)

答:
Here

```<code>using (StreamWriter sw = File.AppendText(@"C:\pctaker.txt"))
    sw.WriteLine(message);
</code>```

You rapidly write to the same file from multiple threads. It's not a good idea and this code actually throws an exception. It goes unnoticed in your code because you don't handle any exceptions and it happens in background thread so does not crash your application. That answers why you have missing items in your log. You can write to the same file like that for example:

```<code>// create it outside `Consumer` and make synchronized
using (var taker = TextWriter.Synchronized(File.AppendText(@"pctaker.txt"))) {
    TaskCount = 3;
    Task.Factory.StartNew(() => Producer());
    //Producer();
    for (int i = 0; i < TaskCount; i++)
        // pass to consumer
        Task.Factory.StartNew(() => Consumer(taker));
    Console.ReadKey();
}

private static void Consumer(TextWriter writer)
{
    int count = 1;
    foreach (var item in queue.GetConsumingEnumerable())
    {
        var message = string.Format("{3}.Item taken: {0} at {1} by thread {2}.", item, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),
                Thread.CurrentThread.ManagedThreadId, count);
        Console.WriteLine(message);
        writer.WriteLine(message);
        writer.Flush();
        count += 1;
    }
}
</code>```

Or just put a lock around writing to the file.

As for second question - consumers still pull items in FIFO order, but since you have multiple consumers - order of processing is of course not guaranteed, because all consumers process items in parallel. Consumer A pulls item 1, consumer B pulls item 2 at the same time. Consumer A takes 100ms to process item 1, consumer B takes 10ms to process item 2. In result - item 2 is processed (that is - written to your log) before item 1.

Body:
I have a program as follows

 class Program
    {
        public static int TaskCount { get; set; }
        public static BlockingCollection<string> queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
        static void Main(string[] args)
        {
            TaskCount = 3;
            Task.Factory.StartNew(() => Producer());

            for (int i = 0; i < TaskCount; i++)
                Task.Factory.StartNew(() => Consumer());
            Console.ReadKey();
        }

        private static void Producer()
        {
            using (StreamWriter sw = File.AppendText(@"C:\pcadder.txt"))
            {
                for (int i = 0; i < 15; i++)
                {
                    queue.Add("Item: " + (i+1).ToString());
                    var message = string.Format("{2}.Item added: Item {0} at {1}", (i+1).ToString(), DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),i+1);
                    Console.WriteLine(message);
                    sw.WriteLine(message);

                }
                queue.CompleteAdding();
            }
        }
        private static void Consumer()
        {
            int count = 1;
            foreach (var item in queue.GetConsumingEnumerable())
            {
                var message = string.Format("{3}.Item taken: {0} at {1} by thread {2}.", item, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),
                        Thread.CurrentThread.ManagedThreadId,count);
                Console.WriteLine(message);

                using (StreamWriter sw = File.AppendText(@"C:\pctaker.txt"))
                    sw.WriteLine(message);
                count += 1;
            }
        }
    }

The Output

1.Item added: Item 1 at 2017.07.06 09:58:49.784734
2.Item added: Item 2 at 2017.07.06 09:58:49.784734
3.Item added: Item 3 at 2017.07.06 09:58:49.784734
4.Item added: Item 4 at 2017.07.06 09:58:49.784734
5.Item added: Item 5 at 2017.07.06 09:58:49.784734
6.Item added: Item 6 at 2017.07.06 09:58:49.784734
7.Item added: Item 7 at 2017.07.06 09:58:49.784734
8.Item added: Item 8 at 2017.07.06 09:58:49.784734
9.Item added: Item 9 at 2017.07.06 09:58:49.784734
10.Item added: Item 10 at 2017.07.06 09:58:49.784734
11.Item added: Item 11 at 2017.07.06 09:58:49.784734
12.Item added: Item 12 at 2017.07.06 09:58:49.784734
13.Item added: Item 13 at 2017.07.06 09:58:49.784734
14.Item added: Item 14 at 2017.07.06 09:58:49.784734
15.Item added: Item 15 at 2017.07.06 09:58:49.784734

1.Item taken: Item: 3 at 2017.07.06 09:58:49.784734 by thread 7.
1.Item taken: Item: 2 at 2017.07.06 09:58:49.784734 by thread 4.
1.Item taken: Item: 1 at 2017.07.06 09:58:49.784734 by thread 5.
2.Item taken: Item: 5 at 2017.07.06 09:58:49.784734 by thread 4.
2.Item taken: Item: 4 at 2017.07.06 09:58:49.784734 by thread 7.
2.Item taken: Item: 6 at 2017.07.06 09:58:49.784734 by thread 5.
3.Item taken: Item: 7 at 2017.07.06 09:58:49.784734 by thread 4.
3.Item taken: Item: 8 at 2017.07.06 09:58:49.784734 by thread 7.
3.Item taken: Item: 9 at 2017.07.06 09:58:49.784734 by thread 5.
4.Item taken: Item: 11 at 2017.07.06 09:58:49.784734 by thread 7.
4.Item taken: Item: 12 at 2017.07.06 09:58:49.784734 by thread 5.
5.Item taken: Item: 13 at 2017.07.06 09:58:49.784734 by thread 7.
5.Item taken: Item: 14 at 2017.07.06 09:58:49.784734 by thread 5.
6.Item taken: Item: 15 at 2017.07.06 09:58:49.784734 by thread 7.

After almost every running the program, I have one item missing in consumer logs.(Here, Item 10 is missing). I could't catch why this is happening.

How does not this item processed?

While using multiple tasks as consumer, is processing items in order (FIFO) being spoiled? If I want to keep/force processing in FIFO order inside the consumer method, should I avoid using multiple tasks? (Processing may include I/O,Networking operations)

Body:
Here

using (StreamWriter sw = File.AppendText(@"C:\pctaker.txt"))
    sw.WriteLine(message);

You rapidly write to the same file from multiple threads. It's not a good idea and this code actually throws an exception. It goes unnoticed in your code because you don't handle any exceptions and it happens in background thread so does not crash your application. That answers why you have missing items in your log. You can write to the same file like that for example:

// create it outside `Consumer` and make synchronized
using (var taker = TextWriter.Synchronized(File.AppendText(@"pctaker.txt"))) {
    TaskCount = 3;
    Task.Factory.StartNew(() => Producer());
    //Producer();
    for (int i = 0; i < TaskCount; i++)
        // pass to consumer
        Task.Factory.StartNew(() => Consumer(taker));
    Console.ReadKey();
}

private static void Consumer(TextWriter writer)
{
    int count = 1;
    foreach (var item in queue.GetConsumingEnumerable())
    {
        var message = string.Format("{3}.Item taken: {0} at {1} by thread {2}.", item, DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss.ffffff"),
                Thread.CurrentThread.ManagedThreadId, count);
        Console.WriteLine(message);
        writer.WriteLine(message);
        writer.Flush();
        count += 1;
    }
}

Or just put a lock around writing to the file.

As for second question - consumers still pull items in FIFO order, but since you have multiple consumers - order of processing is of course not guaranteed, because all consumers process items in parallel. Consumer A pulls item 1, consumer B pulls item 2 at the same time. Consumer A takes 100ms to process item 1, consumer B takes 10ms to process item 2. In result - item 2 is processed (that is - written to your log) before item 1.


问:
Upload multiple images in one request
I want to upload more than one image in single service request. How can I do that. As of now I am able to upload single image like as

```<code> NSData *imageData = UIImageJPEGRepresentation(image, 90);

 NSString *boundary = @"---------------------------14737809831466499882746641449";

   NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

NSMutableData *postBody = [NSMutableData data];

// file
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"files\"; filename=\”%@\”\r\n”,@“imagename”]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
</code>```

Now I want to upload two images to server how can I do that.

答:
```<code>NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:@"IOS Testing" forKey:@"subject"];
[parameters setValue:@"Message" forKey:@"message"];
   for (NSString *param in parameters) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

NSMutableArray *multipleArray=[[NSMutableArray alloc] init];
[multipleArray addObject:[UIImage imageNamed:@"images.jpeg"]];
[multipleArray addObject:[UIImage imageNamed:@"pic3.png"]];
for (int i=0; i<multipleArray.count;i++ )
{
    NSData *imageData;
    imageData = UIImageJPEGRepresentation([multipleArray objectAtIndex:i], 1.0);
    if (imageData)
    {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"uploaded_file[]"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    else
    {
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:BASEURL]];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                           if ([httpResponse statusCode] == 200) {
                               NSLog(@"success");
                           }

}];
</code>```

<p>}</p>

Title: Upload multiple images in one request

Body:
I want to upload more than one image in single service request. How can I do that. As of now I am able to upload single image like as

 NSData *imageData = UIImageJPEGRepresentation(image, 90);

 NSString *boundary = @"---------------------------14737809831466499882746641449";

   NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

NSMutableData *postBody = [NSMutableData data];

// file
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"files\"; filename=\”%@\”\r\n”,@“imagename”]] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

Now I want to upload two images to server how can I do that.

Body:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"------VohpleBoundary4QuqLuM1cE5lMwCy";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

NSMutableData *body = [NSMutableData data];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setValue:@"IOS Testing" forKey:@"subject"];
[parameters setValue:@"Message" forKey:@"message"];
   for (NSString *param in parameters) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

NSMutableArray *multipleArray=[[NSMutableArray alloc] init];
[multipleArray addObject:[UIImage imageNamed:@"images.jpeg"]];
[multipleArray addObject:[UIImage imageNamed:@"pic3.png"]];
for (int i=0; i<multipleArray.count;i++ )
{
    NSData *imageData;
    imageData = UIImageJPEGRepresentation([multipleArray objectAtIndex:i], 1.0);
    if (imageData)
    {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"uploaded_file[]"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type:image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[NSData dataWithData:imageData]];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }
    else
    {
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setURL:[NSURL URLWithString:BASEURL]];
[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                           if ([httpResponse statusCode] == 200) {
                               NSLog(@"success");
                           }

}];

}