问:
Cannot find symbol - integer
I'm learning Java and searched this error, which is very common.  But I cannot find the solution.  I'm trying to re-use the result of finalScore, but no matter how I declare it or where I place it, IntelliJ does not recognize it.  I know I'm missing something fundamentally obvious here.  How can I declare the integers so that they can be re-used in different methods?  Anywhere outside of the gameOver method is a problem.  I also tried public static int finalScore but that also threw error.  And calculateScore.finalScore but still error.

```<code>package com.test;

public class Main {

    public static void main(String[] args) {
        // write your code here

        calculateScore(true, 5, 5, 200, "sam");
        calculateScore(true, 5, 8, 200, "bob");
    }

    public static void displayHighScore(){

        if (finalScore > 100);           //problem line of code
        System.out.println("helloworld");
    }

    public static int calculateScore(boolean gameOver, int score, int levelCompleted, int bonus, String name) {

        if (gameOver) {
            int finalScore = score + (levelCompleted * bonus);
            finalScore += 2000;
            System.out.println("your final score was " + finalScore);
            return finalScore;

            if ((finalScore > 100) || (finalScore < 200));
            System.out.println( name "is in position 4");

        }
        return -1;    //if the above isn't required/doesn't run, this statement is:  else return -1
        //or we can just type is as } else { return -1;

        }
    }
</code>```

答:
There are lots of problems in your code here. But for what you mentioned as the issue, you need to declare finalScore as global static variable as below

```<code>...
    static int finalScore;

    public static void main(String[] args) {
        // write your code here

        calculateScore(true, 5, 5, 200, "sam");
        calculateScore(true, 5, 8, 200, "bob");
    }
...
</code>```

Also, you need to put the return finalScore statement at the end of the if(gameOver) block as below or you will get not reachable error for line if ((finalScore > 100) || (finalScore < 200));

```<code>if (gameOver) {
            finalScore = score + (levelCompleted * bonus);
            finalScore += 2000;
            System.out.println("your final score was " + finalScore);

            if ((finalScore > 100) || (finalScore < 200));
                System.out.println( name +"is in position 4");
            return finalScore;

        }
</code>```

Title: Cannot find symbol - integer

Body:
I'm learning Java and searched this error, which is very common.  But I cannot find the solution.  I'm trying to re-use the result of finalScore, but no matter how I declare it or where I place it, IntelliJ does not recognize it.  I know I'm missing something fundamentally obvious here.  How can I declare the integers so that they can be re-used in different methods?  Anywhere outside of the gameOver method is a problem.  I also tried public static int finalScore but that also threw error.  And calculateScore.finalScore but still error.

package com.test;

public class Main {

    public static void main(String[] args) {
        // write your code here

        calculateScore(true, 5, 5, 200, "sam");
        calculateScore(true, 5, 8, 200, "bob");
    }

    public static void displayHighScore(){

        if (finalScore > 100);           //problem line of code
        System.out.println("helloworld");
    }

    public static int calculateScore(boolean gameOver, int score, int levelCompleted, int bonus, String name) {

        if (gameOver) {
            int finalScore = score + (levelCompleted * bonus);
            finalScore += 2000;
            System.out.println("your final score was " + finalScore);
            return finalScore;

            if ((finalScore > 100) || (finalScore < 200));
            System.out.println( name "is in position 4");

        }
        return -1;    //if the above isn't required/doesn't run, this statement is:  else return -1
        //or we can just type is as } else { return -1;

        }
    }

Body:
There are lots of problems in your code here. But for what you mentioned as the issue, you need to declare finalScore as global static variable as below

...
    static int finalScore;

    public static void main(String[] args) {
        // write your code here

        calculateScore(true, 5, 5, 200, "sam");
        calculateScore(true, 5, 8, 200, "bob");
    }
...

Also, you need to put the return finalScore statement at the end of the if(gameOver) block as below or you will get not reachable error for line if ((finalScore > 100) || (finalScore < 200));

if (gameOver) {
            finalScore = score + (levelCompleted * bonus);
            finalScore += 2000;
            System.out.println("your final score was " + finalScore);

            if ((finalScore > 100) || (finalScore < 200));
                System.out.println( name +"is in position 4");
            return finalScore;

        }


来源: stackexchange

问:
getting ExpressionChangedAfterItHasBeenCheckedError Angular 4
Im aware similar questions exist but none of those have provided me with an answer that works..

Basically I have a site with some services that inject data dynamically

In my app.component.ts I have two headers.. one when your on the home page and one for when your on any other page

app.component.html

```<code><app-header *ngIf="router.url !== '/'"></app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home>
<router-outlet></router-outlet>
<app-footer></app-footer>
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  router: string;

  constructor(
    private _router: Router
  ) {
       this.router = _router.url;
  }
}
</code>```

now I also have a service that dynamically injects the title of the header

headerTitle.service.ts

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: any) {
  this.title.next(title);
  }
}
</code>```

then In my home component for example I set the title

home.component.ts

```<code>import { Component, OnInit, AfterViewInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
import { HeaderImageService } from '../../services/headerImage.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService,
    private headerImageService: HeaderImageService
  ) { }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.headerTitleService.setTitle(`
    We strive to create things
    <br> that are engaging, progressive
    <br> & above all
    <span class="highlight">
    <em>innovative.</em>
    </span>
  `);
 }

}
</code>```

now basically it was all working until I put in the if statements on the two headers

now Im getting this error

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '
    We strive to create things

 that are engaging, progressive

 & above all

    innovative.

  '.

not sure how I can fix this.. I tried setting the values in ngAfterViewInit but it did nothing

or does anyone know another way I could accomplish this??

Thanks

答:
I know i fixed this in mine.

here is a great post

everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror

i have forced the change detection

```<code>export class AppComponent {
name = 'I am A component';
text = 'A message for the child component';

constructor(private cd: ChangeDetectorRef) {
}

ngAfterViewInit() {
    this.cd.detectChanges();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im aware similar questions exist but none of those have provided me with an answer that works..

Basically I have a site with some services that inject data dynamically

In my app.component.ts I have two headers.. one when your on the home page and one for when your on any other page

app.component.html

<app-header *ngIf="router.url !== '/'"></app-header>
<app-header-home *ngIf="router.url != '/'"></app-header-home>
<router-outlet></router-outlet>
<app-footer></app-footer>

app.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'app';
  router: string;

  constructor(
    private _router: Router
  ) {
       this.router = _router.url;
  }
}

now I also have a service that dynamically injects the title of the header

headerTitle.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class HeaderTitleService {
  title = new BehaviorSubject('');

  constructor() { }

  setTitle(title: any) {
  this.title.next(title);
  }
}

then In my home component for example I set the title

home.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { HeaderTitleService } from '../../services/headerTitle.service';
import { HeaderImageService } from '../../services/headerImage.service';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(
    private headerTitleService: HeaderTitleService,
    private headerImageService: HeaderImageService
  ) { }

  ngOnInit() {

  }

  ngAfterViewInit() {
    this.headerTitleService.setTitle(`
    We strive to create things

 that are engaging, progressive

 & above all

    innovative.

  `);
 }

}

now basically it was all working until I put in the if statements on the two headers

now Im getting this error

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '
    We strive to create things

 that are engaging, progressive

 & above all

    innovative.

  '.

not sure how I can fix this.. I tried setting the values in ngAfterViewInit but it did nothing

or does anyone know another way I could accomplish this??

Thanks

Body:
I know i fixed this in mine.

here is a great post

everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror

i have forced the change detection

export class AppComponent {
name = 'I am A component';
text = 'A message for the child component';

constructor(private cd: ChangeDetectorRef) {
}

ngAfterViewInit() {
    this.cd.detectChanges();
}


问:
get UIView's viewcontroller (iphone)
I've done this to get the view:

```<code>[self.superview viewWithTag:10]
</code>```

But how can I get that view's viewcontroller. Just like you can get the the viewcontroller's view I want to go the other way so I can send a message (call a method) to that viewcontroller. eg:

```<code>[[self.superview viewWithTag:10].viewController doSomething];
</code>```

(obviously that not actual code but I want something like that)

答:
You can use the -nextResponder method to do it:

```<code>[(YourUIViewController *)[[self.superview viewWithTag:10] nextResponder] doSomething];
</code>```

According to http://developer.apple.com/library/ios/documentation/uikit/reference/UIResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/UIResponder/nextResponder , "UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn’t)"

ContentLicense: CC BY-SA 2.5

Title: get UIView's viewcontroller (iphone)

Body:
I've done this to get the view:

[self.superview viewWithTag:10]

But how can I get that view's viewcontroller. Just like you can get the the viewcontroller's view I want to go the other way so I can send a message (call a method) to that viewcontroller. eg:

[[self.superview viewWithTag:10].viewController doSomething];

(obviously that not actual code but I want something like that)

Body:
You can use the -nextResponder method to do it:

[(YourUIViewController *)[[self.superview viewWithTag:10] nextResponder] doSomething];

According to http://developer.apple.com/library/ios/documentation/uikit/reference/UIResponder_Class/Reference/Reference.html#//apple_ref/occ/instm/UIResponder/nextResponder , "UIView implements this method by returning the UIViewController object that manages it (if it has one) or its superview (if it doesn’t)"


问:
Why does the JS code prevent the hyperlinks from working?
I have created a HTML accordion using HTML,CSS and JS. The hyperlinks I have added to the HTML list do not work. I assume something is wrong with the JS that prevents the hyperlinks from working but don't know what went wrong.

below is the html list

```<code><div class="container">
    <div class="acc">
        <dl>
            <dt><a class="acc_title" href="#">Business Intelligence</a></dt>
            <dd class="acc_panel acc_panel_col">
                <ul>
                    <li><a href="https://teams.connect.te.com/sites/ebs/bi/pages/home.aspx">TED 1.0-Cognos</a></li>
                    <li><a href="https://businessobjects.us.tycoelectronics.com/BOE/BI/">TED 2.0-SAP Business Objects</a></li>
                </ul>
                </p>
            </dd>
            <dt><a href="#" class="acc_title">Insights</a></dt>
            <dd class="acc_panel acc_panel_col">
            <ul>
                <li><a href="https://teams.connect.te.com/sites/Insights/pages/home.aspx">Big Data analytics</a></li>

            </ul>
        </dd>
        <dt><a href="#" class="acc_title">Finance</a></dt>
        <dd class="acc_panel acc_panel_col">
            <ul>
                <li><a href="http://tebit.us.tycoelectronics.com/default.aspx">TEBIT:Project savings tracker</a></li>
                <li><a href="http://fmd.tycoelectronics.com/RateInquiry.aspx">TE Currency Exchange rates</a></li>
            </ul>
        </dd>
        <dt><a href="#" class="acc_title">Supply Chain</a></dt>
        <dd class="acc_panel acc_panel_col">
            <h3>Materials</h3>
            <ul>
                <li><a href="http://cpr/">Central Part Registry(CPR)</a></li>
                <li><a href="https://bomnavigator.tycoelectronics.com/TECbca/view.faces
http://dcms/main_page.aspx">Bill of material navigator</a></li>
            </ul>
            <h3>Locations</h3>
            <ul>
                <li><a href="http://dcms/main_page.aspx">DC Management System</a></li>
                <li><a href="http://supplynetwork.tycoelectronics.com/global/gsc/footprint.do">TE Locations</a></li>
            </ul>
            <h3>Freight</h3>
            <ul>
                <li><a href="http://qlikview/qlikView/">TMS information: Qlikview</a></li>
                <li><a href="http://cognos/cognos/cgi-bin/cognosisapi.dll?b_action=xts.run&m=portal/welcome/welcome.xts
">Carrier information: Cognos Freight forwarder shipments</a></li>
            </ul>
        </dd>
        <dt><a href="#" class="acc_title">SAP Reports</a></dt>
        <dd class="acc_panel acc_panel_col">
            <h3>Inbound</h3>
            <ul>
                <li>Vendor master: ZMM3TR046</li>
                <li>Inbound lead times (ZTDY): ZMM3TR075</li>
                <li>Cartons received by BU: ZMM3TR839</li>
                <li>Dock to Stock time: ZMM4TR083</li>
            </ul>
            <h3>Warehouse</h3>
            <ul>
                <li>Warehouse occupation: LX04</li>
                <li>Bin Occupations by profit center: ZMM4TR004</li>
                <li>Weights and Volumes (ZZAPQ): ZSD4TR260</li>
                <li>Location – material touches: MB51</li>
                <li>Warehouse troughput time: ZSD4TR058</li>
            </ul>

            <h3>outbound</h3>
                <ul>
                    <li>Customer master: ZSD5TR038</li>
                    <li>Customer partner listing: ZSD4TR218</li>
                    <li>Shipment report: ZSD3TR008N</li>
                    <li>Routes and route determination: ZSD4TR612</li>
                    <li>Shipping performance: ZSD3TR028</li>
                    <li>Carrier determination (ZV14): ZSD4TR407</li>
                </ul>

                <h3>Freight</h3>
                <ul>
                    <li>Premium Freight: ZSD4TR708</li>
                    <li>Freight payments: ZFI2TI305</li>
                </ul>
            </dd>
        </dl>
     </div>
 </div>
</code>```

below is the JS code

```<code><script type="text/javascript">
/*!
 * classie - class helper functions
 * from bonzo https://github.com/ded/bonzo
 */

(function(window) {
  "use strict";

  // class helper functions from bonzo https://github.com/ded/bonzo

  function classReg(className) {
    return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
  }

  // classList support for class management
  // altho to be fair, the api sucks because it won't accept multiple classes at once
  var hasClass, addClass, removeClass;

  if ("classList" in document.documentElement) {
    hasClass = function(elem, c) {
      return elem.classList.contains(c);
    };
    addClass = function(elem, c) {
      elem.classList.add(c);
    };
    removeClass = function(elem, c) {
      elem.classList.remove(c);
    };
  } else {
    hasClass = function(elem, c) {
      return classReg(c).test(elem.className);
    };
    addClass = function(elem, c) {
      if (!hasClass(elem, c)) {
        elem.className = elem.className + " " + c;
      }
    };
    removeClass = function(elem, c) {
      elem.className = elem.className.replace(classReg(c), " ");
    };
  }

  function toggleClass(elem, c) {
    var fn = hasClass(elem, c) ? removeClass : addClass;
    fn(elem, c);
  }

  var classie = {
    // full names
    hasClass: hasClass,
    addClass: addClass,
    removeClass: removeClass,
    toggleClass: toggleClass,
    // short names
    has: hasClass,
    add: addClass,
    remove: removeClass,
    toggle: toggleClass
  };

  // transport
  if (typeof define === "function" && define.amd) {
    // AMD
    define(classie);
  } else {
    // browser global
    window.classie = classie;
  }
})(window);

//fake jQuery
var $ = function(selector) {
  return document.querySelector(selector);
};
var accordion = $(".acc");

//add event listener to all anchor tags with accordion title class
accordion.addEventListener("click", function(e) {
  e.stopPropagation();
  e.preventDefault();
  if (e.target && e.target.nodeName == "A") {
    var classes = e.target.className.split(" ");
    if (classes) {
      for (var x = 0; x < classes.length; x++) {
        if (classes[x] == "acc_title") {
          var title = e.target;

          //next element sibling needs to be tested in IE8+ for any crashing problems
          var content = e.target.parentNode.nextElementSibling;

          //use classie to then toggle the active class which will then open and close the accordion

          classie.toggle(title, "acc_title_active");
          //this is just here to allow a custom animation to treat the content
          if (classie.has(content, "acc_panel_col")) {
            if (classie.has(content, "anim_out")) {
              classie.remove(content, "anim_out");
            }
            classie.add(content, "anim_in");
          } else {
            classie.remove(content, "anim_in");
            classie.add(content, "anim_out");
          }
          //remove or add the collapsed state
          classie.toggle(content, "acc_panel_col");
        }
      }
    }
  }
});
</script>
</code>```

答:
Move these two lines:

```<code>e.stopPropagation();
e.preventDefault();
</code>```

from here:

```<code>accordion.addEventListener("click", function(e) {
  e.stopPropagation();
  e.preventDefault();
</code>```

to here:

```<code>if (classes) {
  for (var x = 0; x < classes.length; x++) {
    if (classes[x] == "acc_title") {
      e.stopPropagation();
      e.preventDefault();
</code>```

This e.preventDefault(); is preventing the  tag from doing its default operation, which is to navigate to a new page.

You only want that to happen in you are clicking on the correct things and not on anything.

Body:
I have created a HTML accordion using HTML,CSS and JS. The hyperlinks I have added to the HTML list do not work. I assume something is wrong with the JS that prevents the hyperlinks from working but don't know what went wrong.

below is the html list

Business Intelligence

TED 1.0-Cognos

TED 2.0-SAP Business Objects

Insights

Big Data analytics

Finance

TEBIT:Project savings tracker

TE Currency Exchange rates

Supply Chain

Materials

Central Part Registry(CPR)

Bill of material navigator

Locations

DC Management System

TE Locations

Freight

TMS information: Qlikview

Carrier information: Cognos Freight forwarder shipments

SAP Reports

Inbound

Vendor master: ZMM3TR046

Inbound lead times (ZTDY): ZMM3TR075

Cartons received by BU: ZMM3TR839

Dock to Stock time: ZMM4TR083

Warehouse

Warehouse occupation: LX04

Bin Occupations by profit center: ZMM4TR004

Weights and Volumes (ZZAPQ): ZSD4TR260

Location – material touches: MB51

Warehouse troughput time: ZSD4TR058

outbound

Customer master: ZSD5TR038

Customer partner listing: ZSD4TR218

Shipment report: ZSD3TR008N

Routes and route determination: ZSD4TR612

Shipping performance: ZSD3TR028

Carrier determination (ZV14): ZSD4TR407

Freight

Premium Freight: ZSD4TR708

Freight payments: ZFI2TI305

below is the JS code

Body:
Move these two lines:

e.stopPropagation();
e.preventDefault();

from here:

accordion.addEventListener("click", function(e) {
  e.stopPropagation();
  e.preventDefault();

to here:

if (classes) {
  for (var x = 0; x < classes.length; x++) {
    if (classes[x] == "acc_title") {
      e.stopPropagation();
      e.preventDefault();

This e.preventDefault(); is preventing the <a> tag from doing its default operation, which is to navigate to a new page.

You only want that to happen in you are clicking on the correct things and not on anything.


问:
How to show dialog/popup application in kill state?
I want to show dialog/popup when application in kill state and BroadcastReceiver receive any action.

MyReceiver.java

```<code>public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
       MyDialog.showDialog(context);
   }
}
</code>```

I have added permission in manifest.

```<code><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</code>```

I am getting exception when activity foreground

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

style.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

My dialog is not display in activity kill state but receiver is called.

答:
Actually, in this case, or without an activity, you can't launch any kind of dialog.

1. First method

create a dialog activity : How to make dialog activity

2. Second

create popup window: How to make a simple android popup window?

Edit

If the application is not in the foreground, please don't do this. Go for notification

Body:
I want to show dialog/popup when application in kill state and BroadcastReceiver receive any action.

MyReceiver.java

public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
       MyDialog.showDialog(context);
   }
}

I have added permission in manifest.

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

I am getting exception when activity foreground

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

style.xml

My dialog is not display in activity kill state but receiver is called.


问:
localStorage not working for all fields in html5?
Hi guys im working on codeigniter project and on ane of my form i am using localstorage to store selected values and display after page  load.
But somehow its not working for all my fields.
Sometimes first value get works sometimes last value works.
I have total 4 fields and all values should be stored in localstorage.

Html part:

```<code> <div class="control-group">
          <label class="control-label">Select Month</label>
          <div class="controls">
            <select id="month" name="month">
              <option  value="">--Select Option--</option>
              <option value="1">January</option>
              <option value="2">February</option>
              <option value="3">March</option>
              <option value="4">April</option>
              <option value="5">May</option>
              <option value="6">June</option>
              <option value="7">July</option>
              <option value="8">August</option>
              <option value="9">September</option>
              <option value="10">October</option>
              <option value="11">November</option>
              <option value="12">December</option>
            </select>
          </div>
        </div>
        <div class="control-group">
          <label class="control-label">Select Year</label>
          <div class="controls">
            <select id="year" name="year">
              <option  value="">--Select Option--</option>
              <option>2017</option>
              <option>2016</option>
              <option>2015</option>
              <option>2014</option>
              <option>2013</option>
              <option>2012</option>
              <option>2011</option>
            </select>
          </div>
        </div>
        <div class="control-group">
          <label class="control-label">Select Employee</label>
          <div class="controls">
            <select id="employee" name="employee_name">
              <option  value="">--Select Option--</option>
            <?php
              foreach ($salary  as $row) {?>
              <option value='<?php echo $row->EMPLOYEE_ID;?>'><?php  echo $row->EMPLOYEE_NAME;}?></option>
            </select>
          </div>
        </div>
              <div class="control-group">
          <label class="control-label">Select Country</label>
          <div class="controls">
            <select id="country" name="org_id">
              <option  value="">--Select Option--</option>
              <option  value="40">UK</option>
              <option  value="41">INDIA</option>
              <option  value="47">POLAND</option>
              <option  value="57">GERMANY</option>
            </select>
          </div>
        </div>
</code>```

Till now only first field that is months is working.On form load only its selected value is stored in localstorage. Rest of all shows blank space in dropdown.
Javascript code:

```<code>  <script type="text/javascript">
    var editingArea = document.getElementById("month");
    var editingArea1 = document.getElementById("year");
    var editingArea2 = document.getElementById("employee");
    var editingArea3 = document.getElementById("country");

var KEY = "storageKey";
var text = localStorage.getItem(KEY);
if(text !== null){
        editingArea.value = text;
}
var KEY = "storageKey";
var text1 = localStorage.getItem(KEY);
if(text1 !== null){
        editingArea1.value = text1;
}
var KEY = "storageKey";
var text2 = localStorage.getItem(KEY);
if(text2 !== null){
        editingArea2value = text2;
}
var KEY = "storageKey";
var text3 = localStorage.getItem(KEY);
if(text3 !== null){
        editingArea3.value = text3;
}

// whenever the textarea is updated, store the contents also into the storage
editingArea.addEventListener("click", function(event){
    localStorage.setItem(KEY,editingArea.value);
},false);
editingArea1.addEventListener("click", function(event){
    localStorage.setItem(KEY,editingArea1.value);
},false);
editingArea2.addEventListener("click", function(event){
    localStorage.setItem(KEY,editingArea2.value);
},false);
editingArea3.addEventListener("click", function(event){
    localStorage.setItem(KEY,editingArea3.value);
},false);

var resetButton = document.getElementById("reset");
resetButton.addEventListener("click", function(event){
    localStorage.setItem(KEY,"");
    editingArea.value = "";
    editingArea1.value = "";
    editingArea2.value = "";
    editingArea3.value = "";
},false);

  </script>
</code>```

答: You are using same var KEY = "storageKey"; for all the fields. Use different  keys for individual fields.

Body:
Hi guys im working on codeigniter project and on ane of my form i am using localstorage to store selected values and display after page  load.
But somehow its not working for all my fields.
Sometimes first value get works sometimes last value works.
I have total 4 fields and all values should be stored in localstorage.

Html part:

          Select Month

            <select id="month" name="month">
              <option  value="">--Select Option--</option>
              <option value="1">January</option>
              <option value="2">February</option>
              <option value="3">March</option>
              <option value="4">April</option>
              <option value="5">May</option>
              <option value="6">June</option>
              <option value="7">July</option>
              <option value="8">August</option>
              <option value="9">September</option>
              <option value="10">October</option>
              <option value="11">November</option>
              <option value="12">December</option>
            </select>

          Select Year

            <select id="year" name="year">
              <option  value="">--Select Option--</option>
              <option>2017</option>
              <option>2016</option>
              <option>2015</option>
              <option>2014</option>
              <option>2013</option>
              <option>2012</option>
              <option>2011</option>
            </select>

          Select Employee

            <select id="employee" name="employee_name">
              <option  value="">--Select Option--</option>
            <?php
              foreach ($salary  as $row) {?>
              <option value='<?php echo $row->EMPLOYEE_ID;?>'><?php  echo $row->EMPLOYEE_NAME;}?></option>
            </select>

          Select Country

            <select id="country" name="org_id">
              <option  value="">--Select Option--</option>
              <option  value="40">UK</option>
              <option  value="41">INDIA</option>
              <option  value="47">POLAND</option>
              <option  value="57">GERMANY</option>
            </select>

Till now only first field that is months is working.On form load only its selected value is stored in localstorage. Rest of all shows blank space in dropdown.
Javascript code:


问:
How to implement a streaks feature
I wish to implement a sort of streaks feature showing a count of the number of times the user opens the app. I would like the counter to increase by one per day. If the user should skip a day, save the counter as a sort of "high score" and restart the counter

So far I have been able to count the number of times the app is opened using the code below:

```<code>    if (savedInstanceState == null) {
        //initialize streak counter
        SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        streakCount = prefs.getInt("counter", 0);
        streakCount++;
        editor.putInt("counter", streakCount);
        editor.apply();
        Toast.makeText(this, "App Opened Count is: " + streakCount, Toast.LENGTH_SHORT)
                .show();
    }
</code>```

Any ideas on how to implement this will be appreciated.

答:
Just use this as a sample

```<code>SharedPreferences sharedPreferences = getSharedPreferences("YOUR PREF KEY", Context.MODE_PRIVATE);
Calendar c = Calendar.getInstance();

        int thisDay = c.get(Calendar.DAY_OF_YEAR); // GET THE CURRENT DAY OF THE YEAR

        int lastDay = sharedPreferences.getInt("YOUR DATE PREF KEY", 0); //If we don't have a saved value, use 0.

        int counterOfConsecutiveDays = sharedPreferences.getInt("YOUR COUNTER PREF KEY", 0); //If we don't have a saved value, use 0.

if(lastDay == thisDay -1){
    // CONSECUTIVE DAYS
    counterOfConsecutiveDays = counterOfConsecutiveDays + 1;

    sharedPreferences.edit.putInt("YOUR DATE PREF KEY", thisDay);

    sharedPreferences.edit.putInt("YOUR COUNTER PREF KEY", counterOfConsecutiveDays).commit;
} else {

    sharedPreferences.edit.putInt("YOUR DATE PREF KEY", thisDay);

    sharedPreferences.edit.putInt("YOUR COUNTER PREF KEY", 1).commit();
}
</code>```

Title: How to implement a streaks feature

Body:
I wish to implement a sort of streaks feature showing a count of the number of times the user opens the app. I would like the counter to increase by one per day. If the user should skip a day, save the counter as a sort of "high score" and restart the counter

So far I have been able to count the number of times the app is opened using the code below:

    if (savedInstanceState == null) {
        //initialize streak counter
        SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        streakCount = prefs.getInt("counter", 0);
        streakCount++;
        editor.putInt("counter", streakCount);
        editor.apply();
        Toast.makeText(this, "App Opened Count is: " + streakCount, Toast.LENGTH_SHORT)
                .show();
    }

Any ideas on how to implement this will be appreciated.

Body:
Just use this as a sample

SharedPreferences sharedPreferences = getSharedPreferences("YOUR PREF KEY", Context.MODE_PRIVATE);
Calendar c = Calendar.getInstance();

        int thisDay = c.get(Calendar.DAY_OF_YEAR); // GET THE CURRENT DAY OF THE YEAR

        int lastDay = sharedPreferences.getInt("YOUR DATE PREF KEY", 0); //If we don't have a saved value, use 0.

        int counterOfConsecutiveDays = sharedPreferences.getInt("YOUR COUNTER PREF KEY", 0); //If we don't have a saved value, use 0.

if(lastDay == thisDay -1){
    // CONSECUTIVE DAYS
    counterOfConsecutiveDays = counterOfConsecutiveDays + 1;

    sharedPreferences.edit.putInt("YOUR DATE PREF KEY", thisDay);

    sharedPreferences.edit.putInt("YOUR COUNTER PREF KEY", counterOfConsecutiveDays).commit;
} else {

    sharedPreferences.edit.putInt("YOUR DATE PREF KEY", thisDay);

    sharedPreferences.edit.putInt("YOUR COUNTER PREF KEY", 1).commit();
}


问:
Switching WooCommerce product description title depending on PolyLang current language
This code changes the description title to 'Attributes' on both English(en) and Thai(th) products on the site. But Obviously it needs to return this only for the English version, and return 'คุณลักษณะ' for the Thai products.

```<code>add_filter('woocommerce_product_description_heading','switch_product_description_heading');
     function switch_product_description_heading() {
     return 'Attributes';
}
</code>```

I have tried this to grab PolyLang's current language but has no effect:

```<code>function language_switch() {
    if(pll_current_language=='en') {
        add_filter( 'woocommerce_product_description_heading', 'switch_product_description_heading' );
        function switch_product_description_heading() {
            return 'Attributes';
        }
    } elseif (pll_current_language=='th') {
        add_filter( 'woocommerce_product_description_heading', 'switch_product_description_heading' );
        function switch_product_description_heading() {
            return 'คุณลักษณะ';
        }
    }
}
</code>```

Any help would be appreciated!

答:
pll_current_language is a function so you should call it

```<code>if(pll_current_language() =='en') {
</code>```

Body:
This code changes the description title to 'Attributes' on both English(en) and Thai(th) products on the site. But Obviously it needs to return this only for the English version, and return 'คุณลักษณะ' for the Thai products.

add_filter('woocommerce_product_description_heading','switch_product_description_heading');
     function switch_product_description_heading() {
     return 'Attributes';
}

I have tried this to grab PolyLang's current language but has no effect:

function language_switch() {
    if(pll_current_language=='en') {
        add_filter( 'woocommerce_product_description_heading', 'switch_product_description_heading' );
        function switch_product_description_heading() {
            return 'Attributes';
        }
    } elseif (pll_current_language=='th') {
        add_filter( 'woocommerce_product_description_heading', 'switch_product_description_heading' );
        function switch_product_description_heading() {
            return 'คุณลักษณะ';
        }
    }
}

Any help would be appreciated!

Body:
pll_current_language is a function so you should call it

if(pll_current_language() =='en') {


问:
Most compatible rich text editor for AJAX and JQuery dialogs?
I'm looking for the most compatible rich text editor to use with a JQuery Dialog, and content that is loaded via AJAX.

I have managed to get tinyMCE playing nice with the dialog after a bit of work, but trying to get it to also work with ajax loaded content has become a real pain.

So, just wondering if anyone else has had any success with similar approaches?

答: Have you tried CkEditor? It has a nice bridge to jQuery and it works quite satisfactorily in one of my projects.</p>


问:
How to trigger an action by clicking the option item of a select element (Vue.js)?
List of options as JS object:

```<code>options: [{
  text: this.$t('analytics.pastDays', { days: 7 }),
  value: 7
}, {
  text: this.$t('analytics.pastDays', { days: 28 }),
  value: 28
}, {
  text: this.$t('analytics.pastDays', { days: 360 }),
  value: 360
}, {
  text: this.$t('analytics.customDate'),
  value: 7,
  method: () => { console.log('Worked') }
}],
</code>```

Select element:

```<code><select
  class="i-select"
  v-model="value"
  @change="onChange($event)">
  <option
    v-for="option in options"
    :value="option.value"
    @click.stop.prevent="option.method($event)">
    {{ option.text }}
  </option>
</select>
</code>```

Right know the console logs never logs.

How to make it so that the analytics.CustomDate options triggers its method?

答:
I think click event on option will not work, we can utilize its change event, (not sure option element is not respecting onclick)

you can check workaround in this snippet

var yourOptions = [{
    text: 'analytics.pastDays',
    value: 7,
    method: function() { console.log('this one is selected (7).') }
  }, {
    text: 'analytics.pastDays',
    value: 28
  }, {
    text: 'analytics.pastDays',
    value: 360,
    method: function() { console.log('this one is selected (360).') }
  }, {
    text: 'analytics.customDate',
    value: 70,
    method: function() { console.log('this one is selected (70).') }
  }];

 var vm = new Vue({
    el: '#app',
    data: {
        options: yourOptions,
        value:''
    },
    mounted: function() {

    },
    methods: {
        onChange: function(value) {
            var selected = yourOptions.filter(function(obj) {
              return obj.value == value
            })
            if(selected.length > 0) {
              selected.forEach(function(option){ if(option.method) { option.method(); } })
            }
        }
    }
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    <div id="app">
        <select
          class="i-select"
          v-model="value"
          @change="onChange(value)">
          <option
            v-for="option in options"
            :value="option.value"
            >
            {{ option.text }}
          </option>
        </select>
    </div>

</body>

</html></code>```

Body:
List of options as JS object:

options: [{
  text: this.$t('analytics.pastDays', { days: 7 }),
  value: 7
}, {
  text: this.$t('analytics.pastDays', { days: 28 }),
  value: 28
}, {
  text: this.$t('analytics.pastDays', { days: 360 }),
  value: 360
}, {
  text: this.$t('analytics.customDate'),
  value: 7,
  method: () => { console.log('Worked') }
}],

Select element:

<select
  class="i-select"
  v-model="value"
  @change="onChange($event)">
  <option
    v-for="option in options"
    :value="option.value"
    @click.stop.prevent="option.method($event)">
    {{ option.text }}
  </option>
</select>

Right know the console logs never logs.

How to make it so that the analytics.CustomDate options triggers its method?

Body:
I think click event on option will not work, we can utilize its change event, (not sure option element is not respecting onclick)

you can check workaround in this snippet

var yourOptions = [{
    text: 'analytics.pastDays',
    value: 7,
    method: function() { console.log('this one is selected (7).') }
  }, {
    text: 'analytics.pastDays',
    value: 28
  }, {
    text: 'analytics.pastDays',
    value: 360,
    method: function() { console.log('this one is selected (360).') }
  }, {
    text: 'analytics.customDate',
    value: 70,
    method: function() { console.log('this one is selected (70).') }
  }];

 var vm = new Vue({
    el: '#app',
    data: {
        options: yourOptions,
        value:''
    },
    mounted: function() {

    },
    methods: {
        onChange: function(value) {
            var selected = yourOptions.filter(function(obj) {
              return obj.value == value
            })
            if(selected.length > 0) {
              selected.forEach(function(option){ if(option.method) { option.method(); } })
            }
        }
    }
  })

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>VueJS</title>
    <script  src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
</head>
<body>
    <div id="app">
        <select
          class="i-select"
          v-model="value"
          @change="onChange(value)">
          <option
            v-for="option in options"
            :value="option.value"
            >
            {{ option.text }}
          </option>
        </select>
    </div>

</body>

</html>


问:
Remove sort mode for treeview
To make my treeview sorting as a new mode i want. I using the following command :

```<code>TreeView1.TreeViewNodeSorter = New NodeSorter()
</code>```

But i don't know how to convert the sort mode back to normal/default. I've try :

```<code>TreeView1.TreeViewNodeSorter = Nothing
</code>```

But nothing happen. How to convert the sort mode back to normal without writing a new sorter class?

答: TreeView1.Sorted = false; // seems to work fine</p>

Title: Remove sort mode for treeview

Body:
To make my treeview sorting as a new mode i want. I using the following command :

TreeView1.TreeViewNodeSorter = New NodeSorter()

But i don't know how to convert the sort mode back to normal/default. I've try :

TreeView1.TreeViewNodeSorter = Nothing

But nothing happen. How to convert the sort mode back to normal without writing a new sorter class?


问:
What is the easiest and fastest way of converting probabilities into prediction labels?
In short, I am looking for a one/two line code for following code:</p>

```<code>for i in range(A.shape[1]):

    # Convert probabilities A[0,i] to actual predictions p[0,i]
    ### START CODE HERE ### (≈ 4 lines of code)
    if(A[i] > .5)
       Y_prediction[i] = 1
    else
        Y_prediction[i] = 0
</code>```

答:
The numpy argmax function should come in handy here. Just pass your array as an argument to the argmax function and it'll give you the labels based on the probabilities.

For more, see here.

Body:
In short, I am looking for a one/two line code for following code:

for i in range(A.shape[1]):

    # Convert probabilities A[0,i] to actual predictions p[0,i]
    ### START CODE HERE ### (≈ 4 lines of code)
    if(A[i] > .5)
       Y_prediction[i] = 1
    else
        Y_prediction[i] = 0


问:
Decrypting code from two lists
I think I have the right idea to solve this function, but I'm not sure why I don't get the desired result. Can anyone please help me fix this?</p>

```<code>>>>decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4])

My output: [0, 1, 2, 3, 4]

>>>decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4])

Desired Output: ['c', 's', 'c', 'a', '2', '0']

def decrypt(characters, code):
    L = []
    for item in range(len(characters)):
        result = characters[item]
        answer = code.index(item)
        L.append(item)
    return L
</code>```

答:
if you want characters - source, code - get char from source order </p>

```<code>def decrypt(characters, code):
    L = []
    for item in range(len(code)):
        result = code[item]
        L.append(characters[result])
    return L

print(decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4]))
</code>```

Title: Decrypting code from two lists

Body:
I think I have the right idea to solve this function, but I'm not sure why I don't get the desired result. Can anyone please help me fix this?

>>>decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4])

My output: [0, 1, 2, 3, 4]

>>>decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4])

Desired Output: ['c', 's', 'c', 'a', '2', '0']

def decrypt(characters, code):
    L = []
    for item in range(len(characters)):
        result = characters[item]
        answer = code.index(item)
        L.append(item)
    return L

Body:
if you want characters - source, code - get char from source order

def decrypt(characters, code):
    L = []
    for item in range(len(code)):
        result = code[item]
        L.append(characters[result])
    return L

print(decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4]))


问:
ng-repeat values in single input with comma separated
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="list.name">
   <label ng-repeat="data in list.types">{{data.work}}{{$last ? '' : ', '}}</label>
  </div>
</div></code>```

Can anyone tell me that how to use ng-repeat values in single input?.

答:
var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];

  $scope.input_model_value  = ''
  var  temp = []
  $scope.list.forEach(function(t1){
      t1.types.forEach(function(val){
      temp.push(val.work)
    })
  })
   $scope.input_model_value = temp.join(',')
 }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="input_model_value">
   <label ng-repeat="data in list.types">{{data.work}}</label>
  </div>
</div></code>```

Body:
I have list array.Inside that I have one nested array called types.
I am trying to show types.work inside an input field with comma separated.

This is what I have tried:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];
      }
});

   <input type="text" ng-model="list.name">
   {{data.work}}{{$last ? '' : ', '}}

Can anyone tell me that how to use ng-repeat values in single input?.

Body:
var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
 $scope.init = function(){
 $scope.list=[
   {
     "name":"john",
     "types":[
       {"work":"aa"},
       {"work":"bb"}
     ]
   }
 ];

  $scope.input_model_value  = ''
  var  temp = []
  $scope.list.forEach(function(t1){
      t1.types.forEach(function(val){
      temp.push(val.work)
    })
  })
   $scope.input_model_value = temp.join(',')
 }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>

<div ng-app="app">
  <div ng-controller="MainCtrl" ng-init="init()">
   <input type="text" ng-model="input_model_value">
   <label ng-repeat="data in list.types">{{data.work}}</label>
  </div>
</div>


问:
What's wrong with this HTML code?
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

```<code><!DOCTYPE html>
<html>
<head>
    <title>Hi</title>
    <style type="text/css">
    body
    {
        background-color: #369;
    }
    li.changeMe
    {
        background-color: #DEE;
        color: #369;
        font-weight: bold;
        padding: 8px 16px;
        margin: 5px;
        display: inline;
    }
    #bodystuff
    {
        background-color: White;
        display: block;
        padding: 15px 10px;
    }

    </style>
</head>

<body>
    <div style="margin: 15px 10px 0;">
    <div style="font-size: 30pt; font-weight: bold; color: White; font-family: Arial;">My Website</div>
    <div style="float: right; display: block; margin: 0 0 25px 0"><ul style="list-style-type: none; "><li class="changeMe">Hi</li><li class="changeMe">Hello</li></ul></div>
    <div id="bodystuff">Hi this is the body</div>
    </div>
</body>
</html>
</code>```

答:
I think you're missing the position:absolute in the div that needs to float. Otherwise it will be inline.

EDIT: Sorry, I misread the question.

Title: What's wrong with this HTML code?

Body:
I want the body part to be underneath the menu, but instead the menu is merged with the body.

http://jsfiddle.net/aqFGD/

<!DOCTYPE html>

    <title>Hi</title>

My Website

Hi

Hello

Hi this is the body

OwnerDisplayName: Anonymous

LastEditorDisplayName: Anonymous


问:
Codename One - tests.dat file needed when using build.unitTest=1
I created a test extending the AbstractTest class. The test works correctly in Netbeans: I right-click on the project name, then on "Test". Of course the Netbeans test in done in the Codename One Simulator. I want to repeat the test on several real devices, as I asked in "Codename One - Test Recorder: execute a test on a real device"

So I added the build.unitTest=1 build hint and I checked that my build.xml contains:

```<code><target name="test-for-ios-device" depends="clean,copy-ios-override,copy-libs,compile-test,clean-override">
    <codeNameOne
        jarFile="${dist.jar}"
        displayName="${codename1.displayName}"
        packageName = "${codename1.packageName}"
        mainClassName = "${codename1.mainName}"
        version="${codename1.version}"
        icon="${codename1.icon}"
        vendor="${codename1.vendor}"
        subtitle="${codename1.secondaryTitle}"
        buildArgs="build.unitTest=1"
        targetType="iphone"
        certificate="${codename1.ios.debug.certificate}"
        certPassword="${codename1.ios.debug.certificatePassword}"
        provisioningProfile="${codename1.ios.debug.provision}"
        appid="${codename1.ios.appid}"
        automated="${automated}"
        />
</target>

<target name="test-for-android-device" depends="clean,copy-android-override,copy-libs,compile-test,clean-override">
    <codeNameOne
        jarFile="${dist.jar}"
        displayName="${codename1.displayName}"
        packageName = "${codename1.packageName}"
        mainClassName = "${codename1.mainName}"
        version="${codename1.version}"
        icon="${codename1.icon}"
        vendor="${codename1.vendor}"
        subtitle="${codename1.secondaryTitle}"
        buildArgs="build.unitTest=1"
        targetType="android"
        keystoreAlias="${codename1.android.keystoreAlias}"
        keystore="${codename1.android.keystore}"
        certPassword="${codename1.android.keystorePassword}"
        automated="${automated}"
        />
</target>
</code>```

After that, I sent an iOS build: it doesn't compile. So I tried to send an Android build. The generated apk, on a real device, produces an error because the /tests.dat file is absent. The exact error is: "Test data not found in the file, make sure the ant task was executed in full" (it's produced by DeviceRunner class at line 57). I added an empty tests.dat in /src, but it's not useful, because no test is runned.

I don't know what I have to do.

I need step-by-step instructions to test an app on a real device in the same way that I do in the Codename One Simulator. Thanks.

答:
In the compile-test target which is the base target required we have this line:

```<code><prepareTests classesDir="${build.classes.dir}" testClassesDir="${build.test.classes.dir}" seJar="JavaSE.jar" metaDataFile="${build.test.classes.dir}/tests.dat" />
</code>```

This should generate a valid tests.dat file for the test directory which should get packaged into the build.

Body:
I created a test extending the AbstractTest class. The test works correctly in Netbeans: I right-click on the project name, then on "Test". Of course the Netbeans test in done in the Codename One Simulator. I want to repeat the test on several real devices, as I asked in "Codename One - Test Recorder: execute a test on a real device"

So I added the build.unitTest=1 build hint and I checked that my build.xml contains:

<target name="test-for-ios-device" depends="clean,copy-ios-override,copy-libs,compile-test,clean-override">
    <codeNameOne
        jarFile="${dist.jar}"
        displayName="${codename1.displayName}"
        packageName = "${codename1.packageName}"
        mainClassName = "${codename1.mainName}"
        version="${codename1.version}"
        icon="${codename1.icon}"
        vendor="${codename1.vendor}"
        subtitle="${codename1.secondaryTitle}"
        buildArgs="build.unitTest=1"
        targetType="iphone"
        certificate="${codename1.ios.debug.certificate}"
        certPassword="${codename1.ios.debug.certificatePassword}"
        provisioningProfile="${codename1.ios.debug.provision}"
        appid="${codename1.ios.appid}"
        automated="${automated}"
        />
</target>

<target name="test-for-android-device" depends="clean,copy-android-override,copy-libs,compile-test,clean-override">
    <codeNameOne
        jarFile="${dist.jar}"
        displayName="${codename1.displayName}"
        packageName = "${codename1.packageName}"
        mainClassName = "${codename1.mainName}"
        version="${codename1.version}"
        icon="${codename1.icon}"
        vendor="${codename1.vendor}"
        subtitle="${codename1.secondaryTitle}"
        buildArgs="build.unitTest=1"
        targetType="android"
        keystoreAlias="${codename1.android.keystoreAlias}"
        keystore="${codename1.android.keystore}"
        certPassword="${codename1.android.keystorePassword}"
        automated="${automated}"
        />
</target>

After that, I sent an iOS build: it doesn't compile. So I tried to send an Android build. The generated apk, on a real device, produces an error because the /tests.dat file is absent. The exact error is: "Test data not found in the file, make sure the ant task was executed in full" (it's produced by DeviceRunner class at line 57). I added an empty tests.dat in /src, but it's not useful, because no test is runned.

I don't know what I have to do.

I need step-by-step instructions to test an app on a real device in the same way that I do in the Codename One Simulator. Thanks.

Body:
In the compile-test target which is the base target required we have this line:

<prepareTests classesDir="${build.classes.dir}" testClassesDir="${build.test.classes.dir}" seJar="JavaSE.jar" metaDataFile="${build.test.classes.dir}/tests.dat" />

This should generate a valid tests.dat file for the test directory which should get packaged into the build.


问:
Java 9 - How to see help on Jshell?
Anybody here familiar with any good documentation on how could we work with jshell. I am struggling even to find help for same inside the jshell. Any good reference will work too.</p>

答:
Well though you got a answer, I think anybody will get almost all information from oracle docs for REPL i.e. JSHELL

This is a really nice documentation.

Also, we have another good documentation here

Title: Java 9 - How to see help on Jshell?


问:
Adding notification on webview
I want to know how to add notification to this,or if I want to trigger a certain word to pop up as a notification that would be greatly appreciated

```<code> public class NewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);
    String url = "https://www.example.com";
    WebView web = (WebView) findViewById(R.id.webView4);
    web.loadUrl(url);

    final WebView mWebView = (WebView) findViewById(R.id.webView4);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mWebView.getSettings().setSavePassword(true);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setSaveFormData(true);
    mWebView.getSettings().setSupportZoom(false);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setSupportMultipleWindows(false);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    mWebView.setWebViewClient(new WebViewClient() {

        public boolean shouldOverrideUrlLoading (WebView view, String url){

            return true;
        }
    });
    mWebView.loadUrl("https://www.example.com");

}
</code>```

}

答:
In java File

```<code>public class NewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);
    String url = "https://www.example.com";
    WebView web = (WebView) findViewById(R.id.webView4);
    web.loadUrl(url);

    final WebView mWebView = (WebView) findViewById(R.id.webView4);
    mWebView.getSettings().setJavaScriptEnabled(true);

    // Now I create an instance of my JavaScriptInterface class in my OnCreate method.
    final JavaScriptInterface myJavaScriptInterface
        = new JavaScriptInterface(this);
    //After the initialization of the JavaScriptInterface class, I added one more line in my OnCreate method:
    mWebView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mWebView.getSettings().setSavePassword(true);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setSaveFormData(true);
    mWebView.getSettings().setSupportZoom(false);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setSupportMultipleWindows(false);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    mWebView.setWebViewClient(new WebViewClient() {

        public boolean shouldOverrideUrlLoading (WebView view, String url){

            return true;
        }
    });
    mWebView.loadUrl("https://www.example.com");

}

public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        public void showNotification(String webMessage){
             String tittle="Sample Notification";
            String subject="Sample Subject";
            String body=webMessage;

            NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notify=new Notification.Builder
               (getApplicationContext()).setContentTitle(tittle).setContentText(body).
               setContentTitle(subject).setSmallIcon(R.drawable.abc).build();

               notify.flags |= Notification.FLAG_AUTO_CANCEL;
               notif.notify(0, notify);
        }
    }
}
</code>```

And in You webpage, you should write this.

```<code><!DOCTYPE >
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport"

          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="viewport" content="target-densitydpi=device-dpi" />
        <script type="text/javascript">
           function init()
           {
               var testVal = document.getElementById('mytextId').value;
               AndroidFunction.showNotification(testVal);
           }
        </script>
    </head>
    <body>
        <div style="float: left;width: 50%;">
           <input type="text" style="width: 180px;"

                   name="myText" id="mytextId" />

        </div>
        <div style="clear: both;height: 3px;"> </div>
        <div>
          <input value="submit" type="button" name="submit"

            id="btnSubmit" onclick="javascript:return init();" />
        </div>
    </body>
</html>
</code>```

Title: Adding notification on webview

Body:
I want to know how to add notification to this,or if I want to trigger a certain word to pop up as a notification that would be greatly appreciated

 public class NewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);
    String url = "https://www.example.com";
    WebView web = (WebView) findViewById(R.id.webView4);
    web.loadUrl(url);

    final WebView mWebView = (WebView) findViewById(R.id.webView4);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mWebView.getSettings().setSavePassword(true);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setSaveFormData(true);
    mWebView.getSettings().setSupportZoom(false);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setSupportMultipleWindows(false);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    mWebView.setWebViewClient(new WebViewClient() {

        public boolean shouldOverrideUrlLoading (WebView view, String url){

            return true;
        }
    });
    mWebView.loadUrl("https://www.example.com");

}

}

Body:
In java File

public class NewActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_new);
    String url = "https://www.example.com";
    WebView web = (WebView) findViewById(R.id.webView4);
    web.loadUrl(url);

    final WebView mWebView = (WebView) findViewById(R.id.webView4);
    mWebView.getSettings().setJavaScriptEnabled(true);

    // Now I create an instance of my JavaScriptInterface class in my OnCreate method.
    final JavaScriptInterface myJavaScriptInterface
        = new JavaScriptInterface(this);
    //After the initialization of the JavaScriptInterface class, I added one more line in my OnCreate method:
    mWebView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mWebView.getSettings().setSavePassword(true);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setSaveFormData(true);
    mWebView.getSettings().setSupportZoom(false);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setSupportMultipleWindows(false);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    mWebView.setWebViewClient(new WebViewClient() {

        public boolean shouldOverrideUrlLoading (WebView view, String url){

            return true;
        }
    });
    mWebView.loadUrl("https://www.example.com");

}

public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        public void showNotification(String webMessage){
             String tittle="Sample Notification";
            String subject="Sample Subject";
            String body=webMessage;

            NotificationManager notif=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
            Notification notify=new Notification.Builder
               (getApplicationContext()).setContentTitle(tittle).setContentText(body).
               setContentTitle(subject).setSmallIcon(R.drawable.abc).build();

               notify.flags |= Notification.FLAG_AUTO_CANCEL;
               notif.notify(0, notify);
        }
    }
}

And in You webpage, you should write this.

<!DOCTYPE >
<html xmlns="http://www.w3.org/1999/xhtml" debug="true">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport"

          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="viewport" content="target-densitydpi=device-dpi" />
        <script type="text/javascript">
           function init()
           {
               var testVal = document.getElementById('mytextId').value;
               AndroidFunction.showNotification(testVal);
           }
        </script>
    </head>
    <body>
        <div style="float: left;width: 50%;">
           <input type="text" style="width: 180px;"

                   name="myText" id="mytextId" />

        </div>
        <div style="clear: both;height: 3px;"> </div>
        <div>
          <input value="submit" type="button" name="submit"

            id="btnSubmit" onclick="javascript:return init();" />
        </div>
    </body>
</html>


问:
Using ScatterV to split an array to multiple processes
I am working with MPI and I have to send parts of an array to different processes. As an example, consider 3 processes. Then I need to send the red elements to the first process, the greed to the second and the black to the third process.

I know I could use Scatterv twice, but I want to minimize the communication between processes and the real array that I'm splitting apart is huge. Does anyone have a suggestion on how I can accomplish this?

Here is my attempt with a derived data type:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

void print_array(int *array,int n){
    int i;
    printf("\t[");
    for (i=0; i<n; i++) {
        printf(" %d",array[i]);
    }
    printf("]\n");
}

int main(int argc, char **argv){

int rank,world_size,i,n = 16, block_count = 2;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);

int *array = malloc(n * sizeof(int));
for (i=0; i<n; i++) { array[i]=i;}
if (rank==0) { print_array(array,n);}

int *sendcounts = malloc(world_size * sizeof(int));
int *reccounts = malloc(world_size * sizeof(int));
int *displs = malloc(world_size * sizeof(int));

sendcounts[0]=3; sendcounts[1]=3; sendcounts[2]=2;
displs[0]=0; displs[1]=3; displs[2]=6;

for (i=0; i<world_size; i++) {
    reccounts[i] = sendcounts[i]*block_count;
}

int root = 0;
int *recvbuf = malloc(reccounts[rank] * sizeof(int));
MPI_Datatype newtype;
MPI_Type_contiguous(block_count, MPI_INT, &newtype);
MPI_Type_commit(&newtype);

if (rank==0) {
    MPI_Scatterv(array, sendcounts, displs,
                 newtype, recvbuf, sendcounts[rank],
                 newtype, root, MPI_COMM_WORLD);
}
else {
    MPI_Scatterv(NULL, sendcounts, displs,
                 newtype, recvbuf, reccounts[rank],
                 newtype, root, MPI_COMM_WORLD);
}

MPI_Type_free (&newtype);

print_array(recvbuf,reccounts[rank]);

free(array);array = NULL;
free(sendcounts);sendcounts = NULL;
free(displs);displs = NULL;
free(recvbuf);recvbuf = NULL;
MPI_Finalize();
return 0;
}
</code>```

答:
There is a way, but it is a bit convoluted.

The idea is you create a derived datatype with two elements at offset 0 and 8, and then resize this datatype so the upper bound is the size of one element.
Then you can MPI_Scatterv() once with counts={3,3,2} and displs={0,3,6}.
Note you also need to create a derived datatype on the receive side, otherwise MPI task 1 would receive {3, 11, 4, 12, 5, 13} when i guess you expect {3, 4, 5, 11, 12, 13}

Body:
I am working with MPI and I have to send parts of an array to different processes. As an example, consider 3 processes. Then I need to send the red elements to the first process, the greed to the second and the black to the third process.

I know I could use Scatterv twice, but I want to minimize the communication between processes and the real array that I'm splitting apart is huge. Does anyone have a suggestion on how I can accomplish this?

Here is my attempt with a derived data type:

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

void print_array(int *array,int n){
    int i;
    printf("\t[");
    for (i=0; i<n; i++) {
        printf(" %d",array[i]);
    }
    printf("]\n");
}

int main(int argc, char **argv){

int rank,world_size,i,n = 16, block_count = 2;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);

int *array = malloc(n * sizeof(int));
for (i=0; i<n; i++) { array[i]=i;}
if (rank==0) { print_array(array,n);}

int *sendcounts = malloc(world_size * sizeof(int));
int *reccounts = malloc(world_size * sizeof(int));
int *displs = malloc(world_size * sizeof(int));

sendcounts[0]=3; sendcounts[1]=3; sendcounts[2]=2;
displs[0]=0; displs[1]=3; displs[2]=6;

for (i=0; i<world_size; i++) {
    reccounts[i] = sendcounts[i]*block_count;
}

int root = 0;
int *recvbuf = malloc(reccounts[rank] * sizeof(int));
MPI_Datatype newtype;
MPI_Type_contiguous(block_count, MPI_INT, &newtype);
MPI_Type_commit(&newtype);

if (rank==0) {
    MPI_Scatterv(array, sendcounts, displs,
                 newtype, recvbuf, sendcounts[rank],
                 newtype, root, MPI_COMM_WORLD);
}
else {
    MPI_Scatterv(NULL, sendcounts, displs,
                 newtype, recvbuf, reccounts[rank],
                 newtype, root, MPI_COMM_WORLD);
}

MPI_Type_free (&newtype);

print_array(recvbuf,reccounts[rank]);

free(array);array = NULL;
free(sendcounts);sendcounts = NULL;
free(displs);displs = NULL;
free(recvbuf);recvbuf = NULL;
MPI_Finalize();
return 0;
}


问:
Obtain consecutive substrings in python
Given a n-gram word I want to get the consecutive substrings patterns from 'start to end' and 'end to start'.

For example, for the 4-gram computer supported machine translation I should get the following substrings.

from start to end: computer supported, computer supported machine

from end to start: machine translation, supported machine translation

for the 3-gram natural language processing, I should get natural language and language processing.

I have really large n-grams, so I am interested in knowing the quickest way of doing this!

答:
You should use a function and then just pass the ngram as parameter :

some piece of code borrowed from @Galen :

```<code>def count_grams(gram,sentence):
    grams = sentence.split(" ")

    words=[]
    for i in range(gram,len(grams)):
        start=[]
        start.append(" ".join(grams[:i]))
        words.append(start)
    for j in range(gram,len(grams)):
        end=[]
        end.append(" ".join(grams[-j:]))
        words.append(end)

    return words

print(count_grams(2,'computer supported machine translation'))
print(count_grams(2,'natural language processing'))
</code>```

output:

```<code>[['computer supported'], ['computer supported machine'], ['machine translation'], ['supported machine translation']]
[['natural language'], ['language processing']]
</code>```

If you don't want result in list you can use " ".join()

Title: Obtain consecutive substrings in python

Body:
You should use a function and then just pass the ngram as parameter :

some piece of code borrowed from @Galen :

def count_grams(gram,sentence):
    grams = sentence.split(" ")

    words=[]
    for i in range(gram,len(grams)):
        start=[]
        start.append(" ".join(grams[:i]))
        words.append(start)
    for j in range(gram,len(grams)):
        end=[]
        end.append(" ".join(grams[-j:]))
        words.append(end)

    return words

print(count_grams(2,'computer supported machine translation'))
print(count_grams(2,'natural language processing'))

output:

[['computer supported'], ['computer supported machine'], ['machine translation'], ['supported machine translation']]
[['natural language'], ['language processing']]

If you don't want result in list you can use " ".join()


问:
How do I load Angular 4 into an AngularJS app using SystemJS?
I want to convert an AngularJS app to Angular 4. I'm reading the official Angular documentation for upgrading from AngularJS at https://angular.io/guide/upgrade. It states this:

To begin converting your AngularJS application to a hybrid, you need
  to load the Angular framework. You can see how this can be done with
  SystemJS by following the instructions in Setup, selectively copying
  code from the QuickStart github repository.

The 'Setup' link however leads to a page which doesn't mention SystemJS. How do I use SystemJS to load/build the Angular 4 framework into the existing AngularJS app?

答:
That quote I gave from the Angular documentation is very confusing. What you actually need to do when upgrading is to somehow set up the scaffolding for an Angular 4 app within your project, then use SystemJS as the module loader that will load the Angular 4 modules at runtime (since there is currently incomplete native browser support for the EcmaScript module system).

I figured out by reading further through the upgrade guide (specifically the 'PhoneCat Upgrade Tutorial - https://angular.io/guide/upgrade#phonecat-upgrade-tutorial) that what you're expected to do is set up the QuickStart project in an independent location, somehow move most of it into your existing AngularJS project to provide the scaffolding for an Angular 4 project, then wire up SystemJS as the module loader by selectively using some of the SystemJS configuration that is inside your 'built' QuickStart project.


问:
Validation expression in asp.net
How to disallow use of double quotes " in a textbox

答:
Use String.Contains()

Since you can never control what users do the client you might as well just check it on the server, so you would probably use code something like:

```<code>if (textBox1.Text.Contains("\""))
{
Response.Write("Dey aint no way I'm letting you type that!");
}
</code>```

Title: Validation expression in asp.net

Body:
Use String.Contains()

Since you can never control what users do the client you might as well just check it on the server, so you would probably use code something like:

if (textBox1.Text.Contains("\""))
{
Response.Write("Dey aint no way I'm letting you type that!");
}


答:
What's going on is your item variable is the number counting 0,1,2,3,4... for the indices of the code list. Instead, you should iterate over the integers that make up code by doing in code: instead of in range(.... That way, item is the values of code on each item of the list, which are the indices that you want to get out of characters.

```<code>def decrypt(characters, code):
    L = []
    for item in code:
        result = characters[item]
        L.append(result)
    return L

print(decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4]))
</code>```

This could also be done with a list comprehension:

```<code>def decrypt(characters,code):
    return [characters[i] for i in code]
</code>```

Title: Decrypting code from two lists

Body:
What's going on is your item variable is the number counting 0,1,2,3,4... for the indices of the code list. Instead, you should iterate over the integers that make up code by doing in code: instead of in range(.... That way, item is the values of code on each item of the list, which are the indices that you want to get out of characters.

def decrypt(characters, code):
    L = []
    for item in code:
        result = characters[item]
        L.append(result)
    return L

print(decrypt(['a', '2', 's', 'c', '0'], [3, 2, 3, 0, 1, 4]))

This could also be done with a list comprehension:

def decrypt(characters,code):
    return [characters[i] for i in code]


问:
How to find week date ranges for a given month
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.

```<code>$month = $_GET['month'];
$year = $_GET['year'];
 ...

Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017
</code>```

Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.

Thanks.

答:
Here is one method that loops with strtotime.

I add 86400*7 on Unix to add a week.

```<code>$month = 2;
$year = 2017;

$week = date("W", strtotime($year . "-" . $month ."-01")); // weeknumber of first day of month

Echo date("d/m/Y", strtotime($year . "-" . $month ."-01")) ." - "; // first day of month
$unix = strtotime($year."W".$week ."+1 week");
While(date("m", $unix) == $month){ // keep looping/output of while it's correct month

   Echo date("d/m/Y", $unix-86400) . "\n"; // Sunday of previous week
   Echo date("d/m/Y", $unix) ." - "; // this week's monday
   $unix = $unix + (86400*7);
}
Echo date("d/m/Y", strtotime("last day of ".$year . "-" . $month)); //echo last day of month
</code>```

https://3v4l.org/LAMBl

Body:
I need to display a range of dates in corresponding week for selected month.
Suppose the selected values are $month=2 and $year=2017.
The output should show a list of ranged dates for weeks in that particular month selected.

$month = $_GET['month'];
$year = $_GET['year'];
 ...

Output:
Week 1: 01/02/2017 - 05/02/2017
Week 2: 06/02/2017 - 12/02/2017
Week 3: 13/02/2017 - 19/02/2017
Week 4: 20/02/2017 - 26/02/2017
Week 5: 27/02/2017 - 28/02/2017

Ive look through Split the current month in to weeks in php , Get week number in month from date in PHP? and Split date ranges into corresponding weeks , but none of them working for me.

Thanks.

Body:
Here is one method that loops with strtotime.

I add 86400*7 on Unix to add a week.

$month = 2;
$year = 2017;

$week = date("W", strtotime($year . "-" . $month ."-01")); // weeknumber of first day of month

Echo date("d/m/Y", strtotime($year . "-" . $month ."-01")) ." - "; // first day of month
$unix = strtotime($year."W".$week ."+1 week");
While(date("m", $unix) == $month){ // keep looping/output of while it's correct month

   Echo date("d/m/Y", $unix-86400) . "\n"; // Sunday of previous week
   Echo date("d/m/Y", $unix) ." - "; // this week's monday
   $unix = $unix + (86400*7);
}
Echo date("d/m/Y", strtotime("last day of ".$year . "-" . $month)); //echo last day of month

https://3v4l.org/LAMBl


问:
How to get an integer value to a complex dictionary
Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,

```<code>    total[div]['total_transport_allowance'] = abc
</code>```

This error is shown : "KeyError: None"
Please Help

What I want from this statement is to get the abc's value to the key 'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....
```

答:
```<code>total[div]['total_transport_allowance'] = {}
</code>```

This worked..
I have done like this in

```<code>total['Undefined']['total_transport_allowance'] = {}
</code>```

also..
Thanks for everyone's help

Body:
Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,

    total[div]['total_transport_allowance'] = abc

This error is shown : "KeyError: None"
Please Help

What I want from this statement is to get the abc's value to the key 'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....

Body:
total[div]['total_transport_allowance'] = {}

This worked..
I have done like this in

total['Undefined']['total_transport_allowance'] = {}

also..
Thanks for everyone's help