问:
Show navigation loader spinner with delay in angular 2+
I'm new to angular 2+ and RxJS, trying to get used to RxJS.

I show load spinner on route transitions, but only if it takes more then certain amount time, lats say 160ms

I have a load spinner as a separate component, with subscription to ngrx store, so I show/hide load spinner based on value in the sore (showSpinner)

In my app root component, I subscribe to router change events, and dispatch actions (SHOW_SPINNER/HIDE_SPINNER)

So the question is, Is there a simpler way to achieve it?

Here are parts of my code

```<code>....

export const navigationStreamForSpinnerStatuses = {
  NAVIGATION_STARTED: 'NAVIGATION_STARTED',
  NAVIGATION_IN_PROGRESS: 'NAVIGATION_IN_PROGRESS',
  NAVIGATION_ENDED: 'NAVIGATION_ENDED'
};
</code>```

....

```<code>private navigationStartStream;
private navigationStartStreamWithDelay;
private navigationFinishStream;

constructor(private store: Store<IAppState>, private router: Router) {
  this.navigationStartStream = router.events
    .filter(event => {
      return event instanceof NavigationStart;
    })
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_STARTED);

  this.navigationStartStreamWithDelay = this.navigationStartStream
    .delay(160)
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS);

  this.navigationFinishStream = router.events
    .filter(event => {
      return event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError;
    })
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_ENDED);

  this.navigationStartStream
    .merge(this.navigationFinishStream)
    .merge(this.navigationStartStreamWithDelay)
    .pairwise()
    .subscribe([previousStatus, currentStatus] => {
      if (previousStatus !== navigationStreamForSpinnerStatuses.NAVIGATION_ENDED && currentStatus === navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS) {
        this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.SHOW_SPINNER });
      } else if (previousStatus === navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS && currentStatus === navigationStreamForSpinnerStatuses.NAVIGATION_ENDED) {
        this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.HIDE_SPINNER });
      }
    });
}
</code>```

答:
Utilize the takeUntil operator to cancel your spinner timer if it returns before the time. Additionally, create a hot observable using timer to trigger an action after a certain time has passed.

takeUntil Returns the values from the source observable sequence until the other observable sequence or Promise produces a value.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/takeuntil.md

timer Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timer.md

You can simplify your logic here by handling the dispatch directly on each stream.

```<code>this.navigationEnd$ = router.events
  .filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError);

this.navigationStart$ = router.events
  .filter(event => event instanceof NavigationStart)
  .subscribe(_ => {
    Observable.timer(160)
      .takeUntil(this.navigationEnd$)
      .subscribe(_ => this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.SHOW_SPINNER });
  });

this.navigationEnd$.subscribe(_ => this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.HIDE_SPINNER });
</code>```

So what we've done is listen to the start of the navigation and start a timer for 160ms.  If the navigation end event happens before the timer, no spinner will show (takeUntil). Otherwise, the store action will be dispatched and the spinner will show.  Regardless of whether or not the spinner is showing, after the navigation finishes we dispatch the hide spinner action.

Body:
I'm new to angular 2+ and RxJS, trying to get used to RxJS.

I show load spinner on route transitions, but only if it takes more then certain amount time, lats say 160ms

I have a load spinner as a separate component, with subscription to ngrx store, so I show/hide load spinner based on value in the sore (showSpinner)

In my app root component, I subscribe to router change events, and dispatch actions (SHOW_SPINNER/HIDE_SPINNER)

So the question is, Is there a simpler way to achieve it?

Here are parts of my code

....

export const navigationStreamForSpinnerStatuses = {
  NAVIGATION_STARTED: 'NAVIGATION_STARTED',
  NAVIGATION_IN_PROGRESS: 'NAVIGATION_IN_PROGRESS',
  NAVIGATION_ENDED: 'NAVIGATION_ENDED'
};

....

private navigationStartStream;
private navigationStartStreamWithDelay;
private navigationFinishStream;

constructor(private store: Store<IAppState>, private router: Router) {
  this.navigationStartStream = router.events
    .filter(event => {
      return event instanceof NavigationStart;
    })
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_STARTED);

  this.navigationStartStreamWithDelay = this.navigationStartStream
    .delay(160)
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS);

  this.navigationFinishStream = router.events
    .filter(event => {
      return event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError;
    })
    .map(() => navigationStreamForSpinnerStatuses.NAVIGATION_ENDED);

  this.navigationStartStream
    .merge(this.navigationFinishStream)
    .merge(this.navigationStartStreamWithDelay)
    .pairwise()
    .subscribe([previousStatus, currentStatus] => {
      if (previousStatus !== navigationStreamForSpinnerStatuses.NAVIGATION_ENDED && currentStatus === navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS) {
        this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.SHOW_SPINNER });
      } else if (previousStatus === navigationStreamForSpinnerStatuses.NAVIGATION_IN_PROGRESS && currentStatus === navigationStreamForSpinnerStatuses.NAVIGATION_ENDED) {
        this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.HIDE_SPINNER });
      }
    });
}

Body:
Utilize the takeUntil operator to cancel your spinner timer if it returns before the time. Additionally, create a hot observable using timer to trigger an action after a certain time has passed.

takeUntil Returns the values from the source observable sequence until the other observable sequence or Promise produces a value.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/takeuntil.md

timer Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.

https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/timer.md

You can simplify your logic here by handling the dispatch directly on each stream.

this.navigationEnd$ = router.events
  .filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError);

this.navigationStart$ = router.events
  .filter(event => event instanceof NavigationStart)
  .subscribe(_ => {
    Observable.timer(160)
      .takeUntil(this.navigationEnd$)
      .subscribe(_ => this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.SHOW_SPINNER });
  });

this.navigationEnd$.subscribe(_ => this.store.dispatch({ type: StateLoaderSpinnerActionsTypes.HIDE_SPINNER });

So what we've done is listen to the start of the navigation and start a timer for 160ms.  If the navigation end event happens before the timer, no spinner will show (takeUntil). Otherwise, the store action will be dispatched and the spinner will show.  Regardless of whether or not the spinner is showing, after the navigation finishes we dispatch the hide spinner action.


来源: stackexchange

问:
HTML - refresh page after inactivity
I am having a touch screen with some very basic html pages. But if there is no activity for maybe 5 minutes, it should reload the main page again.

So it is not just a refresh of the site, but a load of the main page if there is no activity

just a question Where does the script know which site is the main page ?. If someone goes to "site B" - it should after some minutes without any movement move back to "site A"

答:
Here is plain JavaScript implementation, without any dependencies:

```<code> var inactivityTime = function () {
            var timer;

            window.onload = timerReset;
            document.onkeypress = timerReset;
            document.onmousemove = timerReset;
            document.onmousedown = timerReset;
            document.ontouchstart = timerReset;
            document.onclick = timerReset;
            document.onscroll = timerReset;
            document.onkeypress = timerReset;

            function timerElapsed() {
                console.log("Timer elapsed");
                location.reload();
            };

            function timerReset() {
                console.log("Reseting timer");
                clearTimeout(timer);
                timer = setTimeout(timerElapsed, 5 * 60 * 1000); // 5 mins
            }
        };
</code>```

You can adjust list of events to listen to achieve best performance.

Complete list of DOM events.

ContentLicense: CC BY-SA 3.0

Title: HTML - refresh page after inactivity

Body:
Here is plain JavaScript implementation, without any dependencies:

 var inactivityTime = function () {
            var timer;

            window.onload = timerReset;
            document.onkeypress = timerReset;
            document.onmousemove = timerReset;
            document.onmousedown = timerReset;
            document.ontouchstart = timerReset;
            document.onclick = timerReset;
            document.onscroll = timerReset;
            document.onkeypress = timerReset;

            function timerElapsed() {
                console.log("Timer elapsed");
                location.reload();
            };

            function timerReset() {
                console.log("Reseting timer");
                clearTimeout(timer);
                timer = setTimeout(timerElapsed, 5 * 60 * 1000); // 5 mins
            }
        };

You can adjust list of events to listen to achieve best performance.

Complete list of DOM events.


问:
Java:how to group similar strings (items) to respective array (group)?
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

```<code>[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]
</code>```

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

```<code>String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }
</code>```

答:
```<code>HashMap<String,List<String> myItems = new HashMap<String,List<String>);
</code>```

<p>Then you can whatever class you want with an sting alias and store as many items as you whish. </p>

ContentLicense: CC BY-SA 2.5

Body:
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }

Body:
HashMap<String,List<String> myItems = new HashMap<String,List<String>);

Then you can whatever class you want with an sting alias and store as many items as you whish.


问:
How to flip the Windows archive bit for a file using Go
I am processing a series of files using Go and I would like to indicate if a file has been processed using file metadata. If the file has been processed at least once but hasn't been processed by the program for an hour I would like to delete it.

I thought the Windows archive bit would be a good way of determining if the file has been processed at least once since these files are temporary and will not be backed up preventing accidental flipping of the Windows archive bit.

答:
Use the Microsoft Windows API:

Retrieving and Changing File Attributes

An application can retrieve the file attributes by using the
  GetFileAttributes or GetFileAttributesEx function. The CreateFile and
  SetFileAttributes functions can set many of the attributes.

package windows

import "golang.org/x/sys/windows"

func GetFileAttributes

func GetFileAttributesEx

func SetFileAttributes


问:
Unable to install WebExtension with Selenium
I'm trying to test my firefox webextension but firefox refuses to install it because it doesn't have the install.rdf file. But that file is not used anymore by webextensions.

const firefox = require('selenium-webdriver/firefox');
const webdriver = require('selenium-webdriver');
require('geckodriver');

let profile = new firefox.Profile();
profile.addExtension(process.cwd() + '/build/firefox/');
profile.setPreference('extensions.firebug.showChromeErrors', true);

let options = new firefox.Options().setProfile(profile);

let _driver = new webdriver.Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();
```

Error: ENOENT: no such file or directory, open '/dev/webext/build/firefox/install.rdf'

Is there a setting that I need to enable to tell it it's a webextension?

答:
This is an issue with FirefoxDriver. This issue is already logged in both SeleniumHQ/selenium#4184 and
mozilla/geckodriver#759

GeckoDriver says that

A workaround for the time being would be to use the add-on endpoints
  geckodriver 0.17.0 provides to get an extension installed from the
  local disk.

https://github.com/mozilla/geckodriver/blob/release/src/marionette.rs#L66

So you have to use the geckodriver endpoints to do that. I have already mentioned on how to use the endpoints here

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to test my firefox webextension but firefox refuses to install it because it doesn't have the install.rdf file. But that file is not used anymore by webextensions.

const firefox = require('selenium-webdriver/firefox');
const webdriver = require('selenium-webdriver');
require('geckodriver');

let profile = new firefox.Profile();
profile.addExtension(process.cwd() + '/build/firefox/');
profile.setPreference('extensions.firebug.showChromeErrors', true);

let options = new firefox.Options().setProfile(profile);

let _driver = new webdriver.Builder()
.forBrowser('firefox')
.setFirefoxOptions(options)
.build();

Error: ENOENT: no such file or directory, open '/dev/webext/build/firefox/install.rdf'

Is there a setting that I need to enable to tell it it's a webextension?


问:
 causes "The form component needs to have a UIForm in its ancestry"
According to this answer it is as below possible to eliminate that popup while developing mode enabled.

```<code><h:form id="f1" prependId="false" onsubmit="document.getElementById('f1').action='j_security_check';">
    ...
</h:form>
</code>```

But it's not working for me when I add

```<code><h:form id="f1" prependId="false" onsubmit="document.getElementById('f1').action='j_security_check';">
    <p:growl id="growl" showDetail="true" sticky="true" />
    ...
</h:form>
</code>```

How can I solve it?

My config: Wildfly 8, Mojara 2.2.x (server runtime), PrimeFaces 5.3

答:
In my case the following solved the problem:

```<code><p:menubar id="pmenubar">
    <p:menuitem value="Inicio" url="${facesContext.externalContext.requestContextPath}/hola.xhtml"
                    icon="ui-icon-home" />
</p:menubar>
</code>```

I forgot to close this component. As you might have noticed, the component has neither actionListener nor action, so you need to enclose it in a form:

```<code><h:form>
    <p:menubar id="pmenubar">
        <p:menuitem value="Inicio" url="${facesContext.externalContext.requestContextPath}/productos/crear-producto.xhtml"
                    icon="ui-icon-home" />
    </p:menubar>
</h:form>
</code>```

Title: <p:growl> causes "The form component needs to have a UIForm in its ancestry"

Body:
According to this answer it is as below possible to eliminate that popup while developing mode enabled.

<h:form id="f1" prependId="false" onsubmit="document.getElementById('f1').action='j_security_check';">
    ...
</h:form>

But it's not working for me when I add

<h:form id="f1" prependId="false" onsubmit="document.getElementById('f1').action='j_security_check';">

    ...
</h:form>

How can I solve it?

My config: Wildfly 8, Mojara 2.2.x (server runtime), PrimeFaces 5.3

Body:
In my case the following solved the problem:

<p:menubar id="pmenubar">
    <p:menuitem value="Inicio" url="${facesContext.externalContext.requestContextPath}/hola.xhtml"
                    icon="ui-icon-home" />
</p:menubar>

I forgot to close this component. As you might have noticed, the component has neither actionListener nor action, so you need to enclose it in a form:

<h:form>
    <p:menubar id="pmenubar">
        <p:menuitem value="Inicio" url="${facesContext.externalContext.requestContextPath}/productos/crear-producto.xhtml"
                    icon="ui-icon-home" />
    </p:menubar>
</h:form>


问:
TYPO3 Show fe_user with Hyperlink and GET parameter
I'm using TYPO3 7.6 and I'd like to send an email with a Hyperlink to my TYPO3-Website (page=123). On this page I've listed all fe_users with the following TypoScript, but I'll only show one specific user, f.e. uid=20.

I have two questions:

How can I show only this user (uid) on my page?

How do I call my hyperlink?

Show all users:

```<code>lib.feUserLink = CONTENT
lib.feUserLink {
    table = fe_users

    select.pidInList = 10
    select.max = 10
    select.orderBy = last_name DESC
    where = disable = 0

    renderObj = COA
    renderObj {
        10 = TEXT
        10.field = first_name
        10.wrap = wq<p><strong>|
        ...
        14 = TEXT
        14.field = email
        14.wrap = |</p>
    }
}
</code>```

-> 1. Then I have to edit my WHEREclause, but i dont't know how? All of my tests won't work.

```<code>lib.feUserLink = CONTENT
lib.feUserLink {
  table = fe_users
  ...
  andWhere.dataWrap = uid={GP:fe_users|uid}
  #andWhere.data = GP:feuseruid
  #andWhere.data = GP:fe_user|uid
  #andWhere.intval = 1
  #andWhere.wrap = uid=|
 ...
</code>```

-> 2. And how can I show only the User from the GET-Parameter?

```<code>http://my.domain.tld/index.php?id=123&uid=20
http://my.domain.tld/index.php?id=123&feuser=20
http://my.domain.tld/index.php?id=123&fe_users[uid]=20
...
</code>```

I hope someone can give me a crucial tip ...
... thank you.

Regards
Stefan

my solution was

```<code>lib.feuserLink = CONTENT
lib.feUserLink {
    table = fe_users

    select {
        pidInList = 10
        orderBy = last_name DESC
        where = uid = ###field_uid###
        markers.field_uid.data = GP:user
        markers.field_uid.intval = 1
        max = 1
    }
    ...
</code>```

Thanks for helping ...

答:
2) Build link to page 123 with uid parameter from fe_user. Adds something like

?id=123&user=456&cHash=789

```<code>lib.feUserLink = CONTENT
lib.feUserLink {
    table = fe_users
    select {
        pidInList = 10
        max = 10
        orderBy = last_name DESC
    }
    renderObj = COA
    renderObj {
        10 = TEXT
        10.field = username
        10.typolink {
            parameter = 123
            additionalParams.dataWrap = &user={field:uid}
            useCacheHash = 1
        }
        10.wrap = |</br>
    }
}
</code>```

1) To show only selected user in given list, adapt your select like

```<code>[globalVar = GP:user > 0]
lib.feUserLink.select {
    where = uid = ###field_uid###
    markers.field_uid.data = GP:user
    markers.field_uid.intval = 1
    max = 1
}
[global]
</code>```

You don't need clause where = disable = 0. Its already included in the SQL query by default.

Body:
I'm using TYPO3 7.6 and I'd like to send an email with a Hyperlink to my TYPO3-Website (page=123). On this page I've listed all fe_users with the following TypoScript, but I'll only show one specific user, f.e. uid=20.

I have two questions:

How can I show only this user (uid) on my page?

How do I call my hyperlink?

Show all users:

lib.feUserLink = CONTENT
lib.feUserLink {
    table = fe_users

    select.pidInList = 10
    select.max = 10
    select.orderBy = last_name DESC
    where = disable = 0

    renderObj = COA
    renderObj {
        10 = TEXT
        10.field = first_name
        10.wrap = wq
|
        ...
        14 = TEXT
        14.field = email
        14.wrap = |

    }
}

-> 1. Then I have to edit my WHEREclause, but i dont't know how? All of my tests won't work.

lib.feUserLink = CONTENT
lib.feUserLink {
  table = fe_users
  ...
  andWhere.dataWrap = uid={GP:fe_users|uid}
  #andWhere.data = GP:feuseruid
  #andWhere.data = GP:fe_user|uid
  #andWhere.intval = 1
  #andWhere.wrap = uid=|
 ...

-> 2. And how can I show only the User from the GET-Parameter?

http://my.domain.tld/index.php?id=123&uid=20
http://my.domain.tld/index.php?id=123&feuser=20
http://my.domain.tld/index.php?id=123&fe_users[uid]=20
...

I hope someone can give me a crucial tip ...
... thank you.

Regards
Stefan

my solution was

lib.feuserLink = CONTENT
lib.feUserLink {
    table = fe_users

    select {
        pidInList = 10
        orderBy = last_name DESC
        where = uid = ###field_uid###
        markers.field_uid.data = GP:user
        markers.field_uid.intval = 1
        max = 1
    }
    ...

Thanks for helping ...

Body:
2) Build link to page 123 with uid parameter from fe_user. Adds something like

?id=123&user=456&cHash=789

lib.feUserLink = CONTENT
lib.feUserLink {
    table = fe_users
    select {
        pidInList = 10
        max = 10
        orderBy = last_name DESC
    }
    renderObj = COA
    renderObj {
        10 = TEXT
        10.field = username
        10.typolink {
            parameter = 123
            additionalParams.dataWrap = &user={field:uid}
            useCacheHash = 1
        }
        10.wrap = |</br>
    }
}

1) To show only selected user in given list, adapt your select like

[globalVar = GP:user > 0]
lib.feUserLink.select {
    where = uid = ###field_uid###
    markers.field_uid.data = GP:user
    markers.field_uid.intval = 1
    max = 1
}
[global]

You don't need clause where = disable = 0. Its already included in the SQL query by default.


问:
Weird error when trying to install a module using cpan on a RedHat
When I am trying to install any module on a RedHat 7.3 using cpan, I am getting this weird message - "make: execvp: true: Permission denied":

```<code>sudo cpan
cpan[1]> install Log::Log4perl
...
(tests run ok)
...
Running make install
make: execvp: true: Permission denied
make: *** [blibdirs] Error 127
  MSCHILLI/Log-Log4perl-1.49.tar.gz
  sudo /bin/make install  -- NOT OK
Failed during this command:
 MSCHILLI/Log-Log4perl-1.49.tar.gz            : install NO
</code>```

Then, if I navigate to the cpans build_dir (from MyConfig.pm), find the folder with this module, and run make test; sudo make install there - everything runs fine.

What is wrong with cpan there? How this could be fixed?

答:
If you're installing the module into the system library, you can probably save yourself considerable pain by installing the pre-build RPM package.</p>

```<code>$ sudo yum install perl-Log-Log4perl
</code>```

Body:
When I am trying to install any module on a RedHat 7.3 using cpan, I am getting this weird message - "make: execvp: true: Permission denied":

sudo cpan
cpan[1]> install Log::Log4perl
...
(tests run ok)
...
Running make install
make: execvp: true: Permission denied
make: *** [blibdirs] Error 127
  MSCHILLI/Log-Log4perl-1.49.tar.gz
  sudo /bin/make install  -- NOT OK
Failed during this command:
 MSCHILLI/Log-Log4perl-1.49.tar.gz            : install NO

Then, if I navigate to the cpans build_dir (from MyConfig.pm), find the folder with this module, and run make test; sudo make install there - everything runs fine.

What is wrong with cpan there? How this could be fixed?

Body:
If you're installing the module into the system library, you can probably save yourself considerable pain by installing the pre-build RPM package.

$ sudo yum install perl-Log-Log4perl


问:
'UCS-2' not able to encode
I'm trying to read the text file but it throws one error.

```<code>UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 12416-12416: Non-BMP character not supported in Tk
</code>```

I've tried to ignore it also but it I not working.
Here is the code:

```<code>with io.open('reviews1.txt', mode='r',encoding='utf-8') as myfile:
document1=myfile.read().replace('\n', '')
print(document1)
</code>```

答:
The problem is not with reading the file (that would be a decoding error).
It's with the print expression: your environment is apparently unable to process characters beyond the BMP, such as emoticons.

If you want to print those characters to STDOUT, you can check if your shell/IDE supports an encoding that supports all of Unicode (UTF-8, UTF-16...).
Or you switch to a different environment for running the script.

If you want to run it in the same setting, you can encode the data yourself, which gives you the option to specify a custom error handling:

```<code>data = document1.encode('UCS-2', errors='replace')
sys.stdout.buffer.write(data)
</code>```

This will replace unsupported characters as ? or some other character.
You can also specify errors='ignore', which will suppress the characters.

I couldn't test this, though, because my codecs library doesn't know the UCS-2 encoding. It's an obsolete standard used by Windows until NT.

Title: 'UCS-2' not able to encode

Body:
I'm trying to read the text file but it throws one error.

UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 12416-12416: Non-BMP character not supported in Tk

I've tried to ignore it also but it I not working.
Here is the code:

with io.open('reviews1.txt', mode='r',encoding='utf-8') as myfile:
document1=myfile.read().replace('\n', '')
print(document1)

Body:
The problem is not with reading the file (that would be a decoding error).
It's with the print expression: your environment is apparently unable to process characters beyond the BMP, such as emoticons.

If you want to print those characters to STDOUT, you can check if your shell/IDE supports an encoding that supports all of Unicode (UTF-8, UTF-16...).
Or you switch to a different environment for running the script.

If you want to run it in the same setting, you can encode the data yourself, which gives you the option to specify a custom error handling:

data = document1.encode('UCS-2', errors='replace')
sys.stdout.buffer.write(data)

This will replace unsupported characters as ? or some other character.
You can also specify errors='ignore', which will suppress the characters.

I couldn't test this, though, because my codecs library doesn't know the UCS-2 encoding. It's an obsolete standard used by Windows until NT.


问:
SQL count using multiple join
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

```<code>select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;
</code>```

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

```<code>id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3
</code>```

But what I get is:

```<code>id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3
</code>```

What can be the correct query to get the desired output?

答:
The real issue here is that you have a chain of 1 to many relationships you are working with. If it were just one relationship in the chain a count() function would work fine with no issues. But having them chained together results in the intermediary object (Session in this case) being replicated numerous times by the final relationship. This is why you are getting elevated Session counts.

You could use distinct, which counts each identifier only once. The answer by John Faz is correct, but you would only really need one distinct, not two, since the final table of the relationship (process) won't be replicated.

```<code>select
    host_id = H.ID,
    session_count = count(distinct S.ID),
    process_count = count(P.ID)
    from host H
        left join sessions S on H.ID = S.host_id
        left join process as P on S.ID = P.session_id
    group by H.ID
</code>```

Another option would be to perform your count in multiple stages using a CTE. I think this would be less performant, particularly if you have a larger set of data, but it accurately models the counts you're trying to do.

```<code>;with cteSessions (session_id, host_id, process_count) as (
    select
        session_id = S.ID,
        S.host_id,
        process_count = count(1)
        from sessions S
            left join process P on S.ID = P.session_id
        group by
            S.ID,
            S.host_id
)
select
    host_id = H.ID,
    session_count = count(S.session_id),
    process_count = sum(isnull(s.process_count, 0))
    from host H
        left join cteSessions S on H.ID = S.host_id
    group by
        H.ID
</code>```

You could also use sub-queries. Which I hate, but it would work

```<code>select
    host_id = H.ID,
    session_count = (select count(1) from sessions s where s.host_id = H.ID),
    process_count = (select count(1) from sessions s join process p on s.id = p.session_id where s.host_id = H.ID)
    from host H
</code>```

Title: SQL count using multiple join

Body:
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3

But what I get is:

id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3

What can be the correct query to get the desired output?

Body:
The real issue here is that you have a chain of 1 to many relationships you are working with. If it were just one relationship in the chain a count() function would work fine with no issues. But having them chained together results in the intermediary object (Session in this case) being replicated numerous times by the final relationship. This is why you are getting elevated Session counts.

You could use distinct, which counts each identifier only once. The answer by John Faz is correct, but you would only really need one distinct, not two, since the final table of the relationship (process) won't be replicated.

select
    host_id = H.ID,
    session_count = count(distinct S.ID),
    process_count = count(P.ID)
    from host H
        left join sessions S on H.ID = S.host_id
        left join process as P on S.ID = P.session_id
    group by H.ID

Another option would be to perform your count in multiple stages using a CTE. I think this would be less performant, particularly if you have a larger set of data, but it accurately models the counts you're trying to do.

;with cteSessions (session_id, host_id, process_count) as (
    select
        session_id = S.ID,
        S.host_id,
        process_count = count(1)
        from sessions S
            left join process P on S.ID = P.session_id
        group by
            S.ID,
            S.host_id
)
select
    host_id = H.ID,
    session_count = count(S.session_id),
    process_count = sum(isnull(s.process_count, 0))
    from host H
        left join cteSessions S on H.ID = S.host_id
    group by
        H.ID

You could also use sub-queries. Which I hate, but it would work

select
    host_id = H.ID,
    session_count = (select count(1) from sessions s where s.host_id = H.ID),
    process_count = (select count(1) from sessions s join process p on s.id = p.session_id where s.host_id = H.ID)
    from host H


问:
How to change constraint in ms sql if other bit column is true
I'm building a codebook in database.
There I have three columns:

[IDReal] int identity (1,1), [IsReal] bit not null, [Code] nvarchar (20) null

Now I have somehow get that when user change [IsReal] to 1, that my column [Code] change to not null and unique and vice versa.

I was trying something like

```<code>CREATE TABLE [dbo].[sReal](
[IDReal] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[IsReal] [bit] NOT NULL,

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [DEF_IsReal]  DEFAULT ((0)) FOR [IsReal]
    GO

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [CHNG_IsReal] IF [IsReal]=1 THEN (ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) not null unique)
ELSE END IF
GO`
</code>```

This, of course, is not working and I can't use triggers or functions or procedures to solve that.

Is there any other solution for accomplishing what I'm trying to do.

答:
You cannot solve this problem by dynamically changing the schema. The schema applies to the entire table. Instead, I believe you should add the following:

A filtered unique index to ensure unique values of Code only when IsReal has value 1:

CREATE UNIQUE INDEX ix_code ON dbo.sReal (Code) WHERE IsReal = 1

A check constraint that ensures that Code is never Null when IsReal is 1

ALTER TABLE dbo.sReal ADD CONSTRAINT cc_Code CHECK (IsReal = 0 OR Code IS NOT NULL)

Body:
I'm building a codebook in database.
There I have three columns:

[IDReal] int identity (1,1), [IsReal] bit not null, [Code] nvarchar (20) null

Now I have somehow get that when user change [IsReal] to 1, that my column [Code] change to not null and unique and vice versa.

I was trying something like

CREATE TABLE [dbo].[sReal](
[IDReal] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[IsReal] [bit] NOT NULL,

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [DEF_IsReal]  DEFAULT ((0)) FOR [IsReal]
    GO

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [CHNG_IsReal] IF [IsReal]=1 THEN (ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) not null unique)
ELSE END IF
GO`

This, of course, is not working and I can't use triggers or functions or procedures to solve that.

Is there any other solution for accomplishing what I'm trying to do.


答:
You are on right way but I'd like to correct you a little bit.

Use the following regex to split: str.split("\\s*,\\s*"). This will support all possible spaces.

When you get separate item you have to split it again: item.split("#").

To store all this create data structure like List<List<String>>. Then do the following:

```<code>String[] parts = item.split("#");
int group = Integer.parseInt(parts[0]);
String itemName = parts[1];
List<String> groupList = allGroups.get(group);
if (groupList == null) {
   groupList = new ArrayList<String>();
   allGroups[group] = groupList;
}
groupList.add(itemName);
</code>```

I am sorry if the code sample contains syntax errors. It is written here, on the site and should just help you to see the idea.

Title: Java:how to group similar strings (items) to respective array (group)?

Body:
You are on right way but I'd like to correct you a little bit.

Use the following regex to split: str.split("\\s*,\\s*"). This will support all possible spaces.

When you get separate item you have to split it again: item.split("#").

To store all this create data structure like List<List<String>>. Then do the following:

String[] parts = item.split("#");
int group = Integer.parseInt(parts[0]);
String itemName = parts[1];
List<String> groupList = allGroups.get(group);
if (groupList == null) {
   groupList = new ArrayList<String>();
   allGroups[group] = groupList;
}
groupList.add(itemName);

I am sorry if the code sample contains syntax errors. It is written here, on the site and should just help you to see the idea.


问:
Angular 2 async pipe on a function
I'm trying to get a base64 from an api.
The following code works fine.

```<code>private test = null;

ngOnInit() {
   this.loadCustomers();
   this.test = this.getSiteImage();
}

getSiteImage() {
   return this.CustomerService.getCustomerSiteImage('test.com').share();
}

<img class="avatar avatar-xl" src="{{ (test | async)?.image }}" alt="">
</code>```

But I would rather like to use a function.
When I change the code to the following:

```<code>getSiteImage(url) {
    return this.CustomerService.getCustomerSiteImage(url).share();
}

<img class="avatar avatar-xl" src="{{ (getSiteImage('test.com') | async)?.image }}" alt="">
</code>```

I like to know why this isn't working and how I can properly achieve this.

---------EDIT:

To help people with the same problem in the future.
Just as @thinkinkingmedia suggested. I put the observables in an object with the url as key.

I changed the getSiteImage(url) methode to:

```<code>getSiteImage(url) {
    if (url in this.imageObservables) {
      return this.imageObservables[url];
    } else {
      this.imageObservables[url] = this.CustomerService.getCustomerSiteImage(url).share();
      return this.imageObservables[url];
    }
}
</code>```

答:
The reason it's not working is because async is getting a new observable every time Angular checks the expression for a change.

In your first example:

```<code>{{ (test | async)?.image }}
</code>```

Angular checks the expression which passes the value of the property test to async. Asycn then subscribes to the observable and waits for a value. In the next cycle of checking Angular passes the same observable to Async, and Async makes no changes as it's already subscribed.

In your second example:

```<code>{{ (getSiteImage('test.com') | async)?.image }}
</code>```

Angular checks the expression which calls a function that creates an observable. This is passed to async which waits for a response. In the next cycle this gets repeated. Each change detection creates a new observable and the async never gets a chance to yield a result. For every new observable passed to async it unsubscribes to the previous.

Title: Angular 2 async pipe on a function

Body:
I'm trying to get a base64 from an api.
The following code works fine.

private test = null;

ngOnInit() {
   this.loadCustomers();
   this.test = this.getSiteImage();
}

getSiteImage() {
   return this.CustomerService.getCustomerSiteImage('test.com').share();
}

But I would rather like to use a function.
When I change the code to the following:

getSiteImage(url) {
    return this.CustomerService.getCustomerSiteImage(url).share();
}

I like to know why this isn't working and how I can properly achieve this.

---------EDIT:

To help people with the same problem in the future.
Just as @thinkinkingmedia suggested. I put the observables in an object with the url as key.

I changed the getSiteImage(url) methode to:

getSiteImage(url) {
    if (url in this.imageObservables) {
      return this.imageObservables[url];
    } else {
      this.imageObservables[url] = this.CustomerService.getCustomerSiteImage(url).share();
      return this.imageObservables[url];
    }
}

Body:
The reason it's not working is because async is getting a new observable every time Angular checks the expression for a change.

In your first example:

{{ (test | async)?.image }}

Angular checks the expression which passes the value of the property test to async. Asycn then subscribes to the observable and waits for a value. In the next cycle of checking Angular passes the same observable to Async, and Async makes no changes as it's already subscribed.

In your second example:

{{ (getSiteImage('test.com') | async)?.image }}

Angular checks the expression which calls a function that creates an observable. This is passed to async which waits for a response. In the next cycle this gets repeated. Each change detection creates a new observable and the async never gets a chance to yield a result. For every new observable passed to async it unsubscribes to the previous.


问:
How to load video thumbnails using square picasso library?
Currently I'm loading MediaStore Image Thumbnails using picasso into the ListView with the following snippet: (video.getData() returns the actual path of the image such as mnt/sdcard/...)

```<code>Picasso.with(this.context)
       .load(new File(photo.getData()))
       .resize(50, 50).config(config)
       .centerCrop()
       .into(viewHolder.imageViewItem);
</code>```

Now I'm and unable to load the MediaStore Video Thumbnails by just passing the video.getData() instead of photo.getData()?

答:
```<code>public void bindTo(MediaListHolder mediaListRowHolder, int i) {
    DataPictures message = itemList.get(i);
    try {
        Uri uri = Uri.fromFile(new File(message.getFilePath()));
        if (message.getFileType().equalsIgnoreCase("video")) {
            Bitmap bmThumbnail = ThumbnailUtils.extractThumbnail(ThumbnailUtils.createVideoThumbnail(message.getFilePath(),
                    MediaStore.Video.Thumbnails.FULL_SCREEN_KIND), MAX_WIDTH, MAX_HEIGHT);
            mediaListRowHolder.thumbnail.setImageBitmap(bmThumbnail);
        } else {
            Picasso.with(ApplicationSingleton.getInstance()).load(uri)
                    .resize(size, size)
                    .placeholder(R.drawable.logo_slogan)
                    .into(mediaListRowHolder.thumbnail);
        }
        Log.i(TAG, "bindTo: ");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

Body:
Currently I'm loading MediaStore Image Thumbnails using picasso into the ListView with the following snippet: (video.getData() returns the actual path of the image such as mnt/sdcard/...)

Picasso.with(this.context)
       .load(new File(photo.getData()))
       .resize(50, 50).config(config)
       .centerCrop()
       .into(viewHolder.imageViewItem);

Now I'm and unable to load the MediaStore Video Thumbnails by just passing the video.getData() instead of photo.getData()?


问:
How to find the entries in one table not like those in another
I have a table called whitelist_email which looks like this

```<code>+----+---------------------+-------------+
| id | email_suffix        | create_date |
+----+---------------------+-------------+
|  1 | stackoverflow.com   | 2017-07-07  |
|  2 | example.com         | 2017-07-07  |
</code>```

and a table called user_info with a field called verified_email. I would like to write a command to find all the rows in user_info whose verified_email field does not end with any entry in whitelist_email to give me a list of new users who need to be vetted. The best I can do with my limited knowledge is

```<code>SELECT verified_email
FROM user_info
WHERE verified_email IN (
    SELECT email_suffix
    FROM whitelist_email
);
</code>```

答:
For example

Table user_info

```<code>id;verified_email
1;u1@tu.com
2;u2@example.com
</code>```

Table whitelist_email

```<code>id;email_suffix
1;example.com
2;stackoverflow.com
</code>```

Query

```<code>select *
from user_info u
where not exists(
  select *
  from whitelist_email
  where whitelist_email.email_suffix=substr(u.verified_email,locate('@',u.verified_email)+1)
)
</code>```

Result

```<code>id,verified_email
1,u1@tu.com
</code>```

It is more efficient to store mail account and mail domain in separate fields.

Body:
I have a table called whitelist_email which looks like this

+----+---------------------+-------------+
| id | email_suffix        | create_date |
+----+---------------------+-------------+
|  1 | stackoverflow.com   | 2017-07-07  |
|  2 | example.com         | 2017-07-07  |

and a table called user_info with a field called verified_email. I would like to write a command to find all the rows in user_info whose verified_email field does not end with any entry in whitelist_email to give me a list of new users who need to be vetted. The best I can do with my limited knowledge is

SELECT verified_email
FROM user_info
WHERE verified_email IN (
    SELECT email_suffix
    FROM whitelist_email
);

Body:
For example

Table user_info

id;verified_email
1;u1@tu.com
2;u2@example.com

Table whitelist_email

id;email_suffix
1;example.com
2;stackoverflow.com

Query

select *
from user_info u
where not exists(
  select *
  from whitelist_email
  where whitelist_email.email_suffix=substr(u.verified_email,locate('@',u.verified_email)+1)
)

Result

id,verified_email
1,u1@tu.com

It is more efficient to store mail account and mail domain in separate fields.


问:
What improvements can I make to my ordering a set of n numbers program?
I am just learning how to program in javascript and I made my first program that "does something". I didn't look for help for any part of the algorithm, just in some parts to find the name of a function I wanted to use. This algorithm seems to work, but it doesnt seem to finish when you have a big list of number, like 10 or more. What yo do you think of it? Is wholly ineficient?</p>

```<code>var totNum = Number(prompt("How many numbers you want to compare"));
var unordNum = new Array(totNum);
var ordNum = new Array();
for( var i=1 ; i<= totNum; i++){
    unordNum[i] = Number(prompt("Write a new number","0"));
 }
while(ordNum.length < totNum){ // I will repeat this process until I order all numbers
    for(var i=1; i <=totNum; i++){ //choose a number, lets call it X
        if(!(ordNum.indexOf(unordNum[i]) >=0)){ //if it is already ordered, skip it
            var z = 0;
            for(var j=1; j<=totNum; j++){ //I will compare X against all the others numbers, except
                if(!(ordNum.indexOf(unordNum[j]) >= 0)){ //the ones that are already ordered
                    if( unordNum[i] >= unordNum[j]){ //if X is bigger than a number,
                        z++; // add 1 to z
                        }
                    if(z==totNum-ordNum.length){ // this means X is bigger or equal than all the other numbers
                        ordNum.push(unordNum[i]); //so write X in the first empty space of the ordered list
                        }
                    }
                }
            }
        }
    }
document.write(ordNum + "<br>");
</code>```

答: Once you have numbers in array, you can use array.sort()

Body:
I am just learning how to program in javascript and I made my first program that "does something". I didn't look for help for any part of the algorithm, just in some parts to find the name of a function I wanted to use. This algorithm seems to work, but it doesnt seem to finish when you have a big list of number, like 10 or more. What yo do you think of it? Is wholly ineficient?

var totNum = Number(prompt("How many numbers you want to compare"));
var unordNum = new Array(totNum);
var ordNum = new Array();
for( var i=1 ; i<= totNum; i++){
    unordNum[i] = Number(prompt("Write a new number","0"));
 }
while(ordNum.length < totNum){ // I will repeat this process until I order all numbers
    for(var i=1; i <=totNum; i++){ //choose a number, lets call it X
        if(!(ordNum.indexOf(unordNum[i]) >=0)){ //if it is already ordered, skip it
            var z = 0;
            for(var j=1; j<=totNum; j++){ //I will compare X against all the others numbers, except
                if(!(ordNum.indexOf(unordNum[j]) >= 0)){ //the ones that are already ordered
                    if( unordNum[i] >= unordNum[j]){ //if X is bigger than a number,
                        z++; // add 1 to z
                        }
                    if(z==totNum-ordNum.length){ // this means X is bigger or equal than all the other numbers
                        ordNum.push(unordNum[i]); //so write X in the first empty space of the ordered list
                        }
                    }
                }
            }
        }
    }
document.write(ordNum + "
");


问:
Passing values to Construtor
```<code>package org.apache.wicket.examples.guestbook;

import java.util.Date;
import org.apache.wicket.IClusterable;

public class Comment implements IClusterable {
    private String text;
    private Date date = new Date();

    public Comment() {
    }

    public Comment(final Comment comment) {
        this.text = comment.text;
        this.date = comment.date;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String toString() {
        return "[Comment date = " + date + ", text = " + text + "]";
    }
}
</code>```

Why does the other construtor do here?
Why the Comment comment is declared as final?

答:
The final there is optional in your case. In some projects/companies there is this rule that all method and constructor parameters are declared final.

The idea is that you should not be able to give the comment variable another value.

About the first question ("Why does the other construtor do here?"): this constructor is a so-called "copy-constructor". It gets an existing comment and creates a new instance with the same content.

Title: Passing values to Construtor

Body:
package org.apache.wicket.examples.guestbook;

import java.util.Date;
import org.apache.wicket.IClusterable;

public class Comment implements IClusterable {
    private String text;
    private Date date = new Date();

    public Comment() {
    }

    public Comment(final Comment comment) {
        this.text = comment.text;
        this.date = comment.date;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String toString() {
        return "[Comment date = " + date + ", text = " + text + "]";
    }
}

Why does the other construtor do here?
Why the Comment comment is declared as final?


问:
Custom protoc plugin parsing not working for custom options
I am trying to write a protoc plugin that requires me to use custom options. I defined my custom option as shown in the example (https://developers.google.com/protocol-buffers/docs/proto#customoptions):

```<code>import "google/protobuf/descriptor.proto";

extend google.protobuf.MessageOptions {
    string my_option = 51234;
}
</code>```

I use it as follows:

```<code>message Hello {
    bool greeting = 1;
    string name = 2;
    int32 number = 3;

    option (my_option) = "telephone";
}
</code>```

However, when I read the parsed request, the options field is empty for the "Hello" message.

I am doing the following to read

```<code>data = sys.stdin.read()

request = plugin.CodeGeneratorRequest()
request.ParseFromString(data)
</code>```

When I print "request," it just gives me this

```<code>message_type {
  name: "Hello"
  field {
    name: "greeting"
    number: 1
    label: LABEL_REQUIRED
    type: TYPE_BOOL
    json_name: "greeting"
  }
  field {
    name: "name"
    number: 2
    label: LABEL_REQUIRED
    type: TYPE_STRING
    json_name: "name"
  }
  field {
    name: "number"
    number: 3
    label: LABEL_OPTIONAL
    type: TYPE_INT32
    json_name: "number"
  }
  options {
  }
}
</code>```

As seen, the options field is empty even though I defined options in my .proto file. Is my syntax incorrect for defining custom options? Or could it be a problem with my version of protoc?

答: Turns out you need to have the _pb2.py file imported for the .proto file in which the custom option is defined. For example, it you are parsing a file (using ParseFromString) called example.proto which uses a custom option defined in option.proto, you must import option_pb2.py in the Python file that calls ParseFromString.

Body:
I am trying to write a protoc plugin that requires me to use custom options. I defined my custom option as shown in the example (https://developers.google.com/protocol-buffers/docs/proto#customoptions):

import "google/protobuf/descriptor.proto";

extend google.protobuf.MessageOptions {
    string my_option = 51234;
}

I use it as follows:

message Hello {
    bool greeting = 1;
    string name = 2;
    int32 number = 3;

    option (my_option) = "telephone";
}

However, when I read the parsed request, the options field is empty for the "Hello" message.

I am doing the following to read

data = sys.stdin.read()

request = plugin.CodeGeneratorRequest()
request.ParseFromString(data)

When I print "request," it just gives me this

message_type {
  name: "Hello"
  field {
    name: "greeting"
    number: 1
    label: LABEL_REQUIRED
    type: TYPE_BOOL
    json_name: "greeting"
  }
  field {
    name: "name"
    number: 2
    label: LABEL_REQUIRED
    type: TYPE_STRING
    json_name: "name"
  }
  field {
    name: "number"
    number: 3
    label: LABEL_OPTIONAL
    type: TYPE_INT32
    json_name: "number"
  }
  options {
  }
}

As seen, the options field is empty even though I defined options in my .proto file. Is my syntax incorrect for defining custom options? Or could it be a problem with my version of protoc?


问:
multiple next / previous on same page
I have a div containing a number of sections.
I managed to hide all sections except the first one, and add next/previous buttons.

If you click the "next" button it hides the first and show second section, and so on. If you click "previous" it goes back the same way.

The thing is, if I have several such div in my page, one button does the show/hide for all div and not just its own.

And my counter gets messed up, because it's counting all sections in the page and not in each div separately.

$(function() {

  /* add next/previous buttons to all class body_next */
  $(".body_next").append('<button type="button" class="next">Next ></button>');
  $(".body_next").append('<button type="button" class="prev" style="display:none">< Previous</button>');

  var tracker = 1;
  var n = $(".section_next").length;

  /* hide all section_next except the first */
  $(".body_next").each(function() {
    $(".section_next:not(:first)", this).hide();
  });

  $(".next").click(function() {
    $(".section_next:visible").next(".section_next:hidden").show().prev(".section_next:visible").hide();

    tracker++;

    /* show previous button if displayed section is not the first one */
    if (tracker > 1) {
      $(".prev").show();
    }

    /* hide next button if displayed section is the last one */
    if (tracker == n) {
      $(".next").hide();
    }
  });

  $(".prev").click(function() {
    $(".section_next:visible").prev(".section_next:hidden").show().next(".section_next:visible").hide();

    tracker = tracker - 1;

    /* show next button if displayed section is not the first one */
    if (tracker > 1) {
      $(".next").show();
    }

    /* hide previous button if displayed section is the first one */
    if (tracker == 1) {
      $(".prev").hide();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  margin: 0;
  padding: 0;
}</code>```

blah1

blah1

blah1

blah2

blah2

blah2

blah1

blah1

blah1

blah2

blah2

blah2

blah3

blah3

blah3

```

答:
Check solution demo

Version 2 that puts button in disable state instead of hiding.

You should find the elements like .section_next .prev .next element within the parent .body_next element.

Title: multiple next / previous on same page

Body:
I have a div containing a number of sections.
I managed to hide all sections except the first one, and add next/previous buttons.

If you click the "next" button it hides the first and show second section, and so on. If you click "previous" it goes back the same way.

The thing is, if I have several such div in my page, one button does the show/hide for all div and not just its own.

And my counter gets messed up, because it's counting all sections in the page and not in each div separately.

$(function() {

  /* add next/previous buttons to all class body_next */
  $(".body_next").append('<button type="button" class="next">Next ></button>');
  $(".body_next").append('<button type="button" class="prev" style="display:none">< Previous</button>');

  var tracker = 1;
  var n = $(".section_next").length;

  /* hide all section_next except the first */
  $(".body_next").each(function() {
    $(".section_next:not(:first)", this).hide();
  });

  $(".next").click(function() {
    $(".section_next:visible").next(".section_next:hidden").show().prev(".section_next:visible").hide();

    tracker++;

    /* show previous button if displayed section is not the first one */
    if (tracker > 1) {
      $(".prev").show();
    }

    /* hide next button if displayed section is the last one */
    if (tracker == n) {
      $(".next").hide();
    }
  });

  $(".prev").click(function() {
    $(".section_next:visible").prev(".section_next:hidden").show().next(".section_next:visible").hide();

    tracker = tracker - 1;

    /* show next button if displayed section is not the first one */
    if (tracker > 1) {
      $(".next").show();
    }

    /* hide previous button if displayed section is the first one */
    if (tracker == 1) {
      $(".prev").hide();
    }
  });
});

p {
  margin: 0;
  padding: 0;
}

blah1

blah1

blah1

blah2

blah2

blah2

blah1

blah1

blah1

blah2

blah2

blah2

blah3

blah3

blah3


问:
How do I send to the action parameter value from dropdown?
```<code>         <form class="form-horizontal"
              action="{{ path('category_view', {'program': 'category' }) }}"
              data-ajax-method="get"
              {#onclick="return makeModal(this);"#}>
                        <label for="category" class="col-sm-1 control-label">
                            Category
                        </label>
            <select id="ddlFruits" class="form-control">
                <option value="all">All</option>
                <option value="stress">Stress</option>
                <option value="media">Media</option>
                <option value="mulidrive">Multidrive</option>
                <option value="security">Security</option>
            </select>
         </form>
</code>```

How do I pass selected value from dropdown to program?

答: use .val() to get your value, so would be $('#ddlFruits').val() ;.</p>

Body:
         <form class="form-horizontal"
              action="{{ path('category_view', {'program': 'category' }) }}"
              data-ajax-method="get"
              {#onclick="return makeModal(this);"#}>

                            Category

            <select id="ddlFruits" class="form-control">
                <option value="all">All</option>
                <option value="stress">Stress</option>
                <option value="media">Media</option>
                <option value="mulidrive">Multidrive</option>
                <option value="security">Security</option>
            </select>
         </form>

How do I pass selected value from dropdown to program?


问:
Php script, query ran from value thats passed in
I am pretty new at php, quick note this is an android application that i am calling this script, I am not having the users make up the script lol. There is a series of checkboxs and when they check off certain ones it appends a script to the string builder. i am trying to run a query based on the value of a variable that is being passed in. Usually i do something like this,

```<code>   mssql_query("UPDATE Userdata SET BrowseScript = '".$_REQUEST['sqlscript']."'
WHERE Userdata.Username = '".$_REQUEST['Username']."'");
</code>```

and where it says .$_REQUEST[''] I can grab values that i pass in.

But this time the .$_REQUEST[''] is the whole script, so i want something like this

```<code>mssql_query($_REQUEST['sqlscript']);
</code>```

and thats it i want it to run the query thats in that value, The query is correct, but it just will not return any value, I think i may have some type of syntax error or something, like i said i am new to php. Thanks for any help. Also I am not posting the whole code because everything is running ok, i just cant get that query to run. so all i need assistance with is the mssql_query part thanks again.

答:
For all that's holy, do not do this!

You do not just use request parameters and put them in SQL queries. You at the very least use mysql_real_escape_string (or whatever the MSSQL equivalent is, never used it). And you most certainly don't accept whole queries in the request and execute them sight unseen.

You're opening huge gaping security holes. Especially if you're new, stop that now before it becomes a habit!

```<code>example.com/foo.php?sqlscript=DROP TABLE users
</code>```

Minimum required lecture: http://www.php.net/manual/en/security.database.sql-injection.php

Body:
I am pretty new at php, quick note this is an android application that i am calling this script, I am not having the users make up the script lol. There is a series of checkboxs and when they check off certain ones it appends a script to the string builder. i am trying to run a query based on the value of a variable that is being passed in. Usually i do something like this,

   mssql_query("UPDATE Userdata SET BrowseScript = '".$_REQUEST['sqlscript']."'
WHERE Userdata.Username = '".$_REQUEST['Username']."'");

and where it says .$_REQUEST[''] I can grab values that i pass in.

But this time the .$_REQUEST[''] is the whole script, so i want something like this

mssql_query($_REQUEST['sqlscript']);

and thats it i want it to run the query thats in that value, The query is correct, but it just will not return any value, I think i may have some type of syntax error or something, like i said i am new to php. Thanks for any help. Also I am not posting the whole code because everything is running ok, i just cant get that query to run. so all i need assistance with is the mssql_query part thanks again.

Body:
For all that's holy, do not do this!

You do not just use request parameters and put them in SQL queries. You at the very least use mysql_real_escape_string (or whatever the MSSQL equivalent is, never used it). And you most certainly don't accept whole queries in the request and execute them sight unseen.

You're opening huge gaping security holes. Especially if you're new, stop that now before it becomes a habit!

example.com/foo.php?sqlscript=DROP TABLE users

Minimum required lecture: http://www.php.net/manual/en/security.database.sql-injection.php


问:
How To Remove First Three Line In A File
I have an excel file that I need to remove the earliest three dates from,based on another column.

```<code>        Column A Column B Column C
        Member  Claim          Date
Row1    1234    1111          01/01/2017
Row2    1234    1112          02/01/2017
Row3    1234    1113          03/01/2017
Row4    1234    1114          04/01/2017
Row5    1234    1115          05/01/2017
Row6    1234    1116          06/01/2017
Row7    222     1117          01/01/2017
Row8    222     1118          02/01/2017
</code>```

This is test data, my real file has hundreds of lines and hundreds of members. I need to remove the earliest three per member.
I only want to see the last 3 lines for Member 1234
I have tried using a conditional format, however this has not worked.
Could somebody suggest either a excel formula, or VBA solution?

I am also open to a SQL Solution.
I am unsure how I would write this.

I have

```<code>Select a.mem, count(a.claim) from Temp a
group by a.mem;
</code>```

答:
```<code>=(OFFSET(FIRST_Member, COUNTA(RANGE:RANGE)-3,0,3,1))
</code>```

Where FIRST_Member is the first cell reference you want from the first three values. RANGE:RANGE is the range of the cells you want for the first three values.

If you want just the last three lines from a member, add an =(IF()) format. This should be close to what you are looking for, but your question lacks precise cell references.

```<code>=(IF(A1='1234', OFFSET(FIRST_Member, COUNTA(RANGE:RANGE)-3,0,3,1) )
</code>```

Body:
I have an excel file that I need to remove the earliest three dates from,based on another column.

        Column A Column B Column C
        Member  Claim          Date
Row1    1234    1111          01/01/2017
Row2    1234    1112          02/01/2017
Row3    1234    1113          03/01/2017
Row4    1234    1114          04/01/2017
Row5    1234    1115          05/01/2017
Row6    1234    1116          06/01/2017
Row7    222     1117          01/01/2017
Row8    222     1118          02/01/2017

This is test data, my real file has hundreds of lines and hundreds of members. I need to remove the earliest three per member.
I only want to see the last 3 lines for Member 1234
I have tried using a conditional format, however this has not worked.
Could somebody suggest either a excel formula, or VBA solution?

I am also open to a SQL Solution.
I am unsure how I would write this.

I have

Select a.mem, count(a.claim) from Temp a
group by a.mem;

Body:
=(OFFSET(FIRST_Member, COUNTA(RANGE:RANGE)-3,0,3,1))

Where FIRST_Member is the first cell reference you want from the first three values. RANGE:RANGE is the range of the cells you want for the first three values.

If you want just the last three lines from a member, add an =(IF()) format. This should be close to what you are looking for, but your question lacks precise cell references.

=(IF(A1='1234', OFFSET(FIRST_Member, COUNTA(RANGE:RANGE)-3,0,3,1) )


问:
excel: vba type mismatch using find
I have this sheet where:

If the value in cell in column I is "Não marcou férias" then it should search the whole column A and find all times that the unique number for that specific person appears more than once.

If the unique number appears twice or more and the column I of that row is not "Não marcou férias" then it should compare with current year and write ATUAL in the corresponding cell in column K. If it's true then the row in column K that have "Não marcou férias" should be blank.

Here is my sheet:

And this is what I want to happen:

As you can see as I have two entries with number 59837 and one of them is "Não marcou férias", I want it to run through column A and find if exist another entry and as it is current, it should write "ATUAL" on it.

Here is my code:

```<code>Sub test()

Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim date1 As Date, date2 As Date

Set ws1 = Sheets("Plan1")

lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row

For j = 2 To lastrow

date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)

If ws1.Cells(j, 9) = "Não marcou férias" Then
k = ws1.Cells(j, 1).Value
    With ws1.Range("A2:A" & lastrow)
    Set c = .Find(k, LookIn:=xlValues)

    If Not c Is Nothing Then
    firstAddress = c.Address
        Do
            If ws1.Cells(j, 9) <> "Não marcou férias" Then
                If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then
                    ws1.Cells(j, 13) = "ATUAL"
                Else
                    ws1.Cells(j, 13) = ""
                End If
            End If

    Set c = .FindNext(c)

        If c Is Nothing Then
            GoTo DoneFinding
        End If
        Loop While c.Address <> firstAddress
    End If
DoneFinding:
    End With
End If

Next j

End Sub
</code>```

But when I try to run I get:

Run-time error 13: Type mismatch

And this line is highlighted:

```<code>date1 = ws1.Cells(j, 9)
</code>```

My Excel is in portuguese so here we use date format like dd/mm/yyyy and all my columns are set up as dates correctly.

Is there anyone with suggestions? I don't know why I'm getting this type mismatch again since I've already applied THIS solution.

EDIT: I've tested the suggested solutions, but I still have the same problem in the same line.

```<code>Option Explicit
Sub test2()

Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim date1 As Date, date2 As Date
Dim k As Long
Dim c As Range
Dim firstAddress As String

Set ws1 = Sheets("Plan1")

lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row

For j = 2 To lastrow

date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)

If Not IsDate(ws1.Cells(j, 9)) Then
    k = ws1.Cells(j, 1).Value
    With ws1.Range("A2:A" & lastrow)
    Set c = .Find(k, LookIn:=xlValues)

    If Not c Is Nothing Then
    firstAddress = c.Address
        Do
            If IsDate(ws1.Cells(j, 9)) Then
                If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then
                    ws1.Cells(j, 13) = "ATUAL"
                Else
                    ws1.Cells(j, 13) = ""
                End If
            End If

    Set c = .FindNext(c)

        If c Is Nothing Then
            GoTo DoneFinding
        End If
        Loop While c.Address <> firstAddress
    End If
DoneFinding:
    End With
End If

Next j

End Sub
</code>```

答:
Always make sure that you include Option Explicit on top of your code.

Simply write msgbox ws1.Cells(j, 9).address on the line above the line with the error.

Check the MsgBox coming before the error.

I can bet a virtual beer, that the address is pointing to is a value, which is not a date. For example I6 in your screenshot, saying something nice about vacations and booking in Portuguese.

In your code, you may add something like If IsDate(ws1.cells(j,9)) then. It would check whether the given value is a date or not. In your case Não marcou férias cannot be parsed as a Date format, thus you get an error. Or simply try to replace the code positions like this:

```<code>For j = 2 To lastrow
   If ws1.Cells(j, 9) <> "Não marcou férias" Then
      date1 = ws1.Cells(j, 9)
      date2 = ws1.Cells(j, 12)
      k = ws1.Cells(j, 1).Value
      With ws1.Range("A2:A" & lastrow)
</code>```

If the value is not "Nao marcou ferias" then its probably  a date (although, its better to use the IsDate()).

Have fun, TGIF

Title: excel: vba type mismatch using find

Body:
I have this sheet where:

If the value in cell in column I is "Não marcou férias" then it should search the whole column A and find all times that the unique number for that specific person appears more than once.

If the unique number appears twice or more and the column I of that row is not "Não marcou férias" then it should compare with current year and write ATUAL in the corresponding cell in column K. If it's true then the row in column K that have "Não marcou férias" should be blank.

Here is my sheet:

And this is what I want to happen:

As you can see as I have two entries with number 59837 and one of them is "Não marcou férias", I want it to run through column A and find if exist another entry and as it is current, it should write "ATUAL" on it.

Here is my code:

Sub test()

Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim date1 As Date, date2 As Date

Set ws1 = Sheets("Plan1")

lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row

For j = 2 To lastrow

date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)

If ws1.Cells(j, 9) = "Não marcou férias" Then
k = ws1.Cells(j, 1).Value
    With ws1.Range("A2:A" & lastrow)
    Set c = .Find(k, LookIn:=xlValues)

    If Not c Is Nothing Then
    firstAddress = c.Address
        Do
            If ws1.Cells(j, 9) <> "Não marcou férias" Then
                If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then
                    ws1.Cells(j, 13) = "ATUAL"
                Else
                    ws1.Cells(j, 13) = ""
                End If
            End If

    Set c = .FindNext(c)

        If c Is Nothing Then
            GoTo DoneFinding
        End If
        Loop While c.Address <> firstAddress
    End If
DoneFinding:
    End With
End If

Next j

End Sub

But when I try to run I get:

Run-time error 13: Type mismatch

And this line is highlighted:

date1 = ws1.Cells(j, 9)

My Excel is in portuguese so here we use date format like dd/mm/yyyy and all my columns are set up as dates correctly.

Is there anyone with suggestions? I don't know why I'm getting this type mismatch again since I've already applied THIS solution.

EDIT: I've tested the suggested solutions, but I still have the same problem in the same line.

Option Explicit
Sub test2()

Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim date1 As Date, date2 As Date
Dim k As Long
Dim c As Range
Dim firstAddress As String

Set ws1 = Sheets("Plan1")

lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row

For j = 2 To lastrow

date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)

If Not IsDate(ws1.Cells(j, 9)) Then
    k = ws1.Cells(j, 1).Value
    With ws1.Range("A2:A" & lastrow)
    Set c = .Find(k, LookIn:=xlValues)

    If Not c Is Nothing Then
    firstAddress = c.Address
        Do
            If IsDate(ws1.Cells(j, 9)) Then
                If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then
                    ws1.Cells(j, 13) = "ATUAL"
                Else
                    ws1.Cells(j, 13) = ""
                End If
            End If

    Set c = .FindNext(c)

        If c Is Nothing Then
            GoTo DoneFinding
        End If
        Loop While c.Address <> firstAddress
    End If
DoneFinding:
    End With
End If

Next j

End Sub

Body:
Always make sure that you include Option Explicit on top of your code.

Simply write msgbox ws1.Cells(j, 9).address on the line above the line with the error.

Check the MsgBox coming before the error.

I can bet a virtual beer, that the address is pointing to is a value, which is not a date. For example I6 in your screenshot, saying something nice about vacations and booking in Portuguese.

In your code, you may add something like If IsDate(ws1.cells(j,9)) then. It would check whether the given value is a date or not. In your case Não marcou férias cannot be parsed as a Date format, thus you get an error. Or simply try to replace the code positions like this:

For j = 2 To lastrow
   If ws1.Cells(j, 9) <> "Não marcou férias" Then
      date1 = ws1.Cells(j, 9)
      date2 = ws1.Cells(j, 12)
      k = ws1.Cells(j, 1).Value
      With ws1.Range("A2:A" & lastrow)

If the value is not "Nao marcou ferias" then its probably  a date (although, its better to use the IsDate()).

Have fun, TGIF


问:
Rails / Multi-Tenancy: Conditional default scope based on a different model's db value / global setting?
I've got a Rails application that is multi-tenant. Every model has an account_id, belongs to an account, and has a default scope to a current account id:

```<code>class Derp < ApplicationRecord
  default_scope { where(account_id: Account.current_id) }
  belongs_to :account
end
</code>```

This works well and I've used this pattern in production in other apps (I understand that default scopes are frowned upon, but this is an accepted pattern. See: https://leanpub.com/multi-tenancy-rails).

Now here's the kicker - I have one client (and potentially more down the line, who knows), who wants to run the software on their own server. To solve this, I simply made a Server model with a type attribute:

```<code>class Server < ApplicationRecord
  enum server_type: { multitenant: 0, standalone: 1 }
end
</code>```

Now on my multi-tenant server instance, I simply make one Server record and set the server_type to 0, and on my standalone instance I set it to 1. Then I've got some helper methods in my application controller to help with this, namely:

```<code>class ApplicationController < ActionController::Base
  around_action :scope_current_account

  ...

  def server
    @server ||= Server.first
  end

  def current_account
    if server.standalone?
      @current_account ||= Account.first
    elsif server.first.multitenant?
      @current_account ||= Account.find_by_subdomain(subdomain) if subdomain
    end
  end

  def scope_current_account
    Account.current_id = current_account.id
    yield
  rescue ActiveRecord::RecordNotFound
    redirect_to not_found_path
  ensure
    Account.current_id = nil
  end
end
</code>```

This works, but I've got large record sets that I'm querying on this particular standalone client (70,000 records). I've got an index on the account_id, but it took my main customers table from 100ms to 400ms on my development machine.

Then I realized: standalone servers really don't need to concern themselves with the account id at all, especially if it is going to affect performance.

So really all I've got to do is make this line conditional:

```<code>default_scope { where(account_id: Account.current_id) }
</code>```

I'd like to do something like this:

```<code>class Derp < ApplicationRecord
  if Server.first.multitenant?
    default_scope { where(account_id: Account.current_id) }
  end
end
</code>```

But obviously that syntax wrong. I've seen some other examples on Stack Overflow for conditional scopes, but none seem to work with a conditional statement based on a completely separate model. Is there a way to accomplish something like that in Ruby?

EDIT: Kicker here that I just realized is that this will only solve the speed issue for the one standalone server, and all the multi-tenant accounts will still have to deal with querying with the account_id. Maybe I should focus on that instead...

答:
Here's my solution:

First, abstract the account scoping stuff that any account scoped model will have to an abstract base class that inherits from ApplicationRecord:

```<code>class AccountScopedRecord < ApplicationRecord
  self.abstract_class = true

  default_scope { where(account_id: Account.current_id) }

  belongs_to :account
end
</code>```

Now any model can cleanly be account scoped like:

```<code>class Job < AccountScopedRecord
  ...
end
</code>```

To solve the conditional, abstract that one step further into an ActiveRecord concern:

```<code>module AccountScoped
  extend ActiveSupport::Concern

  included do
    default_scope { where(account_id: Account.current_id) }
    belongs_to :account
  end
end
</code>```

Then the AccountScopedRecord can do:

```<code>class AccountScopedRecord < ApplicationRecord
  self.abstract_class = true

  if Server.first.multitenant?
    send(:include, AccountScoped)
  end
end
</code>```

Now standalone accounts can ignore any account related stuff:

```<code># Don't need this callback on standalone anymore
around_action :scope_current_account, if: multitenant?

# Method gets simplified
def current_account
  @current_account ||= Account.find_by_subdomain(subdomain) if subdomain
end
</code>```

Body:
I've got a Rails application that is multi-tenant. Every model has an account_id, belongs to an account, and has a default scope to a current account id:

class Derp < ApplicationRecord
  default_scope { where(account_id: Account.current_id) }
  belongs_to :account
end

This works well and I've used this pattern in production in other apps (I understand that default scopes are frowned upon, but this is an accepted pattern. See: https://leanpub.com/multi-tenancy-rails).

Now here's the kicker - I have one client (and potentially more down the line, who knows), who wants to run the software on their own server. To solve this, I simply made a Server model with a type attribute:

class Server < ApplicationRecord
  enum server_type: { multitenant: 0, standalone: 1 }
end

Now on my multi-tenant server instance, I simply make one Server record and set the server_type to 0, and on my standalone instance I set it to 1. Then I've got some helper methods in my application controller to help with this, namely:

class ApplicationController < ActionController::Base
  around_action :scope_current_account

  ...

  def server
    @server ||= Server.first
  end

  def current_account
    if server.standalone?
      @current_account ||= Account.first
    elsif server.first.multitenant?
      @current_account ||= Account.find_by_subdomain(subdomain) if subdomain
    end
  end

  def scope_current_account
    Account.current_id = current_account.id
    yield
  rescue ActiveRecord::RecordNotFound
    redirect_to not_found_path
  ensure
    Account.current_id = nil
  end
end

This works, but I've got large record sets that I'm querying on this particular standalone client (70,000 records). I've got an index on the account_id, but it took my main customers table from 100ms to 400ms on my development machine.

Then I realized: standalone servers really don't need to concern themselves with the account id at all, especially if it is going to affect performance.

So really all I've got to do is make this line conditional:

default_scope { where(account_id: Account.current_id) }

I'd like to do something like this:

class Derp < ApplicationRecord
  if Server.first.multitenant?
    default_scope { where(account_id: Account.current_id) }
  end
end

But obviously that syntax wrong. I've seen some other examples on Stack Overflow for conditional scopes, but none seem to work with a conditional statement based on a completely separate model. Is there a way to accomplish something like that in Ruby?

EDIT: Kicker here that I just realized is that this will only solve the speed issue for the one standalone server, and all the multi-tenant accounts will still have to deal with querying with the account_id. Maybe I should focus on that instead...

Body:
Here's my solution:

First, abstract the account scoping stuff that any account scoped model will have to an abstract base class that inherits from ApplicationRecord:

class AccountScopedRecord < ApplicationRecord
  self.abstract_class = true

  default_scope { where(account_id: Account.current_id) }

  belongs_to :account
end

Now any model can cleanly be account scoped like:

class Job < AccountScopedRecord
  ...
end

To solve the conditional, abstract that one step further into an ActiveRecord concern:

module AccountScoped
  extend ActiveSupport::Concern

  included do
    default_scope { where(account_id: Account.current_id) }
    belongs_to :account
  end
end

Then the AccountScopedRecord can do:

class AccountScopedRecord < ApplicationRecord
  self.abstract_class = true

  if Server.first.multitenant?
    send(:include, AccountScoped)
  end
end

Now standalone accounts can ignore any account related stuff:

# Don't need this callback on standalone anymore
around_action :scope_current_account, if: multitenant?

# Method gets simplified
def current_account
  @current_account ||= Account.find_by_subdomain(subdomain) if subdomain
end


问:
Anyone knows how to give individual limited cluster access to users without using RBAC in kube 1.5.7?
I want to be able to give certain users limited access to the cluster. The admin user is in the kube config but i want to give access to individual users like "bob" but only to just a certain namespace etc. Is the possible without using RBAC?</p>

答: you will need to use ABAC authorization mode: https://kubernetes.io/docs/admin/authorization/abac/</p>


问:
Unit testing with Mocks. Test behaviour not implementation
I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided.

Like the code provided below.

```<code>public class UserRegistrationProcess : IUserRegistration
{
    private readonly IRepository _repository;
    private readonly ISmsService _smsService;

    public UserRegistrationProcess(IRepository repository, ISmsService smsService)
    {
        _repository = repository;
        _smsService = smsService;
    }

    public void Register(string phone)
    {
        var user = new User(phone);
        _repository.Save(user);
        _smsService.Send(phone, "Welcome", "Message!");
    }
}
</code>```

It is a really simple class but how would you go about and test it?

At the moment im using Mocks but I dont really like it

```<code>    [Test]
    public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);
        repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
    }

    [Test]
    public void WhenRegistreringANewUser_ItWillSendANewSms()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);

        smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once());
    }
</code>```

It feels like I am testing the wrong thing here?

Any thoughts on how to make this better?

答:
look at after some refactor</p>

```<code> Mock<IRepository<>> repository;
    private Mock<ISmsService> smsService;
    const string phone = "0768524440";
    [SetUp]
    public void SetUp()
    {
           repository = new Mock<IRepository<>>();
         smsService = new Mock<ISmsService>();
    }
    [Test]
    public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
    {

        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        userRegistration.Register(phone);

        repository.VerifyAll();
        smsService.VerifyAll();
    }
</code>```

Body:
I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided.

Like the code provided below.

public class UserRegistrationProcess : IUserRegistration
{
    private readonly IRepository _repository;
    private readonly ISmsService _smsService;

    public UserRegistrationProcess(IRepository repository, ISmsService smsService)
    {
        _repository = repository;
        _smsService = smsService;
    }

    public void Register(string phone)
    {
        var user = new User(phone);
        _repository.Save(user);
        _smsService.Send(phone, "Welcome", "Message!");
    }
}

It is a really simple class but how would you go about and test it?

At the moment im using Mocks but I dont really like it

    [Test]
    public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);
        repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once());
    }

    [Test]
    public void WhenRegistreringANewUser_ItWillSendANewSms()
    {
        var repository = new Mock<IRepository>();
        var smsService = new Mock<ISmsService>();
        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        var phone = "07012345678";

        userRegistration.Register(phone);

        smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once());
    }

It feels like I am testing the wrong thing here?

Any thoughts on how to make this better?

Body:
look at after some refactor

 Mock<IRepository<>> repository;
    private Mock<ISmsService> smsService;
    const string phone = "0768524440";
    [SetUp]
    public void SetUp()
    {
           repository = new Mock<IRepository<>>();
         smsService = new Mock<ISmsService>();
    }
    [Test]
    public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase()
    {

        var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object);

        userRegistration.Register(phone);

        repository.VerifyAll();
        smsService.VerifyAll();
    }


问:
Python Decorators & Nested Functions return statement. Proper usage with parenthesis?
What's the difference including/not including the parentheses on the return statement for inner function for decorators (and any nested functions)? Are the parenthesis only required if the function returns more than 1 variable?

In the example below I know this won't work unless I use return inner(), but I see other examples that don't use the () on the return and they work fine.

Terminology behind the reason would great so help me fully understand. Thanks.

```<code>def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner()

@stars
def func():
    print('Decorate this message.')
</code>```

It initially prints my message, decorated. But if I call func() again, it will not print anything.

Another working example, but return inner works fine in this case, long as I have set up my function to support a callable variable, being msg for my example:

```<code>def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def func(msg):
    print(msg)
func("Another message to be decorated")
</code>```

And I can call func('my new message') each time to print my message, decorated. Why is this compared to the previous example when I don't use a callable function?

答:
Your invoking the inner function instead of returning it. The code below wraps the func function instead of calling it immediately like the code you've pasted above.

```<code>def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner

@stars
def func():
    print('Decorate this message.')
</code>```

Body:
What's the difference including/not including the parentheses on the return statement for inner function for decorators (and any nested functions)? Are the parenthesis only required if the function returns more than 1 variable?

In the example below I know this won't work unless I use return inner(), but I see other examples that don't use the () on the return and they work fine.

Terminology behind the reason would great so help me fully understand. Thanks.

def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner()

@stars
def func():
    print('Decorate this message.')

It initially prints my message, decorated. But if I call func() again, it will not print anything.

Another working example, but return inner works fine in this case, long as I have set up my function to support a callable variable, being msg for my example:

def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def func(msg):
    print(msg)
func("Another message to be decorated")

And I can call func('my new message') each time to print my message, decorated. Why is this compared to the previous example when I don't use a callable function?

Body:
Your invoking the inner function instead of returning it. The code below wraps the func function instead of calling it immediately like the code you've pasted above.

def stars(func):
    def inner():
        print("*" * 50)
        func()
        print("*" * 50)
    return inner

@stars
def func():
    print('Decorate this message.')


问:
NSLocale.current.description crashing in Xcode 9
I created a brand new single view application and added one line to the viewDidLoad method of the ViewController.swift file:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    _ = NSLocale.current.description
}
</code>```

The NSLocale.current.description line crashes in Xcode 9 with no stack trace (just a EXC_BAD_ACCESS code=EXC_I386_GPFLT error message). The same project runs fine in Xcode 8.3.3. Anyone have any ideas why this is happening?

Here is my simulator region settings:

答:
Based on the stack trace, it looks like it's trying to treat description as an ObjC property rather than a Swift property. Based on the source code, this shouldn't be happening. It's likely a bug in the latest Swift compiler that is producing the Swift libraries because it crashes on an iOS 9 device as well.

Be sure to file a bug with Swift since this seems to be a language bug. I've verified that it is still broken in the latest Swift 4 toolchain. In the meantime, you can get the same behavior of description using your own extension by simply duplicating the intended implementation like I've shown here.

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // let brokenDescription = NSLocale.current.description
        // let otherBrokenDescription = Locale.current.description

        let objcDescription = (Locale.current as NSLocale).debugDescription //"<__NSCFLocale: 0x1c00dbc10> \'en_US\'}"
        let myDescription = Locale.current.myDescription // "en_US (current)"
    }
}

extension Locale {
    private var _kindDescription : String {
        if self == Locale.autoupdatingCurrent {
            return "autoupdatingCurrent"
        } else if self == Locale.current {
            return "current"
        } else {
            return "fixed"
        }
    }

    public var myDescription: String {
        return "\(identifier) (\(_kindDescription))"
    }

    public var myDebugDescription : String {
        return "\(identifier) (\(_kindDescription))"
    }
}
</code>```

Body:
I created a brand new single view application and added one line to the viewDidLoad method of the ViewController.swift file:

override func viewDidLoad() {
    super.viewDidLoad()
    _ = NSLocale.current.description
}

The NSLocale.current.description line crashes in Xcode 9 with no stack trace (just a EXC_BAD_ACCESS code=EXC_I386_GPFLT error message). The same project runs fine in Xcode 8.3.3. Anyone have any ideas why this is happening?

Here is my simulator region settings:

Body:
Based on the stack trace, it looks like it's trying to treat description as an ObjC property rather than a Swift property. Based on the source code, this shouldn't be happening. It's likely a bug in the latest Swift compiler that is producing the Swift libraries because it crashes on an iOS 9 device as well.

Be sure to file a bug with Swift since this seems to be a language bug. I've verified that it is still broken in the latest Swift 4 toolchain. In the meantime, you can get the same behavior of description using your own extension by simply duplicating the intended implementation like I've shown here.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // let brokenDescription = NSLocale.current.description
        // let otherBrokenDescription = Locale.current.description

        let objcDescription = (Locale.current as NSLocale).debugDescription //"<__NSCFLocale: 0x1c00dbc10> \'en_US\'}"
        let myDescription = Locale.current.myDescription // "en_US (current)"
    }
}

extension Locale {
    private var _kindDescription : String {
        if self == Locale.autoupdatingCurrent {
            return "autoupdatingCurrent"
        } else if self == Locale.current {
            return "current"
        } else {
            return "fixed"
        }
    }

    public var myDescription: String {
        return "\(identifier) (\(_kindDescription))"
    }

    public var myDebugDescription : String {
        return "\(identifier) (\(_kindDescription))"
    }
}


答:
By calling the inner function, instead of returning the function object, func is called at decoration time.

```<code>stars(func) -> inner() -> func() # with some side effects
</code>```

Which is usually not what we want. The function is decorated to be called at a later time.

More so, in the case when your function takes argument(s), this is certainly not going work, as you'll need to actually call the decorated function with valid parameters to have them passed to inner and then on to func.

Title: Python Decorators & Nested Functions return statement. Proper usage with parenthesis?

Body:
By calling the inner function, instead of returning the function object, func is called at decoration time.

stars(func) -> inner() -> func() # with some side effects

Which is usually not what we want. The function is decorated to be called at a later time.

More so, in the case when your function takes argument(s), this is certainly not going work, as you'll need to actually call the decorated function with valid parameters to have them passed to inner and then on to func.