问:
Fetching data from a ReST Micro service in angular 2
I am trying to fetch data from a ReST Micro service which gives me data ( username and password) in JSON format ( [{"username":"Mark","password":"mark123"}] ) through its endpoint
"http://localhost:8080/checkUsers"

I created a simple application in angular 2 with userdetail.component.ts file and user.service.ts which fetches data from the userdata.json file placed in my apidata folder within assets folder in my application

Below shown is my code

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Http, Response} from '@angular/http';

import { AppComponent } from './app.component';
import { UserListComponent } from './user-list.component';
import {  UserDetailComponent } from './user-detail.component';
import { UserService } from './user.service';

@NgModule({
  declarations: [
    AppComponent,
    UserListComponent,
    UserDetailComponent
  ],

  imports: [ BrowserModule, HttpModule ],

  providers: [UserService],

  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',

  providers: [UserService]

})
export class AppComponent {
  title = '';
}
</code>```

app.component.html

```<code> <user-detail></user-detail>
</code>```

user-detail.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

@Component({
    selector: 'user-detail',
    template: `<h4>User Details</h4>'
                <ul *ngFor=" let user of users ">
                <li>username={{user.username}}-------password={{user.password}}</li>
                </ul>`
})

export class UserDetailComponent implements OnInit{
users = [];

constructor(private _userService:UserService){}
ngOnInit(){
this._userService.getUsers()
.subscribe(resUserData => this.users = resUserData);
}
}
</code>```

user.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {
private _url: string = "http://localhost:4200/assets/apidata/userdata.json"
constructor(private _http: Http){}
    getUsers(){
    return this._http.get(this._url)
    .map((response:Response) => response.json() );
}}
</code>```

can anybody please please guide through the process of fetching data from the ReST micro service in my angular 2 application.

答:
While working with the REST, we need to pre-fetch the essential data before loading (intializing) the component. To achieve this, implement the resolver and use the service as you implemented.

```<code>import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { UserService } from './user.service';

@Injectable()
export class UserDataResolver implements Resolve<any> {

    constructor(private userService: UserService,
                private router: Router) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.userService.getUsers()
            .map(response => {
                let users = response['users'];
                if (users) {
                    return users;
                }
                console.log(`NO users`);
                //navigate if you want to....
                this.router.navigate(['']);
                return null;
            })
            .catch(error => {
                console.log(`Retrieval error: ${error}`);
                this.router.navigate(['']);
                return Observable.of(null);
            });
    }
}
</code>```

Now use this resolver with routes to load the data through REST

```<code>const appRoutes: Routes = [
    {
     path: '',
     component: AppComponent,
     children: [
      { path: 'user', component: UserComponent, resolve: { users: UserDataResolver } }
     ]
    },
    { path: '**', component: PageNotFoundComponent }

];
</code>```

Access this data in the component:

```<code>@Component({
  selector: 'user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {

  usersList:any;
  constructor(private route: ActivatedRoute) {
   }

  ngOnInit() {
    this.usersList = this.route.snapshot.data['users'];
  }

}
</code>```

If you want to fetch some other data while working with the component, get it through services directly injected in to the component.

Body:
I am trying to fetch data from a ReST Micro service which gives me data ( username and password) in JSON format ( [{"username":"Mark","password":"mark123"}] ) through its endpoint
"http://localhost:8080/checkUsers"

I created a simple application in angular 2 with userdetail.component.ts file and user.service.ts which fetches data from the userdata.json file placed in my apidata folder within assets folder in my application

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Injectable } from '@angular/core';
import { HttpModule } from '@angular/http';
import { Http, Response} from '@angular/http';

import { AppComponent } from './app.component';
import { UserListComponent } from './user-list.component';
import {  UserDetailComponent } from './user-detail.component';
import { UserService } from './user.service';

@NgModule({
  declarations: [
    AppComponent,
    UserListComponent,
    UserDetailComponent
  ],

  imports: [ BrowserModule, HttpModule ],

  providers: [UserService],

  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',

  providers: [UserService]

})
export class AppComponent {
  title = '';
}

app.component.html

 <user-detail></user-detail>

user-detail.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

@Component({
    selector: 'user-detail',
    template: `
User Details
'

username={{user.username}}-------password={{user.password}}

`
})

export class UserDetailComponent implements OnInit{
users = [];

constructor(private _userService:UserService){}
ngOnInit(){
this._userService.getUsers()
.subscribe(resUserData => this.users = resUserData);
}
}

user.service.ts

import { Injectable } from '@angular/core';
import { Http, Response} from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class UserService {
private _url: string = "http://localhost:4200/assets/apidata/userdata.json"
constructor(private _http: Http){}
    getUsers(){
    return this._http.get(this._url)
    .map((response:Response) => response.json() );
}}

can anybody please please guide through the process of fetching data from the ReST micro service in my angular 2 application.

Body:
While working with the REST, we need to pre-fetch the essential data before loading (intializing) the component. To achieve this, implement the resolver and use the service as you implemented.

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { UserService } from './user.service';

@Injectable()
export class UserDataResolver implements Resolve<any> {

    constructor(private userService: UserService,
                private router: Router) { }

    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        return this.userService.getUsers()
            .map(response => {
                let users = response['users'];
                if (users) {
                    return users;
                }
                console.log(`NO users`);
                //navigate if you want to....
                this.router.navigate(['']);
                return null;
            })
            .catch(error => {
                console.log(`Retrieval error: ${error}`);
                this.router.navigate(['']);
                return Observable.of(null);
            });
    }
}

Now use this resolver with routes to load the data through REST

const appRoutes: Routes = [
    {
     path: '',
     component: AppComponent,
     children: [
      { path: 'user', component: UserComponent, resolve: { users: UserDataResolver } }
     ]
    },
    { path: '**', component: PageNotFoundComponent }

];

Access this data in the component:

@Component({
  selector: 'user-detail',
  templateUrl: './user-detail.component.html',
  styleUrls: ['./user-detail.component.css']
})
export class UserDetailComponent implements OnInit {

  usersList:any;
  constructor(private route: ActivatedRoute) {
   }

  ngOnInit() {
    this.usersList = this.route.snapshot.data['users'];
  }

}

If you want to fetch some other data while working with the component, get it through services directly injected in to the component.


来源: stackexchange

问:
Mininet Cannot find required executable controller
Whenever I want to run sshd.py example in mininet or some custome code I have written myself I get

```<code>*** Creating network
*** Adding controller
*** Adding hosts:
h1 h2 h3 h4 h5
*** Adding switches:
s1
*** Adding links:
(h1, s1) (h2, s1) (h3, s1) (h4, s1) (h5, s1)
*** Configuring hosts
h1 h2 h3 h4 h5
*** Starting controller
Cannot find required executable controller.
Please make sure that it is installed and available in your $PATH:
(/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin)
</code>```

Though $ sudo mn --test pingall works fine!

I guess I should find the open flow controller executable and add it to the path but I don't know where is it located. but the test create a controller and works fine!

I have tried to reinstalling mininet with

```<code>$ ~/mininet/util/install.sh -a or [-fnv]
</code>```

答:
In the newst versions of OVS, the ovs-controller was renamed to test-controller.

First install the openvswitch-testcontroller if you haven't with the following command:

```<code> sudo apt-get install openvswitch-testcontroller
</code>```

Second, create a symbolic link to the test-controller:

```<code> sudo ln /usr/bin/ovs-testcontroller /usr/bin/controller
</code>```

That works for me.

You also, can review this link: http://installfights.blogspot.com.co/2016/09/cannot-find-required-executable.html

ContentLicense: CC BY-SA 3.0

Body:
Whenever I want to run sshd.py example in mininet or some custome code I have written myself I get

*** Creating network
*** Adding controller
*** Adding hosts:
h1 h2 h3 h4 h5
*** Adding switches:
s1
*** Adding links:
(h1, s1) (h2, s1) (h3, s1) (h4, s1) (h5, s1)
*** Configuring hosts
h1 h2 h3 h4 h5
*** Starting controller
Cannot find required executable controller.
Please make sure that it is installed and available in your $PATH:
(/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin)

Though $ sudo mn --test pingall works fine!

I guess I should find the open flow controller executable and add it to the path but I don't know where is it located. but the test create a controller and works fine!

I have tried to reinstalling mininet with

$ ~/mininet/util/install.sh -a or [-fnv]

Body:
In the newst versions of OVS, the ovs-controller was renamed to test-controller.

First install the openvswitch-testcontroller if you haven't with the following command:

 sudo apt-get install openvswitch-testcontroller

Second, create a symbolic link to the test-controller:

 sudo ln /usr/bin/ovs-testcontroller /usr/bin/controller

That works for me.

You also, can review this link: http://installfights.blogspot.com.co/2016/09/cannot-find-required-executable.html


问:
Add suffix to comma-separated strings in bash ecosystem
Is there a way of transforming a comma-delimited variable to add a suffix to each token using standard gnu tools? e.g.

```<code>VARIABLE=`aaa,bbb,ccc`
suffix=`-foo`
Expected output = `aaa-foo,bbb-foo,ccc-foo`
</code>```

Additionally, if I have only one token, the transformation should behave in the same way

e.g. aaa -> aaa-foo

答:
The following:

```<code>s="aaa,bbb,ccc"
IFS=,
a=( $s )
mapfile -t b < <(printf '%s-foo\n' "${a[@]}")
</code>```

should give us:

```<code>$ declare -p b
declare -a b=([0]="aaa-foo" [1]="bbb-foo" [2]="ccc-foo")
</code>```

From there, if you can reconstruct the original format in a number of ways...

```<code>IFS=, eval 'JOINED="${b[*]}"'
</code>```

Or if you don't like using eval, perhaps:

```<code>d=""; o=""
for x in "${b[@]}"; do
  printf -v o '%s%s%s' "$o" "$d" "$x"
  d=,
done
</code>```

... which will put the complete modified string in $o.

Body:
Is there a way of transforming a comma-delimited variable to add a suffix to each token using standard gnu tools? e.g.

VARIABLE=`aaa,bbb,ccc`
suffix=`-foo`
Expected output = `aaa-foo,bbb-foo,ccc-foo`

Additionally, if I have only one token, the transformation should behave in the same way

e.g. aaa -> aaa-foo

Body:
The following:

s="aaa,bbb,ccc"
IFS=,
a=( $s )
mapfile -t b < <(printf '%s-foo\n' "${a[@]}")

should give us:

$ declare -p b
declare -a b=([0]="aaa-foo" [1]="bbb-foo" [2]="ccc-foo")

From there, if you can reconstruct the original format in a number of ways...

IFS=, eval 'JOINED="${b[*]}"'

Or if you don't like using eval, perhaps:

d=""; o=""
for x in "${b[@]}"; do
  printf -v o '%s%s%s' "$o" "$d" "$x"
  d=,
done

... which will put the complete modified string in $o.


问:
How to determine if a message is read in Slack using simple-slack-api
I'm using the simple-slack.api to send and receive Slack messages.
Is there a way to decide if a message was read?

I found that I can get the history of a channel, but the SlackMessagePosted does not contain any field if the message was read or not (the MessageSubType does not include it)

答:
Its not possible.

The Slack API (e.g. channels.history or conversations.history) does not provide any information about which messages are unread and by whom.

The only thing you get is the total number of unread messages for your current user as defined by the token you are using (by setting the parameter unreads to true), but I guess that is not what you are looking for.


问:
using underscore library with wordpress
I'm using underscore library for array manipulation. I enqueued the library with the following code in my functions.php

```<code>    add_action( 'wp_enqueue_scripts', 'jt_enqueue_scripts' );

    function jt_enqueue_scripts() {
        wp_enqueue_script( 'wp-util' );
    }
</code>```

But when i try using it in my code, i get reference error stating underscore is not defined.

```<code>$json = json_decode($response_body);
$items =  _.map($json,'items'); // throws error:'_' is not defined
echo '<script>console.log('.$items.')</script>';
</code>```

答:
The code you provided is from an old tutorial and some things have changed in WP.

So the way underscore is imported now is through a load-scripts.php, it has a GET parameter what to load. So underscore isn't in the wp-util file it is in its separate file \wp-includes\js\underscore.min.js

Here is how to include it:

wp_enqueue_script('undescore', includes_url('js') . '/underscore.min.js' );

Documentation for includes_url on devoloper.wordpress.org

Edit (another option)

As I stated above, WP uses the load-scripts.php file to load scripts from include, you can use this:
http://localhost/wp-admin/load-scripts.php?load=underscore

You can add a c= parameter for compression.

I don't recommend this method, use the above stated with enqueue scripts!!!

Title: using underscore library with wordpress

Body:
I'm using underscore library for array manipulation. I enqueued the library with the following code in my functions.php

    add_action( 'wp_enqueue_scripts', 'jt_enqueue_scripts' );

    function jt_enqueue_scripts() {
        wp_enqueue_script( 'wp-util' );
    }

But when i try using it in my code, i get reference error stating underscore is not defined.

$json = json_decode($response_body);
$items =  _.map($json,'items'); // throws error:'_' is not defined
echo '';


问:
Generate stl mesh from csv
I have a csv file that encodes elevation data of a 9000x5000 resolution photo of a dam, and I want to generate an stl file that I can print on my 3d printer. The csv has 3 parameters: X, Y, and Z, where X & Y denote a pixel location on the photo and Z is the elevation of the topography at Pixel (X,Y).
I want a 3D stl file of the photo in question with the nooks, crannies, and hills denoted by the elevation data. I attempted to do this using the Python library numpy-stl, but I'm realizing that I just don't know enough about stl files to accomplish the print job.
Any information on how I can make this file, or on how stl files encode information would be remarkably helpful.

答:
What you have is a collection of vertices. However, what STL encodes is a list of triangles. So what you need to do is to construct triangular mesh connecting your vertices. I assume that you want to code it yourself and I will provide you some hints on how to do it.

First, you should find out, whether your points are structured or not. By structured I mean that the x- and y-coordinates of the points form a regular grid (this is often the case when the data are obtained from airborne scanning).

If the points are structured

If the points are structured, you have a decent chance of constructing the mesh by yourself. Denote P(i,j) the point (X[i],Y[j],Z[i,j]), that is, the point whose first coordinate is the i-th number in the list of the x-coordinates, whose second coordinate is the j-th number in the list of y-coordinates and whose third coordinate is the z-coordinate corresponding to the first two. Figure 1 illustrates.

Now you need to decide the orientation of your triangles. They all should be either positively (counter-clockwise) or negatively oriented (clockwise). Assuming you decide for negative orientation, you can now create the triangle connecting the points P(i,j), P(i+1,j) and P(i+1,j+1). See Figure 2.

In the next step, you can create the neighbouring triangle with the same orientation, say P(i,j), P(i+1,j+1), P(i,j+1). See the darker triangle in Figure 3.

Proceeding the same way for all suitable i's and j's, you can obtain all the necessary triangles.

The only missing part is the normal for each triangle. This you can compute with a cross-product as suggested in this answer.

Now you are ready to write everything to your file. Following the description on Wikipedia, for each triangle you write its normal and the three vertices.

If the points aren't structured

In this situation you don't have much chance of creating your mesh without a significant study of meshing methods (you will probably need to learn about Delaunay triangulations). Fortunately, there are some libraries available. For instance, Fade2.5D is a C++ library that can help you and it is free of charge for personal non-commercial research. Maybe there is something similar available for Python as well.

Title: Generate stl mesh from csv


问:
Retrieve the instance created by class_based_view
Django documentation specify as_view method in
class-based-views

as_view() class method creates an instance of the class and calls its dispatch() method.

I attempt to print the instance.
 For illustration:

```<code> # urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
    url(r'^about/$', MyView.as_view()),
]

#views.py
from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')
</code>```

I added a print statement to views.py:

```<code>class MyView(View):
    print(self)
    def get(self, request):
        # <view logic>
        return HttpResponse('result')
</code>```

It reports NameError.

How can I print the instance created by class 'View'?

答:
Something like that will not print much usefulness like:

```<code><app.views.MyView object at 0x000001720304E128>
</code>```

Of course you can make it better by defining:

```<code>def __str__(self):
    return self.attibutehere
</code>```

However I get the feeling that you are looking for the implementation details of the class. This is done by a process called "introspection".

As an example amongst other powerful commands there is a dir() command which could be used like this from the command line:

```<code>project location>python manage.py shell
>>>from polls.views import IndexView
>>>iv=IndexView()
>>>dir(iv)
['__class__', ...whole bunch of interesting stuf here... , 'template_name_suffix']
>>> iv.__class__
<class 'polls.views.IndexView'>
</code>```

Body:
Django documentation specify as_view method in
class-based-views

as_view() class method creates an instance of the class and calls its dispatch() method.

I attempt to print the instance.
 For illustration:

 # urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
    url(r'^about/$', MyView.as_view()),
]

#views.py
from django.http import HttpResponse
from django.views import View

class MyView(View):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')

I added a print statement to views.py:

class MyView(View):
    print(self)
    def get(self, request):
        # <view logic>
        return HttpResponse('result')

It reports NameError.

How can I print the instance created by class 'View'?

Body:
Something like that will not print much usefulness like:

<app.views.MyView object at 0x000001720304E128>

Of course you can make it better by defining:

def __str__(self):
    return self.attibutehere

However I get the feeling that you are looking for the implementation details of the class. This is done by a process called "introspection".

As an example amongst other powerful commands there is a dir() command which could be used like this from the command line:

project location>python manage.py shell
>>>from polls.views import IndexView
>>>iv=IndexView()
>>>dir(iv)
['__class__', ...whole bunch of interesting stuf here... , 'template_name_suffix']
>>> iv.__class__
<class 'polls.views.IndexView'>


问:
Python: inotify, concurrent.futures - how to add exisiting files
I've got this simple script that processes files using inotify module and mulit-threading:

```<code>import concurrent.futures

import inotify.adapters

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/data')

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    # inotify event: IN_CLOSE_WRITE
                    if header.mask == 8:
                        future = executor.submit(process, filename.decode('utf-8'))
                        future.add_done_callback(future_callback)
        finally:
            i.remove_watch(b'/data')

if __name__ == '__main__':
    main()
</code>```

The problem I've got is that the watched directory can have many files before the script is actually started.

I thought about something like the example below but this won't start "yielding" inotify generator until all existing files are processed and it will also miss new events created during this time:

```<code>import concurrent.futures

import inotify.adapters

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/data')

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        files = os.listdir('/data')
        if files:
            for filename in files:
                future = executor.submit(run, filename)
                future.add_done_callback(future_callback)
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    # inotify event: IN_CLOSE_WRITE
                    if header.mask == 8:
                        future = executor.submit(process, filename.decode('utf-8'))
                        future.add_done_callback(future_callback)
        finally:
            i.remove_watch(b'/data')

if __name__ == '__main__':
    main()
</code>```

Is there a way to manually send inotify event or perhaps add these files to i.event_gen() generator?

答:
Here's an example that processes the old files inside one of the workers allowing for new events to be captured in parallel while processing the old, existing files. For the record, even using your linear code, I had no trouble with missing events.

Also, the PyInotify module is "defunct and no longer available." according to this inotify module which I used.

```<code>#!/usr/bin/env python3

import concurrent.futures
import inotify.adapters
import time
import os
from functools import partial

DIRECTORY='.'

def run(filename, suffix=''):
    time.sleep(1)
    return 'run: ' + filename + suffix

def process(filename):
    return run(filename, suffix=' (inotify)')

def future_callback(fut):
    print('future_callback: ' + fut.result())

def do_directory(executor):
    fn = partial(run, suffix=' (dir list)')
    for filename in os.listdir(DIRECTORY):
        future = executor.submit(fn, filename)
        future.add_done_callback(future_callback)

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(DIRECTORY.encode())

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        # Process the directory in a thread or locally. Not sure if it
        # is safe to submit to the executor from within one its workers.
        # Seems like it should be.
        executor.submit(do_directory, executor)
        # do_directory(executor)
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    # inotify event: IN_CLOSE_WRITE
                    if header.mask == 8:
                        future = executor.submit(process, filename.decode('utf-8'))
                        future.add_done_callback(future_callback)
                        print('Submitted inotify for', filename.decode())
        except KeyboardInterrupt:
            pass
        finally:
            i.remove_watch(DIRECTORY.encode())

if __name__ == '__main__':
    main()
</code>```

Test:

Start with a directory containing 10 files. Start the program, wait 2 seconds, and then create 5 new files. Look for the "submit" messages to see that the events were received and queued while still processing the initial files and that the new files are eventually handled.

```<code>~/p/TEST $ touch A1 A2 A3 A4 A5 A6 A7 A8 A9 A10
~/p/TEST $ do_test() {
> rm B*
> ../inotify-test.py &
> sleep 2
> touch B1 B2 B3 B4 B5
> sleep 5
> pkill -f inotify-test.py
> }
~/p/TEST $ do_test
[1] 26663
future_callback: run: A10 (dir list)
future_callback: run: A4 (dir list)
future_callback: run: A5 (dir list)
future_callback: run: A9 (dir list)
future_callback: run: A2 (dir list)
Submitted inotify for B1
Submitted inotify for B2
Submitted inotify for B3
Submitted inotify for B4
Submitted inotify for B5
future_callback: run: A3 (dir list)
future_callback: run: A8 (dir list)
future_callback: run: A1 (dir list)
future_callback: run: A7 (dir list)
future_callback: run: A6 (dir list)
future_callback: run: B1 (inotify)
future_callback: run: B2 (inotify)
future_callback: run: B3 (inotify)
future_callback: run: B4 (inotify)
future_callback: run: B5 (inotify)
~/p/TEST $
[1]+  Terminated              ../inotify-test.py
~/p/TEST $
</code>```

Body:
I've got this simple script that processes files using inotify module and mulit-threading:

import concurrent.futures

import inotify.adapters

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/data')

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    # inotify event: IN_CLOSE_WRITE
                    if header.mask == 8:
                        future = executor.submit(process, filename.decode('utf-8'))
                        future.add_done_callback(future_callback)
        finally:
            i.remove_watch(b'/data')

if __name__ == '__main__':
    main()

The problem I've got is that the watched directory can have many files before the script is actually started.

I thought about something like the example below but this won't start "yielding" inotify generator until all existing files are processed and it will also miss new events created during this time:

import concurrent.futures

import inotify.adapters

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(b'/data')

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        files = os.listdir('/data')
        if files:
            for filename in files:
                future = executor.submit(run, filename)
                future.add_done_callback(future_callback)
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    # inotify event: IN_CLOSE_WRITE
                    if header.mask == 8:
                        future = executor.submit(process, filename.decode('utf-8'))
                        future.add_done_callback(future_callback)
        finally:
            i.remove_watch(b'/data')

if __name__ == '__main__':
    main()

Is there a way to manually send inotify event or perhaps add these files to i.event_gen() generator?

Body:
Here's an example that processes the old files inside one of the workers allowing for new events to be captured in parallel while processing the old, existing files. For the record, even using your linear code, I had no trouble with missing events.

Also, the PyInotify module is "defunct and no longer available." according to this inotify module which I used.

#!/usr/bin/env python3

import concurrent.futures
import inotify.adapters
import time
import os
from functools import partial

DIRECTORY='.'

def run(filename, suffix=''):
    time.sleep(1)
    return 'run: ' + filename + suffix

def process(filename):
    return run(filename, suffix=' (inotify)')

def future_callback(fut):
    print('future_callback: ' + fut.result())

def do_directory(executor):
    fn = partial(run, suffix=' (dir list)')
    for filename in os.listdir(DIRECTORY):
        future = executor.submit(fn, filename)
        future.add_done_callback(future_callback)

def main():
    i = inotify.adapters.Inotify()

    i.add_watch(DIRECTORY.encode())

    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        # Process the directory in a thread or locally. Not sure if it
        # is safe to submit to the executor from within one its workers.
        # Seems like it should be.
        executor.submit(do_directory, executor)
        # do_directory(executor)
        try:
            for event in i.event_gen():
                if event is not None:
                    (header, type_names, watch_path, filename) = event
                    # inotify event: IN_CLOSE_WRITE
                    if header.mask == 8:
                        future = executor.submit(process, filename.decode('utf-8'))
                        future.add_done_callback(future_callback)
                        print('Submitted inotify for', filename.decode())
        except KeyboardInterrupt:
            pass
        finally:
            i.remove_watch(DIRECTORY.encode())

if __name__ == '__main__':
    main()

Test:

Start with a directory containing 10 files. Start the program, wait 2 seconds, and then create 5 new files. Look for the "submit" messages to see that the events were received and queued while still processing the initial files and that the new files are eventually handled.

~/p/TEST $ touch A1 A2 A3 A4 A5 A6 A7 A8 A9 A10
~/p/TEST $ do_test() {
> rm B*
> ../inotify-test.py &
> sleep 2
> touch B1 B2 B3 B4 B5
> sleep 5
> pkill -f inotify-test.py
> }
~/p/TEST $ do_test
[1] 26663
future_callback: run: A10 (dir list)
future_callback: run: A4 (dir list)
future_callback: run: A5 (dir list)
future_callback: run: A9 (dir list)
future_callback: run: A2 (dir list)
Submitted inotify for B1
Submitted inotify for B2
Submitted inotify for B3
Submitted inotify for B4
Submitted inotify for B5
future_callback: run: A3 (dir list)
future_callback: run: A8 (dir list)
future_callback: run: A1 (dir list)
future_callback: run: A7 (dir list)
future_callback: run: A6 (dir list)
future_callback: run: B1 (inotify)
future_callback: run: B2 (inotify)
future_callback: run: B3 (inotify)
future_callback: run: B4 (inotify)
future_callback: run: B5 (inotify)
~/p/TEST $
[1]+  Terminated              ../inotify-test.py
~/p/TEST $


问:
Get multiple connection strings from web.config
How to get all the connection strings's names from the web.config via code in C#?

I tried this:

```<code>System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection x = webConfig.ConnectionStrings;
string here = x.SectionInformation.Name;
</code>```

答:
This is how to use LINQ to get list of connection string names:

```<code>List<string> names = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .Select(v => v.Name)
    .ToList();
</code>```

Or you can build a dictionary of it:

```<code>Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .ToDictionary(v => v.Name, v => v.ConnectionString);
</code>```

Body:
How to get all the connection strings's names from the web.config via code in C#?

I tried this:

System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
ConnectionStringsSection x = webConfig.ConnectionStrings;
string here = x.SectionInformation.Name;

Body:
This is how to use LINQ to get list of connection string names:

List<string> names = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .Select(v => v.Name)
    .ToList();

Or you can build a dictionary of it:

Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
    .Cast<ConnectionStringSettings>()
    .ToDictionary(v => v.Name, v => v.ConnectionString);


问:
Fluent NHibernate - joined subclass ForeignKey Name
I am looking at moving to Fluent NHibernate - the only issue I have encounter so far is that you can not specify a foreign key name on a joined sub class mapping.

Has anyone got a solution for this, or a workaround?

I found this post but the suggestion clearly was not added to the code.

I would like to avoid customising the code myself if possible.

Any help would be great...

Example:

```<code>public class Product
{
    public string Name { get; set; }
}

public class Hammer : Product
{
    public string Description { get; set; }
}

public class ProductMap : ClassMap<Product, long>
{
    public ProductMap()
    {
        Polymorphism.Implicit();
        Map(x => x.Name);
    }
}

public class HammerMap : SubclassMap<Hammer>
{
    public HammerMap()
    {
        Extends<Product>();
    }
}
</code>```

This generates something like:

```<code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="field.camelcase-underscore" auto-import="false" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" dynamic-insert="true" dynamic-update="true" mutable="true" polymorphism="implicit" optimistic-lock="version" name="Domain.Product, Domain" table="Product">
    <id name="Id" type="System.Int64">
      <column name="Id" />
      <generator class="native">
        <param name="sequence">ProductId</param>
      </generator>
    </id>
    <property name="Name" type="System.String">
        <column name="Name" />
    </property>
    <joined-subclass name="Domain.Hammer, Domain" table="Hammer">
      <key>
        <column name="Product_Id" />
      </key>
        <property name="Description" type="System.String">
          <column name="Description" />
        </property>
    </joined-subclass>
  </class>
</hibernate-mapping>
</code>```

Note that there is no foreign key name specified in the mapping hbm file - as in:

```<code><joined-subclass name="Domain.Hammer, Domain" table="Hammer">
   <key column="Product_Id" foreign-key="FK_Hammer_Product"/>
</joined-subclass>
</code>```

答:
Try something like this</p>

```<code>public class JoinedSubclassForeignKeyConvention : IJoinedSubclassConvention
{
   public void Apply(IJoinedSubclassInstance instance)
   {
      instance.Key.ForeignKey(string.Format("FK_{0}_{1}",
                    instance.EntityType.Name, instance.Type.Name));
   }
}
</code>```

Body:
I am looking at moving to Fluent NHibernate - the only issue I have encounter so far is that you can not specify a foreign key name on a joined sub class mapping.

Has anyone got a solution for this, or a workaround?

I found this post but the suggestion clearly was not added to the code.

I would like to avoid customising the code myself if possible.

Any help would be great...

Example:

public class Product
{
    public string Name { get; set; }
}

public class Hammer : Product
{
    public string Description { get; set; }
}

public class ProductMap : ClassMap<Product, long>
{
    public ProductMap()
    {
        Polymorphism.Implicit();
        Map(x => x.Name);
    }
}

public class HammerMap : SubclassMap<Hammer>
{
    public HammerMap()
    {
        Extends<Product>();
    }
}

This generates something like:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="field.camelcase-underscore" auto-import="false" default-cascade="none" default-lazy="true">
  <class xmlns="urn:nhibernate-mapping-2.2" dynamic-insert="true" dynamic-update="true" mutable="true" polymorphism="implicit" optimistic-lock="version" name="Domain.Product, Domain" table="Product">
    <id name="Id" type="System.Int64">
      <column name="Id" />
      <generator class="native">
        <param name="sequence">ProductId</param>
      </generator>
    </id>
    <property name="Name" type="System.String">
        <column name="Name" />
    </property>
    <joined-subclass name="Domain.Hammer, Domain" table="Hammer">
      <key>
        <column name="Product_Id" />
      </key>
        <property name="Description" type="System.String">
          <column name="Description" />
        </property>
    </joined-subclass>
  </class>
</hibernate-mapping>

Note that there is no foreign key name specified in the mapping hbm file - as in:

<joined-subclass name="Domain.Hammer, Domain" table="Hammer">
   <key column="Product_Id" foreign-key="FK_Hammer_Product"/>
</joined-subclass>

Body:
Try something like this

public class JoinedSubclassForeignKeyConvention : IJoinedSubclassConvention
{
   public void Apply(IJoinedSubclassInstance instance)
   {
      instance.Key.ForeignKey(string.Format("FK_{0}_{1}",
                    instance.EntityType.Name, instance.Type.Name));
   }
}

ContentLicense: CC BY-SA 2.5


问:
Percona MySQL Server working but filling the messages log with errors
I have Percona MySQL server 5.7 running under CentOS 7 and although mysql is running without any noticeable errors, it is filling my /var/log/messages with the following every ten seconds:

```<code>Nov 15 10:07:27 server systemd: mysqld.service holdoff time over, scheduling restart.
Nov 15 10:07:27 server systemd: Starting MySQL Percona Server...
Nov 15 10:07:27 server mysqld_safe: 171115 10:07:27 mysqld_safe Adding '/usr/lib64/libjemalloc.so.1' to LD_PRELOAD for mysqld
Nov 15 10:07:27 server mysqld_safe: 171115 10:07:27 mysqld_safe Logging to '/var/lib/mysql/server.local.err'.
Nov 15 10:07:27 server mysqld_safe: 171115 10:07:27 mysqld_safe A mysqld process already exists
Nov 15 10:07:27 server systemd: mysqld.service: main process exited, code=exited, status=1/FAILURE
Nov 15 10:07:28 server systemd: Failed to start MySQL Percona Server.
Nov 15 10:07:28 server systemd: Unit mysqld.service entered failed state.
Nov 15 10:07:28 server systemd: Triggering OnFailure= dependencies of mysqld.service.
Nov 15 10:07:28 server systemd: mysqld.service failed.
Nov 15 10:07:28 server systemd: Started Service Status Monitor.
Nov 15 10:07:28 server systemd: Starting Service Status Monitor...
</code>```

Even though it's stating in there that it failed to start the Percona server, it appears to be working as my website is still doing mysql queries. I know very little about mysql admin and was hoping a mysql guru could shed some light on what is happening.

答:
The clue is here: "A mysqld process already exists". It can't start mysqld because another mysqld process is already running, and using the same port. You need to kill that process before the one you tried to start can start.

Re your comment:

Since this is CentOS 7, I assume mysql.service is being called by systemd.

In my experience, if you start mysqld "ad hoc" without using systemd, then systemd has no idea that it's running, and tries to start mysqld on its own. Systemd also cannot shut down an instance of mysqld unless it started that instance.

Body:
I have Percona MySQL server 5.7 running under CentOS 7 and although mysql is running without any noticeable errors, it is filling my /var/log/messages with the following every ten seconds:

Nov 15 10:07:27 server systemd: mysqld.service holdoff time over, scheduling restart.
Nov 15 10:07:27 server systemd: Starting MySQL Percona Server...
Nov 15 10:07:27 server mysqld_safe: 171115 10:07:27 mysqld_safe Adding '/usr/lib64/libjemalloc.so.1' to LD_PRELOAD for mysqld
Nov 15 10:07:27 server mysqld_safe: 171115 10:07:27 mysqld_safe Logging to '/var/lib/mysql/server.local.err'.
Nov 15 10:07:27 server mysqld_safe: 171115 10:07:27 mysqld_safe A mysqld process already exists
Nov 15 10:07:27 server systemd: mysqld.service: main process exited, code=exited, status=1/FAILURE
Nov 15 10:07:28 server systemd: Failed to start MySQL Percona Server.
Nov 15 10:07:28 server systemd: Unit mysqld.service entered failed state.
Nov 15 10:07:28 server systemd: Triggering OnFailure= dependencies of mysqld.service.
Nov 15 10:07:28 server systemd: mysqld.service failed.
Nov 15 10:07:28 server systemd: Started Service Status Monitor.
Nov 15 10:07:28 server systemd: Starting Service Status Monitor...

Even though it's stating in there that it failed to start the Percona server, it appears to be working as my website is still doing mysql queries. I know very little about mysql admin and was hoping a mysql guru could shed some light on what is happening.


问:
How to test if an input has only specific characters
Im trying to make a script that tests id there are characters in the input that are not A, T, C, G and if there are than the input is false.

I dont have any clue how to start. I would love if someone could help.
Thanks!

答:
```<code>output = True
nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
n = input("Insert DNA seqence: ").upper()
for c in n:
    if(c in ("A", "T", "C", "G")):
        output = False
if(output == False):
    print('Issue detected please try again')
    print(n)
    print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))
else:
    print("All good")
</code>```


问:
How can I give access to certain objects in Firebase database based on id
I have this data structure:

The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.

I have tried different methods for showing only the animals that have id that is stored in the current user node.

Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".

Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.

```<code>     myAnimalRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
                AnimalCard animal = new AnimalCard();
                String name = value.getName();
                int age = value.getAge();
                String url = value.getUrl();
                animal.setName(name);
                animal.setAge(age);
                animal.setUrl(url);
                list.add(animal);

            }
            recyclerViewSetAdapter();
            progressDialog.dismiss();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG1, "failed to read value: " + databaseError.toException());
        }
    });
</code>```

How can get my code to filter out every animal that does not have their ID in the user node?

The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.

答:
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using

```<code>mdatabaseRef.child("animals").orderByChild().equalTo("value")
</code>```

and also you can add check on key by orderByKey()

```<code>    private FirebaseAuth mAuth;

    private FirebaseDatabase mdatabase;

    private DatabaseReference mdatabaseRef;

mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();

 ArrayList<User> allUserList = new ArrayList<>();
 Array<Animal> allAnimalList=new ArrayList<>();

mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            String key = childSnapshot.getKey();

            Animal animal = childSnapshot.getValue(Animal.class);
            allAnimalList.add(animal );
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            String key = childSnapshot.getKey();

            User user = childSnapshot.getValue(User .class);
            allUserList.add(user);
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
</code>```

Body:
I have this data structure:

The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.

I have tried different methods for showing only the animals that have id that is stored in the current user node.

Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".

Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.

     myAnimalRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<AnimalCard>();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){

                AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
                AnimalCard animal = new AnimalCard();
                String name = value.getName();
                int age = value.getAge();
                String url = value.getUrl();
                animal.setName(name);
                animal.setAge(age);
                animal.setUrl(url);
                list.add(animal);

            }
            recyclerViewSetAdapter();
            progressDialog.dismiss();

        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.d(TAG1, "failed to read value: " + databaseError.toException());
        }
    });

How can get my code to filter out every animal that does not have their ID in the user node?

The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.

Body:
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using

mdatabaseRef.child("animals").orderByChild().equalTo("value")

and also you can add check on key by orderByKey()

    private FirebaseAuth mAuth;

    private FirebaseDatabase mdatabase;

    private DatabaseReference mdatabaseRef;

mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();

 ArrayList<User> allUserList = new ArrayList<>();
 Array<Animal> allAnimalList=new ArrayList<>();

mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            String key = childSnapshot.getKey();

            Animal animal = childSnapshot.getValue(Animal.class);
            allAnimalList.add(animal );
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
            String key = childSnapshot.getKey();

            User user = childSnapshot.getValue(User .class);
            allUserList.add(user);
        }

    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});


问:
How to retrieve OS version details and all network adapter info in macOS?
I am developing a tool which supposes to collect information about a client if installed by the user. This tool will be collecting information like
OS version, MAC addresses, IP4, registered username and computer name.

I am very new to macOS, so please help me out and give references or any relevant links.

答:
For the OS version:

On the command line:

```<code>$ sysctl kern.osrelease
kern.osrelease: 12.0.0
$ sysctl kern.osversion
kern.osversion: 12A269
</code>```

Programmatically:

```<code>#include <errno.h>
#include <sys/sysctl.h>

char str[256];
size_t size = sizeof(str);
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);
</code>```

Darwin version to OS X release:

```<code>16.x.x  macOS 10.12.x Sierra
15.x.x  OS X  10.11.x El Capitan
14.x.x  OS X  10.10.x Yosemite
13.x.x  OS X  10.9.x  Mavericks
12.x.x  OS X  10.8.x  Mountain Lion
11.x.x  OS X  10.7.x  Lion
10.x.x  OS X  10.6.x  Snow Leopard
 9.x.x  OS X  10.5.x  Leopard
 8.x.x  OS X  10.4.x  Tiger
 7.x.x  OS X  10.3.x  Panther
 6.x.x  OS X  10.2.x  Jaguar
 5.x    OS X  10.1.x  Puma
</code>```

For the network adapter you could run something like:

```<code>networksetup -listallhardwareports
</code>```

And parse it out

Body:
For the OS version:

On the command line:

$ sysctl kern.osrelease
kern.osrelease: 12.0.0
$ sysctl kern.osversion
kern.osversion: 12A269

Programmatically:

#include <errno.h>
#include <sys/sysctl.h>

char str[256];
size_t size = sizeof(str);
int ret = sysctlbyname("kern.osrelease", str, &size, NULL, 0);

Darwin version to OS X release:

16.x.x  macOS 10.12.x Sierra
15.x.x  OS X  10.11.x El Capitan
14.x.x  OS X  10.10.x Yosemite
13.x.x  OS X  10.9.x  Mavericks
12.x.x  OS X  10.8.x  Mountain Lion
11.x.x  OS X  10.7.x  Lion
10.x.x  OS X  10.6.x  Snow Leopard
 9.x.x  OS X  10.5.x  Leopard
 8.x.x  OS X  10.4.x  Tiger
 7.x.x  OS X  10.3.x  Panther
 6.x.x  OS X  10.2.x  Jaguar
 5.x    OS X  10.1.x  Puma

For the network adapter you could run something like:

networksetup -listallhardwareports

And parse it out


问:
How to resolve this error - Severity: Notice Message: Undefined variable: table
My controller is:

```<code>public function index() {
    if ($this->session->userdata ( 'logged_in' )) {
        $condition = array(
            'qes_status'=>'Y'
        );
        $data = array();
        $data['orders'] = $this->common_model->get_all( 'qes_order');
        $id=$this->session->userdata( 'user_id' );
        $table['quote'] = $this->common_model->get_count_of($id);
        $this->load->view ( 'layouts/inc_header' );
        $this->load->view ( 'layouts/dashboard',$data,$table );
        $this->load->view ( 'layouts/inc_footer' );
    } else {
        redirect ( 'vendor', 'refresh' );
    }
}
</code>```

My view is:

```<code><div class="dash-box-body">
    <span class="dash-box-count"><?php echo $table?></span>
    <span class="dash-box-title">Quotes Awaited</span>
</div>
</code>```

My model is:

```<code>public function get_count_of($id){
    $this->db->select ( '*' );
    $this->db->from ('qes_quote');
    $this->db->where ('qes_vendor_id',$id );
    $query = $this->db->get ();
    return $query->num_rows ();
}
</code>```

This is my code. The error is:

Severity: Notice Message: Undefined variable: table.

Please help me to resolve the issue.

答:
You need to pass $table to your view:

```<code>$data['table'] = $table;
$this->load->view('view', $data);
</code>```

And since it looks like $table is an array, in your view:

```<code><span class="dash-box-count"><?php echo $table['quote'];?></span>
</code>```

Body:
My controller is:

public function index() {
    if ($this->session->userdata ( 'logged_in' )) {
        $condition = array(
            'qes_status'=>'Y'
        );
        $data = array();
        $data['orders'] = $this->common_model->get_all( 'qes_order');
        $id=$this->session->userdata( 'user_id' );
        $table['quote'] = $this->common_model->get_count_of($id);
        $this->load->view ( 'layouts/inc_header' );
        $this->load->view ( 'layouts/dashboard',$data,$table );
        $this->load->view ( 'layouts/inc_footer' );
    } else {
        redirect ( 'vendor', 'refresh' );
    }
}

My view is:

    <?php echo $table?>
    Quotes Awaited

My model is:

public function get_count_of($id){
    $this->db->select ( '*' );
    $this->db->from ('qes_quote');
    $this->db->where ('qes_vendor_id',$id );
    $query = $this->db->get ();
    return $query->num_rows ();
}

This is my code. The error is:

Severity: Notice Message: Undefined variable: table.

Please help me to resolve the issue.

Body:
You need to pass $table to your view:

$data['table'] = $table;
$this->load->view('view', $data);

And since it looks like $table is an array, in your view:

<span class="dash-box-count"><?php echo $table['quote'];?></span>


问:
Static variable shadowing global
I am trying to create an object using placement new (I know to use smart pointers, this is just to learn). My code is as follows:

```<code>#include <vector>
#include <iostream>
#include <memory>

using namespace std; // please excuse this

// if you change like 19 to arr1 (or any other var name) instead of arr and line 40 to arr1 then it works

struct A
{
    int in = 999;
    A()
    {cout << "A ctor\n";}
    ~A()
    {cout << "A dtor\n";}
};

char arr[sizeof(A)];

class B
{
    public:
    static char arr[sizeof(A)];

    const static A* a_obj;

    B()
    {
        cout << "B ctor\n";
        //cout << (a_obj->in) << endl;
    }
    ~B()
    {
        cout << "B dtor\n";
    }
};

const A* B::a_obj = new(arr) A;

int main()
{
    B g;
}
</code>```

I have created a global array named arr and another array named arrin B. It seems like when I do my placement new the arr being used is from the class as I get what I think are linker errors.

Why is this happening? why isn't the global arr being used? If i change the placement new to use my renamed global array it works. I think it has to do something with lookups but I don't have a concrete answer.

答:
The reason arr is attribute to the class B and not the global scope is due to unqualified name lookup rules.

Specifically:

Static data member definition For a name used in the definition of a
  static data member, lookup proceeds the same way as for a name used in
  the definition of a member function.

Meaning:

```<code>struct X {
    static int x;
    static const int n = 1; // found 1st
};
int n = 2; // found 2nd.
int X::x = n; // finds X::n, sets X::x to 1, not 2
</code>```

If you are intrested you can see more information here:
http://en.cppreference.com/w/cpp/language/unqualified_lookup

As people suggested to get what you want just use:

```<code>const A* B::a_obj = new(::arr) A;
</code>```

Title: Static variable shadowing global

Body:
I am trying to create an object using placement new (I know to use smart pointers, this is just to learn). My code is as follows:

#include <vector>
#include <iostream>
#include <memory>

using namespace std; // please excuse this

// if you change like 19 to arr1 (or any other var name) instead of arr and line 40 to arr1 then it works

struct A
{
    int in = 999;
    A()
    {cout << "A ctor\n";}
    ~A()
    {cout << "A dtor\n";}
};

char arr[sizeof(A)];

class B
{
    public:
    static char arr[sizeof(A)];

    const static A* a_obj;

    B()
    {
        cout << "B ctor\n";
        //cout << (a_obj->in) << endl;
    }
    ~B()
    {
        cout << "B dtor\n";
    }
};

const A* B::a_obj = new(arr) A;

int main()
{
    B g;
}

I have created a global array named arr and another array named arrin B. It seems like when I do my placement new the arr being used is from the class as I get what I think are linker errors.

Why is this happening? why isn't the global arr being used? If i change the placement new to use my renamed global array it works. I think it has to do something with lookups but I don't have a concrete answer.

Body:
The reason arr is attribute to the class B and not the global scope is due to unqualified name lookup rules.

Specifically:

Static data member definition For a name used in the definition of a
  static data member, lookup proceeds the same way as for a name used in
  the definition of a member function.

Meaning:

struct X {
    static int x;
    static const int n = 1; // found 1st
};
int n = 2; // found 2nd.
int X::x = n; // finds X::n, sets X::x to 1, not 2

If you are intrested you can see more information here:
http://en.cppreference.com/w/cpp/language/unqualified_lookup

As people suggested to get what you want just use:

const A* B::a_obj = new(::arr) A;


问:
Customising jaxb marshalling output
My class is like the following:

```<code>class Employee {
  private String Code;
      //getter and setter below
}
</code>```

Using jaxb when I marshal I am getting these elements:

```<code><employee><code>some value</code></employee>
</code>```

But I want the output to be like:

```<code><Employee><Code>some value</Code></Employee>
</code>```

To get above output I changed my code to:

```<code>@XmlRootElement(name="Employee")
class Employee {
      @XmlElement(name = "Myname")
  private String Code;
      //getter and setter below
}
</code>```

When I marshal I am getting output as:

```<code><Employee><Code>some value</Code><code>some value</code></Employee>
</code>```

How can I avoid creating some value?

答:
Put the

```<code>@XmlElement(name = "Code")
</code>```

On the getter method

Title: Customising jaxb marshalling output

Body:
My class is like the following:

class Employee {
  private String Code;
      //getter and setter below
}

Using jaxb when I marshal I am getting these elements:

<employee>some value</employee>

But I want the output to be like:

<Employee>some value</Employee>

To get above output I changed my code to:

@XmlRootElement(name="Employee")
class Employee {
      @XmlElement(name = "Myname")
  private String Code;
      //getter and setter below
}

When I marshal I am getting output as:

<Employee>some valuesome value</Employee>

How can I avoid creating some value?

Body:
Put the

@XmlElement(name = "Code")

On the getter method


问:
Get the method name from a java.util.function.Function
Is it possible to get the method name of a java.util.function.Function. I would like to log each time the name of the method being used. The following example prints the Lambda object but I have not found an easy way to get the method name:</p>

```<code>public class Example {

    public static void main(String[]  args) {
        Example ex = new Example();
        ex.callService(Integer::getInteger, "123");
    }

    private Integer callService(Function<String, Integer> sampleMethod, String input) {
            Integer output = sampleMethod.apply(input);
            System.out.println("Calling method "+ sampleMethod);
            return output;
    }
}
</code>```

答:
You have to think about, what you're actually doing, when passing a method reference. Because this:

```<code>Integer::getInteger
</code>```

Is almost identical (there is a stack layer more with the below approach) to this:

```<code>s -> Integer.getInteger(s)
</code>```

And above is again similar to the following:

```<code>new Function<String, Integer> {
    @Override
    public Integer apply(String s){
        return Integer.getInteger(s);
    }
}
</code>```

And in the last snippet you clearly see that there is no logical connection to the called method Integer#getInteger(String). Which explaind why it is impossible to do what you intend without introducing something new.

Body:
Is it possible to get the method name of a java.util.function.Function. I would like to log each time the name of the method being used. The following example prints the Lambda object but I have not found an easy way to get the method name:

public class Example {

    public static void main(String[]  args) {
        Example ex = new Example();
        ex.callService(Integer::getInteger, "123");
    }

    private Integer callService(Function<String, Integer> sampleMethod, String input) {
            Integer output = sampleMethod.apply(input);
            System.out.println("Calling method "+ sampleMethod);
            return output;
    }
}

Body:
You have to think about, what you're actually doing, when passing a method reference. Because this:

Integer::getInteger

Is almost identical (there is a stack layer more with the below approach) to this:

s -> Integer.getInteger(s)

And above is again similar to the following:

new Function<String, Integer> {
    @Override
    public Integer apply(String s){
        return Integer.getInteger(s);
    }
}

And in the last snippet you clearly see that there is no logical connection to the called method Integer#getInteger(String). Which explaind why it is impossible to do what you intend without introducing something new.


问:
If statement based on user input
Trying to run a if statement based off a user input, would this be the correct way? So if the user is on a subscription then isSubscription is true.   </p>

```<code>var subscription = window.alert("Is this a subscription? (Y/N)");
    if (subscription == "Y") {
        isSubscription = true;
      } else {
        isSubscription = false;
        window.alert("No activation key");
      }
</code>```

答:
Try like this way,

var subscription = window.confirm("Is this a subscription? (Y/N)");

    if (subscription == true) {
        window.alert("activation key available");
        isSubscription = true;
      } else {
        isSubscription = false;
        window.alert("No activation key");
      }```

Title: If statement based on user input

Body:
Trying to run a if statement based off a user input, would this be the correct way? So if the user is on a subscription then isSubscription is true.

var subscription = window.alert("Is this a subscription? (Y/N)");
    if (subscription == "Y") {
        isSubscription = true;
      } else {
        isSubscription = false;
        window.alert("No activation key");
      }


问:
Spring Data GemFire unique constraint
I am working with Spring Data GemFire and using it like this:

Repository:

```<code>@Region("Token")
public interface TokenRepository extends GemfireRepository<Token, String> {}
</code>```

Entity:

```<code>public class Token implements Serializable {

@Id
private UUID id;
private String serial;
</code>```

Is it possible to enforce uniqueness on the serial property, like with JPAs @Column(unique=true)? At best it should throw an Exception on saving.

答:
The quick and simple answer is NO.  Neither Spring Data GemFire nor Pivotal GemFire (itself) support the ability to enforce unique properties on objects stored in a Region.

Even when using JPA (e.g. Hibernate), the @Column(unique = true) is implemented as an RDMBS table column (uniqueness) constraint, so there is nothing that JPA in particular is doing to enforce uniqueness.  If this column constraint was not present in the RDBMS table, then Column(unique = true) would have no effect.

See here.

This means that the uniqueness needs to be enforced at the data store, which would be especially true for Pivotal GemFire, since...

Pivotal GemFire is a key/value store where the value is your (entire) object and the objects stored in a particular Region will be distributed and replicated (for redundancy in HA scenarios) across the GemFire cluster, which would not only make enforcing uniqueness very difficult, but also very expensive (e.g. time consuming to check).

There are of course other ways to handle this, such as keeping an in-memory data structure of value hashes for each of the unique columns/properties.  But, that puts pressure on memory and you also need to keep the data structure up-to-date.  Also, depending on the hash algorithm used, they are not always guaranteed to be strictly unique.

So, there really is not a good answer here.

Title: Spring Data GemFire unique constraint

Body:
I am working with Spring Data GemFire and using it like this:

Repository:

@Region("Token")
public interface TokenRepository extends GemfireRepository<Token, String> {}

Entity:

public class Token implements Serializable {

@Id
private UUID id;
private String serial;

Is it possible to enforce uniqueness on the serial property, like with JPAs @Column(unique=true)? At best it should throw an Exception on saving.


问:
How to use IF OR & AND in excel formula
I am not a coder, but I'm trying to work on an excel sheet to make things more efficient at work.
I have two formulas that I need to combine and I can't figure it out! please help. I am trying to put this on my T2 cell.

This is the first one. I basically want to say if O2, R2, and S2 =yes, OR if Q2, R2, and S2 =yes, then "yes" otherwise leave blank. This is what I figured out and it is working!
=IF(OR(AND(O2="YES",R2="YES",S2="YES"),AND(Q2="YES",R2="YES",S2="YES")),"YES"," ")

However, If O2=NO and Q2=NO, then I want it to say No, otherwise leave blank. I have the two separate formulas but can't figure out how to combine.
IF(OR(AND(O2="NO", Q2="NO"),"NO", " ")

I was thinking maybe I can do this: =IF(OR(AND(O2="YES",R2="YES",S2="YES"),AND(Q2="YES",R2="YES",S2="YES")),"YES","NO") the only problem with this is that it automatically fills a NO, even if the cells are blank. I want it to skip it if its blank.
Link to spreadsheet image below:

答:
Put it in the else

```<code>=IF(OR(AND(O2="YES",R2="YES",S2="YES"),AND(Q2="YES",R2="YES",S2="YES"));
"YES",
IF(OR(AND(O2="NO", Q2="NO"),
     "NO",
     " "))
</code>```

Title: How to use IF OR & AND in excel formula

Body:
Put it in the else

=IF(OR(AND(O2="YES",R2="YES",S2="YES"),AND(Q2="YES",R2="YES",S2="YES"));
"YES",
IF(OR(AND(O2="NO", Q2="NO"),
     "NO",
     " "))


问:
LabVIEW 2017 does not open *.vi-File from LabVIEW 2016
On my Windows 10 PC LabVIEW 2017 is installed. A file I created in LabVIEW 2016 at my Uni will not be opened. When I doubleklick, LabVIEW starts normally, but only as if I had opened it without any file. If I start LabVIEW normally and try to open the file out of the program, nothing will happen, not even an error will occur. Why is this?

Note: Right now I am using LabVIEW 2017 in Evaluation-Mode.

答:
Technically, I think the answer is that ASCII 26 is not a valid character for a Windows path or filename, per the following: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx

Use any character in the current code page for a name, including
  Unicode characters and characters in the extended character set
  (128–255), except for the following:

The following reserved characters:

< (less than)

> (greater than)

: (colon)

" (double quote)

/ (forward slash)

\ (backslash)

| (vertical bar or pipe)

? (question mark)

* (asterisk)

Integer value zero, sometimes referred to as the ASCII NUL character.

Characters whose integer representations are in the range from 1
  through 31, except for alternate data streams where these characters
  are allowed. For more information about file streams, see File
  Streams.

Any other character that the target file system does not allow.

(Emphasis mine.)


问:
EF 6 suspend Execution Strategy and overlapping executions - "does not support user initiated transactions" exception
I implemented suspension of the EF 6 execution strategy wherever I need to use distributed transaction to avoid "'SqlAzureExecutionStrategy' does not support user initiated transactions" exceptions, following these examples:

https://romiller.com/2013/08/19/ef6-suspendable-execution-strategy/
https://msdn.microsoft.com/en-us/library/dn307226(v=vs.113).aspx

However, recently I got two failures of this during a bulk data management session, resulting in getting the above exception after all.

If I understand it correctly, the given examples enable/disable the execution strategy on a global level, which would mean that if actions are executed simultaneously on multiple threads one action can end the suspension before another one is completed. The effect is probably most noticeable if using .NET 4.6.1 for transactions spanning multiple SQL Azure DBs, which can take a while to complete.

To avoid this I resorted to creating a global transaction counter, which is incremented and decremented in a thread safe way, and lifting the suspension only if there are no transactions pending anymore, like:

```<code>    public class MyConfiguration : DbConfiguration
    {
        public MyConfiguration()
        {
            this.SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
              ? (IDbExecutionStrategy)new DefaultExecutionStrategy()
              : new SqlAzureExecutionStrategy());
        }

        public static bool SuspendExecutionStrategy
        {
            get
            {
                return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false;
            }
            set
            {
                CallContext.LogicalSetData("SuspendExecutionStrategy", value);
            }
        }
    }
</code>```

And then:

```<code>public class ExecutionHelper
{
    private static int _pendingTransactions;

    public void ExecuteUsingTransaction(Action action)
    {
        SuspendExeutionStrategy();
        try
        {
            using (var transaction = new TransactionScope())
            {
                action();
                transaction.Complete();
            }
            ResetSuspension();
        }
        catch (Exception ex)
        {
            ResetSuspension();
            throw ex;
        }
    }

    private void SuspendExeutionStrategy()
    {
        Interlocked.Increment(ref _pendingTransactions);
        MyConfiguration.SuspendExecutionStrategy = true;
    }

    private void ResetSuspension()
    {
        Interlocked.Decrement(ref _pendingTransactions);
        if (_pendingTransactions < 1 )
        {
            MyConfiguration.SuspendExecutionStrategy = false;
        }
    }
}
</code>```

I am still puzzled though that the example given on MSDN does not take this into account. Is there something I overlooked?

答:
Update:

Turns out the CallContext is thread specific anyway, so you don't have to worry about multi-threading in this scenario anyway. (see remarks: https://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.callcontext(v=vs.110).aspx)

Came across this whilst i was trying to get something similar to work.

Pretty sure your solution there isn't actually thread safe. A thread can still come in and set the suspension to true between the reset decrementing the number and setting the suspension to false, meaning the new thread wouldn't have the suspension set to true and would fail.

You would need a ReaderWriterLock to ensure you blocked any new threads setting the suspension to true whilst you decremented, checked and "falsed" the suspension in the reset method. Like:

```<code>   private ReaderWriterLock _readerWriterLock = new ReaderWriterLock();

    private void SuspendExeutionStrategy()
    {
        _readerWriterLock.AcquireReaderLock(_timeout);
        Interlocked.Increment(ref _pendingTransactions);
        MyConfiguration.SuspendExecutionStrategy = true;
        _readerWriterLock.ReleaseReaderLock();
    }

    private void ResetSuspension()
    {
        _readerWriterLock.AcquireWriterLock(_timeout);
        Interlocked.Decrement(ref _pendingTransactions);
        if (_pendingTransactions < 1)
        {
            MyConfiguration.SuspendExecutionStrategy = false;
        }
        _readerWriterLock.ReleaseWriterLock();
    }
</code>```

Body:
I implemented suspension of the EF 6 execution strategy wherever I need to use distributed transaction to avoid "'SqlAzureExecutionStrategy' does not support user initiated transactions" exceptions, following these examples:

https://romiller.com/2013/08/19/ef6-suspendable-execution-strategy/
https://msdn.microsoft.com/en-us/library/dn307226(v=vs.113).aspx

However, recently I got two failures of this during a bulk data management session, resulting in getting the above exception after all.

If I understand it correctly, the given examples enable/disable the execution strategy on a global level, which would mean that if actions are executed simultaneously on multiple threads one action can end the suspension before another one is completed. The effect is probably most noticeable if using .NET 4.6.1 for transactions spanning multiple SQL Azure DBs, which can take a while to complete.

To avoid this I resorted to creating a global transaction counter, which is incremented and decremented in a thread safe way, and lifting the suspension only if there are no transactions pending anymore, like:

    public class MyConfiguration : DbConfiguration
    {
        public MyConfiguration()
        {
            this.SetExecutionStrategy("System.Data.SqlClient", () => SuspendExecutionStrategy
              ? (IDbExecutionStrategy)new DefaultExecutionStrategy()
              : new SqlAzureExecutionStrategy());
        }

        public static bool SuspendExecutionStrategy
        {
            get
            {
                return (bool?)CallContext.LogicalGetData("SuspendExecutionStrategy") ?? false;
            }
            set
            {
                CallContext.LogicalSetData("SuspendExecutionStrategy", value);
            }
        }
    }

And then:

public class ExecutionHelper
{
    private static int _pendingTransactions;

    public void ExecuteUsingTransaction(Action action)
    {
        SuspendExeutionStrategy();
        try
        {
            using (var transaction = new TransactionScope())
            {
                action();
                transaction.Complete();
            }
            ResetSuspension();
        }
        catch (Exception ex)
        {
            ResetSuspension();
            throw ex;
        }
    }

    private void SuspendExeutionStrategy()
    {
        Interlocked.Increment(ref _pendingTransactions);
        MyConfiguration.SuspendExecutionStrategy = true;
    }

    private void ResetSuspension()
    {
        Interlocked.Decrement(ref _pendingTransactions);
        if (_pendingTransactions < 1 )
        {
            MyConfiguration.SuspendExecutionStrategy = false;
        }
    }
}

I am still puzzled though that the example given on MSDN does not take this into account. Is there something I overlooked?

Body:
Update:

Turns out the CallContext is thread specific anyway, so you don't have to worry about multi-threading in this scenario anyway. (see remarks: https://msdn.microsoft.com/en-us/library/system.runtime.remoting.messaging.callcontext(v=vs.110).aspx)

Came across this whilst i was trying to get something similar to work.

Pretty sure your solution there isn't actually thread safe. A thread can still come in and set the suspension to true between the reset decrementing the number and setting the suspension to false, meaning the new thread wouldn't have the suspension set to true and would fail.

You would need a ReaderWriterLock to ensure you blocked any new threads setting the suspension to true whilst you decremented, checked and "falsed" the suspension in the reset method. Like:

   private ReaderWriterLock _readerWriterLock = new ReaderWriterLock();

    private void SuspendExeutionStrategy()
    {
        _readerWriterLock.AcquireReaderLock(_timeout);
        Interlocked.Increment(ref _pendingTransactions);
        MyConfiguration.SuspendExecutionStrategy = true;
        _readerWriterLock.ReleaseReaderLock();
    }

    private void ResetSuspension()
    {
        _readerWriterLock.AcquireWriterLock(_timeout);
        Interlocked.Decrement(ref _pendingTransactions);
        if (_pendingTransactions < 1)
        {
            MyConfiguration.SuspendExecutionStrategy = false;
        }
        _readerWriterLock.ReleaseWriterLock();
    }


问:
DateFormat parse - not return date in UTC
Here my java code that try to get current date in UTC on Android device:

```<code>public static Date getCurrentDateUTC() {
    try {
        TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
        Date localTime = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
        dateFormat.setTimeZone(timeZoneUTC);
        String dateUTCAsString = dateFormat.format(localTime);
        Debug.d(TAG, "getCurrentDateUTC: dateUTCAsString = " + dateUTCAsString);
        Date dateResult = dateFormat.parse(dateUTCAsString);
        Debug.d(TAG, "getCurrentDateUTC: dateResult = " + dateResult);
        return dateResult;
    } catch (ParseException e) {
        Debug.e(TAG, "getCurrentDateUTC: ", e);
        return null;
    }
}
</code>```

Result:

```<code>dateUTCAsString = 2017-11-15T12:54:25 +0000
dateResult = Wed Nov 15 14:54:25 EET 2017
</code>```

As you can see the dateUTCAsString  IS CORRECT show current date in UTC, but after parse the dateResult  is not correct. Why?

答:
Excuse me for mentioning it, I suspect that there is no problem in your code, there’s only confusion. If you think the old Date class is behaving confusingly, allow me to be the first of many to agree with you. The good and sound solution to this problem is you stop using Date and start using the modern Java date and time API instead.

Since you are coding for Android, you first step is to get the ThreeTenABP, the library for Android that offers the modern API (if you were using Java 8 or 9, you could skip this step since the modern API wold be built in). The details are described in this question: How to use ThreeTenABP in Android Project. Now you can do:

```<code>    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss Z");
    String dateUTCAsString = "2017-11-15T12:54:25 +0000";
    Instant dateResult = OffsetDateTime.parse(dateUTCAsString, formatter).toInstant();
    System.out.println(dateResult);
</code>```

On my computer this just printed:

```<code>2017-11-15T12:54:25Z
</code>```

The Z at the end means Zulu time zone or UTC.

As you may know, System.out.println(dateResult) implicitly calls the toString method of the dateResult object. Objects of the class Instant produce the above format, always in UTC, as I understood you wanted. The Instant class is the natural replacement for the old-fashioned Date class for most purposes. Internally the Instant holds the number of seconds and nanoseconds since the epoch, which is defined as January 1 1970 at 0:00 midnight UTC. I encourage you to consider this an irrelevant implementation detail. An Instant is a point on the time-line.

What went wrong?

You asked for a date in UTC. Depending on how you look at it, you can or cannot have this.

On one hand a Date is implemented as the number of seconds and milliseconds since the epoch, so if you use the above definition of the epoch, you may say that it is always in UTC.

On the other hand you shouldn’t worry about implementation details. Conceptually a Date (like an Instant) is a point on the time-line, and does not and cannot have a time zone or offset; it cannot be in UTC. To make matters more confusing, when you do "getCurrentDateUTC: dateResult = " + dateResult, then dateResult.toString() is implicitly called. This method grabs your JVM’s time zone setting and converts the date-time to this zone and uses it for the generated string (without modifying the Date object). This is why you will see the time in EET on your computer or device no matter which Date you try to print.

java.time or JSR-310

The modern date and time API is know as java.time or JSR-310. One good source for learning to use it is the Oracle tutorial.

Body:
Here my java code that try to get current date in UTC on Android device:

public static Date getCurrentDateUTC() {
    try {
        TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");
        Date localTime = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z");
        dateFormat.setTimeZone(timeZoneUTC);
        String dateUTCAsString = dateFormat.format(localTime);
        Debug.d(TAG, "getCurrentDateUTC: dateUTCAsString = " + dateUTCAsString);
        Date dateResult = dateFormat.parse(dateUTCAsString);
        Debug.d(TAG, "getCurrentDateUTC: dateResult = " + dateResult);
        return dateResult;
    } catch (ParseException e) {
        Debug.e(TAG, "getCurrentDateUTC: ", e);
        return null;
    }
}

Result:

dateUTCAsString = 2017-11-15T12:54:25 +0000
dateResult = Wed Nov 15 14:54:25 EET 2017

As you can see the dateUTCAsString  IS CORRECT show current date in UTC, but after parse the dateResult  is not correct. Why?

Body:
Excuse me for mentioning it, I suspect that there is no problem in your code, there’s only confusion. If you think the old Date class is behaving confusingly, allow me to be the first of many to agree with you. The good and sound solution to this problem is you stop using Date and start using the modern Java date and time API instead.

Since you are coding for Android, you first step is to get the ThreeTenABP, the library for Android that offers the modern API (if you were using Java 8 or 9, you could skip this step since the modern API wold be built in). The details are described in this question: How to use ThreeTenABP in Android Project. Now you can do:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss Z");
    String dateUTCAsString = "2017-11-15T12:54:25 +0000";
    Instant dateResult = OffsetDateTime.parse(dateUTCAsString, formatter).toInstant();
    System.out.println(dateResult);

On my computer this just printed:

2017-11-15T12:54:25Z

The Z at the end means Zulu time zone or UTC.

As you may know, System.out.println(dateResult) implicitly calls the toString method of the dateResult object. Objects of the class Instant produce the above format, always in UTC, as I understood you wanted. The Instant class is the natural replacement for the old-fashioned Date class for most purposes. Internally the Instant holds the number of seconds and nanoseconds since the epoch, which is defined as January 1 1970 at 0:00 midnight UTC. I encourage you to consider this an irrelevant implementation detail. An Instant is a point on the time-line.

What went wrong?

You asked for a date in UTC. Depending on how you look at it, you can or cannot have this.

On one hand a Date is implemented as the number of seconds and milliseconds since the epoch, so if you use the above definition of the epoch, you may say that it is always in UTC.

On the other hand you shouldn’t worry about implementation details. Conceptually a Date (like an Instant) is a point on the time-line, and does not and cannot have a time zone or offset; it cannot be in UTC. To make matters more confusing, when you do "getCurrentDateUTC: dateResult = " + dateResult, then dateResult.toString() is implicitly called. This method grabs your JVM’s time zone setting and converts the date-time to this zone and uses it for the generated string (without modifying the Date object). This is why you will see the time in EET on your computer or device no matter which Date you try to print.

java.time or JSR-310

The modern date and time API is know as java.time or JSR-310. One good source for learning to use it is the Oracle tutorial.


问:
Powershell script to create folders from list of names in a file
I have a text file that contains a list of files in different directories, e.g

C:\FolderOne\Testing.jpg

C:\FolderTwo\Test.jpg

I'd like to turn those names into folders. And if two files exist in one folder, e.g FolderOne, then both those files should go into the same folder.

I understand that the backslashes will also have to be replaced by underscores and the colon replaced by an underscore too.

Thus far, I'm able to get the contents from the file list and copy it into a specified folder. I would like to create a folder for each file in the file list, but the folder name needs to include C_FolderOne and C_FolderTwo and so on....

Any help would be appreciated!

What I have so far:

```<code>Param (
    [String]$model
)

# Debug line
$model = "DEV2";

[String]$drive = "C:";

#Go to the PG_dump directory
CD "C:\Program Files\PostgreSQL\9.4\bin"

##Execute PG_dump with no password
.\pg_dump.exe --host localhost --port 5432 --username "postgres" --role "postgres" --no-password  --format custom --blobs --verbose --file     "C:\Test\$date-DEV-$X.backup" "DEV"

#Get the content from the file list
$file_list = Get-Content "$drive\Testing\DEV33.txt"
foreach ($file in $file_list)
{
    Copy-Item  $file -Destination "C:\Testing"
}
</code>```

答:
Here's a method to do what you're asking.  It'll grab the parent path for the file and create the destination folder.</p>

```<code>## Get the content from the file list.
foreach ($file in Get-Content -Path "$drive\Testing\DEV33.txt") {
    $name = (Split-Path -Path $file -Parent) -replace '\\', '_' -replace ':'
    New-Item -Path "path\to\$name" -ItemType Directory
}
</code>```

Body:
I have a text file that contains a list of files in different directories, e.g

C:\FolderOne\Testing.jpg

C:\FolderTwo\Test.jpg

I'd like to turn those names into folders. And if two files exist in one folder, e.g FolderOne, then both those files should go into the same folder.

I understand that the backslashes will also have to be replaced by underscores and the colon replaced by an underscore too.

Thus far, I'm able to get the contents from the file list and copy it into a specified folder. I would like to create a folder for each file in the file list, but the folder name needs to include C_FolderOne and C_FolderTwo and so on....

Any help would be appreciated!

What I have so far:

Param (
    [String]$model
)

# Debug line
$model = "DEV2";

[String]$drive = "C:";

#Go to the PG_dump directory
CD "C:\Program Files\PostgreSQL\9.4\bin"

##Execute PG_dump with no password
.\pg_dump.exe --host localhost --port 5432 --username "postgres" --role "postgres" --no-password  --format custom --blobs --verbose --file     "C:\Test\$date-DEV-$X.backup" "DEV"

#Get the content from the file list
$file_list = Get-Content "$drive\Testing\DEV33.txt"
foreach ($file in $file_list)
{
    Copy-Item  $file -Destination "C:\Testing"
}

Body:
Here's a method to do what you're asking.  It'll grab the parent path for the file and create the destination folder.

## Get the content from the file list.
foreach ($file in Get-Content -Path "$drive\Testing\DEV33.txt") {
    $name = (Split-Path -Path $file -Parent) -replace '\\', '_' -replace ':'
    New-Item -Path "path\to\$name" -ItemType Directory
}

ContentLicense: CC BY-SA 4.0


问:
Reading from hdfs and writting to oracle 12

Hi.

I am trying to read from hdfs and write in oracle using pyspark, but I
have an error. I attach the code that I am using and the error that I
get:

```<code>pyspark --driver-class-path "/opt/oracle/app/oracle/product/12.1.0.2/dbhome_1/jdbc/lib/ojdbc7.jar"
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext, Row
conf = SparkConf().setAppName("myFirstApp").setMaster("local")
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
lines = sc.textFile("hdfs://bigdatalite.localdomain:8020/user/oracle/ACTIVITY/part-m-00000")
parts = lines.map(lambda l: l.split(","))
people = parts.map(lambda p: Row(name=p[0], age=p[1]))
schemaPeople = sqlContext.createDataFrame(people)
url = "jdbc:oracle:thin@localhost:1521/orcl"
properties = {
    "user": "MOVIEDEMO",
    "password": "welcome1",
    "driver": "oracle.jdbc.driver.OracleDriver"
}
schemaPeople.write.jdbc(url=url, table="ACTIVITY", mode="append", properties=properties)
</code>```

..and the error that show is:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/spark/python/pyspark/sql/readwriter.py", line 530, in jdbc
    self._jwrite.mode(mode).jdbc(url, table, jprop)
  File "/usr/lib/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
  File "/usr/lib/spark/python/pyspark/sql/utils.py", line 45, in deco
    return f(*a, **kw)
  File "/usr/lib/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o66.jdbc.
: java.sql.SQLException: Invalid Oracle URL specified
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:453)
    at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:61)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:52)
    at org.apache.spark.sql.DataFrameWriter.jdbc(DataFrameWriter.scala:278)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:748)
</code>```

PD: I using spark 1.6.0

答:
Url should be specified in the "service" format, ie.</p>

```<code>jdbc:oracle:thin:@//myhost:1521/orcl
</code>```

Body:
Hi.

I am trying to read from hdfs and write in oracle using pyspark, but I
have an error. I attach the code that I am using and the error that I
get:

pyspark --driver-class-path "/opt/oracle/app/oracle/product/12.1.0.2/dbhome_1/jdbc/lib/ojdbc7.jar"
from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext, Row
conf = SparkConf().setAppName("myFirstApp").setMaster("local")
sc = SparkContext(conf=conf)
sqlContext = SQLContext(sc)
lines = sc.textFile("hdfs://bigdatalite.localdomain:8020/user/oracle/ACTIVITY/part-m-00000")
parts = lines.map(lambda l: l.split(","))
people = parts.map(lambda p: Row(name=p[0], age=p[1]))
schemaPeople = sqlContext.createDataFrame(people)
url = "jdbc:oracle:thin@localhost:1521/orcl"
properties = {
    "user": "MOVIEDEMO",
    "password": "welcome1",
    "driver": "oracle.jdbc.driver.OracleDriver"
}
schemaPeople.write.jdbc(url=url, table="ACTIVITY", mode="append", properties=properties)

..and the error that show is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/spark/python/pyspark/sql/readwriter.py", line 530, in jdbc
    self._jwrite.mode(mode).jdbc(url, table, jprop)
  File "/usr/lib/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py", line 813, in __call__
  File "/usr/lib/spark/python/pyspark/sql/utils.py", line 45, in deco
    return f(*a, **kw)
  File "/usr/lib/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py", line 308, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o66.jdbc.
: java.sql.SQLException: Invalid Oracle URL specified
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:453)
    at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:61)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:52)
    at org.apache.spark.sql.DataFrameWriter.jdbc(DataFrameWriter.scala:278)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:748)

PD: I using spark 1.6.0

Body:
Url should be specified in the "service" format, ie.

jdbc:oracle:thin:@//myhost:1521/orcl


问:
Python module for shell commands
I've got a bash script that's starting to cross that grey area where it should probably be rewritten in a scripting language.  Since I'm constantly tweaking the script bash is perfect because of how concise things are.  Mostly I'm manipulating output from one program to put into another program (i.e. using cat, grep, sed, tail, head).  I'm familiar with Python so I'm looking for a module that can essentially perform these commands.  I've found some stuff that uses subprocess to call bash commands but I don't want a wrapper for bash commands.  I also realize I could simply take the time to write most of these commands in python and even chain them fairly easily if I encapsulated them all into one class.  It seems like such an obvious thing though I find it hard to believe these utilities don't exist in a module that already exists.</p>

答:
You can use the os module in python to have a command executed exactly as it would be in a command shell.

For example, if you have a file named "junk.txt" and want to use the "head" command on it, you would write head junk.txt in your shell.

In Python, it's

```<code>import os
os.system("head junk.txt")
</code>```

Title: Python module for shell commands

Body:
You can use the os module in python to have a command executed exactly as it would be in a command shell.

For example, if you have a file named "junk.txt" and want to use the "head" command on it, you would write head junk.txt in your shell.

In Python, it's

import os
os.system("head junk.txt")