问:
How to find if an array is strictly in an increasing order after omitting only one element
I have given the following problem where I am stuck right now. I am not having the perfect logic for this. Here is the problem below :

Given a sequence of integers as an array, determine whether it is
  possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example 1:

```<code>For sequence = [1, 3, 2, 1], the output should be false.
There is no one element that can be removed to get a strictly an increasing sequence
</code>```

Example 2:

```<code>For sequence = [1, 3, 2], the output should be true.
You can remove 3 or 2 to get the strictly increasing sequence [1, 2] or [1,3] respectively
</code>```

I have tried as follows :

```<code>boolean almostIncreasingSequence(int[] sequence) {
    ArrayList<Integer> list = new ArrayList<>();

    for(int i=0; i<sequence.length;i++) {
        list.add(sequence[i]);
    }

    int omittedCounter = 0;

    boolean status = true;

    for(int i=1; i<list.size();i++) {
        if(list.get(i-1) >= list.get(i)) {
            omittedCounter ++;
            list.remove(i-1);
            break;
        }
    }

    if (omittedCounter > 0) {
        for(int i=1; i<list.size();i++) {
            if(list.get(i-1) >= list.get(i)) {
                omittedCounter ++;
                list.remove(i-1);
                break;
            }
        }
    }

    if (omittedCounter > 1) {
        status = false;
    }

    return status;
}
</code>```

But I am having trouble when I am given this sequence: [1, 2, 3, 4, 3, 6]

```<code>Output:           false
Expected Output:  true
</code>```

答:
One way to achieve that is doing something like this (approx. O(n*2) in worst scenario):

```<code>static boolean analyse(int[] sequence){
    int counter =0;
    //LinkedHashSet Keep Order But Remove Duplicates
    Set<Integer> set = new LinkedHashSet<>();
    //Copy Array To The Set
    for(int i=0; i<sequence.length; i++){
        set.add(sequence[i]);
    }
    //Count How Many Duplicates Found
    counter+=(sequence.length-set.size());

    if(counter>1){return false;}
    Integer[] seq = set.toArray(new Integer[set.size()]);

    // Loop Through The Array
    // If Any Breaks The Rule -> Increment Counter
    for(int i=0; i<seq.length-1; i++){
       if(i==0 && seq[i]>seq[i+1]) {counter++;}
       if(i!=0 && !(seq[i]<seq[i+1]&&seq[i-1]<seq[i])){counter++;}
       if(counter>1){return false;}
    }
    return true;
}
</code>```

Test

```<code>int [] s  = {1,2,3,4,3,5};
int [] s1 = {1,2,3,4,3,6,1};
int [] s2 = {1,2,3,4,3,6};
int [] s3 = {1,2,3,10,10,6};
int [] s4 = {1,2,3,10,3,6};
System.out.println(analyse(s));
System.out.println(analyse(s1));
System.out.println(analyse(s2));
System.out.println(analyse(s3));
System.out.println(analyse(s4));
</code>```

Output

```<code>true
false
true
false
false
</code>```

Body:
I have given the following problem where I am stuck right now. I am not having the perfect logic for this. Here is the problem below :

Given a sequence of integers as an array, determine whether it is
  possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Example 1:

For sequence = [1, 3, 2, 1], the output should be false.
There is no one element that can be removed to get a strictly an increasing sequence

Example 2:

For sequence = [1, 3, 2], the output should be true.
You can remove 3 or 2 to get the strictly increasing sequence [1, 2] or [1,3] respectively

I have tried as follows :

boolean almostIncreasingSequence(int[] sequence) {
    ArrayList<Integer> list = new ArrayList<>();

    for(int i=0; i<sequence.length;i++) {
        list.add(sequence[i]);
    }

    int omittedCounter = 0;

    boolean status = true;

    for(int i=1; i<list.size();i++) {
        if(list.get(i-1) >= list.get(i)) {
            omittedCounter ++;
            list.remove(i-1);
            break;
        }
    }

    if (omittedCounter > 0) {
        for(int i=1; i<list.size();i++) {
            if(list.get(i-1) >= list.get(i)) {
                omittedCounter ++;
                list.remove(i-1);
                break;
            }
        }
    }

    if (omittedCounter > 1) {
        status = false;
    }

    return status;
}

But I am having trouble when I am given this sequence: [1, 2, 3, 4, 3, 6]

Output:           false
Expected Output:  true

Body:
One way to achieve that is doing something like this (approx. O(n*2) in worst scenario):

static boolean analyse(int[] sequence){
    int counter =0;
    //LinkedHashSet Keep Order But Remove Duplicates
    Set<Integer> set = new LinkedHashSet<>();
    //Copy Array To The Set
    for(int i=0; i<sequence.length; i++){
        set.add(sequence[i]);
    }
    //Count How Many Duplicates Found
    counter+=(sequence.length-set.size());

    if(counter>1){return false;}
    Integer[] seq = set.toArray(new Integer[set.size()]);

    // Loop Through The Array
    // If Any Breaks The Rule -> Increment Counter
    for(int i=0; i<seq.length-1; i++){
       if(i==0 && seq[i]>seq[i+1]) {counter++;}
       if(i!=0 && !(seq[i]<seq[i+1]&&seq[i-1]<seq[i])){counter++;}
       if(counter>1){return false;}
    }
    return true;
}

Test

int [] s  = {1,2,3,4,3,5};
int [] s1 = {1,2,3,4,3,6,1};
int [] s2 = {1,2,3,4,3,6};
int [] s3 = {1,2,3,10,10,6};
int [] s4 = {1,2,3,10,3,6};
System.out.println(analyse(s));
System.out.println(analyse(s1));
System.out.println(analyse(s2));
System.out.println(analyse(s3));
System.out.println(analyse(s4));

Output

true
false
true
false
false


来源: stackexchange

问:
Angular 2 shared service to pass data to component-to-component
I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component.

I retrieve the list.show value, and send it to my TitleService in like so in my:

landingpage.component.html

```<code><ol>
  <li (click)="selectShow(list.show)" [routerLink]="['/details', list.id]" *ngFor="let list of shows">{{list.show}}
  </li>
</ol>
</code>```

landingpage.component.ts

```<code>import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}
</code>```

The above sends the list.show value to my:

title.service.ts

```<code>// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    return title;
  }
}
</code>```

And here is how I manage the routing in my:

app-routing.module.ts

```<code>import { TitleService } from './services/title.service';

const routes: Routes = [
  { path: '', component: LandingPage },
  {
    path: 'details/:id', component: ResultPage
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [TitleService]
})
</code>```

My question

Once I receive the title.show value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)

How can I send my title value from my service to my ResultPage.component?

答:
In title.service.ts you can declare a variable called title and have setter and getter:

```<code>title: string ="";

// replace fetchTitle with setTitle
// remember to change it in the component too
setTitle(title) {
    this.title = title;
  }

getTitle() {
    return this.title;
  }
</code>```

Then, when ResultPage.component is initialized, call getTitle() from TitleService and set the result to a variable declared in the component.

Here's an example of sharing data via shared services.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to pass the string value of this.title from my LandingPage.component to my ResultPage.component.

I retrieve the list.show value, and send it to my TitleService in like so in my:

landingpage.component.html

{{list.show}}

landingpage.component.ts

import { TitleService } from '../../services/title.service';

constructor(private TitleService: TitleService) {}

selectShow(show) {
  this.TitleService.fetchTitle(show)
}

The above sends the list.show value to my:

title.service.ts

// this gives us the name of the clicked show, which we send to TitleResolver
@Injectable()
export class TitleService {
  fetchTitle(title) {
    console.log("title is " + title); // this outputs correctly
    return title;
  }
}

And here is how I manage the routing in my:

app-routing.module.ts

import { TitleService } from './services/title.service';

const routes: Routes = [
  { path: '', component: LandingPage },
  {
    path: 'details/:id', component: ResultPage
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [TitleService]
})

My question

Once I receive the title.show value in my service component, I'm unsure how to then send it to my receiving component (resultpage.component)

How can I send my title value from my service to my ResultPage.component?

Body:
In title.service.ts you can declare a variable called title and have setter and getter:

title: string ="";

// replace fetchTitle with setTitle
// remember to change it in the component too
setTitle(title) {
    this.title = title;
  }

getTitle() {
    return this.title;
  }

Then, when ResultPage.component is initialized, call getTitle() from TitleService and set the result to a variable declared in the component.

Here's an example of sharing data via shared services.


问:
Refresh HTML Document via Javascript in a GAS Embedded Environment
So I've created a simple time-keeping app in Google Appscript to store data in spreadsheets and display the information in an embedded Javascript/JQuery applet on the internal Google Site. It looks like this:

My problem is that some users leave the browser page open for too long and have to click the object twice in order to log out or log in, or refresh the page. I was hoping to set an interval timer to do the refresh for them to save them a step. Below is my code on the front end to process an interval refresh and recreate the body HTML after a set amount of idle time:

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script>
var DATA = <?!= JSON.stringify(dataFromServerTemplate) ?>;
</script>
<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>
</head>
<body onload="start()">

<div id = "loader" class="heart-rate">
  <svg version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 125 73" enable-background="new 0 0 150 73">
    <polyline fill="none" stroke="#CE0000" stroke-width="3" stroke-miterlimit="10" points="0,45.486 38.514,45.486 44.595,33.324 50.676,45.486 57.771,45.486 62.838,55.622 71.959,9 80.067,63.729 84.122,45.486 97.297,45.486 103.379,40.419 110.473,45.486 150,45.486"
    />
  </svg>
  <div class="fade-in"></div>
  <div class="fade-out"></div>
</div>

<p  id = 'title' style="font-size:18px; text-align: center; display: none;"><b>Time<font color="#ff0000">Track</font></b></p>
<div id="clock" style = "display: none;"><small>Current Time:<div id = 'time'></div></small></div><br>
<div id="interface" tex-align: center;></div>
<div id = 'modal' class = 'modal'>
<div id = 'modalContent' class = 'modal-content'>
</div></div>
<span id = 'closeModal' class = 'close'></span>
<form id="timeCardPost" method="post" action="MustSetURL" target="TheWindow">
<input type="hidden" name="payload" value="set card JSON here" />
</form>
<?!= HtmlService.createHtmlOutputFromFile('JS-TimeTrack').getContent();?>
</body>
</html></code>```

unfortunately, after the first refresh, the interval seems to reload the page and then add another copy of the body under it ad infinitum, like in the screenshot below:

I've tried location.reload(with true and false statements). That just results in a white screen. I've tried setting the HTML body to (), but that seems to work the same way. Would anyone know how to reset the body tag of the page instead of just concatenating?

Thanks,
        Nathaniel

答:
jquery clone() method makes a copy of the selected element.  What you are ending up with is body tags inside of other body tags, each one nested inside of the other.

Currently

```<code>var body = $('body').clone();
document.body.innerHTML = '';
$('body').html(body);
start();
var body = $('body').clone();
</code>```

Try

```<code>var body = document.body.innerHTML;//Get the HTML inside of the `body` tag
document.body.innerHTML = '';//Clear the existing HTML from the `body` tag

console.log('body: ' + body);

document.body.innerHTML = body;

start();
</code>```

Body:
So I've created a simple time-keeping app in Google Appscript to store data in spreadsheets and display the information in an embedded Javascript/JQuery applet on the internal Google Site. It looks like this:

My problem is that some users leave the browser page open for too long and have to click the object twice in order to log out or log in, or refresh the page. I was hoping to set an interval timer to do the refresh for them to save them a step. Below is my code on the front end to process an interval refresh and recreate the body HTML after a set amount of idle time:

<!DOCTYPE html>

<?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>

  <svg version="1.0" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 125 73" enable-background="new 0 0 150 73">
    <polyline fill="none" stroke="#CE0000" stroke-width="3" stroke-miterlimit="10" points="0,45.486 38.514,45.486 44.595,33.324 50.676,45.486 57.771,45.486 62.838,55.622 71.959,9 80.067,63.729 84.122,45.486 97.297,45.486 103.379,40.419 110.473,45.486 150,45.486"
    />
  </svg>

TimeTrack

Current Time:

<form id="timeCardPost" method="post" action="MustSetURL" target="TheWindow">
<input type="hidden" name="payload" value="set card JSON here" />
</form>
<?!= HtmlService.createHtmlOutputFromFile('JS-TimeTrack').getContent();?>

unfortunately, after the first refresh, the interval seems to reload the page and then add another copy of the body under it ad infinitum, like in the screenshot below:

I've tried location.reload(with true and false statements). That just results in a white screen. I've tried setting the HTML body to (), but that seems to work the same way. Would anyone know how to reset the body tag of the page instead of just concatenating?

Thanks,
        Nathaniel

Body:
jquery clone() method makes a copy of the selected element.  What you are ending up with is body tags inside of other body tags, each one nested inside of the other.

Currently

var body = $('body').clone();
document.body.innerHTML = '';
$('body').html(body);
start();
var body = $('body').clone();

Try

var body = document.body.innerHTML;//Get the HTML inside of the `body` tag
document.body.innerHTML = '';//Clear the existing HTML from the `body` tag

console.log('body: ' + body);

document.body.innerHTML = body;

start();


问:
Column outline overriden by row highlight? (html table, css formatting)
I used a derivation of ThinkingStiff's answer to this question cols, colgroups and css :hover psuedoclass to create a table that outlines columns and highlights rows on hover. (Vertical column headers intentionally not outlined).

See below:

table {
  overflow: hidden;
}
caption {
  background-color: #fff;
  padding: 0px
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
  width: 100%
}
th, td {
    width: 100px;
    height: 50px;
    position: relative;
}
tr:hover {
  background-color: #FBFEFD;
}

td:hover::after {
  content: "";
  position: absolute;
  outline: solid black 2px !important;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="ComparisonTable">
 <caption>Comparison Table</caption>
  <tbody>
    <tr>
      <th class="CompTabProdCat">Category</th>
      <td>ProdCat1</td>
      <td>ProdCat2</td>
      <td>ProdCat3</td>
      <td>ProdCat4</td>
      <td>ProdCat5</td>
    </tr>
    <tr>
      <th class="CompTabProdName">ProdName</th>
      <td>ProdName1</td>
      <td>ProdName2</td>
      <td>ProdName3</td>
      <td>ProdName4</td>
      <td>ProdName5</td>
    </tr>
    <tr>
      <th class="CompTabProdRat">Rating</th>
      <td>ProdRating1</td>
      <td>ProdRating2</td>
      <td>ProdRating3</td>
      <td>ProdRating4</td>
      <td>ProdRating5</td>
    </tr>
    <tr>
      <th class="CompTabProdPho">Photo</th>
      <td>ProdImage1</td>
      <td>ProdImage2</td>
      <td>ProdImage3</td>
      <td>ProdImage4</td>
      <td>ProdImage5</td>
    </tr>
    <tr>
      <th class="CompTabProdSum">Summary</th>
      <td>ProdSum1</td>
      <td>ProdSum2</td>
      <td>ProdSum3</td>
      <td>ProdSum4</td>
      <td>ProdSum5</td>
    </tr>
  </tbody>
</table></code>```

Does anyone know why the column outline disappears for the selected row? I thought the !important tag would maintain that outline, but apparently not. Any other workarounds available to maintain that outline?

Bonus question is why I'm losing the rightmost border (less stuck and less concerned with that question).

Thanks a ton; I appreciate it!

答:
I'm not sure there's a css only solution, but some brief javascript took care of it.

Used box-shadow to avoid shifting text (as border would do) or highlighting full cells (as outline would do).

$('td').hover(function() {
    var t = parseInt($(this).index()) + 1;
    $('td:nth-child(' + t + ')').addClass('ct-col-highlighted');
},
function() {
    var t = parseInt($(this).index()) + 1;
    $('td:nth-child(' + t + ')').removeClass('ct-col-highlighted');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.comparison-table {
  border: 1px solid black;
  border-collapse: collapse;
  width: 100%;
  text-align: center;
}

.comparison-table caption {
  padding: 15px
}

.comparison-table th, td {
  border: 1px solid black;
  width: auto;
  height: 50px;
}

.comparison-table tr:hover {
  background-color: #FBFEFD;
}

.ct-col-highlighted {
 box-shadow: -2px 0px 0px 0px black, 3px 0px 0px 0px black;</code>```

Caption

  H-A
  A1
  A2
  A3

  H-B
  B1
  B2
  B3

  H-C
  C1
  C2
  C3

  H-D
  D1
  D2
  D3

```

Body:
I used a derivation of ThinkingStiff's answer to this question cols, colgroups and css :hover psuedoclass to create a table that outlines columns and highlights rows on hover. (Vertical column headers intentionally not outlined).

See below:

table {
  overflow: hidden;
}
caption {
  background-color: #fff;
  padding: 0px
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
  width: 100%
}
th, td {
    width: 100px;
    height: 50px;
    position: relative;
}
tr:hover {
  background-color: #FBFEFD;
}

td:hover::after {
  content: "";
  position: absolute;
  outline: solid black 2px !important;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}

Comparison Table

      Category
      ProdCat1
      ProdCat2
      ProdCat3
      ProdCat4
      ProdCat5

      ProdName
      ProdName1
      ProdName2
      ProdName3
      ProdName4
      ProdName5

      Rating
      ProdRating1
      ProdRating2
      ProdRating3
      ProdRating4
      ProdRating5

      Photo
      ProdImage1
      ProdImage2
      ProdImage3
      ProdImage4
      ProdImage5

      Summary
      ProdSum1
      ProdSum2
      ProdSum3
      ProdSum4
      ProdSum5

Does anyone know why the column outline disappears for the selected row? I thought the !important tag would maintain that outline, but apparently not. Any other workarounds available to maintain that outline?

Bonus question is why I'm losing the rightmost border (less stuck and less concerned with that question).

Thanks a ton; I appreciate it!

Body:
I'm not sure there's a css only solution, but some brief javascript took care of it.

Used box-shadow to avoid shifting text (as border would do) or highlighting full cells (as outline would do).

$('td').hover(function() {
    var t = parseInt($(this).index()) + 1;
    $('td:nth-child(' + t + ')').addClass('ct-col-highlighted');
},
function() {
    var t = parseInt($(this).index()) + 1;
    $('td:nth-child(' + t + ')').removeClass('ct-col-highlighted');
});

.comparison-table {
  border: 1px solid black;
  border-collapse: collapse;
  width: 100%;
  text-align: center;
}

.comparison-table caption {
  padding: 15px
}

.comparison-table th, td {
  border: 1px solid black;
  width: auto;
  height: 50px;
}

.comparison-table tr:hover {
  background-color: #FBFEFD;
}

.ct-col-highlighted {
 box-shadow: -2px 0px 0px 0px black, 3px 0px 0px 0px black;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class='comparison-table'>
 <caption>Caption</caption>
 <tr>
  <th>H-A</th>
  <td>A1 </td>
  <td>A2</td>
  <td>A3</td>
 </tr>
 <tr>
  <th>H-B</th>
  <td>B1</td>
  <td>B2</td>
  <td>B3</td>
 </tr>
 <tr>
  <th>H-C</th>
  <td>C1</td>
  <td>C2</td>
  <td>C3</td>
 </tr>
 <tr>
  <th>H-D</th>
  <td>D1</td>
  <td>D2</td>
  <td>D3</td>
 </tr>
</table>


问:
Page Background-Color doesn't work (CSS)
I'm a real noob at CSS/HTML, so please forgive me.

I tried to change the background page color on the CSS file linked to my html file, and it doesn't work. Whereas when I just flat out change it between the style tags in my HTML file, it works. What gives?

Plain and simple:

Ex1.css

```<code><head>
<style>
body {
   background-color: lightblue;
}
</style>
</head>
</code>```

SamplePage.html

```<code><!doctype html>
<html>
  <head>
    <title> Sample Page </title>
    <link rel = "stylesheet" href="Ex1.css">
  </head>
  <body>

      Hello. This is a sample Page.

  </body>
</html>
</code>```

答:
Your HTML is correct, and links to your CSS correctly (assuming Ex1.css is in the same folder as your HTML).

Your CSS is almost correct; the only problem is that you shouldn't include any HTML tags in your CSS document. Ex1.css should only contain the actual CSS declarations themselves (body { }).

body {
  background-color: lightblue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  Hello. This is a sample Page.
</body></code>```

If in doubt, you can validate your CSS with W3's CSS Validator.

Hope this helps! :)

Body:
I'm a real noob at CSS/HTML, so please forgive me.

I tried to change the background page color on the CSS file linked to my html file, and it doesn't work. Whereas when I just flat out change it between the style tags in my HTML file, it works. What gives?

Plain and simple:

Ex1.css

SamplePage.html

<!doctype html>

    <title> Sample Page </title>
    <link rel = "stylesheet" href="Ex1.css">

      Hello. This is a sample Page.

Body:
Your HTML is correct, and links to your CSS correctly (assuming Ex1.css is in the same folder as your HTML).

Your CSS is almost correct; the only problem is that you shouldn't include any HTML tags in your CSS document. Ex1.css should only contain the actual CSS declarations themselves (body { }).

body {
  background-color: lightblue;
}

<body>
  Hello. This is a sample Page.
</body>

If in doubt, you can validate your CSS with W3's CSS Validator.

Hope this helps! :)


问:
JQuery tooltip that supports new line
I'm looking for a lightweight jquery plugin for displaying tooltips when the user hovers over an element. I would like the plugin to get the content from the title attribute and also it's important that I can make new lines.

Any help is appreciated!

答:
Most browsers (not Firefox or Opera - newlines will disappear) support newlines in the title attribute.

If your plugin doesn't render them as
, do this on the text first...

```<code>var tooltip = $('#whatever').attr('title').replace(/\n/g, '<br />');
</code>```

... and then pass tooltip to your tooltip library (e.g. qTip).

ContentLicense: CC BY-SA 2.5

Title: JQuery tooltip that supports new line

Body:
Most browsers (not Firefox or Opera - newlines will disappear) support newlines in the title attribute.

If your plugin doesn't render them as <br />, do this on the text first...

var tooltip = $('#whatever').attr('title').replace(/\n/g, '<br />');

... and then pass tooltip to your tooltip library (e.g. qTip).


答:
Reduce the contents of your Ex1.css file to this:

```<code>body {
   background-color: lightblue;
}
</code>```

(no HTML code in CSS files!)

Title: Page Background-Color doesn't work (CSS)

Body:
Reduce the contents of your Ex1.css file to this:

body {
   background-color: lightblue;
}

(no HTML code in CSS files!)


答:
your css file will just have. Plain and simple </p>

```<code>body {
   background-color: lightblue;
}
</code>```

Body:
your css file will just have. Plain and simple

body {
   background-color: lightblue;
}


问:
Razor mutliselect dropdown- Set values as selected in the multiselect dropdown in ASP.Net MVC
I need a way to set already selected values in a multi select dropdown in a edit view in a web application (ASP.NET, Mvc)

```<code><div class="form-group">
 <label>Choose Categories</label>
     @Html.DropDownListFor(model => model.SelectedValues, new MultiSelectList(Models.GetCategoryList().OrderBy(c => c.Value), "Key", "Value"), "Select Category", new { @class = "chzn-select form-control", multiple = "multiple" })
   </div>
</code>```

this is view code, here I passed selected ids in to selected values array.(when I return values from DB , assign those in to a array then assign to here.

I need a edit view like this

please anyone suggest way to do this

Thank you.

答:
To generate this view you can use select2 jquery plugin. Check out the following link.

https://select2.github.io/examples.html#multiple

Body:
I need a way to set already selected values in a multi select dropdown in a edit view in a web application (ASP.NET, Mvc)

 Choose Categories
     @Html.DropDownListFor(model => model.SelectedValues, new MultiSelectList(Models.GetCategoryList().OrderBy(c => c.Value), "Key", "Value"), "Select Category", new { @class = "chzn-select form-control", multiple = "multiple" })

this is view code, here I passed selected ids in to selected values array.(when I return values from DB , assign those in to a array then assign to here.

I need a edit view like this

please anyone suggest way to do this

Thank you.


问:
How can I make all of the buttons selected revert back to original when the other buttons are clicked?
When I designed my switch I made it so when the on button was clicked the off color changed back to the original color and when the off button is clicked the on button changed back to the original color.

However, when I use more than one switch in my div I want the on button of one switch to turn off any other on buttons that were clicked. I've tried to do this code my self using this:

$("#darkmodeon, #colorfulon").click(function() {
  $('#responsiveoff').css({
    "background-color": "#d8d8d8",
    "color": "#777777",
    "transition": "all 0.2s ease"
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdowns > div {
  display: block !important;
}

body {
  margin: 0 auto;
  width: 950px;
  /* border: solid;
     border-color: black; */
  background-color: #f2f2f2;
}

/*--------------Navigation Bar------------*/

#navbar {
  width: 100%;
  background-color: white;
  overflow: auto;
  position: fixed;
  left: 0px;
  top: 0px;
  border-bottom: solid;
  border-width: 1px;
  border-color: #d8d8d8;
  overflow: hidden;
  z-index: 10;
}

#nav-container {
  max-width: 950px;
  min-width: 875px;
  margin: 0 auto;
}

#nav-container h1 {
  float: left;
  margin: 0 auto;
  padding-top: 10px;
  font-family: "calibri light";
  font-size: 25px;
  letter-spacing: 0.3em;
  margin-left: 5px;
  transition: color 0.3s ease;
}

#nav-container a {
  float: right;
  display: block;
  padding: 15px 15px;
  text-decoration: none;
  color: black;
  font-family: "calibri light", sans-serif;
  font-size: 18px;
  transition: background-color 0.5s ease;
}

#nav-container a:hover {
  background-color: #f4f4f4;
  transition: background-color 0.5s ease;
}

#nav-container a:active {
  background-color: #bfbfbf;
}

#nav-container h1:hover {
  color: #aaaaaa;
  transition: color 0.3s ease;
}

#webdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#webdsn-content {
  width: 950px;
  margin: 0 auto;
}

#pfdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#pfdsn-content {
  width: 950px;
  margin: 0 auto;
}

#bc-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#bcdsn-content {
  width: 950px;
  margin: 0 auto;
}

#ldsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#ldsn-content {
  width: 950px;
  margin: 0 auto;
}

/*----------THEMES-DROPDOWN-AREA--------*/

#switches-container {
  display: flex;
  justify-content: space-between;
  padding: 15px;
}

#themes-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#themes-content {
  width: 950px;
  margin: 0 auto;
}

/*--SWITCH--*/

.theme-switch {
  display: flex;
  justify-content: space-between;
  position: relative;
  width: 295px;
}

.themename {
  font-family: 'calibri light';
  font-weight: bold;
  font-size: 20.5px;
  color: #777777;
  position: relative;
  top: 15.5px;
  display: inline-block;
}

#darkmodebox {
  width: 240px;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border: solid 2px #d8d8d8;
  border-radius: 50px;
  width: 100px;
  padding: 5px;
  margin: 25px 10px;
}

button {
  width: 37px;
  height: 37px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer;
  outline: none;
}

/*--------------------------------------*/

.subname-container {
  display: block;
}

.subname {
  color: black;
  border: solid;
  border-width: 1px;
  border-radius: 7.5px;
  padding: 5px 15px;
  display: inline;
  font-family: 'calibri light';
  letter-spacing: 2.5px;
  transition: background-color, color, 0.5s ease;
}

.subname:hover {
  background-color: #353535;
  border-color: white;
  color: white;
  transition: background-color, color, 0.5s ease;
}</code>```

<!DOCTYPE HTML>

  <title>Home</title>
  <link id="defaultcss" rel="stylesheet" type="text/css" href="main.css">

PORTFOLIO

      Theme Settings
      Logo Design
      Business Cards
      Posters & Flyers
      Website Design

WEBSITE DESIGN

POSTERS & FLYERS

BUSINESS CARDS

LOGO DESIGN

THEME SETTINGS

DARK MODE

              <button id="darkmodeon">ON</button>
              <button id="darkmodeoff">OFF</button>

COLOURFUL MODE

              <button id="colorfulon">ON</button>
              <button id="colorfuloff">OFF</button>

RESPONSIVE MODE

              <button id="responsiveon">ON</button>
              <button id="responsiveoff">OFF</button>

```
</div>
</div>
</p>

<p>Entire JavaScript:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){

        $('#web').hover(function(){
            $('#webdsn-drop').slideDown(250);
        },
        function(){
          $('#webdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});

     if($('#webdsn-drop').is(':visible'))
      $('#webdsn-drop').slideUp(250);

     });

     $('#webdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#pf').hover(function(){
            $('#pfdsn-drop').slideDown(250);
        },
        function(){
          $('#pfdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#pfdsn-drop').is(':visible'))
      $('#pfdsn-drop').slideUp(250);
     });
     $('#pfdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#bc').hover(function(){
            $('#bc-drop').slideDown(250);
        },
        function(){
          $('#bc-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#bc-drop').is(':visible'))
      $('#bc-drop').slideUp(250);
     });
     $('#bc-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#ld').hover(function(){
            $('#ldsn-drop').slideDown(250);
        },
        function(){
          $('#ldsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#ldsn-drop').is(':visible'))
      $('#ldsn-drop').slideUp(250);
     });
     $('#ldsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#themes').hover(function(){
            $('#themes-drop').slideDown(250);
        },
        function(){
          $('#themes-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#themes-drop').is(':visible'))
      $('#themes-drop').slideUp(250);
     });
     $('#themes-drop').mouseenter(function(){
            $(this).stop();
        });

    //-----------DARK-MODE-SWITCH-----------

     var darkon = '#darkmodeon';
     var darkoff = '#darkmodeoff';

     $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
      $('#darkmodeoff')[0].style.color = "white";

      $(darkon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(darkoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var colorfulon = '#colorfulon';
     var colorfuloff = '#colorfuloff';

     $('#colorfuloff')[0].style.backgroundColor = "#85c452";
      $('#colorfuloff')[0].style.color = "white";

      $(colorfulon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfuloff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(colorfuloff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfulon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var responson = '#responsiveon';
     var responsoff = '#responsiveoff';

     $('#responsiveoff')[0].style.backgroundColor = "#85c452";
      $('#responsiveoff')[0].style.color = "white";

      $(responson).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(responsoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    //-------------CSS-STYLES-------------------

     $('#darkmodeon').click(function (){
        $('link[href="main.css"]').attr('href','dark-main.css');
     });
     $('#darkmodeoff').click(function (){
        $('link[href="dark-main.css"]').attr('href','main.css');
     });

     $('#colorfulon').click(function (){
        $('link[href="main.css"]').attr('href','colorful-main.css');
     });
     $('#colorfuloff').click(function (){
        $('link[href="colorful-main.css"]').attr('href','main.css');
     });

     $('#responsiveon').click(function (){
        $('link[href="main.css"]').attr('href','responsive-main.css');
     });
     $('#responsiveoff').click(function (){
        $('link[href="responsive-main.css"]').attr('href','main.css');
     });

    });

    //-----------------RESET-ALL-SWITCH----------------

    $("#darkmodeon, #colorfulon").click(function(){
       $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    });</code>```

答:
You look pretty savvy in jQuery so, I'm going to give you the method that I would use.

When a button is clicked, I would add an active class. Before that active class is added, I would remove the active class from all other elements.

Something like this:

```<code>$('#some-id button').click(function () {
    $('#some-id .active').removeClass('active');
    $(this).addClass('active')
});
</code>```

I would then style that active class with whatever color you want.

Play with it and if you still don't get it, I'll provide further assistance.

ContentLicense: CC BY-SA 4.0

Body:
When I designed my switch I made it so when the on button was clicked the off color changed back to the original color and when the off button is clicked the on button changed back to the original color.

However, when I use more than one switch in my div I want the on button of one switch to turn off any other on buttons that were clicked. I've tried to do this code my self using this:

$("#darkmodeon, #colorfulon").click(function() {
  $('#responsiveoff').css({
    "background-color": "#d8d8d8",
    "color": "#777777",
    "transition": "all 0.2s ease"
  });
});

#dropdowns > div {
  display: block !important;
}

body {
  margin: 0 auto;
  width: 950px;
  /* border: solid;
     border-color: black; */
  background-color: #f2f2f2;
}

/*--------------Navigation Bar------------*/

#navbar {
  width: 100%;
  background-color: white;
  overflow: auto;
  position: fixed;
  left: 0px;
  top: 0px;
  border-bottom: solid;
  border-width: 1px;
  border-color: #d8d8d8;
  overflow: hidden;
  z-index: 10;
}

#nav-container {
  max-width: 950px;
  min-width: 875px;
  margin: 0 auto;
}

#nav-container h1 {
  float: left;
  margin: 0 auto;
  padding-top: 10px;
  font-family: "calibri light";
  font-size: 25px;
  letter-spacing: 0.3em;
  margin-left: 5px;
  transition: color 0.3s ease;
}

#nav-container a {
  float: right;
  display: block;
  padding: 15px 15px;
  text-decoration: none;
  color: black;
  font-family: "calibri light", sans-serif;
  font-size: 18px;
  transition: background-color 0.5s ease;
}

#nav-container a:hover {
  background-color: #f4f4f4;
  transition: background-color 0.5s ease;
}

#nav-container a:active {
  background-color: #bfbfbf;
}

#nav-container h1:hover {
  color: #aaaaaa;
  transition: color 0.3s ease;
}

#webdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#webdsn-content {
  width: 950px;
  margin: 0 auto;
}

#pfdsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#pfdsn-content {
  width: 950px;
  margin: 0 auto;
}

#bc-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#bcdsn-content {
  width: 950px;
  margin: 0 auto;
}

#ldsn-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  height: 200px;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#ldsn-content {
  width: 950px;
  margin: 0 auto;
}

/*----------THEMES-DROPDOWN-AREA--------*/

#switches-container {
  display: flex;
  justify-content: space-between;
  padding: 15px;
}

#themes-drop {
  padding: 75px 0 0 0;
  background-color: rgba(252, 252, 252, 0.95);
  border-bottom: solid 1px #d8d8d8;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  box-shadow: 0 10px 10px -5px rgba(0, 0, 0, 0.3);
  z-index: 9;
  display: none;
}

#themes-content {
  width: 950px;
  margin: 0 auto;
}

/*--SWITCH--*/

.theme-switch {
  display: flex;
  justify-content: space-between;
  position: relative;
  width: 295px;
}

.themename {
  font-family: 'calibri light';
  font-weight: bold;
  font-size: 20.5px;
  color: #777777;
  position: relative;
  top: 15.5px;
  display: inline-block;
}

#darkmodebox {
  width: 240px;
}

.switchcontainer {
  background-color: white;
  display: flex;
  justify-content: space-between;
  border: solid 2px #d8d8d8;
  border-radius: 50px;
  width: 100px;
  padding: 5px;
  margin: 25px 10px;
}

button {
  width: 37px;
  height: 37px;
  border: none;
  border-radius: 50px;
  background-color: #d8d8d8;
  color: #777777;
  font-family: 'calibri light';
  font-size: 17px;
  font-weight: bold;
  cursor: pointer;
  outline: none;
}

/*--------------------------------------*/

.subname-container {
  display: block;
}

.subname {
  color: black;
  border: solid;
  border-width: 1px;
  border-radius: 7.5px;
  padding: 5px 15px;
  display: inline;
  font-family: 'calibri light';
  letter-spacing: 2.5px;
  transition: background-color, color, 0.5s ease;
}

.subname:hover {
  background-color: #353535;
  border-color: white;
  color: white;
  transition: background-color, color, 0.5s ease;
}

<!DOCTYPE HTML>

  <title>Home</title>
  <link id="defaultcss" rel="stylesheet" type="text/css" href="main.css">

PORTFOLIO

      Theme Settings
      Logo Design
      Business Cards
      Posters & Flyers
      Website Design

WEBSITE DESIGN

POSTERS & FLYERS

BUSINESS CARDS

LOGO DESIGN

THEME SETTINGS

DARK MODE

              <button id="darkmodeon">ON</button>
              <button id="darkmodeoff">OFF</button>

COLOURFUL MODE

              <button id="colorfulon">ON</button>
              <button id="colorfuloff">OFF</button>

RESPONSIVE MODE

              <button id="responsiveon">ON</button>
              <button id="responsiveoff">OFF</button>

Entire JavaScript:

$(document).ready(function(){

        $('#web').hover(function(){
            $('#webdsn-drop').slideDown(250);
        },
        function(){
          $('#webdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});

     if($('#webdsn-drop').is(':visible'))
      $('#webdsn-drop').slideUp(250);

     });

     $('#webdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#pf').hover(function(){
            $('#pfdsn-drop').slideDown(250);
        },
        function(){
          $('#pfdsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#pfdsn-drop').is(':visible'))
      $('#pfdsn-drop').slideUp(250);
     });
     $('#pfdsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#bc').hover(function(){
            $('#bc-drop').slideDown(250);
        },
        function(){
          $('#bc-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#bc-drop').is(':visible'))
      $('#bc-drop').slideUp(250);
     });
     $('#bc-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#ld').hover(function(){
            $('#ldsn-drop').slideDown(250);
        },
        function(){
          $('#ldsn-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#ldsn-drop').is(':visible'))
      $('#ldsn-drop').slideUp(250);
     });
     $('#ldsn-drop').mouseenter(function(){
            $(this).stop();
        });

     $('#themes').hover(function(){
            $('#themes-drop').slideDown(250);
        },
        function(){
          $('#themes-drop').hover(function(){}, function(){$(this).slideUp(250);});
     if($('#themes-drop').is(':visible'))
      $('#themes-drop').slideUp(250);
     });
     $('#themes-drop').mouseenter(function(){
            $(this).stop();
        });

    //-----------DARK-MODE-SWITCH-----------

     var darkon = '#darkmodeon';
     var darkoff = '#darkmodeoff';

     $('#darkmodeoff')[0].style.backgroundColor = "#85c452";
      $('#darkmodeoff')[0].style.color = "white";

      $(darkon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(darkoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#darkmodeon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var colorfulon = '#colorfulon';
     var colorfuloff = '#colorfuloff';

     $('#colorfuloff')[0].style.backgroundColor = "#85c452";
      $('#colorfuloff')[0].style.color = "white";

      $(colorfulon).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfuloff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(colorfuloff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#colorfulon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      var responson = '#responsiveon';
     var responsoff = '#responsiveoff';

     $('#responsiveoff')[0].style.backgroundColor = "#85c452";
      $('#responsiveoff')[0].style.color = "white";

      $(responson).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

      $(responsoff).click(function() {
        $(this).css({
          "background-color": "#85c452",
          "color": "white",
          "transition": "all 0.2s ease"
        });
        $('#responsiveon').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    //-------------CSS-STYLES-------------------

     $('#darkmodeon').click(function (){
        $('link[href="main.css"]').attr('href','dark-main.css');
     });
     $('#darkmodeoff').click(function (){
        $('link[href="dark-main.css"]').attr('href','main.css');
     });

     $('#colorfulon').click(function (){
        $('link[href="main.css"]').attr('href','colorful-main.css');
     });
     $('#colorfuloff').click(function (){
        $('link[href="colorful-main.css"]').attr('href','main.css');
     });

     $('#responsiveon').click(function (){
        $('link[href="main.css"]').attr('href','responsive-main.css');
     });
     $('#responsiveoff').click(function (){
        $('link[href="responsive-main.css"]').attr('href','main.css');
     });

    });

    //-----------------RESET-ALL-SWITCH----------------

    $("#darkmodeon, #colorfulon").click(function(){
       $('#responsiveoff').css({
          "background-color": "#d8d8d8",
          "color": "#777777",
          "transition": "all 0.2s ease"
        });
      });

    });

Body:
You look pretty savvy in jQuery so, I'm going to give you the method that I would use.

When a button is clicked, I would add an active class. Before that active class is added, I would remove the active class from all other elements.

Something like this:

$('#some-id button').click(function () {
    $('#some-id .active').removeClass('active');
    $(this).addClass('active')
});

I would then style that active class with whatever color you want.

Play with it and if you still don't get it, I'll provide further assistance.


问:
Methods defined in class Object are instance and class one at the same time
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

```<code>class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method
</code>```

答:
Every object is an instance of Object. Thus, every object will respond to boo.

Foo is an object (classes are objects, too), ergo, Foo is an instance of Object (it is an instance of Class, which is a subclass of Module, which is a subclass of Object).

Foo.new is an object (it is an instance of Foo, which is a subclass of Object).

Since both Foo and Foo.new are instances of Object, both respond to boo.

[Note: I am ignoring the existence of BasicObject.]

Body:
How can be described that a method boo defined in Object class becomes instance and class one at the same time in class Foo?

class Foo; end

class Object
  def boo
    'boo method'
  end
end

p Foo.boo # => boo method
p Foo.new.boo # => boo method


问:
reactjs - moving list items back and forth between two components
I have a small exercise I'm working on to learn ReactJS. I'm making an API call to display a list from iTunes, and when the individual list items are clicked on, they move over to a new list (kind of like a queue). When clicked on in the new list, they move back to the original list, however the list item is not being removed from the new list when it gets moved back. Here is a jsfiddle of my problem: https://jsfiddle.net/6k9ncbr6/</p>

```<code>class App extends React.Component {
constructor(props) {
    super(props);

    this.state = {
            searchResults: [],
            moveResults: []
    }

    this.handleEvent = this.handleEvent.bind(this);
}

showResults = (response) => {
    this.setState({
        searchResults: response.results,
        moveResults: []
    })
}

search = (URL) => {
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response) {
            this.showResults(response);
        }.bind(this)
    });
}

handleEvent = (clickedTrack) => {
    const { searchResults, moveResults } = this.state;
    const isInSearchResults = searchResults.some(result => result.trackId === clickedTrack.trackId);

    this.setState({
        searchResults: isInSearchResults ? searchResults.filter(i => i.trackId  !== clickedTrack.trackId) : [...searchResults, clickedTrack],
        moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack)
    });
}

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=broods');
}

render(){
    return (
        <div>
            <Results
              searchResults={this.state.searchResults}
              handleEvent={this.handleEvent}/>
            <Results
              searchResults={this.state.moveResults}
              handleEvent={this.handleEvent} />
        </div>
    );
  }
}
class Results extends React.Component {
  render(){
    const { handleEvent, searchResults } = this.props;
    return(
        <ul>
            {this.props.searchResults.map((result, idx) =>
                    <ResultItem
                 key={`${result.trackId}-${idx}`}
                 trackName={result.trackName}
                 track={result}
                 handleClick={handleEvent} />
                    )}
        </ul>
    );
  }
}

  class ResultItem extends React.Component {
     render(){
        const { handleClick, track, trackName } = this.props
    return <li onClick={() => handleClick(track)}> {trackName} </li>;
   }
 }

ReactDOM.render(
   <App />, document.getElementById('root')
);
</code>```

答:
You left off a property name:

```<code>moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack.trackId)
</code>```

The clickedTrack.trackId is missing the .trackId in your existing code.

Here's the working jsFiddle.

Body:
I have a small exercise I'm working on to learn ReactJS. I'm making an API call to display a list from iTunes, and when the individual list items are clicked on, they move over to a new list (kind of like a queue). When clicked on in the new list, they move back to the original list, however the list item is not being removed from the new list when it gets moved back. Here is a jsfiddle of my problem: https://jsfiddle.net/6k9ncbr6/

class App extends React.Component {
constructor(props) {
    super(props);

    this.state = {
            searchResults: [],
            moveResults: []
    }

    this.handleEvent = this.handleEvent.bind(this);
}

showResults = (response) => {
    this.setState({
        searchResults: response.results,
        moveResults: []
    })
}

search = (URL) => {
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response) {
            this.showResults(response);
        }.bind(this)
    });
}

handleEvent = (clickedTrack) => {
    const { searchResults, moveResults } = this.state;
    const isInSearchResults = searchResults.some(result => result.trackId === clickedTrack.trackId);

    this.setState({
        searchResults: isInSearchResults ? searchResults.filter(i => i.trackId  !== clickedTrack.trackId) : [...searchResults, clickedTrack],
        moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack)
    });
}

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=broods');
}

render(){
    return (

            <Results
              searchResults={this.state.searchResults}
              handleEvent={this.handleEvent}/>
            <Results
              searchResults={this.state.moveResults}
              handleEvent={this.handleEvent} />

    );
  }
}
class Results extends React.Component {
  render(){
    const { handleEvent, searchResults } = this.props;
    return(

            {this.props.searchResults.map((result, idx) =>
                    <ResultItem
                 key={`${result.trackId}-${idx}`}
                 trackName={result.trackName}
                 track={result}
                 handleClick={handleEvent} />
                    )}

    );
  }
}

  class ResultItem extends React.Component {
     render(){
        const { handleClick, track, trackName } = this.props
    return
 handleClick(track)}> {trackName}
;
   }
 }

ReactDOM.render(
   <App />, document.getElementById('root')
);

Body:
You left off a property name:

moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack.trackId)

The clickedTrack.trackId is missing the .trackId in your existing code.

Here's the working jsFiddle.


问:
How can I pass a function with arguments when the arguments aren't known yet?
This code does not run. It fails during the run(gate) function. The first error I get is from the .__name__ call. This isn't my main issue, so I'm not particularly worried about this error yet

The second error I get is in the last line of run(gate). The error message says gate is not callable.

I believe my actual issue is with the structure of my program. Am I misunderstanding (or misapplying) some object-oriented principles? I would appreciate it if somebody could provide an example or a correction to my code for a better way of structuring it. Thank you!

main.py

```<code>import builtins
import logic

print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
   run(logic.andGate)
elif(int(logicGate) == 2):
   run(logic.nandGate)
elif(int(logicGate) == 3):
   run(logic.orGate)
elif(int(logicGate) == 4):
   run(logic.norGate)
elif(logicGate.lower() == 'q'):
   prog = 'n'
else:
   print("Invalid input. Please try again")

def toBool(s):
   if s == 'True':
      return True
   elif s == 'False':
      return False
   else:
      raise ValueError

def run(gate):
   print(gate.__name__ + " Gate function")
   print("Enter value for 'a'")
   valA = input()
   print("Enter value for 'b'")
   valB = input()
   print("Result: " + str(gate(toBool(valA), toBool(valB))))
</code>```

And logic.py

```<code>def andGate(a, b):
   if(a and b):
      return True
   else:
      return False

def nandGate(a,b):
   if(a and b):
      return False
   else:
      return True

def orGate(a, b):
   if(a or b):
      return True
   else:
      return False

def norGate(a, b):
   if(a or b):
      return False
   else:
      return True
</code>```

答:
move your defs under imports and just remove the else: raise.... etc ect part... itnot used correctly.</p>

```<code>import builtins
import logic

def toBool(s):
   if s == 'True':
      return True
   elif s == 'False':
      return False

def run(gate):
   print(gate.__name__ + " Gate function")
   print("Enter value for 'a'")
   valA = input()
   print("Enter value for 'b'")
   valB = input()
   print("Result: " + str(gate(toBool(valA), toBool(valB))))

print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
   run(logic.andGate)
elif(int(logicGate) == 2):
   run(logic.nandGate)
elif(int(logicGate) == 3):
   run(logic.orGate)
elif(int(logicGate) == 4):
   run(logic.norGate)
elif(logicGate.lower() == 'q'):
   prog = 'n'
else:
   print("Invalid input. Please try again")
</code>```

Body:
This code does not run. It fails during the run(gate) function. The first error I get is from the .__name__ call. This isn't my main issue, so I'm not particularly worried about this error yet

The second error I get is in the last line of run(gate). The error message says gate is not callable.

I believe my actual issue is with the structure of my program. Am I misunderstanding (or misapplying) some object-oriented principles? I would appreciate it if somebody could provide an example or a correction to my code for a better way of structuring it. Thank you!

main.py

import builtins
import logic

print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
   run(logic.andGate)
elif(int(logicGate) == 2):
   run(logic.nandGate)
elif(int(logicGate) == 3):
   run(logic.orGate)
elif(int(logicGate) == 4):
   run(logic.norGate)
elif(logicGate.lower() == 'q'):
   prog = 'n'
else:
   print("Invalid input. Please try again")

def toBool(s):
   if s == 'True':
      return True
   elif s == 'False':
      return False
   else:
      raise ValueError

def run(gate):
   print(gate.__name__ + " Gate function")
   print("Enter value for 'a'")
   valA = input()
   print("Enter value for 'b'")
   valB = input()
   print("Result: " + str(gate(toBool(valA), toBool(valB))))

And logic.py

def andGate(a, b):
   if(a and b):
      return True
   else:
      return False

def nandGate(a,b):
   if(a and b):
      return False
   else:
      return True

def orGate(a, b):
   if(a or b):
      return True
   else:
      return False

def norGate(a, b):
   if(a or b):
      return False
   else:
      return True

Body:
move your defs under imports and just remove the else: raise.... etc ect part... itnot used correctly.

import builtins
import logic

def toBool(s):
   if s == 'True':
      return True
   elif s == 'False':
      return False

def run(gate):
   print(gate.__name__ + " Gate function")
   print("Enter value for 'a'")
   valA = input()
   print("Enter value for 'b'")
   valB = input()
   print("Result: " + str(gate(toBool(valA), toBool(valB))))

print("Select a logic gate:")
print("1) AND")
print("2) NAND")
print("3) OR")
print("4) NOR")
print("Q) Quit Program")
logicGate = input()
if(int(logicGate) == 1):
   run(logic.andGate)
elif(int(logicGate) == 2):
   run(logic.nandGate)
elif(int(logicGate) == 3):
   run(logic.orGate)
elif(int(logicGate) == 4):
   run(logic.norGate)
elif(logicGate.lower() == 'q'):
   prog = 'n'
else:
   print("Invalid input. Please try again")


问:
Searching through nested list
```<code>from nltk import word_tokenize

list_1 = [a, b, c, d, e, f]
list_2 = [[aa, bb, cc], [dd, ee], [ff], [gg, hh, ii, jj], [kk, ll], [mm, nn, oo]]
text = 'The lazy aa moves along the hh'
text_token = word_tokenize(text)

for word in text:
     if word in [j for i in list_2 for j in i]:
        print(list_2.index(word))
     else:
        print(word)

ValueError: 'hh' is not in list
</code>```

I'm attempting textual analysis on large bodies of French text. I have already tried using the NLTK Stemmer and it doesn't stem a significant amount of words that I'm analyzing.

I'm not very familiar with python or any of the other coding languages (I'm coming from the Humanities) so I'm also not entirely sure as to how to search for the issue that I'm looking for, and I apologize in  if this question is either redundant or easily solved.

I've attempted to approach this by finding a list of French words with their various grammatical forms. I already complied the list into two separate lists: the first list contains the root of the word that I would like the others to take on, while the second list is the variant forms that the item in the first list can take on. I've made it so that both lists correspond to each other. For example, list_1[0] would correspond to the words in list_2[0]. As a result, there are a lot of nested lists of different lengths within list_2.

My issue seems to arise when I'm searching through nested lists. I have to iterate through text_token to check if any of the words in text_token exist in list_2. If text_token exists in list_2 then find misc = list_2.index(word) . After finding misc, I want to replace word with search list_1[misc]. However, after confirming that word exists in list_2, I try to print(list_2.index(word)) to see if it works, but i keep receiving ValueError: 'hh' is not in list I'm not entirely sure how to cycle through nested lists after already having done so in order to avoid this error, because I'm assuming that when I search through the definitions a second time, it doesn't see the nested list as multiple items. I've tried to circumvent this by trying another list comprehension after checking it in the original one, but it ends up returning individual letters. I've also tried making these two lists into a dictionary, but I can't seem to figure out how to yield .keys() from .values().

答:
You really just want a map, i.e. a dict. You can quickly munge your current data into a map using the following dict comprehension*:

```<code>rootmap = {var:root for root, variants in zip(list1, list2) for var in variants}
</code>```

Then you can use:

```<code>print(rootmap.get(word, word))
</code>```

This uses the .get method, which takes a second value as a default in case the first argument isn't found. As an aside, dict membership testing is much more efficient than checking a list, it is a constant time operation, whereas for a list membership tests are linear operations. This becomes more important if you are using this many times with many varients in list2.

*The equivalent can also be written using for-loops:

```<code>rootmap = {}
for root, variants in zip(list1, list2): # iterate over your lists in parallel
    for var in variants:
        rootmap[var] = root
</code>```

Caveat:

Read more about dicts in the documentation. Keep in mind, dicts map unique keys to values.

Title: Searching through nested list

Body:
from nltk import word_tokenize

list_1 = [a, b, c, d, e, f]
list_2 = [[aa, bb, cc], [dd, ee], [ff], [gg, hh, ii, jj], [kk, ll], [mm, nn, oo]]
text = 'The lazy aa moves along the hh'
text_token = word_tokenize(text)

for word in text:
     if word in [j for i in list_2 for j in i]:
        print(list_2.index(word))
     else:
        print(word)

ValueError: 'hh' is not in list

I'm attempting textual analysis on large bodies of French text. I have already tried using the NLTK Stemmer and it doesn't stem a significant amount of words that I'm analyzing.

I'm not very familiar with python or any of the other coding languages (I'm coming from the Humanities) so I'm also not entirely sure as to how to search for the issue that I'm looking for, and I apologize in  if this question is either redundant or easily solved.

I've attempted to approach this by finding a list of French words with their various grammatical forms. I already complied the list into two separate lists: the first list contains the root of the word that I would like the others to take on, while the second list is the variant forms that the item in the first list can take on. I've made it so that both lists correspond to each other. For example, list_1[0] would correspond to the words in list_2[0]. As a result, there are a lot of nested lists of different lengths within list_2.

My issue seems to arise when I'm searching through nested lists. I have to iterate through text_token to check if any of the words in text_token exist in list_2. If text_token exists in list_2 then find misc = list_2.index(word) . After finding misc, I want to replace word with search list_1[misc]. However, after confirming that word exists in list_2, I try to print(list_2.index(word)) to see if it works, but i keep receiving ValueError: 'hh' is not in list I'm not entirely sure how to cycle through nested lists after already having done so in order to avoid this error, because I'm assuming that when I search through the definitions a second time, it doesn't see the nested list as multiple items. I've tried to circumvent this by trying another list comprehension after checking it in the original one, but it ends up returning individual letters. I've also tried making these two lists into a dictionary, but I can't seem to figure out how to yield .keys() from .values().

Body:
You really just want a map, i.e. a dict. You can quickly munge your current data into a map using the following dict comprehension*:

rootmap = {var:root for root, variants in zip(list1, list2) for var in variants}

Then you can use:

print(rootmap.get(word, word))

This uses the .get method, which takes a second value as a default in case the first argument isn't found. As an aside, dict membership testing is much more efficient than checking a list, it is a constant time operation, whereas for a list membership tests are linear operations. This becomes more important if you are using this many times with many varients in list2.

*The equivalent can also be written using for-loops:

rootmap = {}
for root, variants in zip(list1, list2): # iterate over your lists in parallel
    for var in variants:
        rootmap[var] = root

Caveat:

Read more about dicts in the documentation. Keep in mind, dicts map unique keys to values.


问:
Use of unassigned local variable after going through a list
```<code>List <State> states = JsonConvert.DeserializeObject <List<State>> (json);

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    }
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}
</code>```

"state" in "state.Actions.Approved.NextStateID != null ? true : false;" is giving the "use of unassigned local variable" even though it assigned.

答:
What if states doesn't have anything in it? state might not be populated.

maybe something like:

```<code>List < State > states = JsonConvert.DeserializeObject < List < State >> (json);

if(!states.Any())
    return;

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    }
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}
</code>```

Body:
List <State> states = JsonConvert.DeserializeObject <List<State>> (json);

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    }
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}

"state" in "state.Actions.Approved.NextStateID != null ? true : false;" is giving the "use of unassigned local variable" even though it assigned.

Body:
What if states doesn't have anything in it? state might not be populated.

maybe something like:

List < State > states = JsonConvert.DeserializeObject < List < State >> (json);

if(!states.Any())
    return;

State state;
foreach(State i in states) {
if (i.StateID == Convert.ToInt32(extendedProperties["WFState"])) {
    state = i;
    }
else {}
}

try {
    btnApprove.Visible = state.Actions.Approved.NextStateID != null ? true : false;
    btnApprove.Text = state.Actions.Approved.Title.ToString();
}
catch (Exception ex) {
    btnApprove.Visible = false;
}


问:
Oracle/PLSQL performance tips
I living problem in my query. When i add ROUND and DECODE query takes too long time but when i delete directly return value. When i search for sql advice no any advice. How i can fix this 2 syntax ?

```<code>SELECT I.*,
Q.INVOICE_DATE,
Q.SERIES_ID IFS_SERIES_ID,
Q.INVOICE_NO,
Q.IDENTITY,
Q.IDENTITY_NAME,
Q.ASSOCIATION_NO,
Q.NET_CURR_AMOUNT,
Q.VAT_CURR_AMOUNT,
Q.TOTAL_CURR_AMOUNT,
Q.CURRENCY_CODE,
ROUND(Q.CURR_RATE,:"SYS_B_0") CURR_RATE,
Q.PROFILE_ID DEFAULT_PROFILE_ID,
X.XML_CONTENT,
DECODE(NVL(DBMS_LOB.INSTR(X.XML_CONTENT,:"SYS_B_1",:"SYS_B_2",:"SYS_B_3"), :"SYS_B_4"), :"SYS_B_5",:"SYS_B_6", :"SYS_B_7") SINGED_UBL,
X.SCHEMATRON_RESULT,
q.SHIPMENT_ID,
APP.TBN_UTILITY_API.GET_NUMBER(I.COMPANY, I.INVOICE_ID) DESPATCH_REFERENCE,
X.OBJID XML_OBJID,
X.OBJVERSION XML_OBJVERSION,
APP.API_MODULE.GET_DESC(I.MODULE_ID) MODULE_NAME
FROM APP.TREF_INVOICE I,
APP.TREF_INVOICE_INFO_QRY Q,
APP.TREF_XML_ARCHIVE X
WHERE Q.COMPANY = I.COMPANY
AND Q.INVOICE_ID = I.INVOICE_ID
AND X.XML_ARCHIVE_ID(+) = I.XML_ARCHIVE_ID
AND I.COMPANY = :COMPANY
AND I.INVOICE_ID = :INVOICE_ID
</code>```

答:
You should trace one or more executions of each statement to see exactly what it does. When you profile the trace data you will know what to do.

```<code>SQL> select value from v$diag_info where name = 'Default Trace File'/* name of the trace file */;
SQL> exec dbms_monitor.session_trace_enable(null, null, true, false, 'all_executions')
SQL> your query executed under normal circumstances
SQL> exec dbms_monitor.session_trace_disable(null, null)
</code>```

Title: Oracle/PLSQL performance tips

Body:
I living problem in my query. When i add ROUND and DECODE query takes too long time but when i delete directly return value. When i search for sql advice no any advice. How i can fix this 2 syntax ?

SELECT I.*,
Q.INVOICE_DATE,
Q.SERIES_ID IFS_SERIES_ID,
Q.INVOICE_NO,
Q.IDENTITY,
Q.IDENTITY_NAME,
Q.ASSOCIATION_NO,
Q.NET_CURR_AMOUNT,
Q.VAT_CURR_AMOUNT,
Q.TOTAL_CURR_AMOUNT,
Q.CURRENCY_CODE,
ROUND(Q.CURR_RATE,:"SYS_B_0") CURR_RATE,
Q.PROFILE_ID DEFAULT_PROFILE_ID,
X.XML_CONTENT,
DECODE(NVL(DBMS_LOB.INSTR(X.XML_CONTENT,:"SYS_B_1",:"SYS_B_2",:"SYS_B_3"), :"SYS_B_4"), :"SYS_B_5",:"SYS_B_6", :"SYS_B_7") SINGED_UBL,
X.SCHEMATRON_RESULT,
q.SHIPMENT_ID,
APP.TBN_UTILITY_API.GET_NUMBER(I.COMPANY, I.INVOICE_ID) DESPATCH_REFERENCE,
X.OBJID XML_OBJID,
X.OBJVERSION XML_OBJVERSION,
APP.API_MODULE.GET_DESC(I.MODULE_ID) MODULE_NAME
FROM APP.TREF_INVOICE I,
APP.TREF_INVOICE_INFO_QRY Q,
APP.TREF_XML_ARCHIVE X
WHERE Q.COMPANY = I.COMPANY
AND Q.INVOICE_ID = I.INVOICE_ID
AND X.XML_ARCHIVE_ID(+) = I.XML_ARCHIVE_ID
AND I.COMPANY = :COMPANY
AND I.INVOICE_ID = :INVOICE_ID

Body:
You should trace one or more executions of each statement to see exactly what it does. When you profile the trace data you will know what to do.

SQL> select value from v$diag_info where name = 'Default Trace File'/* name of the trace file */;
SQL> exec dbms_monitor.session_trace_enable(null, null, true, false, 'all_executions')
SQL> your query executed under normal circumstances
SQL> exec dbms_monitor.session_trace_disable(null, null)


问:
How can I cancel a ProgressBar?
So, I have switched to using a ProgressBar from ProgressDialog and I don't find now any method to make the ProgressBar cancellable meaning if I click anywhere outside the ProgressBar's view area, it will dismiss and also I want to attach a listener to it so that I am able to execute some code when it does get canceled.

This ProgressBar is the simplest, indeterminate, non-customized one, I have:

```<code><ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>
</code>```

How can I achieve the above?

答:
At top most(Parent)layout.Apply OnTouchListener ,and put this line  </p>

```<code>progressBar.setVisibility(View.GONE);
</code>```

Title: How can I cancel a ProgressBar?

Body:
So, I have switched to using a ProgressBar from ProgressDialog and I don't find now any method to make the ProgressBar cancellable meaning if I click anywhere outside the ProgressBar's view area, it will dismiss and also I want to attach a listener to it so that I am able to execute some code when it does get canceled.

This ProgressBar is the simplest, indeterminate, non-customized one, I have:

<ProgressBar
        android:id="@+id/search_tutors_progress_bar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

How can I achieve the above?

Body:
At top most(Parent)layout.Apply OnTouchListener ,and put this line

progressBar.setVisibility(View.GONE);


答:
change your css file to this:</p>

```<code>body {
   background-color: lightblue;
}
</code>```

Body:
I'm a real noob at CSS/HTML, so please forgive me.

I tried to change the background page color on the CSS file linked to my html file, and it doesn't work. Whereas when I just flat out change it between the style tags in my HTML file, it works. What gives?

Plain and simple:

Ex1.css

SamplePage.html

<!doctype html>

    <title> Sample Page </title>
    <link rel = "stylesheet" href="Ex1.css">

      Hello. This is a sample Page.

Body:
change your css file to this:

body {
   background-color: lightblue;
}


问:
Using Number::Phone to validate and format
I'm trying to use Number::Phone from CPAN to accomplish 2 tasks:

Validate a Phone Number; and

Format the number in E.164 Notation.

However, I'm unable to figure out how it works. My sample code is:

#!/usr/bin/perl -w
use strict;
use warnings;
use Number::Phone;

foreach my $fnum ( '17888888', '97338888888', '00923455555333', '+97366767777' , '38383838') {
    my $phone = Number::Phone->new($fnum);
    my $norm = "";
    eval {
        $norm = $phone->format_using('E123'); # or 'Raw'
        print "E164 => '$norm'\n";
    } or do {
        print STDERR "Unable to parse '$fnum'\n";
    }
}
```

<p>Expected output:</p>

<pre class="lang-sh prettyprint-override"><code>E164 => '+97317888888'
E164 => '+97338888888'
E164 => '+923455555333'
E164 => '+97366767777'
E164 => '+97338383838'
</code>```

But the results were incorrect. I tried using Number::Phone::Normalize, but still not successful:

#!/usr/bin/perl -w
use strict;
use warnings;
use Number::Phone::Normalize;

my %params = (
    'CountryCode'=>'973',
    'IntlPrefix' =>'00',
    'CountryCodeOut'=>'973',
    'IntlPrefixOut' => '+',
    );
my $nlz = Number::Phone::Normalize->new( %params );

foreach my $number ('17888888', '97338888888', '00923455555333', '+97366767777' , '38383838') {
    my $e164 = $nlz->intl( $number );
    print "E164 => '$e164'\n";
}
```

<p>with the same expected output of:
</p>

```E164 => '+97317888888'
E164 => '+97338888888'
E164 => '+923455555333'
E164 => '+97366767777'
E164 => '+97338383838'
```

<p>However, this produced the wrong results too. The snippet Java code below works perfectly, and it's what I'm trying to achieve in Perl.</p>

<pre class="lang-java prettyprint-override"><code>// Uses libphonenumber: http://code.google.com/p/libphonenumber/
// setenv CLASSPATH .:libphonenumber-8.5.2.jar

// libphonenumber
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;

public class ValidateList {
    public static void main(String[] args) {
        try {
            if (args.length != 1) {
                throw new IllegalArgumentException("Invalid number of arguments.");
            }

            String file = args[0];
            PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

            try (java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader(file))) {
                String line = null;
                while ((line = br.readLine()) != null) {

                    try {
                        PhoneNumber phoneNumber = phoneUtil.parse(line, "BH");
                        boolean isValid = phoneUtil.isValidNumber(phoneNumber);
                        if (isValid) {
                            System.out.println( "E164 => " + phoneUtil.format(phoneNumber, PhoneNumberFormat.E164) );
                        }
                        else {
                            System.err.println( "Invalid => " + line);
                        }
                    }
                    catch (NumberParseException e) {
                        System.err.println("NumberParseException for ("+line+"): " + e.toString());
                    }

                }
            }

        }
        catch (Exception e) {
            System.err.println(e);
            System.err.println("Usage: java ValidateList <fileNameWithPhoneNumbers>");
        }
    }
}
</code>```

% cat input.txt
17888888
97338888888
00923455555333
+97366767777
38383838

% javac -cp libphonenumber-8.5.2.jar ValidateList.java

% java -cp .:libphonenumber-8.5.2.jar ValidateList input.txt
E164 => +97317888888
E164 => +97338888888
E164 => +923455555333
E164 => +97366767777
E164 => +97338383838
```

Your input is greatly appreciated.

答:
When I run the first example code for the numbers, two of those fail to be parsed:

17888888 - this is obvious, when calling Number::Phone without a country code, this will not be parsed as it's unclear what country this is from

00923455555333 - 923 is, according to a quick google search, the country code for Pakistan. The Wikipedia page for dialing codes in Pakistan shows no 455, leading me to think that this is not a known area code to either Number::Phone or Wikipedia. I suspect it is an invalid number.

So for the first Number: specify which country this is supposed to be from.

If you are certain the other number is correct, you know more about that than the developer of Number::Phone currently and I'm sure he'd be happy to receive your input in the form of a more complete Number::Phone localized package.

The fact that your Java code accepts the (probably) invalid number does not necessarily mean it is more correct, just that it is less picky in what it declares to be a correct number.

Edit:

Asking Phone::Number to parse the input '+923455555333' instead of '00923455555333' leads to the desired output.

Looking at the source of Phone::Number:

```<code># ... processing input arguments
$number = "+$number" unless($number =~ /^\+/);
</code>```

It becomes clear that the 00 is interpreted as '+00' and then rejected as being an invalid number.
View some discussion on that here

It seems to me you will have to handle this yourself.
One way may be to simply replace leading 00 with '+' - preferably only if parsing failed.

The other number can be parsed if you make it clear what country it should belong to.

Perhaps like so:

```<code>my $phone = Number::Phone->new($fnum);
unless ($phone){
    $phone = Number::Phone->new('BH',$fnum);
    if ( !$phone && $fnum =~ s/^00/+/ ){
        # You should probably check the discussion I linked.
        # There may well be problems with this approach!
        $phone = Number::Phone->new($fnum);
    }
}
</code>```

Body:
I'm trying to use Number::Phone from CPAN to accomplish 2 tasks:

Validate a Phone Number; and

Format the number in E.164 Notation.

However, I'm unable to figure out how it works. My sample code is:

#!/usr/bin/perl -w
use strict;
use warnings;
use Number::Phone;

foreach my $fnum ( '17888888', '97338888888', '00923455555333', '+97366767777' , '38383838') {
    my $phone = Number::Phone->new($fnum);
    my $norm = "";
    eval {
        $norm = $phone->format_using('E123'); # or 'Raw'
        print "E164 => '$norm'\n";
    } or do {
        print STDERR "Unable to parse '$fnum'\n";
    }
}

Expected output:

E164 => '+97317888888'
E164 => '+97338888888'
E164 => '+923455555333'
E164 => '+97366767777'
E164 => '+97338383838'

But the results were incorrect. I tried using Number::Phone::Normalize, but still not successful:

#!/usr/bin/perl -w
use strict;
use warnings;
use Number::Phone::Normalize;

my %params = (
    'CountryCode'=>'973',
    'IntlPrefix' =>'00',
    'CountryCodeOut'=>'973',
    'IntlPrefixOut' => '+',
    );
my $nlz = Number::Phone::Normalize->new( %params );

foreach my $number ('17888888', '97338888888', '00923455555333', '+97366767777' , '38383838') {
    my $e164 = $nlz->intl( $number );
    print "E164 => '$e164'\n";
}

with the same expected output of:

E164 => '+97317888888'
E164 => '+97338888888'
E164 => '+923455555333'
E164 => '+97366767777'
E164 => '+97338383838'

However, this produced the wrong results too. The snippet Java code below works perfectly, and it's what I'm trying to achieve in Perl.

// Uses libphonenumber: http://code.google.com/p/libphonenumber/
// setenv CLASSPATH .:libphonenumber-8.5.2.jar

// libphonenumber
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;

public class ValidateList {
    public static void main(String[] args) {
        try {
            if (args.length != 1) {
                throw new IllegalArgumentException("Invalid number of arguments.");
            }

            String file = args[0];
            PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();

            try (java.io.BufferedReader br = new java.io.BufferedReader(new java.io.FileReader(file))) {
                String line = null;
                while ((line = br.readLine()) != null) {

                    try {
                        PhoneNumber phoneNumber = phoneUtil.parse(line, "BH");
                        boolean isValid = phoneUtil.isValidNumber(phoneNumber);
                        if (isValid) {
                            System.out.println( "E164 => " + phoneUtil.format(phoneNumber, PhoneNumberFormat.E164) );
                        }
                        else {
                            System.err.println( "Invalid => " + line);
                        }
                    }
                    catch (NumberParseException e) {
                        System.err.println("NumberParseException for ("+line+"): " + e.toString());
                    }

                }
            }

        }
        catch (Exception e) {
            System.err.println(e);
            System.err.println("Usage: java ValidateList <fileNameWithPhoneNumbers>");
        }
    }
}

% cat input.txt
17888888
97338888888
00923455555333
+97366767777
38383838

% javac -cp libphonenumber-8.5.2.jar ValidateList.java

% java -cp .:libphonenumber-8.5.2.jar ValidateList input.txt
E164 => +97317888888
E164 => +97338888888
E164 => +923455555333
E164 => +97366767777
E164 => +97338383838

Your input is greatly appreciated.

Body:
When I run the first example code for the numbers, two of those fail to be parsed:

17888888 - this is obvious, when calling Number::Phone without a country code, this will not be parsed as it's unclear what country this is from

00923455555333 - 923 is, according to a quick google search, the country code for Pakistan. The Wikipedia page for dialing codes in Pakistan shows no 455, leading me to think that this is not a known area code to either Number::Phone or Wikipedia. I suspect it is an invalid number.

So for the first Number: specify which country this is supposed to be from.

If you are certain the other number is correct, you know more about that than the developer of Number::Phone currently and I'm sure he'd be happy to receive your input in the form of a more complete Number::Phone localized package.

The fact that your Java code accepts the (probably) invalid number does not necessarily mean it is more correct, just that it is less picky in what it declares to be a correct number.

Edit:

Asking Phone::Number to parse the input '+923455555333' instead of '00923455555333' leads to the desired output.

Looking at the source of Phone::Number:

# ... processing input arguments
$number = "+$number" unless($number =~ /^\+/);

It becomes clear that the 00 is interpreted as '+00' and then rejected as being an invalid number.
View some discussion on that here

It seems to me you will have to handle this yourself.
One way may be to simply replace leading 00 with '+' - preferably only if parsing failed.

The other number can be parsed if you make it clear what country it should belong to.

Perhaps like so:

my $phone = Number::Phone->new($fnum);
unless ($phone){
    $phone = Number::Phone->new('BH',$fnum);
    if ( !$phone && $fnum =~ s/^00/+/ ){
        # You should probably check the discussion I linked.
        # There may well be problems with this approach!
        $phone = Number::Phone->new($fnum);
    }
}


问:
MVC Why unit test controllers
just a Provocative Question

why do you thing we should unit test controllers in MVC why not just write test against models or service layer.

答:
A good example should be this one (in BDD-style):

Given the user 'snehal' does not exists

When I create a new user with credentials 'snehal' and 'so@123'

And I log in with this user

Then I should see a welcome page

This scenario is expecting that new user should see a welcome page when they log in for the first time. At least for me, this is the Controller's job and is a nice feature that I would like to make sure it is works.

Title: MVC Why unit test controllers


问:
Network centric application
Javascript is said to be designed for creating network-centric applications.

from my readings, network-centric applications are applications that send data to the server and are interconnected by a communications network.

Can you explain what the term network-centric application mean?

答:
Facebook would be a perfect example. Sure it falls under the category of social network as well, but from a tech standpoint it's a very large network-centric application.

It not only connects people with each other but through things like push notifications, synchronization, being able to use multiple devices, etc., it is a comprehensive network-centric app.

Title: Network centric application