问:
convert array of array of objects into single array of objects in lodash
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

```<code>const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];
</code>```

I wanted as below intended result;

```<code>[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];
</code>```

I have tried reduce function to generate such intended result as below:

```<code>let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);
</code>```

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks

答:
Just use below Lodash function</p>

```<code>_.flattenDeep(temp1);
</code>```

Body:
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];

I wanted as below intended result;

[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];

I have tried reduce function to generate such intended result as below:

let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks

Body:
Just use below Lodash function

_.flattenDeep(temp1);


来源: stackexchange

问:
Autocomplete from 10 000 items in .NET
I've got an in memory collection of around 10K objects. I want to give users the ability to type part of the item name or description and display an autocomplete list. What is an efficient way to do it? I really need the fastest possible response time, users are very fast.

Thanks a lot,
Mary

答:
Typically you don't want to give the user every possible choice- for example, if the list of items is a set of names, typing the letter "E" and getting every name with an E in it in the dropdown would be neither efficient or quick-performing for the user.  Have you considered only suggesting a result when the user has typed 3 (or more) characters?

If the set of items is static, this would (potentially) allow you you pre-calculate the set of items for every unique 3- or 4-character set, and store them in a dictionary of lists, something like:

```<code>Dictionary<String, List<Item>> itemsByKey;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Autocomplete from 10 000 items in .NET

Body:
Typically you don't want to give the user every possible choice- for example, if the list of items is a set of names, typing the letter "E" and getting every name with an E in it in the dropdown would be neither efficient or quick-performing for the user.  Have you considered only suggesting a result when the user has typed 3 (or more) characters?

If the set of items is static, this would (potentially) allow you you pre-calculate the set of items for every unique 3- or 4-character set, and store them in a dictionary of lists, something like:

Dictionary<String, List<Item>> itemsByKey;


问:
FPDF Table cell wrap
I Created a table with FPDF and I want to wrap the word in the cells(table).
this is my code .

```<code>$w = array(7, 150, 40);
$pdf->Cell($w[0], 6, $count, 'LR');
$pdf->Cell($w[1], 6, $column_heading, 'LR');
$pdf->Cell($w[2], 6, $rekey, 'LR', 0, 'R');

$pdf->Ln();
$pdf->Cell(array_sum($w), 0, '', 'T');
$count++;
</code>```

This is out put of the code how can I break the text in cells.

答:
If you cannot use multicell, you could try shrinking the text until it fits in the cell by getting the string width.

example:

```<code>//loop the data
foreach($data as $item){
    $pdf->Cell(10, 5,$item[0],1,0);
    $pdf->Cell(60, 5,$item[1],1,0);

    //shrink font size until it fits the cell width
    while($pdf->getStringWidth($item[2]) > $cellWidth){// loop until the string width is smaller than cell width
        $pdf->SetFontSize($tempFontSize -= 0.1);
    }
    $pdf->Cell($cellWidth,5,$item[2],1,0);
    //reset font size to standard
    $tempFontSize = $fontSize;
    $pdf->SetFontSize($fontSize);

    $pdf->Cell(40,5,$item[3],1,1);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: FPDF Table cell wrap

Body:
I Created a table with FPDF and I want to wrap the word in the cells(table).
this is my code .

$w = array(7, 150, 40);
$pdf->Cell($w[0], 6, $count, 'LR');
$pdf->Cell($w[1], 6, $column_heading, 'LR');
$pdf->Cell($w[2], 6, $rekey, 'LR', 0, 'R');

$pdf->Ln();
$pdf->Cell(array_sum($w), 0, '', 'T');
$count++;

This is out put of the code how can I break the text in cells.

Body:
If you cannot use multicell, you could try shrinking the text until it fits in the cell by getting the string width.

example:

//loop the data
foreach($data as $item){
    $pdf->Cell(10, 5,$item[0],1,0);
    $pdf->Cell(60, 5,$item[1],1,0);

    //shrink font size until it fits the cell width
    while($pdf->getStringWidth($item[2]) > $cellWidth){// loop until the string width is smaller than cell width
        $pdf->SetFontSize($tempFontSize -= 0.1);
    }
    $pdf->Cell($cellWidth,5,$item[2],1,0);
    //reset font size to standard
    $tempFontSize = $fontSize;
    $pdf->SetFontSize($fontSize);

    $pdf->Cell(40,5,$item[3],1,1);
}


问:
ReyclerView isn't working
I'm trying to show list of my model on recyclerview. but for some reason it doesnt show anything. I'm getting my list items from FirebaseDatabase and save all the data on "videoList". Then i want to presents the data that i have received, but it doesnt show anything.

Please tell me what i'm doing wrong.

```<code>  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return 0;
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }
</code>```

答:
Your VideoViewAdapter should know how many items he should show, for that purposes you need to provide the size of your data variable, through getItemCount() method:

```<code>@Override
public int getItemCount() {
    return data.size();
}
</code>```

Title: ReyclerView isn't working

Body:
I'm trying to show list of my model on recyclerview. but for some reason it doesnt show anything. I'm getting my list items from FirebaseDatabase and save all the data on "videoList". Then i want to presents the data that i have received, but it doesnt show anything.

Please tell me what i'm doing wrong.

  public class MyPlayListFragment extends Fragment {
    private FirebaseDatabase refToVideos;
    private FirebaseUser currentUser;
    private ArrayList<Video> videosList;
    private VideoViewAdapter adapter;
    private RecyclerView rvVideos;

public MyPlayListFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_my_play_list, container, false);
    rvVideos = (RecyclerView)v.findViewById(R.id.rvVideos);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    videosList = new ArrayList<>();
    refToVideos = FirebaseDatabase.getInstance();
    currentUser = FirebaseAuth.getInstance().getCurrentUser();

    refToVideos.getReference(Params.VIDEOS).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                videosList.add(snapshot.getValue(Video.class));
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new VideoViewAdapter(getContext(),videosList);
    rvVideos.setLayoutManager(new LinearLayoutManager(getContext()));
    rvVideos.setAdapter(adapter);

}

public class VideoViewAdapter extends RecyclerView.Adapter<VideoViewHolder>{
  private LayoutInflater inflater;
  private Context context;
  private ArrayList<Video> data;

  public VideoViewAdapter( Context context, ArrayList<Video> data) {
      this.context = context;
      this.inflater = LayoutInflater.from(context);
      this.data = data;
  }

  @Override
  public VideoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
      View v = inflater.inflate(R.layout.video_item,parent,false);
      return new VideoViewHolder(v);
  }

  @Override
  public void onBindViewHolder(VideoViewHolder holder, int position) {
      Video video = data.get(position);
      holder.tvTitleVideo.setText(video.getVideoName());
      holder.tvLikes.setText(String.valueOf(video.getLikes()));
      holder.tvViews.setText(String.valueOf(video.getViews()));
      Uri uri = Uri.parse(video.getVideoURL());
      holder.videoViewUser.setVideoURI(uri);
      holder.videoViewUser.start();

  }

  @Override
  public int getItemCount() {
      return 0;
  }
}

public  class VideoViewHolder extends RecyclerView.ViewHolder{
    private TextView tvTitleVideo,tvLikes,tvViews;
    private VideoView videoViewUser;

    public VideoViewHolder(View itemView) {
        super(itemView);
        tvTitleVideo = (TextView) itemView.findViewById(R.id.videoTitle);
        tvLikes = (TextView)itemView.findViewById(R.id.tvLikes);
        tvViews = (TextView)itemView.findViewById(R.id.tvViews);
        videoViewUser = (VideoView)itemView.findViewById(R.id.videoViewUser);

      }
    }

 }

Body:
Your VideoViewAdapter should know how many items he should show, for that purposes you need to provide the size of your data variable, through getItemCount() method:

@Override
public int getItemCount() {
    return data.size();
}


问:
Is loop a good choice instead of what I have created?
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...</p>

```<code>// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});
</code>```

答:
You can group these ids in an array and loop over the array for applying similar operation.

Since inputTitleTag and  tytul do not share operation with others, there is no point in looping over them.

```<code>document.getElementById("resetTitleBtn").addEventListener("click", function(){
  var ids = ['titleTag', 'example', 'good'];
  document.getElementById('inputTitleTag').value = "";
  document.getElementById("tytul").style.color = "";
  ids.forEach(function(id){
      document.getElementById(id).innerHTML = "";
  });
});
</code>```

Body:
I am learning JS by my own and I have created first little script :). Script is counting the number of signs for the tag tittle of a webpage to be between 50 and 60 etc.... Below there is one button that resets all the data in the script and its working 100% but I have a question -  Can I use some kind of loop instead of that code that I have created? A loop that will be reseting all elements below. Thx for Your help :) and advice...

// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  document.getElementById('inputTitleTag').value = "";
  document.getElementById('titleTag').innerHTML = "";
  document.getElementById('example').innerHTML = "";
  document.getElementById("tytul").style.color = "";
  document.getElementById("good").innerHTML = "";
});

Body:
You can group these ids in an array and loop over the array for applying similar operation.

Since inputTitleTag and  tytul do not share operation with others, there is no point in looping over them.

document.getElementById("resetTitleBtn").addEventListener("click", function(){
  var ids = ['titleTag', 'example', 'good'];
  document.getElementById('inputTitleTag').value = "";
  document.getElementById("tytul").style.color = "";
  ids.forEach(function(id){
      document.getElementById(id).innerHTML = "";
  });
});


问:
How can I compare two floating point numbers in Bash?
I am trying hard to compare two floating point numbers within a Bash script. I have two variables, e.g.

```<code>let num1=3.17648e-22
let num2=1.5
</code>```

Now, I just want do a simple comparison of these two numbers:

```<code>st=`echo "$num1 < $num2" | bc`
if [ $st -eq 1]; then
  echo -e "$num1 < $num2"
else
  echo -e "$num1 >= $num2"
fi
</code>```

Unfortunately, I have some problems with the right treatment of the num1 which can be of the "e-format".

答:
Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.

```<code>if [[ $((10#${num1/.})) < $((10#${num2/.})) ]]; then
    ...
</code>```

This obviously requires you to be sure that both values have the same number of decimal places.

ContentLicense: CC BY-SA 4.0

Body:
I am trying hard to compare two floating point numbers within a Bash script. I have two variables, e.g.

let num1=3.17648e-22
let num2=1.5

Now, I just want do a simple comparison of these two numbers:

st=`echo "$num1 < $num2" | bc`
if [ $st -eq 1]; then
  echo -e "$num1 < $num2"
else
  echo -e "$num1 >= $num2"
fi

Unfortunately, I have some problems with the right treatment of the num1 which can be of the "e-format".

Body:
Of course, if you don't need really floating-point arithmetic, just arithmetic on e.g. dollar values where there are always exactly two decimal digits, you might just drop the dot (effectively multiplying by 100) and compare the resulting integers.

if [[ $((10#${num1/.})) < $((10#${num2/.})) ]]; then
    ...

This obviously requires you to be sure that both values have the same number of decimal places.


问:
Python import coding style
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

```<code>import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)
</code>```

I move all my imports into the function where they're actually used., like this:

```<code>def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)
</code>```

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

答: I believe this is a recommended approach in some cases/scenarios. For example in Google App Engine lazy-loading big modules is recommended since it will minimize the warm-up cost of instantiating new Python VMs/interpreters. Have a look at a Google Engineer's presentation describing this. However keep in mind this doesn't mean you should lazy-load all your modules.

OwnerDisplayName: TokenMacGuy

Title: Python import coding style

Body:
I've discovered a new pattern.  Is this pattern well known or what is the opinion about it?

Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of

import foo
from bar.baz import quux

def myFunction():
    foo.this.that(quux)

I move all my imports into the function where they're actually used., like this:

def myFunction():
    import foo
    from bar.baz import quux

    foo.this.that(quux)

This does a few things.  First, I rarely accidentally pollute my modules with the contents of other modules.  I could set the __all__ variable for the module, but then I'd have to update it as the module evolves, and that doesn't help the namespace pollution for code that actually lives in the module.

Second, I rarely end up with a litany of imports at the top of my modules, half or more of which I no longer need because I've refactored it.  Finally, I find this pattern MUCH easier to read, since every referenced name is right there in the function body.

OwnerDisplayName: fuentesjr

LastEditorDisplayName: fuentesjr


问:
Difference between throw and throws in finally
I am preparing for OCP exam and I'm using Enthuware.
I got this question, what is the result of compiling and running the following code?

```<code>try {
    throw new IOException();
} catch(IOException e) {
    throw e;
} finally {
    throw new RuntimeException();
}
</code>```

Obviously, the code does compile but it throws a RuntimeException and I totally understand why.
I'm just curious why the following code doesn't compile:

```<code>try {
    throw new IOException();
} catch(IOException e) {
    throw e;
} finally {
    test();
}
</code>```

Where test() function looks like:

```<code>static final void test() throws RuntimeException {
    throw new RuntimeException();
}
</code>```

Even though I declared test function as final because I thought that it might the compiler is aware of overriding ...

Could someone please explain it to me?

Sorry for bad English!

-- Edit:
Just wondering why down-vote?

Error message is compile error:

Unhandled exception type IOException

And the error message when I tried to compile it is:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
      Unhandled exception type IOException

答:
The first snippet compiles because the finally block runs before a value is returned or an exception thrown from the non-finally part of the method.  The fact that you're throwing a RuntimeException means that you won't be throwing the IOException that you otherwise would.  The compiler can work this out, and it therefore doesn't insist that you either declare or catch the IOException.

But the compiler only looks at one method at a time when it's performing this check.  So the second snippet fails to compile, because the compiler doesn't check whether test() will always throw the RuntimeException.  Instead, it assumes that test() might not throw the RuntimeException; and if that were to happen, the IOException would be thrown.  Therefore, the compiler insists that you either catch that IOException, or declare it in a throws clause.

Body:
I am preparing for OCP exam and I'm using Enthuware.
I got this question, what is the result of compiling and running the following code?

try {
    throw new IOException();
} catch(IOException e) {
    throw e;
} finally {
    throw new RuntimeException();
}

Obviously, the code does compile but it throws a RuntimeException and I totally understand why.
I'm just curious why the following code doesn't compile:

try {
    throw new IOException();
} catch(IOException e) {
    throw e;
} finally {
    test();
}

Where test() function looks like:

static final void test() throws RuntimeException {
    throw new RuntimeException();
}

Even though I declared test function as final because I thought that it might the compiler is aware of overriding ...

Could someone please explain it to me?

Sorry for bad English!

-- Edit:
Just wondering why down-vote?

Error message is compile error:

Unhandled exception type IOException

And the error message when I tried to compile it is:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
      Unhandled exception type IOException


答:
While I don't think in this case a loop is necassary, you could do something like this:</p>

```<code>// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  var tags = ['titleTag', 'example', 'good'];
  for(var i = 0; i < tags.length; i++){
    document.getElementById(tag).value = "";
  }
  document.getElementById('inputTitleTag').value = "";
  document.getElementById("tytul").style.color = "";
});
</code>```

Title: Is loop a good choice instead of what I have created?

Body:
While I don't think in this case a loop is necassary, you could do something like this:

// reset Title tag check
document.getElementById("resetTitleBtn").addEventListener("click", function(){
  var tags = ['titleTag', 'example', 'good'];
  for(var i = 0; i < tags.length; i++){
    document.getElementById(tag).value = "";
  }
  document.getElementById('inputTitleTag').value = "";
  document.getElementById("tytul").style.color = "";
});


问:
PowerShell Try/Catch and Retry
I have a fairly large powershell scripts with many (20+) functions which perform various actions.

Right now all of the code doesn't really have any error handling or retry functionality. If a particular task/function fails it just fails and continues on.

I would like to improve error handling and implement retries to make it more robust.

I was thinking something similar to this:

```<code>$tries = 0
while ($tries -lt 5) {
    try{

       # Do Something

       # No retries necessary
       $tries = 5;
    } catch {
       # Report the error
       # Other error handling
    }
 }
</code>```

The problem is that I have many many steps where I would need to do this.

I don't think it make sense to implement the above code 20 times. That seems really superfluous.

I was thinking about writing an "TryCatch" function with a single parameter that contains the actual function I want to call?

I'm not sure that's the right approach either though. Won't I end up with a script that reads something like:

```<code>TryCatch "Function1 Parameter1 Parameter2"
TryCatch "Function2 Parameter1 Parameter2"
TryCatch "Function3 Parameter1 Parameter2"
</code>```

Is there a better way to do this?

答:
Solution with passing a delegate into a function instead of script block:</p>

```<code>function Retry([Action]$action)
{
    $attempts=3
    $sleepInSeconds=5
    do
    {
        try
        {
            $action.Invoke();
            break;
        }
        catch [Exception]
        {
            Write-Host $_.Exception.Message
        }
        $attempts--
        if ($attempts -gt 0) { sleep $sleepInSeconds }
    } while ($attempts -gt 0)
}

function MyFunction($inputArg)
{
    Throw $inputArg
}

#Example of a call:
Retry({MyFunction "Oh no! It happend again!"})
</code>```

Title: PowerShell Try/Catch and Retry

Body:
I have a fairly large powershell scripts with many (20+) functions which perform various actions.

Right now all of the code doesn't really have any error handling or retry functionality. If a particular task/function fails it just fails and continues on.

I would like to improve error handling and implement retries to make it more robust.

I was thinking something similar to this:

$tries = 0
while ($tries -lt 5) {
    try{

       # Do Something

       # No retries necessary
       $tries = 5;
    } catch {
       # Report the error
       # Other error handling
    }
 }

The problem is that I have many many steps where I would need to do this.

I don't think it make sense to implement the above code 20 times. That seems really superfluous.

I was thinking about writing an "TryCatch" function with a single parameter that contains the actual function I want to call?

I'm not sure that's the right approach either though. Won't I end up with a script that reads something like:

TryCatch "Function1 Parameter1 Parameter2"
TryCatch "Function2 Parameter1 Parameter2"
TryCatch "Function3 Parameter1 Parameter2"

Is there a better way to do this?

Body:
Solution with passing a delegate into a function instead of script block:

function Retry([Action]$action)
{
    $attempts=3
    $sleepInSeconds=5
    do
    {
        try
        {
            $action.Invoke();
            break;
        }
        catch [Exception]
        {
            Write-Host $_.Exception.Message
        }
        $attempts--
        if ($attempts -gt 0) { sleep $sleepInSeconds }
    } while ($attempts -gt 0)
}

function MyFunction($inputArg)
{
    Throw $inputArg
}

#Example of a call:
Retry({MyFunction "Oh no! It happend again!"})


问:
DP6 - No UI on application start
I have upgraded my Android of Things OS on my RPi3 from DP4 to DP6 recently.   But since, when I launch my application from Android Studio, the UI does not display but I can still interact with it button click event.

I'm also using the official RPi 7" Touchscreen Display as my main screen.

Any idea where does the problem come from?

答: Ok I found where the problem was, it seems that DP6 on RPi3 with the 7" Official Touchscreen Display do not display UI from app that are launched on a portrait screen orientation.

Title: DP6 - No UI on application start


问:
Autofit columns inside JQGrid
I have a jqGrid with following config

shrinkToFit: true,

autowidth: true,

I have not set any width to any of the columns in grid.

If I set column width manually, on large screen it does not display properly.

I want the columnns to fit automatically inside the grid with no scrollbars.

Is there any other way to handle this?

答: You might have given scrollOffset: true.Set scrollOffset:0, Now your grid will display without scrollbars.

Title: Autofit columns inside JQGrid


问:
Tensorflow doesn't see GPU and uses CPU instead, how come?
I'm running a Python script using GPU-enabled Tensorflow. However, the program doesn't seem to recognize any GPU and starts using CPU straight away. What could be the cause of this?</p>

答:
Just want to add to the discussion that tensorflow may stop seeing a GPU due to CUDA initialization failure, in other words, tensorflow detects the GPU, but can't dispatch any op onto it, so it falls back to CPU. In this case, you should see an error in the log, like this

```<code>E tensorflow/stream_executor/cuda/cuda_driver.cc:481] failed call to cuInit: CUDA_ERROR_UNKNOWN
</code>```

The cause is likely to be the conflict between different processes using GPU simultaneously. When that is the case, the most reliable way I found to get tensorflow working is to restart the machine. In the worst case, reinstalling tensorflow and / or NVidia driver.

See also one more case when GPU suddenly stops working.

Body:
Just want to add to the discussion that tensorflow may stop seeing a GPU due to CUDA initialization failure, in other words, tensorflow detects the GPU, but can't dispatch any op onto it, so it falls back to CPU. In this case, you should see an error in the log, like this

E tensorflow/stream_executor/cuda/cuda_driver.cc:481] failed call to cuInit: CUDA_ERROR_UNKNOWN

The cause is likely to be the conflict between different processes using GPU simultaneously. When that is the case, the most reliable way I found to get tensorflow working is to restart the machine. In the worst case, reinstalling tensorflow and / or NVidia driver.

See also one more case when GPU suddenly stops working.


问:
Why the Suffix Array use less space than the Suffix Tree?

I'm researching about Suffix Array and Suffix Tree for my project.
In several papers such as :

"Suffix arrays: A new method for on-line string searches" by Manber and Myers - 1993.

"Simple Linear Work Suffix Array Construction" by Juha Karkkainen and Peter Sanders - 2003.

The author said that: "The advantage of the Suffix Array use less space than the Suffix Tree".

My question is "How can we know that ? Do we have any mathematical proof for that or we base on the practical experiments ?"

By observation, an array data structure seems to use less space than a tree data structure. But I want to know exactly why.

答:
Seems like the paper mentioned at below link (section 1.2.4) will give answer to your query:

http://web.cs.iastate.edu/~cs548/suffix.pdf


问:
NoResourceEntry-x REPL tree output
For some reason for the Xamarin Test app for which I am 100% sure that its elements have Ids, I can only see "NoResourceEntry".

Not sure what is the reason, but either it is related to Emulator, Target Framework or something else.

Did someone have this issue? And do you know what is causing it?
I am running the simple test and just trying to trigger the REPL tree command
Please refer to screenshots below:

REPL tree
DeviceConfiguration

答:
Whilst the original answer is valid, you can get the elements using the Text property.

e.g.  <Button x:Name="Button1" Text="My Button"

and then to retrieve the element: var result = app.Query(m => m.Marked("My Button"));

In your circumstance this a possible approach.

Title: NoResourceEntry-x REPL tree output


问:
How to extract some data from url using Python
I have an url as follows:

```<code>https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400
</code>```

What I need is to get the string after v2/, thus ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=

I use furl to extract the parameter value. I do it as follows:

```<code>furl(url).args['category'] // gives PASSENGER
</code>```

But here I do not have the name of the parameter.

How can I do that?

答:
If you don't need a generalized solution but for the url you have provided in question. Then you can do the following:</p>

```<code>url="https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400"
answer=url.split('/')[5]
</code>```

Body:
I have an url as follows:

https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400

What I need is to get the string after v2/, thus ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=

I use furl to extract the parameter value. I do it as follows:

furl(url).args['category'] // gives PASSENGER

But here I do not have the name of the parameter.

How can I do that?

Body:
If you don't need a generalized solution but for the url you have provided in question. Then you can do the following:

url="https://some_url/vivi/v2/ZUxOZmVrdzJqTURxV20wQ0RvRld6SytEQWNocThwMGVnbFJ4RDQrZzJMeGRBcnhPYnUzV1pRPT0=/BE?category=PASSENGER&make=30&model=124&regmonth=3&regdate=2015-03&body=443,4781&facelift=252&seats=4&bodyHeight=443&bodyLength=443&weight=-1&engine=1394&wheeldrive=196&transmission=400"
answer=url.split('/')[5]


问:
OpenVR (missing from build)
I set up a clean project and import steamVR from Asset Store:

I chose to Import All

In player Setting OpenVR doesn't even show up in my list of supported virtual reality. Instead it shows that it's "missing from build".

On the build I get an error :

```<code>DllNotFoundException: openvr_api
Valve.VR.OpenVR.GetInitToken () (at Assets/SteamVR/Plugins/openvr_api.cs:4195)
</code>```

Any ideas?

Thanks

EDIT : Add step of the import as requested.

答:
I not exactly know what happened, but I can give you some steps to check that:

make sure you installed Steam and then installed SteamVR

running SteamVR and sure this app works normally using your HMD like HTC Vive

check you Unity3D edition does support VR, and a latest one prefer.

I think the DllNotFoundException in your case caused by SteamVR installed incorrectly.

Title: OpenVR (missing from build)

Body:
I set up a clean project and import steamVR from Asset Store:

I chose to Import All

In player Setting OpenVR doesn't even show up in my list of supported virtual reality. Instead it shows that it's "missing from build".

On the build I get an error :

DllNotFoundException: openvr_api
Valve.VR.OpenVR.GetInitToken () (at Assets/SteamVR/Plugins/openvr_api.cs:4195)

Any ideas?

Thanks

EDIT : Add step of the import as requested.


问:
SQL Server 2008 Backup Compression Standard Edition
I'm trying to backup a database in SQL Server 2008 and have the database compressed using the new compression feature. However, when I run the following code, I get a weird error message:

```<code>Backup Database <Database> To Disk 'C:\Backup' With Compression
</code>```

I get this error message:

Backup Database With Compression is not supported on Standard Edition

Does this mean I have to upgrade to the full version or is there a way to enable compression in standard edition?

答: To confirm, from SQL Server 2012 onwards, all editions (except Express and Web) support backup compression: https://technet.microsoft.com/en-us/library/cc645993(v=sql.110).aspx</p>

OwnerDisplayName: GateKiller

Body:
I'm trying to backup a database in SQL Server 2008 and have the database compressed using the new compression feature. However, when I run the following code, I get a weird error message:

Backup Database <Database> To Disk 'C:\Backup' With Compression

I get this error message:

Backup Database With Compression is not supported on Standard Edition

Does this mean I have to upgrade to the full version or is there a way to enable compression in standard edition?

LastEditorDisplayName: Cade Roux


问:
org.w3c.dom.Node with Android version less than 2.2
getTextContent() is not a recognized function.  getNodeValue() works fine for strings, but anytime I try to parse a number using getNodeValue(), it returns null!

How can I parse a Long from XML using this class?

答:
You need to navigate down to the text node. For instance, with something like this:

```<code><val>10000</val>
</code>```

the parsed XML tree has an Element node for the  tag which, in turn, has a child Text node for the "10000". A typical idiom is

```<code>valNode.getFirstChild().getNodeValue()
</code>```

Body:
You need to navigate down to the text node. For instance, with something like this:

<val>10000</val>

the parsed XML tree has an Element node for the  tag which, in turn, has a child Text node for the "10000". A typical idiom is

valNode.getFirstChild().getNodeValue()


问:
Updating button events in Swift?
I am creating a Check List app and trying to update button event which is set images itself after clicked.

Here is my code:

```<code>protocol CustomeCellDelegate {
   func cell(cell: UITableViewCell, updateTheButton button: UIButton)
}

class Cells: UITableViewCell, UITextFieldDelegate {

@IBOutlet weak var checkBox: UIButton!
    var buttonPressed = true
@IBAction func checkBoxAction(_ sender: UIButton) {
    if buttonPressed {
        sender.setImage(UIImage(named: "checkBoxB"), for: UIControlState.normal)
        buttonPressed = false
    } else {
        sender.setImage(UIImage(named:""), for: UIControlState.normal)
        buttonPressed = true
    }
}
 @objc func recordButtonImage(_ button: UIButton) {
    cellDelegate?.cell(cell: self, updateTheButton: button)  // cell notify the button that touched.
}
override func awakeFromNib() {
    checkBox.addTarget(self, action: #selector(recordButtonImage(_:)), for: UIControlEvents.touchUpInside)
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, CustomeCellDelegate {

@IBOutlet weak var tableView: UITableView!

var myImages: [UIImage?]!

override func viewDidLoad() {
  super.viewDidLoad()
    self.tableView.delegate   = self
    self.tableView.dataSource = self
    myImages = Array(repeatElement(nil, count: 50))
    let nib = UINib(nibName: "Cells", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "Cells")
 }

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

internal func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "theCells") as? Cells
        cell?.theTextField.delegate = self
        cell?.cellDelegate = self
        cell?.checkBox.setImage(myImages[indexPath.row], for: UIControlState.normal)

    return cell!
}

// This function from protocol and it helps to update button images.
func cell(cell: UITableViewCell, updateTheButton button: UIButton) {
    print("Delegate method Update Button Images.")
    if let indexPath = tableView.indexPath(for: cell), let buttonImage = button.image(for: UIControlState.normal) {
        myImages[indexPath.row] = buttonImage
    }
}
</code>```

I would like to update both events of the button that set image after checked and unchecked. Therefore, my table view can dequeue Reusable Cell and have those events updated.

But the result is just one event of button which is checked updated but not the unchecked one. The checked button still repeats whatever I do to uncheck it.

答:
The best way to handle UIButton is using its own state.

You need to hold current state value in one array. So you can keep the state in cellForRow and other things. By default set all state to false.

In CellForRow, just put below code:

```<code>  YOUR_BUTTON.isSelected = aryState[indexPath.row] as! Bool
</code>```

Set image for your button

```<code>YOUR_BUTTON.setImage(UIImage(named: NORMAL_IMAGE), for: .normal)
YOUR_BUTTON.setImage(UIImage(named: SELECTED_IMAGE), for: .selected)
</code>```

Just change button state when it clicked:

```<code>@IBAction func checkBoxAction(_ sender: UIButton) {
    let button = sender
    button.isSelected = !button.isSelected
}
</code>```

Title: Updating button events in Swift?

Body:
I am creating a Check List app and trying to update button event which is set images itself after clicked.

Here is my code:

protocol CustomeCellDelegate {
   func cell(cell: UITableViewCell, updateTheButton button: UIButton)
}

class Cells: UITableViewCell, UITextFieldDelegate {

@IBOutlet weak var checkBox: UIButton!
    var buttonPressed = true
@IBAction func checkBoxAction(_ sender: UIButton) {
    if buttonPressed {
        sender.setImage(UIImage(named: "checkBoxB"), for: UIControlState.normal)
        buttonPressed = false
    } else {
        sender.setImage(UIImage(named:""), for: UIControlState.normal)
        buttonPressed = true
    }
}
 @objc func recordButtonImage(_ button: UIButton) {
    cellDelegate?.cell(cell: self, updateTheButton: button)  // cell notify the button that touched.
}
override func awakeFromNib() {
    checkBox.addTarget(self, action: #selector(recordButtonImage(_:)), for: UIControlEvents.touchUpInside)
    }
}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, CustomeCellDelegate {

@IBOutlet weak var tableView: UITableView!

var myImages: [UIImage?]!

override func viewDidLoad() {
  super.viewDidLoad()
    self.tableView.delegate   = self
    self.tableView.dataSource = self
    myImages = Array(repeatElement(nil, count: 50))
    let nib = UINib(nibName: "Cells", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "Cells")
 }

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

internal func tableView(_ tableView:UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "theCells") as? Cells
        cell?.theTextField.delegate = self
        cell?.cellDelegate = self
        cell?.checkBox.setImage(myImages[indexPath.row], for: UIControlState.normal)

    return cell!
}

// This function from protocol and it helps to update button images.
func cell(cell: UITableViewCell, updateTheButton button: UIButton) {
    print("Delegate method Update Button Images.")
    if let indexPath = tableView.indexPath(for: cell), let buttonImage = button.image(for: UIControlState.normal) {
        myImages[indexPath.row] = buttonImage
    }
}

I would like to update both events of the button that set image after checked and unchecked. Therefore, my table view can dequeue Reusable Cell and have those events updated.

But the result is just one event of button which is checked updated but not the unchecked one. The checked button still repeats whatever I do to uncheck it.

Body:
The best way to handle UIButton is using its own state.

You need to hold current state value in one array. So you can keep the state in cellForRow and other things. By default set all state to false.

In CellForRow, just put below code:

  YOUR_BUTTON.isSelected = aryState[indexPath.row] as! Bool

Set image for your button

YOUR_BUTTON.setImage(UIImage(named: NORMAL_IMAGE), for: .normal)
YOUR_BUTTON.setImage(UIImage(named: SELECTED_IMAGE), for: .selected)

Just change button state when it clicked:

@IBAction func checkBoxAction(_ sender: UIButton) {
    let button = sender
    button.isSelected = !button.isSelected
}


问:
Python - Use %s in value of config file
I use a config file (type .ini) to save my SQL queries, then i get  a query by its key. All work fine, until creating a query with parameters, example :

```<code>;the ini file

product_by_cat = select * from products where cat =%s
</code>```

I use :

```<code>config = configparser.ConfigParser()
args= ('cat1')
config.read(path_to_ini_file)
query= config.get(section_where_are_stored_thequeries,key_of_the_query)
complete_query= query%args
</code>```

I get the error :

TypeError: not all arguments converted during string formatting

So it try to format the string at retrieving the value from the ini file.
Any proposition of my problem.

答:
depending on the versions of ConfigParser (Python 2 or Python 3) you may need to double the % like this or it throws an error:

```<code>product_by_cat = select * from products where cat =%%s
</code>```

Although a better way would be to use the raw version of the config parser, so the % char isn't interpreted

```<code>config = configparser.RawConfigParser()
</code>```

Title: Python - Use %s in value of config file

Body:
I use a config file (type .ini) to save my SQL queries, then i get  a query by its key. All work fine, until creating a query with parameters, example :

;the ini file

product_by_cat = select * from products where cat =%s

I use :

config = configparser.ConfigParser()
args= ('cat1')
config.read(path_to_ini_file)
query= config.get(section_where_are_stored_thequeries,key_of_the_query)
complete_query= query%args

I get the error :

TypeError: not all arguments converted during string formatting

So it try to format the string at retrieving the value from the ini file.
Any proposition of my problem.

Body:
depending on the versions of ConfigParser (Python 2 or Python 3) you may need to double the % like this or it throws an error:

product_by_cat = select * from products where cat =%%s

Although a better way would be to use the raw version of the config parser, so the % char isn't interpreted

config = configparser.RawConfigParser()


问:
Applying CSS styles only to certain elements
I have an existing website with lots of old pages and forms laid out with tables which I am trying to gradually transition to CSS. I want to use the Twitter Bootstrap stylesheets - particularly the styles for forms - but only on sections of pages where I have explicitly requested them. For example, I might surround the whole form in a div like so:

```<code><div class="bootstrap">
 <!-- everything in here should have the Bootstrap CSS applied -->
 <form>
   <p><label for="text_input">Label</label><input type="text" id="text_input" /></p>
 </form>
</div>
</code>```

I want all other forms to remain the same as they are now, because I won't be able to change them all at the same time. Is there a simple way to do this? I could go through every single style in the Bootstrap CSS and add a parent selector (e.g. 'p' would become 'div.bootstrap p'), but that would take a long time and it would be easy to miss styles.

Edit: If such a thing isn't possible, is there a free tool which can extract all the styles from a file, add a prefix and then save them back again?

答:
I have an easy solution.

Copy bootstrap css content to this (http://css2sass.herokuapp.com/) online css to scss/sass converter.

Add your tag information (e.g. div.bootstrap{ ) to the start of scss content and close the tag at the end.

Copy the whole scss content to this scss to css converter (https://www.sassmeister.com/) and convert it :)

Body:
I have an existing website with lots of old pages and forms laid out with tables which I am trying to gradually transition to CSS. I want to use the Twitter Bootstrap stylesheets - particularly the styles for forms - but only on sections of pages where I have explicitly requested them. For example, I might surround the whole form in a div like so:

 <form>

Label<input type="text" id="text_input" />

 </form>

I want all other forms to remain the same as they are now, because I won't be able to change them all at the same time. Is there a simple way to do this? I could go through every single style in the Bootstrap CSS and add a parent selector (e.g. 'p' would become 'div.bootstrap p'), but that would take a long time and it would be easy to miss styles.

Edit: If such a thing isn't possible, is there a free tool which can extract all the styles from a file, add a prefix and then save them back again?


问:
Detecting Simultaneous Button Presses and other Gestures, Shakes and Tilts - Cocos2d & iPhone
I am writing an app for the iPhone using cocos2d where I have 4 Sprites that are buttons. I want to allow and respond to the following (allowing the user 3 seconds to apply his input before timing out):

-- Single button presses (I have this part working).
-- Pressing of more than 1 button at at the same time (each combination would have a different response).
-- Flicking/Swiping gestures that originate from within each of the button Sprites.
-- Shaking the iPhone.
-- Tilting the iphone up, down, left, right (from landscape mode).

Any insight into different approaches would be greatly appreciated. B)

答:
Here is how I implemented this in case anyone else is trying to do this (I attempted to add the shakes/gestures/tilts part yet just the Simultaneous button presses and for now I have limited it to only 2-button combos -- but I could easily extend the logic to handle 3 and 4-button combos as well).

spuButton.h (a CCSprite Subclass)

```<code>#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState buttonState;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end
</code>```

spuButton.m

```<code>#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (buttonState== kButtonStateNotPressed) return NO;
    if (buttonState== kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (buttonState== kButtonStateNotPressed) return YES;
    if (buttonState== kButtonStatePressed) return NO;
    return YES;
}

- (void)makeDisabled {
    buttonStatus = kButtonStatusDisabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}
- (void)makeEnabled {
    buttonStatus = kButtonStatusEnabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (BOOL)isEnabled {
    if (buttonStatus== kButtonStatusDisabled) return NO;
    if (buttonStatus== kButtonStatusEnabled) return YES;
    return NO;
}

- (BOOL)isDisabled {
    if (buttonStatus== kButtonStatusEnabled) return NO;
    if (buttonStatus== kButtonStatusDisabled) return YES;
    return YES;
}

- (void)makeLit {
    [self setTexture:buttonLit];
}

- (void)makeNormal {
    [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
    if ((self = [super initWithTexture:aTexture]) ) {
        buttonState = kButtonStateNotPressed;
        buttonStatus = kButtonStatusEnabled;
    }
    return self;
}

- (void)onEnter {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    [super onEnter];
}

- (void)onExit {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return NO;
    if (buttonState== kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;

    buttonState= kButtonStatePressed;
    [self makeLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if (buttonStatus == kButtonStatusDisabled) return;
    if ([self containsTouchLocation:touch]) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)dealloc {
    [buttonNormal release];
    [buttonLit release];
    [super dealloc];
}

@end
</code>```

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

```<code>-(void)tick:(ccTime)dt {
    if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
        [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
        [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
        [self addChild:[_otherControlsArray objectAtIndex:1]];
        NSLog(@"Play");

        _gameHasNotBeenPlayedYet = NO;
        Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate makeNotPaused];
        [self gameLogic];
    }

    if (_gameHasNotBeenPlayedYet) {
        return;
    }

    if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
        NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
        if ([self checkButtons:_buttonsPressedAndReleased]);
        _buttonsPressed = 0;
        _buttonsPressedAndReleased = 0;

        return;
    }
    if (_buttonsPressed <= 4) { // two buttons have not already been pressed
        for (spuButton *aButton in _fourButtonsArray) {
            if ([aButton isNotPressed]) continue; //this button is not pressed
            if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
                _buttonsPressed = aButton.tag;
                continue;
            }
            //this button is pressed while another has been pressed
            //figure out which two buttons have been pressed
            if (_buttonsPressed == 1) {  //red plus another
                switch (aButton.tag) {
                    case 2:   //blue
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 1;
                        break;
                }
            }
            if (_buttonsPressed == 2) {  //blue plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 2;
                        break;
                }
            }
            if (_buttonsPressed == 3) {  //green plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 3;
                        break;
                }
            }
            if (_buttonsPressed == 4) {  //yellow plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 4;
                        break;
                }
            }
            if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
        }
    }
    //now we know what buttons have been pressed now check to see if they have been released
    //if more than one has been pressed disable the other two
    //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
    switch (_buttonsPressed) {
        case 1:  //red
            if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
            break;
        case 2:  //blue
            if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
            break;
        case 3:  //green
            if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
            break;
        case 4:  //yellow
            if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
            break;
        case 5:  //red & blue
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
            }
            break;
        case 6:  //red & green
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 7:  //red & yellow
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 8:  //blue & green
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 9:  //blue & yellow
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 10:  //green & yellow
            if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
            else {
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        default:
            _buttonsPressedAndReleased = 0;
            break;
    }
}
</code>```

Body:
Here is how I implemented this in case anyone else is trying to do this (I attempted to add the shakes/gestures/tilts part yet just the Simultaneous button presses and for now I have limited it to only 2-button combos -- but I could easily extend the logic to handle 3 and 4-button combos as well).

spuButton.h (a CCSprite Subclass)

#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState buttonState;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end

spuButton.m

#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (buttonState== kButtonStateNotPressed) return NO;
    if (buttonState== kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (buttonState== kButtonStateNotPressed) return YES;
    if (buttonState== kButtonStatePressed) return NO;
    return YES;
}

- (void)makeDisabled {
    buttonStatus = kButtonStatusDisabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}
- (void)makeEnabled {
    buttonStatus = kButtonStatusEnabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (BOOL)isEnabled {
    if (buttonStatus== kButtonStatusDisabled) return NO;
    if (buttonStatus== kButtonStatusEnabled) return YES;
    return NO;
}

- (BOOL)isDisabled {
    if (buttonStatus== kButtonStatusEnabled) return NO;
    if (buttonStatus== kButtonStatusDisabled) return YES;
    return YES;
}

- (void)makeLit {
    [self setTexture:buttonLit];
}

- (void)makeNormal {
    [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
    if ((self = [super initWithTexture:aTexture]) ) {
        buttonState = kButtonStateNotPressed;
        buttonStatus = kButtonStatusEnabled;
    }
    return self;
}

- (void)onEnter {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    [super onEnter];
}

- (void)onExit {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return NO;
    if (buttonState== kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;

    buttonState= kButtonStatePressed;
    [self makeLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if (buttonStatus == kButtonStatusDisabled) return;
    if ([self containsTouchLocation:touch]) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)dealloc {
    [buttonNormal release];
    [buttonLit release];
    [super dealloc];
}

@end

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

-(void)tick:(ccTime)dt {
    if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
        [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
        [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
        [self addChild:[_otherControlsArray objectAtIndex:1]];
        NSLog(@"Play");

        _gameHasNotBeenPlayedYet = NO;
        Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate makeNotPaused];
        [self gameLogic];
    }

    if (_gameHasNotBeenPlayedYet) {
        return;
    }

    if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
        NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
        if ([self checkButtons:_buttonsPressedAndReleased]);
        _buttonsPressed = 0;
        _buttonsPressedAndReleased = 0;

        return;
    }
    if (_buttonsPressed <= 4) { // two buttons have not already been pressed
        for (spuButton *aButton in _fourButtonsArray) {
            if ([aButton isNotPressed]) continue; //this button is not pressed
            if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
                _buttonsPressed = aButton.tag;
                continue;
            }
            //this button is pressed while another has been pressed
            //figure out which two buttons have been pressed
            if (_buttonsPressed == 1) {  //red plus another
                switch (aButton.tag) {
                    case 2:   //blue
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 1;
                        break;
                }
            }
            if (_buttonsPressed == 2) {  //blue plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 2;
                        break;
                }
            }
            if (_buttonsPressed == 3) {  //green plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 3;
                        break;
                }
            }
            if (_buttonsPressed == 4) {  //yellow plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 4;
                        break;
                }
            }
            if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
        }
    }
    //now we know what buttons have been pressed now check to see if they have been released
    //if more than one has been pressed disable the other two
    //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
    switch (_buttonsPressed) {
        case 1:  //red
            if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
            break;
        case 2:  //blue
            if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
            break;
        case 3:  //green
            if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
            break;
        case 4:  //yellow
            if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
            break;
        case 5:  //red & blue
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
            }
            break;
        case 6:  //red & green
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 7:  //red & yellow
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 8:  //blue & green
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 9:  //blue & yellow
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 10:  //green & yellow
            if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
            else {
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        default:
            _buttonsPressedAndReleased = 0;
            break;
    }
}


问:
Scanner doesn't read from file
I'm writing program, which will be read file, choose by user. I have code:

```<code>public class program extends javax.swing.JFrame {

private String textEncode;
...

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fch = new JFileChooser();
    int choose = fch.showOpenDialog(this);
    if(choose == JFileChooser.APPROVE_OPTION) {
        String help = fch.getSelectedFile().getPath();
        jTextField2.setText(help);
        try {
            Scanner in = new Scanner(new File(help));
            while(in.hasNextLine()) {
            textEncode = in.nextLine();
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
        }
    }
    jTextArea1.setText(textEncode);
    System.out.println(textEncode);
}
</code>```

My file has 1 line of text. When program end read file, variable textEncode has value "null". Where is problem?
I try with in.next() and in.hasNext(), but it doesn't work too.

答:
I had the same problem, and it took me a while to figure it out.

My problem was that my file contained french special characters like "é".
This caused the scanner to return "null" for scanner.nextLine() without causing any exception, no matter how long was the file, no matter where the special characters were placed.

To solve this, I just removed all the special characters. If anybody has a solution to make Scanner read the special characters, he's welcome to comment below.

Title: Scanner doesn't read from file

Body:
I'm writing program, which will be read file, choose by user. I have code:

public class program extends javax.swing.JFrame {

private String textEncode;
...

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fch = new JFileChooser();
    int choose = fch.showOpenDialog(this);
    if(choose == JFileChooser.APPROVE_OPTION) {
        String help = fch.getSelectedFile().getPath();
        jTextField2.setText(help);
        try {
            Scanner in = new Scanner(new File(help));
            while(in.hasNextLine()) {
            textEncode = in.nextLine();
            }
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "Nie znaleziono pliku", "Błąd wczytywania", JOptionPane.ERROR_MESSAGE);
        }
    }
    jTextArea1.setText(textEncode);
    System.out.println(textEncode);
}

My file has 1 line of text. When program end read file, variable textEncode has value "null". Where is problem?
I try with in.next() and in.hasNext(), but it doesn't work too.


答:
Use following code:</p>

```<code>l=url.split('/')
m=l[l.index('v2')+1]
print(m)
</code>```

Title: How to extract some data from url using Python

Body:
Use following code:

l=url.split('/')
m=l[l.index('v2')+1]
print(m)


问:
Format XMLGregorianCalendar in java
i have a date String which looks just like this.

2017-12-06T17:39:00Z

What i would like to do is to convert this String to XMLGregorianCalendar but using the same format.

What i do at the moment is:

```<code>String choosenDate = 2017-12-06T17:39:00Z;

GregorianCalendar c = new GregorianCalendar();

DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
TemporalAccessor accessor = timeFormatter.parse(dateChoisie);

Date date = Date.from(Instant.from(accessor));
c.setTime(date);
System.err.println("choosenDate: " + dateChoisie);
System.err.println("date : " + date);
XMLGregorianCalendar dateXMLGreg = null;
try
{
    dateXMLGreg = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    System.err.println("dateXMLGreg: " + dateXMLGreg);
}
catch (DatatypeConfigurationException e)
{
    messages.addMessage(new MessageBuilder().error().code("webservice.failure").build());
}
</code>```

which gives me the following output:

10:47:45,957 ERROR [stderr] (default task-47) choosenDate:
  2017-12-06T17:39:03Z

10:47:45,957 ERROR [stderr] (default task-47) date : Wed Dec 06
  18:39:03 CET 2017

10:47:45,958 ERROR [stderr] (default task-47) dateXMLGreg:
  2017-12-06T18:39:03.000+01:00

So how can i do so i have my XMLGregorianCalendar dateXMLGreg to look like:

2017-12-06T17:39:03Z

答:
This is easier than you think.

```<code>    String isoDateTime = "2017-12-06T17:39:00Z";
    XMLGregorianCalendar dateXMLGreg = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(isoDateTime);
    System.out.println(dateXMLGreg);
</code>```

This prints

```<code>2017-12-06T17:39:00Z
</code>```

newXMLGregorianCalendar has an overloaded version that accepts a string — your string — as argument. I trust you to add try/catch as in your question.

Edit: your XMLGregorianCalendar will have its milliseconds set to DatatypeConstants.FIELD_UNDEFINED. This needs to be so to avoid printing the milliseconds as part of the result from toString() (which gets implicitly called when you print the XMLGregorianCalendar).

One more edit: As Basil Bourque correctly said in a comment, depending on what you need your XMLGregorianCalendar for, you may use and even benefit from using a class from java.time, the modern Java date and time API, instead. For example:

```<code>    Instant dateInst = Instant.parse(isoDateTime);
    System.out.println(dateInst);
</code>```

This gives the exact same output as above, 2017-12-06T17:39:00Z. The Instant class will work only if the offset is always Z, which it probably is since this was what you asked to have back. The potential advantages of java.time include (1) the API is generally much nicer to work with (2) in case you need some further date-time operations, the modern API offers a wealth of them. If the offset may vary, you may experiment with OffsetDateTime, but this is a longer story that I will leave for some other question.

Title: Format XMLGregorianCalendar in java

Body:
i have a date String which looks just like this.

2017-12-06T17:39:00Z

What i would like to do is to convert this String to XMLGregorianCalendar but using the same format.

What i do at the moment is:

String choosenDate = 2017-12-06T17:39:00Z;

GregorianCalendar c = new GregorianCalendar();

DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_DATE_TIME;
TemporalAccessor accessor = timeFormatter.parse(dateChoisie);

Date date = Date.from(Instant.from(accessor));
c.setTime(date);
System.err.println("choosenDate: " + dateChoisie);
System.err.println("date : " + date);
XMLGregorianCalendar dateXMLGreg = null;
try
{
    dateXMLGreg = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    System.err.println("dateXMLGreg: " + dateXMLGreg);
}
catch (DatatypeConfigurationException e)
{
    messages.addMessage(new MessageBuilder().error().code("webservice.failure").build());
}

which gives me the following output:

10:47:45,957 ERROR [stderr] (default task-47) choosenDate:
  2017-12-06T17:39:03Z

10:47:45,957 ERROR [stderr] (default task-47) date : Wed Dec 06
  18:39:03 CET 2017

10:47:45,958 ERROR [stderr] (default task-47) dateXMLGreg:
  2017-12-06T18:39:03.000+01:00

So how can i do so i have my XMLGregorianCalendar dateXMLGreg to look like:

2017-12-06T17:39:03Z

Body:
This is easier than you think.

    String isoDateTime = "2017-12-06T17:39:00Z";
    XMLGregorianCalendar dateXMLGreg = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(isoDateTime);
    System.out.println(dateXMLGreg);

This prints

2017-12-06T17:39:00Z

newXMLGregorianCalendar has an overloaded version that accepts a string — your string — as argument. I trust you to add try/catch as in your question.

Edit: your XMLGregorianCalendar will have its milliseconds set to DatatypeConstants.FIELD_UNDEFINED. This needs to be so to avoid printing the milliseconds as part of the result from toString() (which gets implicitly called when you print the XMLGregorianCalendar).

One more edit: As Basil Bourque correctly said in a comment, depending on what you need your XMLGregorianCalendar for, you may use and even benefit from using a class from java.time, the modern Java date and time API, instead. For example:

    Instant dateInst = Instant.parse(isoDateTime);
    System.out.println(dateInst);

This gives the exact same output as above, 2017-12-06T17:39:00Z. The Instant class will work only if the offset is always Z, which it probably is since this was what you asked to have back. The potential advantages of java.time include (1) the API is generally much nicer to work with (2) in case you need some further date-time operations, the modern API offers a wealth of them. If the offset may vary, you may experiment with OffsetDateTime, but this is a longer story that I will leave for some other question.


问:
Cannot read SqlGeography with Dapper
I followed alot of SO questions and I am getting simillar error but I cannot fix this issue.

My Dapper version is 1.50.1
My Microsoft.SqlServer.Types version is 11.0.2

I have added binding redirect in configuration file as follows:

```<code><runtime>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
      <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.0.0" />
    </dependentAssembly>
</runtime>
</code>```

The error I get is:

Error parsing column 2 (Location=POINT (-122.349 47.651) - Object)

While the inner exception is:

[A]Microsoft.SqlServer.Types.SqlGeography cannot be cast to [B]Microsoft.SqlServer.Types.SqlGeography. Type A originates from 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' in the context 'Default' at location 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.SqlServer.Types\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Types.dll'. Type B originates from 'Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' in the context 'Default' at location 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.SqlServer.Types\11.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Types.dll'.

If I just do a read to dynamic object everything is all right but if I do read to my own type that has SqlGeography I get this error.

I thought I did all as recommended but it seems I missed something.

答:
@Marc Gravell did a good job about that see reference below and it will save your life.

SqlGeography

Issue

For ASP.NET applications, add the following line of code to the Application_Start method in Global.asax.cs:

```<code>SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));
</code>```

For desktop applications, add the following line of code to run before any spatial operations are performed:

```<code>SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);
</code>```

The .LoadNativeAssemblies method will get the correct assembly for you base on CPU architecture.

In bin folder you should have this.

Title: Cannot read SqlGeography with Dapper

Body:
I followed alot of SO questions and I am getting simillar error but I cannot fix this issue.

My Dapper version is 1.50.1
My Microsoft.SqlServer.Types version is 11.0.2

I have added binding redirect in configuration file as follows:

<runtime>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.SqlServer.Types" publicKeyToken="89845dcd8080cc91" culture="neutral" />
      <bindingRedirect oldVersion="10.0.0.0" newVersion="11.0.0.0" />
    </dependentAssembly>
</runtime>

The error I get is:

Error parsing column 2 (Location=POINT (-122.349 47.651) - Object)

While the inner exception is:

[A]Microsoft.SqlServer.Types.SqlGeography cannot be cast to [B]Microsoft.SqlServer.Types.SqlGeography. Type A originates from 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' in the context 'Default' at location 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.SqlServer.Types\10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Types.dll'. Type B originates from 'Microsoft.SqlServer.Types, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' in the context 'Default' at location 'C:\WINDOWS\assembly\GAC_MSIL\Microsoft.SqlServer.Types\11.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Types.dll'.

If I just do a read to dynamic object everything is all right but if I do read to my own type that has SqlGeography I get this error.

I thought I did all as recommended but it seems I missed something.

Body:
@Marc Gravell did a good job about that see reference below and it will save your life.

SqlGeography

Issue

For ASP.NET applications, add the following line of code to the Application_Start method in Global.asax.cs:

SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));

For desktop applications, add the following line of code to run before any spatial operations are performed:

SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

The .LoadNativeAssemblies method will get the correct assembly for you base on CPU architecture.

In bin folder you should have this.


问:
Autocomplete from 10 000 items in .NET
I've got an in memory collection of around 10K objects. I want to give users the ability to type part of the item name or description and display an autocomplete list. What is an efficient way to do it? I really need the fastest possible response time, users are very fast.

Thanks a lot,
Mary

答:
You can use the Trie data structure (or prefix tree) to hold the names of items. See this very detailed article on wikipedia that describes the principles of this data structres and provides some benchmark results.

Each node of the Trie can be implemented as a sorted list of characters corresponding to the N-th position in individual data strings, where N is the depth of the node. You can then use binary search to perform data lookups efficiently.

To make it work in your case, just keep the last node corresponding to the previously entered prefix. When the user types the next letter, just search for the corresponding immediate child.

Everything within the respective subtree is a possible match and hence can be offered to the user. To make the autocomplete smarter, you could keep track of frequencies of individual data items and display the most frequent ones only.

Title: Autocomplete from 10 000 items in .NET