问:
How to make HTTP request at an interval?
I am quite new to angular and rxjs.
I am trying to create an angular2 app that gets some data from staticly served text file(Locally on server), which I would like to retrieve and map to Datamodel using Angular2's http provider and rxjs's map at a fixed time interval(5000). To reflect any changes to the served txt file.

With rxjs 4.x I know you could use Observable.interval(5000) to do the job, but it does not seem to exist in rxjs 5.
My workaround currently refresh the whole application using <meta http-equiv="refresh" content="5" > Which reloads the whole page, and thus reloads the data.

So what I would really like is some way to do this working with observables, maybe to check if any changes have happened. or just to reload the data anew.

Any help or other/better way will be very much appreciated.

What I have so far:

```<code>@Injectable()
export class DataService {

    constructor(private http:Http){}

    getData(url) {
        return this.http.get(url)
            .map(res => {
                return res.text();
            })
            .map(res => {
                return res.split("\n");
            })
            .map(res => {
                var dataModels: DataModel[] = [];
                res.forEach(str => {
                    var s = str.split(",");
                    if(s[0] !== "") {
                        dataModels.push(new DataModel(s[0], parseInt(s[1]), parseInt(s[2])));
                    }
                });
                return dataModels;
            })
    }
}

@Component({
selector: 'my-app',
template: `Some html to display the data`,
providers: [DataService],
export class AppComponent {

data:DataModel[];

constructor(dataService:DataService) {}

ngOnInit() {
    this.dataService.getData('url').subscribe(
        res => {
            this.data= res;

        },
        err => console.log(err),
        () => console.log("Data received")
        );
    }
}
</code>```

Dependencies: package.json

```<code>"dependencies": {
  "angular2": "^2.0.0-beta.3",
  "bootstrap": "^4.0.0-alpha.2",
  "es6-promise": "^3.0.2",
  "es6-shim": "^0.33.13",
  "jquery": "^2.2.0",
  "reflect-metadata": "^0.1.2",
  "rxjs": "^5.0.0-beta.0",
  "systemjs": "^0.19.20",
  "zone.js": "^0.5.11"
},
"devDependencies": {
  "typescript": "^1.7.5"
}
</code>```

index.html imports:

```<code><script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>
</code>```

答:
As @Adam and @Ploppy mentioned, the Observable.interval() is now deprecated not the preferred way of creating such an observable. The preferred way of doing this is via the IntervalObservable or TimerObservable.
[currently in Typscript 2.5.2, rxjs 5.4.3, Angular 4.0.0]

I wanted to add some usage to this answer to demonstrate what I found the best way of doing this in the Angular 2 framework.

First your service (created in angular cli via the 'ng g service MyExample" command). Assuming the service is RESTful (http get request returns a json):

my-example.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response} from "@angular/http";
import { MyDataModel } from "./my-data-model";
import { Observable } from "rxjs";
import 'rxjs/Rx';

@Injectable()
export class MyExampleService {
  private url = 'http://localhost:3000'; // full uri of the service to consume here

  constructor(private http: Http) { }

  get(): Observable<MyDataModel>{
    return this.http
      .get(this.url)
      .map((res: Response) => res.json());
  }
}
</code>```

*** see bottom updates to service for Angular 5 ***

Now your component code ('ng g component MyExample'):

my-example.component.ts:

```<code>import { Component, OnDestroy, OnInit } from '@angular/core';
import { MyDataModel } from "../my-data-model";
import { MyExampleService } from "../my-example.service";
import { Observable } from "rxjs";
import { IntervalObservable } from "rxjs/observable/IntervalObservable";
import 'rxjs/add/operator/takeWhile';

@Component({
  selector: 'app-my-example',
  templateUrl: './my-example.component.html',
  styleUrls: ['./my-example.component.css']
})
export class MyExampleComponent implements OnInit, OnDestroy {
  private data: MyDataModel;
  private display: boolean; // whether to display info in the component
                            // use *ngIf="display" in your html to take
                            // advantage of this

  private alive: boolean; // used to unsubscribe from the IntervalObservable
                          // when OnDestroy is called.

  constructor(private myExampleService: MyExampleService) {
    this.display = false;
    this.alive = true;
  }

  ngOnInit() {
    // get our data immediately when the component inits
    this.myExampleService.get()
      .first() // only gets fired once
      .subscribe((data) => {
        this.data = data;
        this.display = true;
      });

    // get our data every subsequent 10 seconds
    IntervalObservable.create(10000)
      .takeWhile(() => this.alive) // only fires when component is alive
      .subscribe(() => {
        this.myExampleService.get()
          .subscribe(data => {
            this.data = data;
          });
      });
  }

  ngOnDestroy(){
    this.alive = false; // switches your IntervalObservable off
  }
}
</code>```

=== edit ===

Updated the component ts code to consolidate the subscriptions via a TimerObservable:

```<code>import { Component, OnDestroy, OnInit } from '@angular/core';
import { MyDataModel } from "../my-data-model";
import { MyExampleService } from "../my-example.service";
import { Observable } from "rxjs";
import { TimerObservable } from "rxjs/observable/TimerObservable";
import 'rxjs/add/operator/takeWhile';

@Component({
  selector: 'app-my-example',
  templateUrl: './my-example.component.html',
  styleUrls: ['./my-example.component.css']
})
export class MyExampleComponent implements OnInit, OnDestroy {
  private data: MyDataModel;
  private display: boolean; // whether to display info in the component
                            // use *ngIf="display" in your html to take
                            // advantage of this

  private alive: boolean; // used to unsubscribe from the TimerObservable
                          // when OnDestroy is called.
  private interval: number;

  constructor(private myExampleService: MyExampleService) {
    this.display = false;
    this.alive = true;
    this.interval = 10000;
  }

  ngOnInit() {
    TimerObservable.create(0, this.interval)
      .takeWhile(() => this.alive)
      .subscribe(() => {
        this.myExampleService.get()
          .subscribe((data) => {
            this.data = data;
            if(!this.display){
              this.display = true;
            }
          });
      });
  }

  ngOnDestroy(){
    this.alive = false; // switches your TimerObservable off
  }
}
</code>```

=== edit ===

my-example-service.ts (using the HttpClient a la Angular 5):

```<code>import { Injectable } from '@angular/core';
import { HttpClient} from "@angular/common/http";
import { MyDataModel } from "./my-data-model";
import { Observable } from "rxjs";
import 'rxjs/Rx';

@Injectable()
export class MyExampleService {
  private url = 'http://localhost:3000'; // full uri of the service to consume here

  constructor(private http: HttpClient) { }

  get(): Observable<MyDataModel>{
    return this.http
      .get<MyDataModel>(this.url);
  }
}
</code>```

Note change to use the HttpClient rather than Http (deprecated in angular5) and the get method which allows for parsing the response into our data model without having to employ the rxjs .map() operator. While the service changes for angular 5, the component code remains unchanged.

ContentLicense: CC BY-SA 4.0

Body:
I am quite new to angular and rxjs.
I am trying to create an angular2 app that gets some data from staticly served text file(Locally on server), which I would like to retrieve and map to Datamodel using Angular2's http provider and rxjs's map at a fixed time interval(5000). To reflect any changes to the served txt file.

With rxjs 4.x I know you could use Observable.interval(5000) to do the job, but it does not seem to exist in rxjs 5.
My workaround currently refresh the whole application using <meta http-equiv="refresh" content="5" > Which reloads the whole page, and thus reloads the data.

So what I would really like is some way to do this working with observables, maybe to check if any changes have happened. or just to reload the data anew.

Any help or other/better way will be very much appreciated.

What I have so far:

@Injectable()
export class DataService {

    constructor(private http:Http){}

    getData(url) {
        return this.http.get(url)
            .map(res => {
                return res.text();
            })
            .map(res => {
                return res.split("\n");
            })
            .map(res => {
                var dataModels: DataModel[] = [];
                res.forEach(str => {
                    var s = str.split(",");
                    if(s[0] !== "") {
                        dataModels.push(new DataModel(s[0], parseInt(s[1]), parseInt(s[2])));
                    }
                });
                return dataModels;
            })
    }
}

@Component({
selector: 'my-app',
template: `Some html to display the data`,
providers: [DataService],
export class AppComponent {

data:DataModel[];

constructor(dataService:DataService) {}

ngOnInit() {
    this.dataService.getData('url').subscribe(
        res => {
            this.data= res;

        },
        err => console.log(err),
        () => console.log("Data received")
        );
    }
}

Dependencies: package.json

"dependencies": {
  "angular2": "^2.0.0-beta.3",
  "bootstrap": "^4.0.0-alpha.2",
  "es6-promise": "^3.0.2",
  "es6-shim": "^0.33.13",
  "jquery": "^2.2.0",
  "reflect-metadata": "^0.1.2",
  "rxjs": "^5.0.0-beta.0",
  "systemjs": "^0.19.20",
  "zone.js": "^0.5.11"
},
"devDependencies": {
  "typescript": "^1.7.5"
}

index.html imports:

Body:
As @Adam and @Ploppy mentioned, the Observable.interval() is now deprecated not the preferred way of creating such an observable. The preferred way of doing this is via the IntervalObservable or TimerObservable.
[currently in Typscript 2.5.2, rxjs 5.4.3, Angular 4.0.0]

I wanted to add some usage to this answer to demonstrate what I found the best way of doing this in the Angular 2 framework.

First your service (created in angular cli via the 'ng g service MyExample" command). Assuming the service is RESTful (http get request returns a json):

my-example.service.ts

import { Injectable } from '@angular/core';
import { Http, Response} from "@angular/http";
import { MyDataModel } from "./my-data-model";
import { Observable } from "rxjs";
import 'rxjs/Rx';

@Injectable()
export class MyExampleService {
  private url = 'http://localhost:3000'; // full uri of the service to consume here

  constructor(private http: Http) { }

  get(): Observable<MyDataModel>{
    return this.http
      .get(this.url)
      .map((res: Response) => res.json());
  }
}

*** see bottom updates to service for Angular 5 ***

Now your component code ('ng g component MyExample'):

my-example.component.ts:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { MyDataModel } from "../my-data-model";
import { MyExampleService } from "../my-example.service";
import { Observable } from "rxjs";
import { IntervalObservable } from "rxjs/observable/IntervalObservable";
import 'rxjs/add/operator/takeWhile';

@Component({
  selector: 'app-my-example',
  templateUrl: './my-example.component.html',
  styleUrls: ['./my-example.component.css']
})
export class MyExampleComponent implements OnInit, OnDestroy {
  private data: MyDataModel;
  private display: boolean; // whether to display info in the component
                            // use *ngIf="display" in your html to take
                            // advantage of this

  private alive: boolean; // used to unsubscribe from the IntervalObservable
                          // when OnDestroy is called.

  constructor(private myExampleService: MyExampleService) {
    this.display = false;
    this.alive = true;
  }

  ngOnInit() {
    // get our data immediately when the component inits
    this.myExampleService.get()
      .first() // only gets fired once
      .subscribe((data) => {
        this.data = data;
        this.display = true;
      });

    // get our data every subsequent 10 seconds
    IntervalObservable.create(10000)
      .takeWhile(() => this.alive) // only fires when component is alive
      .subscribe(() => {
        this.myExampleService.get()
          .subscribe(data => {
            this.data = data;
          });
      });
  }

  ngOnDestroy(){
    this.alive = false; // switches your IntervalObservable off
  }
}

=== edit ===

Updated the component ts code to consolidate the subscriptions via a TimerObservable:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { MyDataModel } from "../my-data-model";
import { MyExampleService } from "../my-example.service";
import { Observable } from "rxjs";
import { TimerObservable } from "rxjs/observable/TimerObservable";
import 'rxjs/add/operator/takeWhile';

@Component({
  selector: 'app-my-example',
  templateUrl: './my-example.component.html',
  styleUrls: ['./my-example.component.css']
})
export class MyExampleComponent implements OnInit, OnDestroy {
  private data: MyDataModel;
  private display: boolean; // whether to display info in the component
                            // use *ngIf="display" in your html to take
                            // advantage of this

  private alive: boolean; // used to unsubscribe from the TimerObservable
                          // when OnDestroy is called.
  private interval: number;

  constructor(private myExampleService: MyExampleService) {
    this.display = false;
    this.alive = true;
    this.interval = 10000;
  }

  ngOnInit() {
    TimerObservable.create(0, this.interval)
      .takeWhile(() => this.alive)
      .subscribe(() => {
        this.myExampleService.get()
          .subscribe((data) => {
            this.data = data;
            if(!this.display){
              this.display = true;
            }
          });
      });
  }

  ngOnDestroy(){
    this.alive = false; // switches your TimerObservable off
  }
}

=== edit ===

my-example-service.ts (using the HttpClient a la Angular 5):

import { Injectable } from '@angular/core';
import { HttpClient} from "@angular/common/http";
import { MyDataModel } from "./my-data-model";
import { Observable } from "rxjs";
import 'rxjs/Rx';

@Injectable()
export class MyExampleService {
  private url = 'http://localhost:3000'; // full uri of the service to consume here

  constructor(private http: HttpClient) { }

  get(): Observable<MyDataModel>{
    return this.http
      .get<MyDataModel>(this.url);
  }
}

Note change to use the HttpClient rather than Http (deprecated in angular5) and the get method which allows for parsing the response into our data model without having to employ the rxjs .map() operator. While the service changes for angular 5, the component code remains unchanged.


来源: stackexchange

问:
importing python module failed
I am trying to run the development server by using, django-admin runserver and python -m django runserver, the django-admin runserver works but the python -m django runserver gives the following error

```<code>>         Traceback (most recent call last):
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/__main__.py",
> line 9, in <module>
>         management.execute_from_command_line()
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 367, in execute_from_command_line
>         utility.execute()
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 359, in execute
>         self.fetch_command(subcommand).run_from_argv(self.argv)
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 208, in fetch_command
>         klass = load_command_class(app_name, subcommand)
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 40, in load_command_class
>         module = import_module('%s.management.commands.%s' % (app_name, name))
>       File "/home/mohit/anaconda3/lib/python3.6/importlib/__init__.py", line 126,
> in import_module
>         return _bootstrap._gcd_import(name[level:], package, level)
>       File "<frozen importlib._bootstrap>", line 978, in _gcd_import
>       File "<frozen importlib._bootstrap>", line 961, in _find_and_load
>       File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
>       File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
>       File "<frozen importlib._bootstrap_external>", line 678, in exec_module
>       File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py",
> line 12, in <module>
>         from django.core.servers.basehttp import get_internal_wsgi_application, run
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py",
> line 15, in <module>
>         from wsgiref import simple_server
>       File "/home/mohit/anaconda3/lib/python3.6/wsgiref/simple_server.py", line
> 13, in <module>
>         from http.server import BaseHTTPRequestHandler, HTTPServer
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/__init__.py",
> line 1, in <module>
>         from django.http.cookie import SimpleCookie, parse_cookie
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/__init__.py",
> line 1, in <module>
>         from django.http.cookie import SimpleCookie, parse_cookie
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/cookie.py",
> line 7, in <module>
>         from django.utils.six.moves import http_cookies
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/utils/six.py",
> line 92, in __get__
>         result = self._resolve()
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/utils/six.py",
> line 115, in _resolve
>         return _import_module(self.mod)
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/utils/six.py",
> line 82, in _import_module
>         __import__(name)
>     ModuleNotFoundError: No module named 'http.cookies'
</code>```

i am new to django, but i tried the following

```<code>export DJANGO_SETTINGS_MODULE=tutorial.settings

PYTHONPATH=/media/mohit/mohit1/WEEKLY/tutorial
</code>```

but it did not work, help

答:
I think you want

```<code>python manage.py runserver
</code>```

Also, have you gone ahead and created a project and an app in that project?  You need to run the above command from the root of your project directory.

ContentLicense: CC BY-SA 3.0

Title: importing python module failed

Body:
I am trying to run the development server by using, django-admin runserver and python -m django runserver, the django-admin runserver works but the python -m django runserver gives the following error

>         Traceback (most recent call last):
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/__main__.py",
> line 9, in <module>
>         management.execute_from_command_line()
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 367, in execute_from_command_line
>         utility.execute()
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 359, in execute
>         self.fetch_command(subcommand).run_from_argv(self.argv)
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 208, in fetch_command
>         klass = load_command_class(app_name, subcommand)
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py",
> line 40, in load_command_class
>         module = import_module('%s.management.commands.%s' % (app_name, name))
>       File "/home/mohit/anaconda3/lib/python3.6/importlib/__init__.py", line 126,
> in import_module
>         return _bootstrap._gcd_import(name[level:], package, level)
>       File "<frozen importlib._bootstrap>", line 978, in _gcd_import
>       File "<frozen importlib._bootstrap>", line 961, in _find_and_load
>       File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
>       File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
>       File "<frozen importlib._bootstrap_external>", line 678, in exec_module
>       File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py",
> line 12, in <module>
>         from django.core.servers.basehttp import get_internal_wsgi_application, run
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/core/servers/basehttp.py",
> line 15, in <module>
>         from wsgiref import simple_server
>       File "/home/mohit/anaconda3/lib/python3.6/wsgiref/simple_server.py", line
> 13, in <module>
>         from http.server import BaseHTTPRequestHandler, HTTPServer
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/__init__.py",
> line 1, in <module>
>         from django.http.cookie import SimpleCookie, parse_cookie
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/__init__.py",
> line 1, in <module>
>         from django.http.cookie import SimpleCookie, parse_cookie
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/http/cookie.py",
> line 7, in <module>
>         from django.utils.six.moves import http_cookies
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/utils/six.py",
> line 92, in __get__
>         result = self._resolve()
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/utils/six.py",
> line 115, in _resolve
>         return _import_module(self.mod)
>       File "/home/mohit/anaconda3/lib/python3.6/site-packages/django/utils/six.py",
> line 82, in _import_module
>         __import__(name)
>     ModuleNotFoundError: No module named 'http.cookies'

i am new to django, but i tried the following

export DJANGO_SETTINGS_MODULE=tutorial.settings

PYTHONPATH=/media/mohit/mohit1/WEEKLY/tutorial

but it did not work, help

Body:
I think you want

python manage.py runserver

Also, have you gone ahead and created a project and an app in that project?  You need to run the above command from the root of your project directory.


问:
IIS 10 - Chrome 44 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY
After upgrading to Windows 10, I am receiving the ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY in Google Chrome (Firefox 39 just doesn't load the page) when I attempt to access my machine over HTTPS. I have a GoDaddy signed certificate for my computer.

I've attempted disabling most of my encryption ciphers per https://http2.github.io/http2-spec/#BadCipherSuites.

I've gone so far that I've disabled ciphers that are keeping me from RDPing to my desktop...and it still gives me an error!

Any guidance is appreciated.

答:
I ran into this same issue after my win 10 dev machine got updated twice recently (the updates took around 35-40 minutes to deploy each time) and after this i was not able to run my Visual studio 2015 web applications over Https on Chrome but was able to run on IE

I tried out the registry method for disabling Http 2 as mentioned
here, but this did not worked for me

Then I came across the following solution: I downloaded IIS Crypto and
selected "Cipher Suites" option and clicked Best Practices button, and applied
it, My problem was gone and i can now run my web app over Https in Chrome just like before


问:
Leader Not Available Kafka in Console Producer
I am trying to use Kafka.

All configurations are done properly but when I try to produce message from console I keep getting the following error

```<code>WARN Error while fetching metadata with correlation id 39 :
     {4-3-16-topic1=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)
</code>```

Kafka version: 2.11-0.9.0.0

答:
Another possibility for this warning (in 0.10.2.1) is that you try to poll on a topic that has just been created and the leader for this topic-partition is not yet available, you are in the middle of a leadership election.

Waiting a second between topic creation and polling is a workaround.

Body:
I am trying to use Kafka.

All configurations are done properly but when I try to produce message from console I keep getting the following error

WARN Error while fetching metadata with correlation id 39 :
     {4-3-16-topic1=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)

Kafka version: 2.11-0.9.0.0


问:
Orchard CMS taxonomy, import terms
I want to add several terms to an Orchard taxonomy, this taxonomy holds a large number of terms and if I added manually it would take me a life, so tried using the import, I know that it appends new terms but how to add a term under an existent parent term/s?

I tried something like this:

```<code>Parent term1;
    Children term1; taxonomy/test/parent-term1/children-term1
</code>```

but i get:

The term Parent term1 already exists at this level

Is it possible to do?
Thanks.

答:
My preferred method would be to do this through a recipe that creates the items. Here's a sample:

```<code><Orchard>
<Data>
    <TaxNameTerm Id="/alias=parent-term" Status="Published">
      <TitlePart Title="Parent Term Title" />
      <CommonPart Container="/alias=taxname" />
      <TermPart Count="0" Selectable="true" Weight="9" TaxonomyId="/alias=taxname" Path="" />
    </TaxNameTerm>
    <TaxNameTerm Id="/alias=child-term" Status="Published">
      <TitlePart Title="Child Term Title" />
      <CommonPart Container="/alias=parent-term" />
      <TermPart Count="0" Selectable="true" Weight="9" TaxonomyId="/alias=taxname" Path="/alias=parent-term" />
    </TaxNameTerm>
</Data>
</Orchard>
</code>```

This can be done after the parent term has been created as long as you've pointed the Path and Container at the parent.

Title: Orchard CMS taxonomy, import terms

Body:
I want to add several terms to an Orchard taxonomy, this taxonomy holds a large number of terms and if I added manually it would take me a life, so tried using the import, I know that it appends new terms but how to add a term under an existent parent term/s?

I tried something like this:

Parent term1;
    Children term1; taxonomy/test/parent-term1/children-term1

but i get:

The term Parent term1 already exists at this level

Is it possible to do?
Thanks.

Body:
My preferred method would be to do this through a recipe that creates the items. Here's a sample:

<Orchard>
<Data>
    <TaxNameTerm Id="/alias=parent-term" Status="Published">
      <TitlePart Title="Parent Term Title" />
      <CommonPart Container="/alias=taxname" />
      <TermPart Count="0" Selectable="true" Weight="9" TaxonomyId="/alias=taxname" Path="" />
    </TaxNameTerm>
    <TaxNameTerm Id="/alias=child-term" Status="Published">
      <TitlePart Title="Child Term Title" />
      <CommonPart Container="/alias=parent-term" />
      <TermPart Count="0" Selectable="true" Weight="9" TaxonomyId="/alias=taxname" Path="/alias=parent-term" />
    </TaxNameTerm>
</Data>
</Orchard>

This can be done after the parent term has been created as long as you've pointed the Path and Container at the parent.


问:
adding "uses-permission" in manifest doesn't work
SLOVED

Sending the intent like

```<code>Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
</code>```

In the onActivityResult method

```<code>imageUri = data.getData();
    getContentResolver().takePersistableUriPermission(imageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
</code>```

I have found that this is a common issue. I am getting a java.lang.SecurityException: Permission Denial:
error when trying to userImg.setImageURI(tmp.photo);
 in my code. I have tried many solutions found on SO but nothing. I also tried using glide but no luck there.
The uri is read into an object, which I store in memory on runtime, and I request it with tmp.photo. I checked with logging that the Uri is passed successfully into the photo attribute. What can I do?

these are into my manifest.

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

My code is very simple.

```<code>ImageView userImg = (ImageView) findViewById(R.id.userImg);
userImg.setImageURI(tmp.photo);
</code>```

wheretmp.photo is a Uri object.
This generates all of these

```<code>Unable to open content: content://com.android.providers.media.documents/document/image%3A156
java.lang.SecurityException: Permission Denial:
opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord
{74dbab7 13175:com.example.gus.uniman/u0a168} (pid=13175, uid=10168) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
at android.os.Parcel.readException(Parcel.java:1684)
at android.os.Parcel.readException(Parcel.java:1637)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:4199)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5478)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2239)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1517)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1131)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
at android.widget.ImageView.getDrawableFromUri(ImageView.java:900)
at android.widget.ImageView.resolveUri(ImageView.java:871)
at android.widget.ImageView.setImageURI(ImageView.java:490)
at com.example.gus.uniman.PersonDetails.onCreate(PersonDetails.java:78)
at android.app.Activity.performCreate(Activity.java:6682)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2619)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
06-07 19:24:36.919 13175-13175/com.example.gus.uniman W/ImageView: resolveUri failed on bad bitmap uri: content://com.android.providers.media.documents/document/image%3A156
06-07 19:24:37.030 13175-13207/com.example.gus.uniman D/OpenGLRenderer: endAllActiveAnimators on 0x76706ab800 (ListView) with handle 0x768d4df4a0
</code>```

答:
You only have rights to the content identified by the Uri:

In your original component (e.g., the activity that got the Uri via onActivityResult() of ACTION_GET_CONTENT), or

In any components that you pass the Uri to, if you include FLAG_GRANT_READ_URI_PERMISSION in the Intent used to start that component, and

Only while your process is around

In your case, somewhere along the line, you violated those rules. Perhaps you passed the Uri to another component without FLAG_GRANT_READ_URI_PERMISSION, or perhaps you saved the Uri to disk and attempted to use it again later.

See this blog post for more about Uri access lifetime.

Body:
SLOVED

Sending the intent like

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);

In the onActivityResult method

imageUri = data.getData();
    getContentResolver().takePersistableUriPermission(imageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

I have found that this is a common issue. I am getting a java.lang.SecurityException: Permission Denial:
error when trying to userImg.setImageURI(tmp.photo);
 in my code. I have tried many solutions found on SO but nothing. I also tried using glide but no luck there.
The uri is read into an object, which I store in memory on runtime, and I request it with tmp.photo. I checked with logging that the Uri is passed successfully into the photo attribute. What can I do?

these are into my manifest.

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

My code is very simple.

ImageView userImg = (ImageView) findViewById(R.id.userImg);
userImg.setImageURI(tmp.photo);

wheretmp.photo is a Uri object.
This generates all of these

Unable to open content: content://com.android.providers.media.documents/document/image%3A156
java.lang.SecurityException: Permission Denial:
opening provider com.android.providers.media.MediaDocumentsProvider from ProcessRecord
{74dbab7 13175:com.example.gus.uniman/u0a168} (pid=13175, uid=10168) requires android.permission.MANAGE_DOCUMENTS or android.permission.MANAGE_DOCUMENTS
at android.os.Parcel.readException(Parcel.java:1684)
at android.os.Parcel.readException(Parcel.java:1637)
at android.app.ActivityManagerProxy.getContentProvider(ActivityManagerNative.java:4199)
at android.app.ActivityThread.acquireProvider(ActivityThread.java:5478)
at android.app.ContextImpl$ApplicationContentResolver.acquireUnstableProvider(ContextImpl.java:2239)
at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1517)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1131)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
at android.widget.ImageView.getDrawableFromUri(ImageView.java:900)
at android.widget.ImageView.resolveUri(ImageView.java:871)
at android.widget.ImageView.setImageURI(ImageView.java:490)
at com.example.gus.uniman.PersonDetails.onCreate(PersonDetails.java:78)
at android.app.Activity.performCreate(Activity.java:6682)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2619)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6121)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
06-07 19:24:36.919 13175-13175/com.example.gus.uniman W/ImageView: resolveUri failed on bad bitmap uri: content://com.android.providers.media.documents/document/image%3A156
06-07 19:24:37.030 13175-13207/com.example.gus.uniman D/OpenGLRenderer: endAllActiveAnimators on 0x76706ab800 (ListView) with handle 0x768d4df4a0


问:
CheckBox to switch interior color of all cells
Hi I want to make a macro that switch the backgroung color of all cells with a specific color RGB(252, 252, 250) to another color RGB(217, 217, 217) in entire workbook</p>

答:
Try this macro,

```<code>Sub colorSwitch()
Dim i As Long, j As Long
For i = 1 To Rows.Count
For j = 1 To Columns.Count
    If Cells(i, j).Interior.Color = RGB(252, 252, 250) Then
        Cells(i, j).Interior.Color = RGB(217, 217, 217)
    End If
Next j
Next i
End Sub
</code>```

But this would take a while to execute as it loops through all cells in the sheet. It would be better if you have a short range, which you can provide with the i and j variant for the macro to execute faster.

Body:
Try this macro,

Sub colorSwitch()
Dim i As Long, j As Long
For i = 1 To Rows.Count
For j = 1 To Columns.Count
    If Cells(i, j).Interior.Color = RGB(252, 252, 250) Then
        Cells(i, j).Interior.Color = RGB(217, 217, 217)
    End If
Next j
Next i
End Sub

But this would take a while to execute as it loops through all cells in the sheet. It would be better if you have a short range, which you can provide with the i and j variant for the macro to execute faster.


问:
Calculate days excluding weekends in Sharepoint2010
How do I exclude weekends(sat and sun) when counting number of days between a start and end time in Sharepoint 2010 calculate column.

1.I have a calendar added to Sharepoint 2010 and there is two columns as start time and end time and now my requirement is to calculate the number of days between star time and end time excluding the weekends(sat and sun) means it will calculate working days only.
tried this

```<code>=IF(AND((WEEKDAY(EndDate,2))<(WEEKDAY(StartDate,2)),((WEEKDAY(StartDate,2))-(WEEKDAY(EndDate,2)))>1),(((DATEDIF(StartDate,EndDate,"D")+1))-(FLOOR((DATEDIF(StartDate,EndDate,"D")+1)/7,1)*2)-2),(((DATEDIF(StartDate,EndDate,"D")+1))-(FLOOR((DATEDIF(StartDate,EndDate,"D")+1)/7,1)*2)))
</code>```

Also,

```<code>=(DATEDIF([StartDate],[EndDate],"d"))-INT(DATEDIF([StartDate],[EndDate],"d")/7)*2-IF((WEEKDAY([EndDate])-WEEKDAY([StartDate]))>0,2,0)+1
</code>```

but not getting the correct output.

答:
This worked best for me. </p>

```<code>ROUNDUP(([End Time]-[Start Time]),0)-IF(WEEKDAY([End Time])=7,FLOOR((DATEDIF([Start Time],[End Time],"D")+WEEKDAY([Start Time]))/7,1)*2,FLOOR((DATEDIF([Start Time],[End Time],"D")+WEEKDAY([Start Time]))/7,1)*2+1)+IF(WEEKDAY([Start Time])=7,2,1)
</code>```

Body:
How do I exclude weekends(sat and sun) when counting number of days between a start and end time in Sharepoint 2010 calculate column.

1.I have a calendar added to Sharepoint 2010 and there is two columns as start time and end time and now my requirement is to calculate the number of days between star time and end time excluding the weekends(sat and sun) means it will calculate working days only.
tried this

=IF(AND((WEEKDAY(EndDate,2))<(WEEKDAY(StartDate,2)),((WEEKDAY(StartDate,2))-(WEEKDAY(EndDate,2)))>1),(((DATEDIF(StartDate,EndDate,"D")+1))-(FLOOR((DATEDIF(StartDate,EndDate,"D")+1)/7,1)*2)-2),(((DATEDIF(StartDate,EndDate,"D")+1))-(FLOOR((DATEDIF(StartDate,EndDate,"D")+1)/7,1)*2)))

Also,

=(DATEDIF([StartDate],[EndDate],"d"))-INT(DATEDIF([StartDate],[EndDate],"d")/7)*2-IF((WEEKDAY([EndDate])-WEEKDAY([StartDate]))>0,2,0)+1

but not getting the correct output.

Body:
This worked best for me.

ROUNDUP(([End Time]-[Start Time]),0)-IF(WEEKDAY([End Time])=7,FLOOR((DATEDIF([Start Time],[End Time],"D")+WEEKDAY([Start Time]))/7,1)*2,FLOOR((DATEDIF([Start Time],[End Time],"D")+WEEKDAY([Start Time]))/7,1)*2+1)+IF(WEEKDAY([Start Time])=7,2,1)


问:
Constructor behaving like a method
I'm new to Java so not really sure if it's an error on my part. My project has two packages within. I'm trying to use an object belonging to a class of package lovo in an object of a class of package j2. The constructor of object belonging to package lovo is now being treated as a method. Why is that?

```<code>package j2;
import lovo.kulo;

public class J2
{

public static void main(String[] args)
      {

    kulo kla ;
    kla = new kulo();
    //kla.kulo();
      }
}

package lovo;

public class kulo {
    public void kulo(){
    System.out.print("This is supposed to be a constructor");}

}
</code>```

When i run there is no output, however when i remove the comment and add it as code there is an output. Since it's a constructor shouldn't it print as soon as the object is created?

答: It is indeed a method. To make it a constructor, remove the void return type. It'll also be less confusing if you follow Java naming conventions and begin class names (and therefore constructor names) with an uppercase letter.

Title: Constructor behaving like a method

Body:
I'm new to Java so not really sure if it's an error on my part. My project has two packages within. I'm trying to use an object belonging to a class of package lovo in an object of a class of package j2. The constructor of object belonging to package lovo is now being treated as a method. Why is that?

package j2;
import lovo.kulo;

public class J2
{

public static void main(String[] args)
      {

    kulo kla ;
    kla = new kulo();
    //kla.kulo();
      }
}

package lovo;

public class kulo {
    public void kulo(){
    System.out.print("This is supposed to be a constructor");}

}

When i run there is no output, however when i remove the comment and add it as code there is an output. Since it's a constructor shouldn't it print as soon as the object is created?


问:
UIView: How do i make the width automatically end before another image?
Right so i have this image:

And i need the width of the red bar to fit between the 2 images (Buttons) on all devices.

I have looked for answers but i haven't found anything that works yet.

This is the code I'm using:

```<code>_background = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 353, 20)];
    [self addSubview:_background];
    [self sendSubviewToBack:_background];
    [_background setBackgroundColor:[UIColor redColor]];
    _background.layer.cornerRadius = 10;
    _background.clipsToBounds = YES;
    _background.center = CGPointMake(200, 15);
    _background.keepLeftOffsetTo(_sendButton);
    _background.keepCenterAlignTo(self);
    [_background updateConstraintsIfNeeded];
</code>```

There may very well be an easy fix for this but I've only been on Objective-C for about a month! (Coming from Android Java).

Any help would be great right now

Thanks

Update #1: I've tried using Masonry as suggested but i still can't achieve what i need.

答:
you need to use Autolayout to achieve this.

If you are using storyboard to create the above layout, then you need to constraint the redView in between the buttons.

Set the redView leading constraint to the firstImageView.

Set the redViw trailing constraint to the last imageView.

You need to give the height constraint to the redView.

Other constraints for the first and last imageviews:

You need to give the top, height,width cosntraints to the first and last imageviews.

If you are not using storyboard, I suggest to look into MAsonry to apply constraints programmatically.

Body:
Right so i have this image:

And i need the width of the red bar to fit between the 2 images (Buttons) on all devices.

I have looked for answers but i haven't found anything that works yet.

This is the code I'm using:

_background = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 353, 20)];
    [self addSubview:_background];
    [self sendSubviewToBack:_background];
    [_background setBackgroundColor:[UIColor redColor]];
    _background.layer.cornerRadius = 10;
    _background.clipsToBounds = YES;
    _background.center = CGPointMake(200, 15);
    _background.keepLeftOffsetTo(_sendButton);
    _background.keepCenterAlignTo(self);
    [_background updateConstraintsIfNeeded];

There may very well be an easy fix for this but I've only been on Objective-C for about a month! (Coming from Android Java).

Any help would be great right now

Thanks

Update #1: I've tried using Masonry as suggested but i still can't achieve what i need.


问:
Adding JSON objects to existing JSON File
So I've recently been tasked with creating a utility which will allow easy addition of JSON to a .json file via the gson library. I've coded this in Kotlin:

```<code>fun addObject(filePath: String, name: String, values: Array<Array<String>>) {
try {

    var writer: JsonWriter = JsonWriter(FileWriter(File(filePath)))
    writer.beginObject()
    writer.name(name)
    writer.beginObject()
    for(item in values){
        writer.name(item[0]).value(item[1])
    }
    writer.endObject()
    writer.endObject()

    writer.close()

    println("[JSONUtil] Wrote object successfully!")

} catch (e: IOException) {
    e.printStackTrace()
}
}
</code>```

I used a 2 Dimensional array to allow the user to add different objects with any number of values in said object. For instance, you would run it like so:

```<code>addObject("C:\\Users\\Test\\Desktop\\JsonUtility\\output.json", "GENERAL",
arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")))
</code>```

This creates the following JSON:

```<code>{"GENERAL":{"POS_X":"2","POS_Y":"4"}}
</code>```

This is how it was intended and works, my issue is that upon running the function again it completely overwrites the previous JSON in the file, and this is obviously bad.

My questions are:

How can I add new JSON objects inside the entire file, or at specific points, like "addObject("GENERAL", ...)" for this example?

How can I make this better?

I'm fairly new to Kotlin and have been coding in Java mostly, so Java solutions are fine as I'm sure I'll be able to convert it.

Thanks in advance!

EDIT: New Code, no idea how to implement it:

```<code>fun UpdateJson(path: String, name: String, value: String){
    var gson = Gson()
    var reader: FileReader = FileReader(File(path))

    val type = object : TypeToken<Map<String, String>>() {}.type
    println("Type: " + type.toString())
    println("Existing Json: ${gson.fromJson<Map<String,String>>
    (JsonReader(reader), type)}")
    var existingJson: Map<String, String> =
    gson.fromJson<Map<String,String>>(JsonReader(reader), type)
    existingJson.put(name, value)
    FileWriter(File(path)).use({ writer ->
    writer.write(gson.toJson(existingJson)) })
}
</code>```

答:
The easiest way is to, as @KrisRoofe suggested, read the json, then add an element. I would do this by converting the existing json in the file to a Map. Since you don't actually care about the existing json, all you want to do is add a new entry to that Map. Once you do that, simply write the new Map to the File. You can do this like so:

```<code>public class UpdateJson {
    public static void main(String[] args) throws IOException {
        addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")));
    }

    private static void addObject(String fileName, String newObjName, String newObjValue) throws IOException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> existingJson = gson.fromJson(new JsonReader(new FileReader(new File(fileName))), type);
        existingJson.put(newObjName, newObjValue);
        try (FileWriter writer = new FileWriter(new File(fileName))) {
            writer.write(gson.toJson(existingJson));
        }
    }

    private static String arrayOf(String s1, String s2) {
        return "[" + s1 + ", " + s2 + "]";
    }
}
</code>```

EDIT:
The above solution is a Java solution. There seems to be an issue with the Type in Kotlin.

This Stack Overflow question has a workaround by using object:

Also, note that to use reflection with Kotlin, you need a separate jar, according to Kotlin documentation'

EDIT 2: Provided Kotlin Answer:

```<code>fun main(args: Array<String>) {
    addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X", "2"), arrayOf("POS_Y", "4")))
}

fun addObject(path: String, name: String, value: String) {
    val gson = Gson()
    val reader: FileReader = FileReader(File(path))
    val type = object : TypeToken<Map<String, String>>() {}.type
    System.out.println("Type: " + type.toString())
    val existingJson = gson.fromJson<Map<String, String>>(JsonReader(reader), type)
    System.out.println("Existing Json: ${existingJson}")
    val newJsonMap = existingJson.plus(Pair(name, value))
    FileWriter(File(path)).use(
        { writer -> writer.write(gson.toJson(newJsonMap)) }
    )
}

fun arrayOf(s1: String, s2: String): String {
    return "[$s1, $s2]"
}
</code>```

Body:
So I've recently been tasked with creating a utility which will allow easy addition of JSON to a .json file via the gson library. I've coded this in Kotlin:

fun addObject(filePath: String, name: String, values: Array<Array<String>>) {
try {

    var writer: JsonWriter = JsonWriter(FileWriter(File(filePath)))
    writer.beginObject()
    writer.name(name)
    writer.beginObject()
    for(item in values){
        writer.name(item[0]).value(item[1])
    }
    writer.endObject()
    writer.endObject()

    writer.close()

    println("[JSONUtil] Wrote object successfully!")

} catch (e: IOException) {
    e.printStackTrace()
}
}

I used a 2 Dimensional array to allow the user to add different objects with any number of values in said object. For instance, you would run it like so:

addObject("C:\\Users\\Test\\Desktop\\JsonUtility\\output.json", "GENERAL",
arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")))

This creates the following JSON:

{"GENERAL":{"POS_X":"2","POS_Y":"4"}}

This is how it was intended and works, my issue is that upon running the function again it completely overwrites the previous JSON in the file, and this is obviously bad.

My questions are:

How can I add new JSON objects inside the entire file, or at specific points, like "addObject("GENERAL", ...)" for this example?

How can I make this better?

I'm fairly new to Kotlin and have been coding in Java mostly, so Java solutions are fine as I'm sure I'll be able to convert it.

Thanks in advance!

EDIT: New Code, no idea how to implement it:

fun UpdateJson(path: String, name: String, value: String){
    var gson = Gson()
    var reader: FileReader = FileReader(File(path))

    val type = object : TypeToken<Map<String, String>>() {}.type
    println("Type: " + type.toString())
    println("Existing Json: ${gson.fromJson<Map<String,String>>
    (JsonReader(reader), type)}")
    var existingJson: Map<String, String> =
    gson.fromJson<Map<String,String>>(JsonReader(reader), type)
    existingJson.put(name, value)
    FileWriter(File(path)).use({ writer ->
    writer.write(gson.toJson(existingJson)) })
}

Body:
The easiest way is to, as @KrisRoofe suggested, read the json, then add an element. I would do this by converting the existing json in the file to a Map. Since you don't actually care about the existing json, all you want to do is add a new entry to that Map. Once you do that, simply write the new Map to the File. You can do this like so:

public class UpdateJson {
    public static void main(String[] args) throws IOException {
        addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X","2"), arrayOf("POS_Y","4")));
    }

    private static void addObject(String fileName, String newObjName, String newObjValue) throws IOException {
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> existingJson = gson.fromJson(new JsonReader(new FileReader(new File(fileName))), type);
        existingJson.put(newObjName, newObjValue);
        try (FileWriter writer = new FileWriter(new File(fileName))) {
            writer.write(gson.toJson(existingJson));
        }
    }

    private static String arrayOf(String s1, String s2) {
        return "[" + s1 + ", " + s2 + "]";
    }
}

EDIT:
The above solution is a Java solution. There seems to be an issue with the Type in Kotlin.

This Stack Overflow question has a workaround by using object:

Also, note that to use reflection with Kotlin, you need a separate jar, according to Kotlin documentation'

EDIT 2: Provided Kotlin Answer:

fun main(args: Array<String>) {
    addObject("example.json", "GENERAL", arrayOf(arrayOf("POS_X", "2"), arrayOf("POS_Y", "4")))
}

fun addObject(path: String, name: String, value: String) {
    val gson = Gson()
    val reader: FileReader = FileReader(File(path))
    val type = object : TypeToken<Map<String, String>>() {}.type
    System.out.println("Type: " + type.toString())
    val existingJson = gson.fromJson<Map<String, String>>(JsonReader(reader), type)
    System.out.println("Existing Json: ${existingJson}")
    val newJsonMap = existingJson.plus(Pair(name, value))
    FileWriter(File(path)).use(
        { writer -> writer.write(gson.toJson(newJsonMap)) }
    )
}

fun arrayOf(s1: String, s2: String): String {
    return "[$s1, $s2]"
}


问:
AutoHotKey: detect single key release in keycombo for Firefox
Trying to configure key combination Alt+Tab to behave as tab switcher in Firefox with the help of AutoHotKey:

```<code>#IfWinActive Showcase
    LAlt & Tab::Send {tab}
    GetKeyState, state, LAlt
    if state = U
        Send {enter}
</code>```

Basically this prevents Alt+Tab from bringing up the ordinary window switcher of Windows and cycles through open tabs as Tab is being pushed. However, as i’m trying to simulate the behaviour of Windows’ window switcher, i also want this to bring up – Send {enter} – the last selected tab when Left Alt is released. And this i can’t seem to accomplish, as GetKeyState just won’t respond, even though state becomes U. How can key release be detected in this case?

ADD:

So i ended up with the following code, which for the dominant part does what i wanted:

```<code>

    #IfWinActive ahk_exe firefox.exe  <i>; Alt+Tab to Windows</i>
        LAlt & tab::
        Send {F10}  <i>; F10 brings up Showcase in my FF installation</i>
        WinWaitActive Showcase
        GetKeyState, state, LAlt, P
            if state = U
                WinClose Showcase
        IfWinNotActive Showcase
            Send {LWin}
    #IfWinActive Showcase  <i>; Alt+Tab over Firefox’s tabs</i>
        LAlt & tab::
        Send {tab}
        SetTimer, choice, -50
        return
        choice:  <i>; Thanks, <a href="http://stackoverflow.com/a/44418837#44418837">@user3419297</a>!</i>
            KeyWait, LAlt, P
            IfWinActive Showcase
                Send {LAlt up} {space}
        return
    #IfWinActive ahk_exe firefox.exe  <i>; Win+Tab over Firefox’s tabs</i>
        LWin::F10
    #IfWinActive Showcase  <i>; Win+Tab to Windows</i>
        tab::return
        LWin & tab::
        WinClose Showcase
        WinWaitClose Showcase
        WinMinimize ahk_exe firefox.exe
        Send {LWin down} {tab} {LWin up}
    return
    ExitApp

</code>```

This in fact simulates both Alt+ & Win+Tab behaviour in Firefox, which i usually use in fullscreen mode:

pushing Tab while holding down Alt will cycle through open tabs the same way Alt+Tab cycles windows

to get out of FF to Windows, Alt+Tab are quickly pushed and released; this will bring up the Start Menu from where one can use Alt+Tab the normal way

Win+Tab work a bit differently in Windows, in the way that one don’t need to hold down Win for it to stay up, and (at least in Windows 10) one can’t cycle through windows with Tab; this is also simulated the same way here by pushing Win+Tab (actually just Win is enough, but for consistency i press both); Tab is also blocked so it can’t cycle, to simulate the way real Win+Tab works in Windows

to get out of Firefox’s Win+Tab to Windows, the said combo is pushed once more – this will bring up the normal Win+Tab of Windows 10; the taskbar can also be easily accessed this way

Since i didn’t know any AutoHotKey before, looking back this was probably a bit of an overkill task to start with. However, this did force me to actually learn how to programme in AHK, while dusting off my overall programming skill. And for that this has been great. I often found myself instinctively pushing Alt+Tab inside Firefox to cycle through tabs as one would do with windows, only to be reminded that this in fact only works with windows in Windows. Until recently, that is :)

答:
```<code>#IfWinActive Showcase

    LAlt & Tab::
        Send {Tab}
        SetTimer Send_Enter, -50
    return

#IfWinActive     ; turn off context sensitivity

Send_Enter:
    KeyWait, LAlt, L
    Send {Alt Up}{Enter}
return
</code>```

Body:
Trying to configure key combination Alt+Tab to behave as tab switcher in Firefox with the help of AutoHotKey:

#IfWinActive Showcase
    LAlt & Tab::Send {tab}
    GetKeyState, state, LAlt
    if state = U
        Send {enter}

Basically this prevents Alt+Tab from bringing up the ordinary window switcher of Windows and cycles through open tabs as Tab is being pushed. However, as i’m trying to simulate the behaviour of Windows’ window switcher, i also want this to bring up – Send {enter} – the last selected tab when Left Alt is released. And this i can’t seem to accomplish, as GetKeyState just won’t respond, even though state becomes U. How can key release be detected in this case?

ADD:

So i ended up with the following code, which for the dominant part does what i wanted:

    #IfWinActive ahk_exe firefox.exe  ; Alt+Tab to Windows
        LAlt & tab::
        Send {F10}  ; F10 brings up Showcase in my FF installation
        WinWaitActive Showcase
        GetKeyState, state, LAlt, P
            if state = U
                WinClose Showcase
        IfWinNotActive Showcase
            Send {LWin}
    #IfWinActive Showcase  ; Alt+Tab over Firefox’s tabs
        LAlt & tab::
        Send {tab}
        SetTimer, choice, -50
        return
        choice:  ; Thanks, @user3419297!
            KeyWait, LAlt, P
            IfWinActive Showcase
                Send {LAlt up} {space}
        return
    #IfWinActive ahk_exe firefox.exe  ; Win+Tab over Firefox’s tabs
        LWin::F10
    #IfWinActive Showcase  ; Win+Tab to Windows
        tab::return
        LWin & tab::
        WinClose Showcase
        WinWaitClose Showcase
        WinMinimize ahk_exe firefox.exe
        Send {LWin down} {tab} {LWin up}
    return
    ExitApp

This in fact simulates both Alt+ & Win+Tab behaviour in Firefox, which i usually use in fullscreen mode:

pushing Tab while holding down Alt will cycle through open tabs the same way Alt+Tab cycles windows

to get out of FF to Windows, Alt+Tab are quickly pushed and released; this will bring up the Start Menu from where one can use Alt+Tab the normal way

Win+Tab work a bit differently in Windows, in the way that one don’t need to hold down Win for it to stay up, and (at least in Windows 10) one can’t cycle through windows with Tab; this is also simulated the same way here by pushing Win+Tab (actually just Win is enough, but for consistency i press both); Tab is also blocked so it can’t cycle, to simulate the way real Win+Tab works in Windows

to get out of Firefox’s Win+Tab to Windows, the said combo is pushed once more – this will bring up the normal Win+Tab of Windows 10; the taskbar can also be easily accessed this way

Since i didn’t know any AutoHotKey before, looking back this was probably a bit of an overkill task to start with. However, this did force me to actually learn how to programme in AHK, while dusting off my overall programming skill. And for that this has been great. I often found myself instinctively pushing Alt+Tab inside Firefox to cycle through tabs as one would do with windows, only to be reminded that this in fact only works with windows in Windows. Until recently, that is :)


问:
Jtable with conditional formatting like Excel
Does JTable supports 3 color conditional formatting like excel does.
Example:

I checked on google and all I could find assigning single color at a time to a cell which matches the criteria. I was wondering if I could just provide three colors and Jtable would assign shades of color according to the value of the cell.

答:
Here is one of the ways, how you can do this. Additional classes we can find here.

```<code>import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import general.VerticalTableHeaderCellRenderer;
import java.awt.Color;
import java.util.Random;
import javax.swing.table.TableCellRenderer;

//  The class of template for table's presentation of knowledge
//==============================================================================
public class ExcelTable extends JFrame {

    public static int rowCount = 1024;
    public static int colCount = 1024;
    public static int CHLength = 100;
    public static int RWLength = 50;
    public static int DCW = 20;

//  The constructor of this class
//==============================================================================
    public ExcelTable() {
        super("Draw cell rotate");
        setSize(400, 400);

        //The abstract model of table's presentation
        ListModel lm = new AbstractListModel() {
            String[] headers = new String[rowCount];

            @Override
            public int getSize() {
                return headers.length;
            }

            @Override
            public Object getElementAt(int index) {
                return headers[index];

            }
        };

        DefaultTableModel dtm = new DefaultTableModel(lm.getSize(), colCount);
        JTable table = new JTable(dtm) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
                Component comp = super.prepareRenderer(renderer, row, col);
                Object value = getModel().getValueAt(row, col);
                setCellSelectionEnabled(true);

// Here you can write you schemes
                final Random r = new Random();
                Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256), r.nextInt(256));

                if (getSelectedRow() != 0) {
                    if (row % 2 == 0 && col % 2 == 1) {
                        comp.setBackground(c);
                    } else if (row % 2 == 1 && row % 2 == 1) {
                        comp.setBackground(c);
                    } else {
                        comp.setBackground(c);
                    }
                } else {
                    comp.setBackground(Color.white);
                }
                return comp;
            }
        };
        table.getTableHeader().setDefaultRenderer(new VerticalTableHeaderCellRenderer());
        for (int i = 0; i < colCount; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(DCW);// .setTotalColumnWidth();
        }
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        table.setCellSelectionEnabled(true);

        // Create header rotation
        JList rowHeader = new JList(lm);
        // if (fieldlength)
        rowHeader.setFixedCellWidth(RWLength); //RowHeaser width
        rowHeader.setFixedCellHeight(table.getRowHeight());

        //Set render
        rowHeader.setCellRenderer(new RowRenderer(table));

        //JScrollPane
        JScrollPane pane = new JScrollPane(table);
        pane.setColumnHeader(new JViewport() {
            @Override
            public Dimension getPreferredSize() {
                Dimension d = super.getPreferredSize();
                d.height = CHLength;  // Col header Height
                return d;
            }
        });
        pane.setRowHeaderView(rowHeader);
        getContentPane().add(pane, BorderLayout.CENTER);

    }

//=========================================
    public static void main(String[] args) {
        ExcelTable jr = new ExcelTable();
        jr.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        jr.setVisible(true);
    }
}

class RowRenderer extends JLabel implements ListCellRenderer {

    public RowRenderer(JTable table) {
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        setText((value == null) ? "" : value.toString());
        return this;
    }
}
</code>```

OUTPUT:

also:
or

The desired color scheme you must implement into override method:

```<code>   @Override
    public Component prepareRenderer
    (TableCellRenderer renderer, int row, int col

        ) {
                Component comp = super.prepareRenderer(renderer, row, col);
        Object value = getModel().getValueAt(row, col);
        setCellSelectionEnabled(true);

    // Here you can write you schemes in RGB
// of course you need to describe it before mathematicaly
// and using variable `row` and `col` you will have coordinates to the cells
        final Random r = new Random();
        int R = r.nextInt(Math.round(256 / (row + 1)));
        int G = r.nextInt(Math.round(256 / (col + 1)));
        int B = r.nextInt(Math.round(256 / (row + col + 1)));
        Color c = new Color(R, G, B);

        if (getSelectedRow() != 0) {
            if (row % 2 == 0 && col % 2 == 1) {
                comp.setBackground(c);
            } else if (row % 2 == 1 && row % 2 == 1) {
                comp.setBackground(c);
            } else {
                comp.setBackground(c);
            }
        } else {
            comp.setBackground(Color.white);
        }
        return comp;
    }
};
</code>```

Body:
Here is one of the ways, how you can do this. Additional classes we can find here.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import static javax.swing.SwingConstants.CENTER;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;

import general.VerticalTableHeaderCellRenderer;
import java.awt.Color;
import java.util.Random;
import javax.swing.table.TableCellRenderer;

//  The class of template for table's presentation of knowledge
//==============================================================================
public class ExcelTable extends JFrame {

    public static int rowCount = 1024;
    public static int colCount = 1024;
    public static int CHLength = 100;
    public static int RWLength = 50;
    public static int DCW = 20;

//  The constructor of this class
//==============================================================================
    public ExcelTable() {
        super("Draw cell rotate");
        setSize(400, 400);

        //The abstract model of table's presentation
        ListModel lm = new AbstractListModel() {
            String[] headers = new String[rowCount];

            @Override
            public int getSize() {
                return headers.length;
            }

            @Override
            public Object getElementAt(int index) {
                return headers[index];

            }
        };

        DefaultTableModel dtm = new DefaultTableModel(lm.getSize(), colCount);
        JTable table = new JTable(dtm) {
            @Override
            public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
                Component comp = super.prepareRenderer(renderer, row, col);
                Object value = getModel().getValueAt(row, col);
                setCellSelectionEnabled(true);

// Here you can write you schemes
                final Random r = new Random();
                Color c = new Color(r.nextInt(256), r.nextInt(256), r.nextInt(256), r.nextInt(256));

                if (getSelectedRow() != 0) {
                    if (row % 2 == 0 && col % 2 == 1) {
                        comp.setBackground(c);
                    } else if (row % 2 == 1 && row % 2 == 1) {
                        comp.setBackground(c);
                    } else {
                        comp.setBackground(c);
                    }
                } else {
                    comp.setBackground(Color.white);
                }
                return comp;
            }
        };
        table.getTableHeader().setDefaultRenderer(new VerticalTableHeaderCellRenderer());
        for (int i = 0; i < colCount; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(DCW);// .setTotalColumnWidth();
        }
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        table.setCellSelectionEnabled(true);

        // Create header rotation
        JList rowHeader = new JList(lm);
        // if (fieldlength)
        rowHeader.setFixedCellWidth(RWLength); //RowHeaser width
        rowHeader.setFixedCellHeight(table.getRowHeight());

        //Set render
        rowHeader.setCellRenderer(new RowRenderer(table));

        //JScrollPane
        JScrollPane pane = new JScrollPane(table);
        pane.setColumnHeader(new JViewport() {
            @Override
            public Dimension getPreferredSize() {
                Dimension d = super.getPreferredSize();
                d.height = CHLength;  // Col header Height
                return d;
            }
        });
        pane.setRowHeaderView(rowHeader);
        getContentPane().add(pane, BorderLayout.CENTER);

    }

//=========================================
    public static void main(String[] args) {
        ExcelTable jr = new ExcelTable();
        jr.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        jr.setVisible(true);
    }
}

class RowRenderer extends JLabel implements ListCellRenderer {

    public RowRenderer(JTable table) {
        JTableHeader header = table.getTableHeader();
        setOpaque(true);
        setBorder(UIManager.getBorder("TableHeader.cellBorder"));
        setHorizontalAlignment(CENTER);
        setForeground(header.getForeground());
        setBackground(header.getBackground());
        setFont(header.getFont());
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        setText((value == null) ? "" : value.toString());
        return this;
    }
}

OUTPUT:

also:
or

The desired color scheme you must implement into override method:

   @Override
    public Component prepareRenderer
    (TableCellRenderer renderer, int row, int col

        ) {
                Component comp = super.prepareRenderer(renderer, row, col);
        Object value = getModel().getValueAt(row, col);
        setCellSelectionEnabled(true);

    // Here you can write you schemes in RGB
// of course you need to describe it before mathematicaly
// and using variable `row` and `col` you will have coordinates to the cells
        final Random r = new Random();
        int R = r.nextInt(Math.round(256 / (row + 1)));
        int G = r.nextInt(Math.round(256 / (col + 1)));
        int B = r.nextInt(Math.round(256 / (row + col + 1)));
        Color c = new Color(R, G, B);

        if (getSelectedRow() != 0) {
            if (row % 2 == 0 && col % 2 == 1) {
                comp.setBackground(c);
            } else if (row % 2 == 1 && row % 2 == 1) {
                comp.setBackground(c);
            } else {
                comp.setBackground(c);
            }
        } else {
            comp.setBackground(Color.white);
        }
        return comp;
    }
};