问:
Java - Restricting by what a method can be called
I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:

```<code>if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}
</code>```

Is there something else I should be doing, or should I just not forget how my program works?

答:
You should be using visibility to restrict calling - making a method public (or for that matter, javadocing it) is not going to work unless you have dicipline (and you control the callers too). From your description, you are neither.

What you can do is make the class package private, and put it in the same package as the two callers of that class. As long as you have a proper package structure, this can work. E.g.:
Your class that should only be called by A and B:

```<code>package thepackage.of.a.and.b;
//imports here
class CallableByAB {
 public void methodA(){}
 public void methodB(){}
}
</code>```

A:

```<code>package thepackage.of.a.and.b;
public class A {
   /*...other code here */
   new CallableByAB().methodA();
   /*...other code here */
}
</code>```

B:

```<code>package thepackage.of.a.and.b;
public class B {
   /*...other code here */
   new CallableByAB().methodB();
   /*...other code here */
}
</code>```

other classes cannot call  new CallableByAB() or import it. hence, safety.

Body:
I have methods set to public because they must be called by an exterior class, but I only ever want them called by one or two methods. Being called by other methods could create bugs in my program. So, in order to prevent me from accidentally programming around my own methods, I have been doing stuff like this within the methods of which I want to restrict callers:

if(trace.length<2){
    throw new Exception("Class should not call its own function.");
}else if(trace[1].getClassName()!=desiredClassName || trace[1].getMethodName()!=desiredMethodName){
    throw new Exception(trace[1].getClassName()+"\" is invalid function caller. Should only be called by "+desiredClassName+"->"+desiredMethodName+".");
}

Is there something else I should be doing, or should I just not forget how my program works?

Body:
You should be using visibility to restrict calling - making a method public (or for that matter, javadocing it) is not going to work unless you have dicipline (and you control the callers too). From your description, you are neither.

What you can do is make the class package private, and put it in the same package as the two callers of that class. As long as you have a proper package structure, this can work. E.g.:
Your class that should only be called by A and B:

package thepackage.of.a.and.b;
//imports here
class CallableByAB {
 public void methodA(){}
 public void methodB(){}
}

A:

package thepackage.of.a.and.b;
public class A {
   /*...other code here */
   new CallableByAB().methodA();
   /*...other code here */
}

B:

package thepackage.of.a.and.b;
public class B {
   /*...other code here */
   new CallableByAB().methodB();
   /*...other code here */
}

other classes cannot call  new CallableByAB() or import it. hence, safety.


来源: stackexchange

问:
Polygons and keys
hi I am having trouble with this one problem

Given a variable, polygon_sides, that is associated with a dictionary that maps names of polygons to number of sides, create a new dictionary that maps number of sides to polygon names, and associate it with a variable n_polygons.

my current code

```<code>for n_polygons in polygon_sides:
    polygon_sides={n_polygons[]:polygon_sides}
</code>```

the only error it gives me are syntax errors.

do i have to rearrange the whole problem??

答:
It's a one-liner. You need a loop in the expression to get all the elements.</p>

```<code>n_polygons = {v:k for k,v in polygon_sides.items()}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Polygons and keys

Body:
hi I am having trouble with this one problem

Given a variable, polygon_sides, that is associated with a dictionary that maps names of polygons to number of sides, create a new dictionary that maps number of sides to polygon names, and associate it with a variable n_polygons.

my current code

for n_polygons in polygon_sides:
    polygon_sides={n_polygons[]:polygon_sides}

the only error it gives me are syntax errors.

do i have to rearrange the whole problem??

Body:
It's a one-liner. You need a loop in the expression to get all the elements.

n_polygons = {v:k for k,v in polygon_sides.items()}


问:
Hiding previously displayed array elements
So, I have an array of Strings that I have display to the screen one at a time through the text() function. But when I add to the index the previous array element stays on-screen and I can't figure out how to remove it. I just want to scroll through the text on screen and essentially have the next array element replace it on the screen.

```<code>Dialog[] main = new Dialog[12];
int index;

void setup() {
  for (int index = 0; index < main.length; index++) {
    main[index] = new Dialog();
}

void draw() {
  for (int index = 0; index < main.length; index++) {
    main[index].readDialog();
  }
}

if (mousePressed) {
  index++:
}

String[] textScroll = new String[12];

class Dialog {
Dialog () {
   textScroll[0] = "Welcome to the game!";
   textScroll[1] = "Are you ready to play?";
   etc...
}
void readDialog() {
   text(textScroll[index], width/2, 100);
  }
}
</code>```

答:
First off, your syntax is not valid. You're missing curly brackets, and you've got an if statement outside of a function, which is not valid. Please try to post a MCVE with valid syntax instead of a disconnected snippet of code.

But to answer your general question, you can clear out old frames by calling the background() function. Compare this code:

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

<p>to this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.js"></script>
<script type="application/processing">

void draw(){
  background(32);
  ellipse(mouseX, mouseY, 20, 20);
}

</script>
<canvas> </canvas></code>```

The first code draws a circle wherever the mouse is, and it doesn't clear out old frames so you can see all of the previously drawn circles. The second code draws a circle wherever the mouse is, but it clears out old frames so you only see the most recently drawn circle.

You want to do something similar to clear out your old frames. More info can be found in the reference.

Body:
So, I have an array of Strings that I have display to the screen one at a time through the text() function. But when I add to the index the previous array element stays on-screen and I can't figure out how to remove it. I just want to scroll through the text on screen and essentially have the next array element replace it on the screen.

Dialog[] main = new Dialog[12];
int index;

void setup() {
  for (int index = 0; index < main.length; index++) {
    main[index] = new Dialog();
}

void draw() {
  for (int index = 0; index < main.length; index++) {
    main[index].readDialog();
  }
}

if (mousePressed) {
  index++:
}

String[] textScroll = new String[12];

class Dialog {
Dialog () {
   textScroll[0] = "Welcome to the game!";
   textScroll[1] = "Are you ready to play?";
   etc...
}
void readDialog() {
   text(textScroll[index], width/2, 100);
  }
}

Body:
First off, your syntax is not valid. You're missing curly brackets, and you've got an if statement outside of a function, which is not valid. Please try to post a MCVE with valid syntax instead of a disconnected snippet of code.

But to answer your general question, you can clear out old frames by calling the background() function. Compare this code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.js"></script>
<script type="application/processing">

void draw(){
  ellipse(mouseX, mouseY, 20, 20);
}

</script>
<canvas> </canvas>

to this code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/processing.js/1.6.6/processing.js"></script>
<script type="application/processing">

void draw(){
  background(32);
  ellipse(mouseX, mouseY, 20, 20);
}

</script>
<canvas> </canvas>

The first code draws a circle wherever the mouse is, and it doesn't clear out old frames so you can see all of the previously drawn circles. The second code draws a circle wherever the mouse is, but it clears out old frames so you only see the most recently drawn circle.

You want to do something similar to clear out your old frames. More info can be found in the reference.


问:
xcb library: how to draw in colours
I am creating C code that must draw lines and symbols in several graphic windows, in several colors. Consulting the www I learned that I need to use a colormap, however I cannot get them to work.
Most code I found is about creating and populating a new colormap, however I only need a handful of colours (yellow, red, magenta, ...) so I thought the default map would be sufficient.
How can I read what colours are available in the default colormap screen->default_colormap ?
Could someone point me to an elementary example of creating a window and its graphic context, then drawing (say) a green circle in it, or a blue square?</p>

答:
The following code is a few lines extracted from a project I'm working on, in which I draw with quite a number of colors. It works for me - I don't mean to say this is the best, or even a very good way, but I'm just a hobbyist trying to teach myself and out of the sparse examples I've found, this is what I've cobbled together.

check this manpage for: xcb_change_gc(etc.,);

I actually keep a simple array of the rgb values, stored is uint32_ts, which I draw with. Since I only program for my own satisfaction, I've no idea whether this is very portable. Also, it took some experimenting to discover the coding for the colors. I'm sure that's hardware dependent. I think the advantage of colormaps is that they ARE PORTABLE and if you don't have truecolor, colormaps will help you draw with the right colors. I personally don't need to know. I just like drawing using pixels or filled rectangles to explore some maths.

```<code>uint32_t    rgb = 0xFFFFFFFF; // white on my system

uint32_t    mask = XCB_GC_FOREGROUND,
            foreground_value = rgb;

xcb_gcontext_t gc;

gc = xcb_generate_id(connection);
xcb_create_gc (connection, gc, drawing_buffer_pixmap, mask, &foreground_value);

// below, the color of the gc is changed rather than making a new one

xcb_change_gc(connection, *gc, mask, &foreground_value);
</code>```

Title: xcb library: how to draw in colours

Body:
The following code is a few lines extracted from a project I'm working on, in which I draw with quite a number of colors. It works for me - I don't mean to say this is the best, or even a very good way, but I'm just a hobbyist trying to teach myself and out of the sparse examples I've found, this is what I've cobbled together.

check this manpage for: xcb_change_gc(etc.,);

I actually keep a simple array of the rgb values, stored is uint32_ts, which I draw with. Since I only program for my own satisfaction, I've no idea whether this is very portable. Also, it took some experimenting to discover the coding for the colors. I'm sure that's hardware dependent. I think the advantage of colormaps is that they ARE PORTABLE and if you don't have truecolor, colormaps will help you draw with the right colors. I personally don't need to know. I just like drawing using pixels or filled rectangles to explore some maths.

uint32_t    rgb = 0xFFFFFFFF; // white on my system

uint32_t    mask = XCB_GC_FOREGROUND,
            foreground_value = rgb;

xcb_gcontext_t gc;

gc = xcb_generate_id(connection);
xcb_create_gc (connection, gc, drawing_buffer_pixmap, mask, &foreground_value);

// below, the color of the gc is changed rather than making a new one

xcb_change_gc(connection, *gc, mask, &foreground_value);


问:
Bottom border override normal on hover
Hey I can't understand if there is any easy way to solve this:
I want the black border to be on top of the blue border not extend the height of the navigation.

I've looked at inset and adding bottom in the a but I want to override the one from .navigationbar

HTML

```<code><nav class="navigationbar">
  <ul>
    <li>
      <a href="index.html">One</a>
    </li>
    <li>
      <a href="two.html">Two</a>
    </li>
    <li>
      <a href="three.html">Three</a>
    </li>
  </ul>
</nav>
</code>```

CSS

```<code>* {
  margin: 0;
}
.navigationbar {
  background-color: #000000;
  width: 100%;
  border-bottom: .1em solid #0000FF;
}

.navigationbar ul {
  list-style-type: none;
  overflow: hidden;
}

.navigationbar ul li {
  float: left;
  color: #FFFFFF;
}

.navigationbar ul li a {
  height: 100%;
  display: block;
  color: #FFFFFF;
  text-align: center;
  text-decoration: none;
  padding-left: 1em;
  padding-right: 1em;
  padding-top: 1em;
  padding-bottom: 1em;
}

.navigationbar ul li a:hover {
  background: #0000FF;
  color: #FFFFFF;
  border-bottom: .1em solid #000000;
}

.navigationbar img {
  float: left;
}
</code>```

https://jsfiddle.net/55r2e9bq/

答:
Why not just set the border and change its color later?</p>

```<code>.navigationbar ul li a
{
    border-bottom: .1em solid transparent;
}

.navigationbar ul li a:hover
{
    border-bottom-color: #000000;
}
</code>```

Title: Bottom border override normal on hover

Body:
Hey I can't understand if there is any easy way to solve this:
I want the black border to be on top of the blue border not extend the height of the navigation.

I've looked at inset and adding bottom in the a but I want to override the one from .navigationbar

HTML

      One

      Two

      Three

CSS

* {
  margin: 0;
}
.navigationbar {
  background-color: #000000;
  width: 100%;
  border-bottom: .1em solid #0000FF;
}

.navigationbar ul {
  list-style-type: none;
  overflow: hidden;
}

.navigationbar ul li {
  float: left;
  color: #FFFFFF;
}

.navigationbar ul li a {
  height: 100%;
  display: block;
  color: #FFFFFF;
  text-align: center;
  text-decoration: none;
  padding-left: 1em;
  padding-right: 1em;
  padding-top: 1em;
  padding-bottom: 1em;
}

.navigationbar ul li a:hover {
  background: #0000FF;
  color: #FFFFFF;
  border-bottom: .1em solid #000000;
}

.navigationbar img {
  float: left;
}

https://jsfiddle.net/55r2e9bq/

Body:
Why not just set the border and change its color later?

.navigationbar ul li a
{
    border-bottom: .1em solid transparent;
}

.navigationbar ul li a:hover
{
    border-bottom-color: #000000;
}


问:
Node - require('crypto') resolves to { }
I'm using NPM for dependency management and Angular5 with TypeScript.

EDIT I haven't installed the crypto package from npm, I am referencing the node inbuilt package.

No matter what I do, the "crypto" package resolves as an empty object.
I have installed the node @typings package and can see the definition for @typings definition crypto in the node_modules/@typings folder.

What I've tried:

import * as cryp from 'crypto'

declare var crypto:any

declare module crypto

var cryp = require('crypto')

I tried deleting the modules folder and reinstalling.

I tried updating everything to the most recent version.

I tried creating a new project and only using crypto with no additional dependencies. No luck.

The biggest issue here is we are trying to use libraries which depend on this 'crypto' module and they do not function without it.

What's most confusing about this is it doesn't throw any errors, and it's not coming as undefined, but an empty object. It doesn't work in the project or outside of it. And other Node JS/TS modules are working fine, it's literally (so far) just 'crypto' which is having this issue. Any guidance or thoughts here would be great.

Primarily using ng serve to run the application but tried packaging and running using node directly as well.

Per @kendor 's suggestion, I ran a tsc --traceResolution. This is the part regarding crypto. Interestingly it says "node_modules" does not exist, but it clearly does, and other packages are resolving from it correctly.

```<code>======== Resolving module 'crypto' from '[...]/src/app/app.component.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module 'crypto' from 'node_modules' folder, target file type 'TypeScript'.
Directory '[...]/src/app/node_modules' does not exist, skipping all lookups in it.
Directory '[...]/src/node_modules' does not exist, skipping all lookups in it.
File '[...]/node_modules/crypto.ts' does not exist.
File '[...]/node_modules/crypto.tsx' does not exist.
File '[...]/node_modules/crypto.d.ts' does not exist.
File '[...]/node_modules/@types/crypto.d.ts' does not exist.
Directory '[...]/node_modules' does not exist, skipping all lookups in it.
Directory '[...]node_modules' does not exist, skipping all lookups in it.
Directory '/home/node_modules' does not exist, skipping all lookups in it.
Directory '/node_modules' does not exist, skipping all lookups in it.
Loading module 'crypto' from 'node_modules' folder, target file type 'JavaScript'.
Directory '[...]/src/app/node_modules' does not exist, skipping all lookups in it.
Directory '[...]/src/node_modules' does not exist, skipping all lookups in it.
File '[...]/node_modules/crypto.js' does not exist.
File '[...]/node_modules/crypto.jsx' does not exist.
Directory '[...]/node_modules' does not exist, skipping all lookups in it.
Directory '[...]node_modules' does not exist, skipping all lookups in it.
Directory '/home/node_modules' does not exist, skipping all lookups in it.
Directory '/node_modules' does not exist, skipping all lookups in it.
======== Module name 'crypto' was not resolved. ========
</code>```

答:
In order to answer your question I was trying to find the libraries code. While searching for it I noticed that this library has been deprecated and hence you don't have any luck either most likely. See here: https://www.npmjs.com/package/crypto

If you want to make sure that this is the case just check the node_modules/crypto folder and it's code inside of it. If it's available please share it with us :-).

Edit: As @Jaromanda X pointed out in the comments (and written on the npm page) it has been deprecated as npm package and added to nodejs itself (https://nodejs.org/docs/latest-v7.x/api/crypto.html#crypto_crypto). However they still block it's name to avoid malicious use.

Edit 2: This answer assumed he installed the crypto npm package (on the workspace or globally) which could interfere with the builtin crypto package.

Body:
I'm using NPM for dependency management and Angular5 with TypeScript.

EDIT I haven't installed the crypto package from npm, I am referencing the node inbuilt package.

No matter what I do, the "crypto" package resolves as an empty object.
I have installed the node @typings package and can see the definition for @typings definition crypto in the node_modules/@typings folder.

What I've tried:

import * as cryp from 'crypto'

declare var crypto:any

declare module crypto

var cryp = require('crypto')

I tried deleting the modules folder and reinstalling.

I tried updating everything to the most recent version.

I tried creating a new project and only using crypto with no additional dependencies. No luck.

The biggest issue here is we are trying to use libraries which depend on this 'crypto' module and they do not function without it.

What's most confusing about this is it doesn't throw any errors, and it's not coming as undefined, but an empty object. It doesn't work in the project or outside of it. And other Node JS/TS modules are working fine, it's literally (so far) just 'crypto' which is having this issue. Any guidance or thoughts here would be great.

Primarily using ng serve to run the application but tried packaging and running using node directly as well.

Per @kendor 's suggestion, I ran a tsc --traceResolution. This is the part regarding crypto. Interestingly it says "node_modules" does not exist, but it clearly does, and other packages are resolving from it correctly.

======== Resolving module 'crypto' from '[...]/src/app/app.component.ts'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module 'crypto' from 'node_modules' folder, target file type 'TypeScript'.
Directory '[...]/src/app/node_modules' does not exist, skipping all lookups in it.
Directory '[...]/src/node_modules' does not exist, skipping all lookups in it.
File '[...]/node_modules/crypto.ts' does not exist.
File '[...]/node_modules/crypto.tsx' does not exist.
File '[...]/node_modules/crypto.d.ts' does not exist.
File '[...]/node_modules/@types/crypto.d.ts' does not exist.
Directory '[...]/node_modules' does not exist, skipping all lookups in it.
Directory '[...]node_modules' does not exist, skipping all lookups in it.
Directory '/home/node_modules' does not exist, skipping all lookups in it.
Directory '/node_modules' does not exist, skipping all lookups in it.
Loading module 'crypto' from 'node_modules' folder, target file type 'JavaScript'.
Directory '[...]/src/app/node_modules' does not exist, skipping all lookups in it.
Directory '[...]/src/node_modules' does not exist, skipping all lookups in it.
File '[...]/node_modules/crypto.js' does not exist.
File '[...]/node_modules/crypto.jsx' does not exist.
Directory '[...]/node_modules' does not exist, skipping all lookups in it.
Directory '[...]node_modules' does not exist, skipping all lookups in it.
Directory '/home/node_modules' does not exist, skipping all lookups in it.
Directory '/node_modules' does not exist, skipping all lookups in it.
======== Module name 'crypto' was not resolved. ========


问:
facebook JSOn API question
I am using JSON GRAPH API for facebook to retrieve all the post from a particular group. I can access all the post without authentication. However the problem I have is, if a particular post has more comments (like 10) then JSON outputs shows only  3 comments(not all 10). However the "Key" "Count" in JSON output gives the value as 10(meaning 10 comments for the post) but displays only 3. How to resolve this problem.

ANy help is greatly appreciated...!!!

答:
In that json data set there is a a key named 'paging' that gives you the next and previous sets ('next' and 'previous' respectively). You can use those urls to traverse all comments.

See the section named 'Paging' in the docs here: http://developers.facebook.com/docs/api?ref=mf  for more stuff (like limits and time queries)

ContentLicense: CC BY-SA 2.5

Title: facebook JSOn API question


问:
outer function error using function including data-frame referencing
I've trying to get 3D surface using outer function. And a function that I defined refer column in data.frame. Below is brief code which reproducible.

test.txt is

```<code>   a    b   c
   1    0   0
   2    0   0
   3    0   0
   6    0   0
   4    0   0
</code>```

and code is

```<code>test<- read.table(file="test.txt",header=TRUE)

testf<-function(q,w){
test$b<-q
test$c<-w
sum(test$b)+sum(test$c)
}

x<-seq(1,10,by = 1)
y<-seq(0,30,by = 1)

z<-outer(x,y,testf)
</code>```

result shown as error is

```<code>Error in `$<-.data.frame`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7,  :
replacement has 310 rows, data has 5

5.stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N, nrows), domain = NA)

4.`$<-.data.frame`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,  ...

3.`$<-`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,  ...

2. FUN(X, Y, ...)

1. outer(x, y, testf)
</code>```

function itself seems no problem since testf(1,1) works

```<code>> testf(1,1)
[1] 10
</code>```

any advice will be appreciated!

答: I think for loop is only way to generate z axis  value

Body:
I've trying to get 3D surface using outer function. And a function that I defined refer column in data.frame. Below is brief code which reproducible.

test.txt is

   a    b   c
   1    0   0
   2    0   0
   3    0   0
   6    0   0
   4    0   0

and code is

test<- read.table(file="test.txt",header=TRUE)

testf<-function(q,w){
test$b<-q
test$c<-w
sum(test$b)+sum(test$c)
}

x<-seq(1,10,by = 1)
y<-seq(0,30,by = 1)

z<-outer(x,y,testf)

result shown as error is

Error in `$<-.data.frame`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7,  :
replacement has 310 rows, data has 5

5.stop(sprintf(ngettext(N, "replacement has %d row, data has %d",
"replacement has %d rows, data has %d"), N, nrows), domain = NA)

4.`$<-.data.frame`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7,  ...

3.`$<-`(`*tmp*`, "b", value = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,  ...

2. FUN(X, Y, ...)

1. outer(x, y, testf)

function itself seems no problem since testf(1,1) works

> testf(1,1)
[1] 10

any advice will be appreciated!


答:
The border you are seeing comes from the rule .navigationbar ul li a:hover{...} where you have border-bottom: .1em solid #000000;. It is not extending to 100% of width of the navigation bar, but is causing it becomes higher.
If you want the navigationbarstays of the same height you should assign the border also to the normal state of the a element then you can change its color to whatever you want.

This way:

```<code>.navigationbar ul li a {
  height: 100%;
  display: block;
  color: #FFFFFF;
  text-align: center;
  text-decoration: none;
  padding-left: 1em;
  padding-right: 1em;
  padding-top: 1em;
  padding-bottom: 1em;

  border-bottom: .1em solid #ffcc00; /* add this property with the same value of the `:hover` state */
}
</code>```

Title: Bottom border override normal on hover

Body:
The border you are seeing comes from the rule .navigationbar ul li a:hover{...} where you have border-bottom: .1em solid #000000;. It is not extending to 100% of width of the navigation bar, but is causing it becomes higher.
If you want the navigationbarstays of the same height you should assign the border also to the normal state of the a element then you can change its color to whatever you want.

This way:

.navigationbar ul li a {
  height: 100%;
  display: block;
  color: #FFFFFF;
  text-align: center;
  text-decoration: none;
  padding-left: 1em;
  padding-right: 1em;
  padding-top: 1em;
  padding-bottom: 1em;

  border-bottom: .1em solid #ffcc00; /* add this property with the same value of the `:hover` state */
}


答:
You can add border-bottom: 0.1em solid #000000; to .navigationbar ul li a to avoid that movement/height increase:

https://jsfiddle.net/p7L7adhe/1/

Title: Bottom border override normal on hover


问:
Cannot read property '1' of null on my WordPress plugin
I am running a new plugin on a client's WooCommerce/WordPress webshop, but it isn't working as supposed. The browser console is giving me this error:

```<code>Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:1)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)
</code>```

I have 'pretty printed' that error, which will give me the proper lines:

```<code>Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:formatted:206)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)
</code>```

This is what line 206 looks like:

I've never really understood these 'Cannot read property '1' of null' errors, especially this one. Does anybody know what is going wrong here?

This is a link to the specific page: http://wqd.nl/3IFd

The error pops up when selecting something in the select list below 'Kleurkeuze'.

答:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

Match returns null if there are no matches.  So it is throwing an error because you are trying to do an index off of null.  You should check that the element is an array, and has atleast 2 elements, before you try to access it with [1].

Body:
I am running a new plugin on a client's WooCommerce/WordPress webshop, but it isn't working as supposed. The browser console is giving me this error:

Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:1)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)

I have 'pretty printed' that error, which will give me the proper lines:

Uncaught TypeError: Cannot read property '1' of null
    at Object.success (yith-wcp-frontend.min.js:formatted:206)
    at i (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at y (jquery.js:4)
    at XMLHttpRequest.c (jquery.js:4)

This is what line 206 looks like:

I've never really understood these 'Cannot read property '1' of null' errors, especially this one. Does anybody know what is going wrong here?

This is a link to the specific page: http://wqd.nl/3IFd

The error pops up when selecting something in the select list below 'Kleurkeuze'.


问:
How to suppress the "Current Location" callout in map view
Tapping the pulsating blue circle representing the userLocation brings up a "Current Location" callout. Is there a way to suppress that?</p>

答:
I have two ways to help you:

suppress in the mapViewDidFinishLoadingMap

```<code>func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
mapView.showsUserLocation = true
//suppress the title
mapView.userLocation.title = "My Location"
//suppress other params
</code>```

}

suppress in the didUpdate

```<code>func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    //suppress the title
    mapView.userLocation.title = "My Location"
    //suppress other params
}
</code>```

Body:
I have two ways to help you:

suppress in the mapViewDidFinishLoadingMap

func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
mapView.showsUserLocation = true
//suppress the title
mapView.userLocation.title = "My Location"
//suppress other params

}

suppress in the didUpdate

func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
    //suppress the title
    mapView.userLocation.title = "My Location"
    //suppress other params
}


问:
different between neo4j enterprise and neo4j community for windows?
I've just started to learn the Neo4j graphs db. I have a question:

What is the difference between neo4j enterprise and neo4j community for windows?

答:
Neo4j Enterprise just has more 'enterprise features' such as clustering and  additional security for example.   The comparison link the other poster provided is good to see the differences between enterprise and community server but it does not mention that Neo4j Enterprise is also free under it's open source license!  I would just focus on Neo4j server, not the new 'platform' they are now pushing.

If you don't want to play with their Neo4j Desktop under a trial agreement, you can go straight to Neo4j Enterprise server and run it. It starts the same way as the community edition and is open source under the [AGPLv3 license] https://www.gnu.org/licenses/agpl-3.0.en.html.

You can download Neo4j Enterprise versions before 3.3.0 from the  neo4j distribution site below. (3.2.8 is the last version that includes the AGPL license on their distribution site.)

http://dist.neo4j.org/neo4j-enterprise-3.2.8-windows.zip

OR

If you want to use the newest free Neo4j Enterprise edition (currently 3.3.1 as of today) then you can download the free open source binaries we package from source for our government clients at https://igovsol.com/downloads.html

Once you download the zip file to the following to get started. (Assuming you have JAVA setup on your windows machine.)

https://neo4j.com/docs/operations-manual/current/installation/windows/

1) Right-click the downloaded file, click Extract All.
Change directory to top-level extracted directory.

2) Run bin\neo4j console

3) Stop the server by typing Ctrl-C in the console.

The enterprise package is 100% free under it's open source AGPL license.

Unzip the package you download and you can verify it by looking at the LICENSE.txt

If you are curious about learning why you can't get the free AGPL binaries after 3.3.0 - checkout a blog post I wrote at https://blog.igovsol.com/2017/11/14/Neo4j-330-is-out-but-where-are-the-open-source-enterprise-binaries.html


问:
How to Grant User to access all the views in SQL Server but not table and stored procedures?
I am trying to create a new temp user who will have only access to all views to read only.

User should not have to read access to table and stored procedures.

I tried below query but it is giving access to table as well.

```<code>EXEC sp_addrolemember db_datareader, 'user1'

GRANT VIEW DATABASE STATE TO  'user1'
GRANT VIEW DEFINITION TO 'user1'
</code>```

答:
The primary way to do this is to grant permissions to only the view objects. You can loop through all of the views in the db with the following:

```<code>DECLARE @sql VARCHAR(MAX)

SELECT GrantStatement = 'GRANT SELECT ON ' + TABLE_NAME + ' TO user1'
INTO #grants
FROM
INFORMATION_SCHEMA.Views

WHILE EXISTS (SELECT 1 FROM #grants)
BEGIN
    SELECT TOP 1 @sql = GrantStatement
    FROM #grants

    EXEC (@sql)

    DELETE #grants
    WHERE GrantStatement = @sql
END
</code>```

A second technique would be to create a separate schema used only for views, then grant permission to the entire schema. That could be done like this:

```<code>GRANT SELECT ON SCHEMA::ViewSchema TO user1
</code>```

Body:
I am trying to create a new temp user who will have only access to all views to read only.

User should not have to read access to table and stored procedures.

I tried below query but it is giving access to table as well.

EXEC sp_addrolemember db_datareader, 'user1'

GRANT VIEW DATABASE STATE TO  'user1'
GRANT VIEW DEFINITION TO 'user1'

Body:
The primary way to do this is to grant permissions to only the view objects. You can loop through all of the views in the db with the following:

DECLARE @sql VARCHAR(MAX)

SELECT GrantStatement = 'GRANT SELECT ON ' + TABLE_NAME + ' TO user1'
INTO #grants
FROM
INFORMATION_SCHEMA.Views

WHILE EXISTS (SELECT 1 FROM #grants)
BEGIN
    SELECT TOP 1 @sql = GrantStatement
    FROM #grants

    EXEC (@sql)

    DELETE #grants
    WHERE GrantStatement = @sql
END

A second technique would be to create a separate schema used only for views, then grant permission to the entire schema. That could be done like this:

GRANT SELECT ON SCHEMA::ViewSchema TO user1


答:
You've used n_polygons in your code already. My understanding is that you want to swap the key-value pairs in the dict. Try this instead

```<code>n_polygons  = dict((v,k) for k,v in polygon_sides.iteritems())
</code>```

Title: Polygons and keys

Body:
You've used n_polygons in your code already. My understanding is that you want to swap the key-value pairs in the dict. Try this instead

n_polygons  = dict((v,k) for k,v in polygon_sides.iteritems())


问:
subset data.frame using POSIXct vector R
I'm trying to  extract a range of POSIXct dates from a data frame

with a sample data frame (data)...

```<code>library(lubridate)
start <- as.POSIXct('2016-10-08 20:00:00')
time <- seq(start, start + days(1), by = "30 min")
variable <- sample(seq(from = 20, to = 50), size = 49, replace = TRUE)
data <- data.frame(time, variable)
</code>```

I'm trying to create an indexed vector of date, using both a single date as well as a range.  I was going to initially subset the data frame, then extract the date column using the $ operator (although I'm sure there is a more elegant way to do it).

```<code>data_trim <- data[c('2016-10-08 20:00:00', '2016-10-08 22:0:00' %--% '2016-
10-09 13:00:00'),]
</code>```

but the output is

```<code>     time variable
NA   <NA>       NA
NA.1 <NA>       NA
</code>```

does anyone have any suggestions?

Thank you

Body:
I'm trying to  extract a range of POSIXct dates from a data frame

with a sample data frame (data)...

library(lubridate)
start <- as.POSIXct('2016-10-08 20:00:00')
time <- seq(start, start + days(1), by = "30 min")
variable <- sample(seq(from = 20, to = 50), size = 49, replace = TRUE)
data <- data.frame(time, variable)

I'm trying to create an indexed vector of date, using both a single date as well as a range.  I was going to initially subset the data frame, then extract the date column using the $ operator (although I'm sure there is a more elegant way to do it).

data_trim <- data[c('2016-10-08 20:00:00', '2016-10-08 22:0:00' %--% '2016-
10-09 13:00:00'),]

but the output is

     time variable
NA   <NA>       NA
NA.1 <NA>       NA

does anyone have any suggestions?

Thank you

Body:
Is this what you are trying to achieve? You can replace days(1) with 60 * 60 * 24 (seconds * minutes * hours) if you don't need lubridate elsewhere.

EDIT: change to just extract the time vector.

start <- as.POSIXct('2016-10-08 20:00:00')
time <- seq(start, start + 60 * 60 * 24, by = "30 min")
variable <- sample(seq(from = 20, to = 50), size = 49, replace = TRUE)
data <- data.frame(time, variable)

# If you wanted to keep the data.frame
# data_trim <- data[data$time == '2016-10-08 20:00:00' |
#                     (data$time >= '2016-10-08 22:0:00' &
#                        data$time <= '2016-10-09 13:00:00'), ]
# data_trim

# Otherwise just extract the time column into a vector
data$time[data$time == '2016-10-08 20:00:00' |
            (data$time >= '2016-10-08 22:0:00' &
               data$time <= '2016-10-09 13:00:00')]
#>  [1] "2016-10-08 20:00:00 NZDT" "2016-10-08 22:00:00 NZDT"
#>  [3] "2016-10-08 22:30:00 NZDT" "2016-10-08 23:00:00 NZDT"
#>  [5] "2016-10-08 23:30:00 NZDT" "2016-10-09 00:00:00 NZDT"
#>  [7] "2016-10-09 00:30:00 NZDT" "2016-10-09 01:00:00 NZDT"
#>  [9] "2016-10-09 01:30:00 NZDT" "2016-10-09 02:00:00 NZDT"
#> [11] "2016-10-09 02:30:00 NZDT" "2016-10-09 03:00:00 NZDT"
#> [13] "2016-10-09 03:30:00 NZDT" "2016-10-09 04:00:00 NZDT"
#> [15] "2016-10-09 04:30:00 NZDT" "2016-10-09 05:00:00 NZDT"
#> [17] "2016-10-09 05:30:00 NZDT" "2016-10-09 06:00:00 NZDT"
#> [19] "2016-10-09 06:30:00 NZDT" "2016-10-09 07:00:00 NZDT"
#> [21] "2016-10-09 07:30:00 NZDT" "2016-10-09 08:00:00 NZDT"
#> [23] "2016-10-09 08:30:00 NZDT" "2016-10-09 09:00:00 NZDT"
#> [25] "2016-10-09 09:30:00 NZDT" "2016-10-09 10:00:00 NZDT"
#> [27] "2016-10-09 10:30:00 NZDT" "2016-10-09 11:00:00 NZDT"
#> [29] "2016-10-09 11:30:00 NZDT" "2016-10-09 12:00:00 NZDT"
#> [31] "2016-10-09 12:30:00 NZDT" "2016-10-09 13:00:00 NZDT"


问:
What is a good way to find gaps in a set of datespans?
What is a way to find gaps in a set of date spans?

For example, I have these date spans:

```<code>1/ 1/11 - 1/10/11
1/13/11 - 1/15/11
1/20/11 - 1/30/11
</code>```

Then I have a start and end date of 1/7/11 and 1/14/11.

I want to be able to tell that between 1/10/11 and 1/13/11 there is a gap so the start and end date is not possible.  Or I want to return only the datespans up to the first gap encountered.

If this can be done in SQL server that would be good.

I was thinking to go through each date to find out if it lands in a datespan... if it does not then there's a gap on that day.

答:
Jump to 2nd last code block for: *I want to be able to tell that
between 1/10/11 and 1/13/11 there is
a gap so the start and end date is*
not possible.

Jump to last code block for: *I want to return only
the datespans up to the first gap
encountered.*

First of all, here's a virtual table to discuss

```<code>create table spans (date1 datetime, date2 datetime);
insert into spans select '20110101', '20110110';
insert into spans select '20110113', '20110115';
insert into spans select '20110120', '20110130';
</code>```

This is a query that will list, individually, all the dates in the calendar

```<code>declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select distinct a.date1+v.number
from spans A
inner join master..spt_values v
  on v.type='P' and v.number between 0 and datediff(d, a.date1, a.date2)
-- we don't care about spans that don't intersect with our range
where A.date1 <= @enddate
  and @startdate <= A.date2
</code>```

Armed with this query, we can now test to see if there are any gaps, by
counting the days in the calendar against the expected number of days

```<code>declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'

select case when count(distinct a.date1+v.number)
    = datediff(d,@startdate, @enddate) + 1
    then 'No gaps' else 'Gap' end
from spans A
inner join master..spt_values v
  on v.type='P' and v.number between 0 and datediff(d, a.date1, a.date2)
-- we don't care about spans that don't intersect with our range
where A.date1 <= @enddate
  and @startdate <= A.date2
-- count only those dates within our range
   and a.date1 + v.number between @startdate and @enddate
</code>```

Another way to do this is to just build the calendar from @start
to @end up front and look to see if there is a span with this date

```<code>declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
-- startdate+v.number is a day on the calendar
select @startdate + v.number
from master..spt_values v
where v.type='P' and v.number between 0
  and datediff(d, @startdate, @enddate)

-- run the part above this line alone to see the calendar
-- the condition checks for dates that are not in any span (gap)
  and not exists (
    select *
    from spans
    where @startdate + v.number between date1 and date2)
</code>```

The query returns ALL dates that are gaps in the date range @start - @end
A TOP 1 can be added to just see if there are gaps

To return all records that are before the gap, use the query as a
derived table in a larger query

```<code>declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select *
from spans
where date1 <= @enddate and @startdate <= date2 -- overlaps
  and date2 < ( -- before the gap
    select top 1 @startdate + v.number
    from master..spt_values v
    where v.type='P' and v.number between 0
      and datediff(d, @startdate, @enddate)
      and not exists (
        select *
        from spans
        where @startdate + v.number between date1 and date2)
    order by 1 ASC
)
</code>```

Body:
What is a way to find gaps in a set of date spans?

For example, I have these date spans:

1/ 1/11 - 1/10/11
1/13/11 - 1/15/11
1/20/11 - 1/30/11

Then I have a start and end date of 1/7/11 and 1/14/11.

I want to be able to tell that between 1/10/11 and 1/13/11 there is a gap so the start and end date is not possible.  Or I want to return only the datespans up to the first gap encountered.

If this can be done in SQL server that would be good.

I was thinking to go through each date to find out if it lands in a datespan... if it does not then there's a gap on that day.

Body:
Jump to 2nd last code block for: *I want to be able to tell that
between 1/10/11 and 1/13/11 there is
a gap so the start and end date is*
not possible.

Jump to last code block for: *I want to return only
the datespans up to the first gap
encountered.*

First of all, here's a virtual table to discuss

create table spans (date1 datetime, date2 datetime);
insert into spans select '20110101', '20110110';
insert into spans select '20110113', '20110115';
insert into spans select '20110120', '20110130';

This is a query that will list, individually, all the dates in the calendar

declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select distinct a.date1+v.number
from spans A
inner join master..spt_values v
  on v.type='P' and v.number between 0 and datediff(d, a.date1, a.date2)
-- we don't care about spans that don't intersect with our range
where A.date1 <= @enddate
  and @startdate <= A.date2

Armed with this query, we can now test to see if there are any gaps, by
counting the days in the calendar against the expected number of days

declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'

select case when count(distinct a.date1+v.number)
    = datediff(d,@startdate, @enddate) + 1
    then 'No gaps' else 'Gap' end
from spans A
inner join master..spt_values v
  on v.type='P' and v.number between 0 and datediff(d, a.date1, a.date2)
-- we don't care about spans that don't intersect with our range
where A.date1 <= @enddate
  and @startdate <= A.date2
-- count only those dates within our range
   and a.date1 + v.number between @startdate and @enddate

Another way to do this is to just build the calendar from @start
to @end up front and look to see if there is a span with this date

declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
-- startdate+v.number is a day on the calendar
select @startdate + v.number
from master..spt_values v
where v.type='P' and v.number between 0
  and datediff(d, @startdate, @enddate)

-- run the part above this line alone to see the calendar
-- the condition checks for dates that are not in any span (gap)
  and not exists (
    select *
    from spans
    where @startdate + v.number between date1 and date2)

The query returns ALL dates that are gaps in the date range @start - @end
A TOP 1 can be added to just see if there are gaps

To return all records that are before the gap, use the query as a
derived table in a larger query

declare @startdate datetime, @enddate datetime
select @startdate = '20110107', @enddate = '20110114'
select *
from spans
where date1 <= @enddate and @startdate <= date2 -- overlaps
  and date2 < ( -- before the gap
    select top 1 @startdate + v.number
    from master..spt_values v
    where v.type='P' and v.number between 0
      and datediff(d, @startdate, @enddate)
      and not exists (
        select *
        from spans
        where @startdate + v.number between date1 and date2)
    order by 1 ASC
)


问:
I want to test presence of objects in Decision Table
Drools 5 - I want to test for presence of BLueReport object AND SSCData object, and if both are present, then assign some default values.  I've tried a number of conditions, but no luck.

```<code>6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9|                     |                     | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------
</code>```

... and I also tried this:

```<code>     6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9| eval(true)          | eval(true)          | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------
</code>```

I have a test agent that compiles the Excel DT to a DRL file and it reports this as a result:

```<code>//generated from Decision Table
import mypackage.cost.model.*;
// rule values at A11, header at A6
rule "DIV 07"
    salience 65525
    when
    then
        sscData.setORIG_LOC_CD("SLR");
        sscData.setSERVICE_CD("SLIC");
        sscData.appendRuleAudit(drools.getRule().getName());
end
</code>```

I have arrived at this, but don't know what to put in Row 9:

答:
You'll need some specific SSCData bound to a variable otherwise you cannot reference a fact for changing its fields. This modifies allSSCDat` in Working Memory:

```<code>rule x
when
  exists BlueReport()
  sscData: SSCDate()
then
    sscData.setORIG_LOC_CD("SLR");
    sscData.setSERVICE_CD("SLIC");
    sscData.appendRuleAudit(drools.getRule().getName());
end
</code>```

You cannot bind to the pattern after exists as this succeeds once for an arbitrary positive number of matching facts.

Body:
Drools 5 - I want to test for presence of BLueReport object AND SSCData object, and if both are present, then assign some default values.  I've tried a number of conditions, but no luck.

6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9|                     |                     | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------

... and I also tried this:

     6-------------------------------------------------------------------------------
 7| CONDITION           | CONDITION           | ACTION                          |
 8| exists BlueReport   | exists SSCData      | sscData.setORIG_LOC_CD($param); |
 9| eval(true)          | eval(true)          | Set Location Code               |
10|                     |                     | "SLR"                           |
11-------------------------------------------------------------------------------

I have a test agent that compiles the Excel DT to a DRL file and it reports this as a result:

//generated from Decision Table
import mypackage.cost.model.*;
// rule values at A11, header at A6
rule "DIV 07"
    salience 65525
    when
    then
        sscData.setORIG_LOC_CD("SLR");
        sscData.setSERVICE_CD("SLIC");
        sscData.appendRuleAudit(drools.getRule().getName());
end

I have arrived at this, but don't know what to put in Row 9:

Body:
You'll need some specific SSCData bound to a variable otherwise you cannot reference a fact for changing its fields. This modifies allSSCDat` in Working Memory:

rule x
when
  exists BlueReport()
  sscData: SSCDate()
then
    sscData.setORIG_LOC_CD("SLR");
    sscData.setSERVICE_CD("SLIC");
    sscData.appendRuleAudit(drools.getRule().getName());
end

You cannot bind to the pattern after exists as this succeeds once for an arbitrary positive number of matching facts.


答:
You can use the DENY function to prevent the user from having access to the table and the stored procedure. For example:

```<code>DENY SELECT on tablename to user1;
</code>```

As you have added user1 to the db_datareader database role, they will be able to perform SELECT statements on objects within the database unless you DENY them access to the objects.

Title: How to Grant User to access all the views in SQL Server but not table and stored procedures?

Body:
You can use the DENY function to prevent the user from having access to the table and the stored procedure. For example:

DENY SELECT on tablename to user1;

As you have added user1 to the db_datareader database role, they will be able to perform SELECT statements on objects within the database unless you DENY them access to the objects.


问:
How to apply Polynomial Transformation to subset of features in scikitlearn
Scikitlearn's PolynomialFeatures facilitates polynomial feature generation.

Here is a simple example:

```<code>import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures

# Example data:
X = np.arange(6).reshape(3, 2)

# Works fine
poly = PolynomialFeatures(2)
pd.DataFrame(poly.fit_transform(X))

   0  1  2   3   4   5
0  1  0  1   0   0   1
1  1  2  3   4   6   9
2  1  4  5  16  20  25
</code>```

Question: Is there any capability to only have the polynomial transformation apply to a specified list of features?

e.g.

```<code># Use previous dataframe
X2 = X.copy()

# Categorical feature will be handled
# by a one hot encoder in another feature generation step
X2['animal'] = ['dog', 'dog', 'cat']

# Don't try to poly transform the animal column
poly2 = PolynomialFeatures(2, cols=[1,2]) # <-- ("cols" not an actual param)

# desired outcome:
pd.DataFrame(poly2.fit_transform(X))
   0  1  2   3   4   5   'animal'
0  1  0  1   0   0   1   'dog'
1  1  2  3   4   6   9   'dog'
2  1  4  5  16  20  25   'cat'
</code>```

This would be particularly useful when using the Pipeline feature to combine a long series of feature generation and model training code.

One option would be to roll-your-own transformer (great example by Michelle Fullwood), but I figured someone else would have stumbled across this use case before.

答:
Yes there is, check out sklearn-pandas

This should work (there should be a more elegant solution, but can't test it now):

```<code>from sklearn.preprocessing import PolynomialFeatures
from sklearn_pandas import DataFrameMapper

X2.columns = ['col0', 'col1', 'col2', 'col3', 'col4', 'col5', 'animal']

mapper = DataFrameMapper([
('col0', PolynomialFeatures(2)),
('col1', PolynomialFeatures(2)),
('col2', PolynomialFeatures(2)),
('col3', PolynomialFeatures(2)),
('col4', PolynomialFeatures(2)),
('col5', PolynomialFeatures(2)),
('Animal', None)])

X3 = mapper.fit_transform(X2)
</code>```

Body:
Scikitlearn's PolynomialFeatures facilitates polynomial feature generation.

Here is a simple example:

import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures

# Example data:
X = np.arange(6).reshape(3, 2)

# Works fine
poly = PolynomialFeatures(2)
pd.DataFrame(poly.fit_transform(X))

   0  1  2   3   4   5
0  1  0  1   0   0   1
1  1  2  3   4   6   9
2  1  4  5  16  20  25

Question: Is there any capability to only have the polynomial transformation apply to a specified list of features?

e.g.

# Use previous dataframe
X2 = X.copy()

# Categorical feature will be handled
# by a one hot encoder in another feature generation step
X2['animal'] = ['dog', 'dog', 'cat']

# Don't try to poly transform the animal column
poly2 = PolynomialFeatures(2, cols=[1,2]) # <-- ("cols" not an actual param)

# desired outcome:
pd.DataFrame(poly2.fit_transform(X))
   0  1  2   3   4   5   'animal'
0  1  0  1   0   0   1   'dog'
1  1  2  3   4   6   9   'dog'
2  1  4  5  16  20  25   'cat'

This would be particularly useful when using the Pipeline feature to combine a long series of feature generation and model training code.

One option would be to roll-your-own transformer (great example by Michelle Fullwood), but I figured someone else would have stumbled across this use case before.

Body:
Yes there is, check out sklearn-pandas

This should work (there should be a more elegant solution, but can't test it now):

from sklearn.preprocessing import PolynomialFeatures
from sklearn_pandas import DataFrameMapper

X2.columns = ['col0', 'col1', 'col2', 'col3', 'col4', 'col5', 'animal']

mapper = DataFrameMapper([
('col0', PolynomialFeatures(2)),
('col1', PolynomialFeatures(2)),
('col2', PolynomialFeatures(2)),
('col3', PolynomialFeatures(2)),
('col4', PolynomialFeatures(2)),
('col5', PolynomialFeatures(2)),
('Animal', None)])

X3 = mapper.fit_transform(X2)


问:
How do you split a list by space in python?
How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

```<code>def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()
</code>```

the file looks like this

50 60 15 100 60 15 40 /n
100 145 20 150 145 20 45 /n
50 245 25 120 245 25 50 /n
100 360 30 180 360 30 55 /n

答:
Split takes as argument the character you want to split your string with.

I invite you to read the documentation of methods you are using. :)

EDIT : By the way, readline returns a string, not a **list **.
However, split does return a list.

Body:
How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()

the file looks like this

50 60 15 100 60 15 40 /n
100 145 20 150 145 20 45 /n
50 245 25 120 245 25 50 /n
100 360 30 180 360 30 55 /n


问:
Ionic 3 : how to parse data from pushed array
Ok so I followed a tutorial onto how to receive JSON replies and put them into an [] on Ionic and I managed to do that successfully. I stored the response into a this.infoList (declared in class 'infoList = []') and when console logging it it looked as it had all the data as follows(Sorry hid the data but is for illustration):

https://i.stack.imgur.com/o5JsA.png

the code I used to push it was:
this.navCtrl.push(ResultPage,this.infoList);

the code I used in result.ts's constructor to attempt to log one of the details for example id was:
console.log(navParams.get('id'));

yet it always comes out first on console and comes out as undefined, please point me in the right direction <3

答:
this.infoLlist appears to be an array.

Option 1 - Pass the first item in the array as a nav param:

```<code>this.navCtrl.push(ResultPage,this.infoList[0]);
// then you should be able to do this in the constructor
console.log(navParams.get('id'));
</code>```

Option 2 - Pass the entire array as a nav param by wrapping it in an object literal:

```<code>this.navCtrl.push(ResultPage,{infoList: this.infoList});
//then you should be able to do this in the constructor
console.log(navParams.get('infoList')[0].id);
</code>```

Body:
this.infoLlist appears to be an array.

Option 1 - Pass the first item in the array as a nav param:

this.navCtrl.push(ResultPage,this.infoList[0]);
// then you should be able to do this in the constructor
console.log(navParams.get('id'));

Option 2 - Pass the entire array as a nav param by wrapping it in an object literal:

this.navCtrl.push(ResultPage,{infoList: this.infoList});
//then you should be able to do this in the constructor
console.log(navParams.get('infoList')[0].id);


问:
Restore password for FORCE_CHANGE_PASSWORD status
I need to restore or reset user password when his status is FORCE_CHANGE_PASSWORD. This situation happened when user try to restore password using "forgot password" feature and he lost email with temporary password. Now he can't do anything because he don't remember password and he can't reset password again

This code handle forgot password

```<code>return CognitoIdentitySP.forgotPassword(params, (err, resp) => {
  if (err) { ... }
  ...
})
</code>```

And I receive error (in case of FORCE_CHANGE_PASSWORD status)

NotAuthorizedException: User password cannot be reset in the current state.

Is there any way to reset password in such state?

答: You can call admin create user again with the MessageAction set to RESEND in which case Cognito will resend the invitation message to a user that already exists and reset the expiration limit on the user's account. Set to "SUPPRESS" to suppress sending the message. Only one value can be specified. </p>

ContentLicense: CC BY-SA 4.0

Body:
I need to restore or reset user password when his status is FORCE_CHANGE_PASSWORD. This situation happened when user try to restore password using "forgot password" feature and he lost email with temporary password. Now he can't do anything because he don't remember password and he can't reset password again

This code handle forgot password

return CognitoIdentitySP.forgotPassword(params, (err, resp) => {
  if (err) { ... }
  ...
})

And I receive error (in case of FORCE_CHANGE_PASSWORD status)

NotAuthorizedException: User password cannot be reset in the current state.

Is there any way to reset password in such state?


问:
aws-sdk-php v3.44 fails to sendMessage to SQS FIFO Queue: MessageGroupId missing?
I am using the Amazon SDK for PHP version 3.44 (released 2017-11-30). I can connect to my Amazon SQS account and execute the listQueues(), getQueueUrl(), getQueueAttributes(), and receiveMessage() commands just fine. However, the sendMessage() command consistently fails with the following message:

The request must contain the parameter MessageGroupId.

I am most definitely including this parameter. It doesn't seem to matter which version of the aws-sdk-php API I use, this message keeps coming back. Here is my code:

```<code>$queue = SqsClient::factory([
    'profile'     => $profile,
    'region'      => $region,
    'version'     => '2012-11-05',
    'credentials' => $credentials,
]);
$queue_list = $queue->listQueues(); // ok
$url        = $queue->getQueueUrl(['QueueName'=>$queue_name]); // ok
$received   = $queue->receiveMessage(['QueueUrl'=>$url->get('QueueUrl')]); // ok
$response   = $queue->sendMessage([
    'MessageBody'    => $message,
    'MessageGroupId' => $message_group_id,
    'QueueUrl'       => $url->get('QueueUrl'),
]); // fails with message indicating MessageGroupId is missing
</code>```

I have spent several hours searching for a working example of sending a message up to an Amazon SQS FIFO queue through the PHP SDK, and am beginning to believe this is not possible. Has anybody out there been able to get the aws-sdk-php library to work with an SQS FIFO queue?

答: It looks like Amazon has quietly resolved whatever bug was blocking my API call. I did not change my queue settings or my code. The same API call that resulted in error messages last week now runs just fine.</p>

Body:
I am using the Amazon SDK for PHP version 3.44 (released 2017-11-30). I can connect to my Amazon SQS account and execute the listQueues(), getQueueUrl(), getQueueAttributes(), and receiveMessage() commands just fine. However, the sendMessage() command consistently fails with the following message:

The request must contain the parameter MessageGroupId.

I am most definitely including this parameter. It doesn't seem to matter which version of the aws-sdk-php API I use, this message keeps coming back. Here is my code:

$queue = SqsClient::factory([
    'profile'     => $profile,
    'region'      => $region,
    'version'     => '2012-11-05',
    'credentials' => $credentials,
]);
$queue_list = $queue->listQueues(); // ok
$url        = $queue->getQueueUrl(['QueueName'=>$queue_name]); // ok
$received   = $queue->receiveMessage(['QueueUrl'=>$url->get('QueueUrl')]); // ok
$response   = $queue->sendMessage([
    'MessageBody'    => $message,
    'MessageGroupId' => $message_group_id,
    'QueueUrl'       => $url->get('QueueUrl'),
]); // fails with message indicating MessageGroupId is missing

I have spent several hours searching for a working example of sending a message up to an Amazon SQS FIFO queue through the PHP SDK, and am beginning to believe this is not possible. Has anybody out there been able to get the aws-sdk-php library to work with an SQS FIFO queue?


问:
How to find out the name of the user logged on the machine?
Is possible find out the name of the user logged on the windows machine on a ChatBot? i am using "userName = context.Activity.From.Name", but it is not need it.

Thanks in advance.

答:
The bot itself is a server-side web service, so it doesn't have access to the users computer directly except via the various channel clients (Eg. Skype, MS Teams, Slack, etc).

If you need to get user information, you can have the bot users login using their Active Directory (AAD) personal or work account. Once the user is logged in, your bot will have access to user information like name and email.

Overview:

BotAuth it a set of libraries for .NET and Node that simplifies the process of perfoming OAuth and establishing an identity in a project build with the Bot Framework.

You can find an example of the sign-in workflow for bots in the BotAuth repository on GitHub here: https://github.com/richdizz/BotAuth


问:
What is wrong with my C functions? Greatest Common Divisor and Least Common Multiple
```<code>#include <stdio.h>
#include <stdlib.h>

// Function to find the greatest common divisor
int findGCD(int numberOne, int numberTwo) {

    int i, GCD;

    for (i = 1; i <= numberOne && i <= numberTwo; i++) {
        if (numberOne % i == 0 && numberTwo % i == 0);
    }

    GCD = i;

    return GCD;
}

// Function to find the least common multiple using the GCD function

int findLCM(int numberOne, int numberTwo) {

    int GCD, LCM;

    GCD = findGCD(numberOne, numberTwo);
    LCM = (numberOne * numberTwo) / GCD;

    return LCM;
}

// Main function to output the lcm
void main() {

    int numberOne, numberTwo, LCM;

    printf("Please enter two numbers: ");
    scanf_s("%i %i", &numberOne, &numberTwo);

    LCM = findLCM(numberOne, numberTwo);

    printf("The LCM of %i and %i is %i\n", numberOne, numberTwo, LCM);

    system("pause");
}
</code>```

答:
Your findGCD does not compute GCD perfectly. You misplaced GCD = i.

```<code>// Function to find the greatest common divisor
int findGCD(int numberOne, int numberTwo) {

    int i, GCD;

    for (i = 1; i <= numberOne && i <= numberTwo; i++) {
        if (numberOne % i == 0 && numberTwo % i == 0) {
            GCD = i;
        }
    }

    return GCD;
}
</code>```

Body:
Your findGCD does not compute GCD perfectly. You misplaced GCD = i.

// Function to find the greatest common divisor
int findGCD(int numberOne, int numberTwo) {

    int i, GCD;

    for (i = 1; i <= numberOne && i <= numberTwo; i++) {
        if (numberOne % i == 0 && numberTwo % i == 0) {
            GCD = i;
        }
    }

    return GCD;
}


问:
Hiding previously displayed array elements
So, I have an array of Strings that I have display to the screen one at a time through the text() function. But when I add to the index the previous array element stays on-screen and I can't figure out how to remove it. I just want to scroll through the text on screen and essentially have the next array element replace it on the screen.

```<code>Dialog[] main = new Dialog[12];
int index;

void setup() {
  for (int index = 0; index < main.length; index++) {
    main[index] = new Dialog();
}

void draw() {
  for (int index = 0; index < main.length; index++) {
    main[index].readDialog();
  }
}

if (mousePressed) {
  index++:
}

String[] textScroll = new String[12];

class Dialog {
Dialog () {
   textScroll[0] = "Welcome to the game!";
   textScroll[1] = "Are you ready to play?";
   etc...
}
void readDialog() {
   text(textScroll[index], width/2, 100);
  }
}
</code>```

答: Either use background(); with the color you want as the background color as argument. For example, background(0,0,100); is blue background. This will clear your screen at the beginning of each draw() loop. But if you don't want to clear everything from screen everytime your program loop through draw(), just use a rect() same color as your background and on top of your text so that it cover your privious text.

Body:
So, I have an array of Strings that I have display to the screen one at a time through the text() function. But when I add to the index the previous array element stays on-screen and I can't figure out how to remove it. I just want to scroll through the text on screen and essentially have the next array element replace it on the screen.

Dialog[] main = new Dialog[12];
int index;

void setup() {
  for (int index = 0; index < main.length; index++) {
    main[index] = new Dialog();
}

void draw() {
  for (int index = 0; index < main.length; index++) {
    main[index].readDialog();
  }
}

if (mousePressed) {
  index++:
}

String[] textScroll = new String[12];

class Dialog {
Dialog () {
   textScroll[0] = "Welcome to the game!";
   textScroll[1] = "Are you ready to play?";
   etc...
}
void readDialog() {
   text(textScroll[index], width/2, 100);
  }
}


问:
How to display body and headers before sending POST request?
I use a library requests:

```<code>import requests

r = requests.post(url=url, data=data, headers=headers, auth=(self.api_key, ''))
</code>```

How to display body and headers before sending POST request? or display full request how it is sent?

Because server returns 400 HTTP with message Bad Request. So I need to see what is sending.

When I do:

```<code>print r.request.body
</code>```

It returns:

```<code>subcategory_id=1378&category_id=45&features=id&features=value&features=id&features=value&features=id&features=value&offer_type=18979
</code>```

But body is:

```<code>data = {
            'category_id': category_id,
            'subcategory_id': subcategory_id,
            'offer_type': offer_type,
            'features': [
                {"id": "7", "value": "12900"},
                {"id": "12", "value": "Title adadadadasdasdadad"},
                {"id": "16", "value": ["3360383821"]}
          ]
        }
</code>```

How is it possible?

答: You can use portal httpbin.org for test. It sends back all your data.</p>

Body:
I use a library requests:

import requests

r = requests.post(url=url, data=data, headers=headers, auth=(self.api_key, ''))

How to display body and headers before sending POST request? or display full request how it is sent?

Because server returns 400 HTTP with message Bad Request. So I need to see what is sending.

When I do:

print r.request.body

It returns:

subcategory_id=1378&category_id=45&features=id&features=value&features=id&features=value&features=id&features=value&offer_type=18979

But body is:

data = {
            'category_id': category_id,
            'subcategory_id': subcategory_id,
            'offer_type': offer_type,
            'features': [
                {"id": "7", "value": "12900"},
                {"id": "12", "value": "Title adadadadasdasdadad"},
                {"id": "16", "value": ["3360383821"]}
          ]
        }

How is it possible?


问:
DocumentBuilder.newDocument() is returning null
Here is something I wouldn't have anticipated, and the documentation doesn't say whether this is even possible, but after calling DocumentBuilder's newDocument() method, it is returning null :

```<code>    // Initialize the DocumentBuilderFactory and DocumentBuilder factories.
    try {
        m_docFactory = DocumentBuilderFactory.newInstance();
        m_Log.error("m_docFactory is {}", m_docFactory);
        m_docBuilder = m_docFactory.newDocumentBuilder();
        m_Log.error("m_docBuilder is {}", m_docBuilder);
        m_doc = m_docBuilder.newDocument();
        m_Log.error("m_doc is {}", m_doc);
        m_xpath = XPathFactory.newInstance().newXPath();
        m_QCodeParameters = new QCodeParameters();
    }
    catch (DOMException e) {
        m_Log.error(e.toString());
    }
    catch (ParserConfigurationException e) {
        m_Log.error(e.toString());
    }
</code>```

The output I am getting is

```<code>m_docFactory is org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@f20d394c
m_docBuilder is org.apache.xerces.jaxp.DocumentBuilderImpl@a7ce296c
m_doc is [#document: null]
</code>```

Am I missing a jar?  Weird!

答: The object itself is not null, although the Document hasn't got any content. You should append children to it.

Body:
Here is something I wouldn't have anticipated, and the documentation doesn't say whether this is even possible, but after calling DocumentBuilder's newDocument() method, it is returning null :

    // Initialize the DocumentBuilderFactory and DocumentBuilder factories.
    try {
        m_docFactory = DocumentBuilderFactory.newInstance();
        m_Log.error("m_docFactory is {}", m_docFactory);
        m_docBuilder = m_docFactory.newDocumentBuilder();
        m_Log.error("m_docBuilder is {}", m_docBuilder);
        m_doc = m_docBuilder.newDocument();
        m_Log.error("m_doc is {}", m_doc);
        m_xpath = XPathFactory.newInstance().newXPath();
        m_QCodeParameters = new QCodeParameters();
    }
    catch (DOMException e) {
        m_Log.error(e.toString());
    }
    catch (ParserConfigurationException e) {
        m_Log.error(e.toString());
    }

The output I am getting is

m_docFactory is org.apache.xerces.jaxp.DocumentBuilderFactoryImpl@f20d394c
m_docBuilder is org.apache.xerces.jaxp.DocumentBuilderImpl@a7ce296c
m_doc is [#document: null]

Am I missing a jar?  Weird!


问:
Sparkjava unable to put data into the response body
I'm trying to a client (Android) talk to our server which is using sparkjava, but running into the issue that when the client is trying to parse the body of the response response.data with Volley, it's getting that the response body is empty. The client is sending a JsonRequestObject , which will throw a JSONException if the response's body is empty.

Here is our sparkJava controller:

```<code>  public static String doThis(Request request, Response response) {
        response.type("application/json");

        // If the request fails validations, then return a 400
        if (request.failsValidations()) {
            response.status(HTTP_BAD_REQUEST); // 400
            response.header("Error", "Bad request");
        } else {
            response.status(HTTP_SUCCESS); // 200
            // Put the response into the data
            String responseData = "{//someJson}"
            response.header("data", responseData);
            response.body(data);
        }
        return "";
    }
</code>```

I'm setting the same data in the header and body, but when I look at the response received on the client, the data is only in the header and not in the body. So I was thinking that Spark's response.body() method isn't really putting the data into the response being sent back.
Is the way response.body is represented in sparkjava different from how volley views it? Or is there another way to put data into the response body from spark?

答:
You can do it in two ways:

Using a JSON Object

```<code>public static Object doThis(Request request, Response response) {
    response.type("application/json");

    JSONObject jo = new JSONObject();
    jo.put("data", "someData");
    return jo;
}
</code>```

Using a string formatted as JSON

```<code>public static Object doThis(Request request, Response response) {
    response.type("application/json");

    return "{\"data\":\"someData\"}";
}
</code>```

The first one is better IMO because you can modify the JSON object in a much more convenient way (but you have to import org.json.JSONObject).

Then, on the client side, you should treat the data as JSON data type. Hope it helps.

Body:
I'm trying to a client (Android) talk to our server which is using sparkjava, but running into the issue that when the client is trying to parse the body of the response response.data with Volley, it's getting that the response body is empty. The client is sending a JsonRequestObject , which will throw a JSONException if the response's body is empty.

Here is our sparkJava controller:

  public static String doThis(Request request, Response response) {
        response.type("application/json");

        // If the request fails validations, then return a 400
        if (request.failsValidations()) {
            response.status(HTTP_BAD_REQUEST); // 400
            response.header("Error", "Bad request");
        } else {
            response.status(HTTP_SUCCESS); // 200
            // Put the response into the data
            String responseData = "{//someJson}"
            response.header("data", responseData);
            response.body(data);
        }
        return "";
    }

I'm setting the same data in the header and body, but when I look at the response received on the client, the data is only in the header and not in the body. So I was thinking that Spark's response.body() method isn't really putting the data into the response being sent back.
Is the way response.body is represented in sparkjava different from how volley views it? Or is there another way to put data into the response body from spark?

Body:
You can do it in two ways:

Using a JSON Object

public static Object doThis(Request request, Response response) {
    response.type("application/json");

    JSONObject jo = new JSONObject();
    jo.put("data", "someData");
    return jo;
}

Using a string formatted as JSON

public static Object doThis(Request request, Response response) {
    response.type("application/json");

    return "{\"data\":\"someData\"}";
}

The first one is better IMO because you can modify the JSON object in a much more convenient way (but you have to import org.json.JSONObject).

Then, on the client side, you should treat the data as JSON data type. Hope it helps.


问:
Publishing a post with a picture to the facebook page with restFb
When I publish a picture to my wall by

```<code>FacebookType publish = fc.publish("me/photos", FacebookType.class,
                      BinaryAttachment.with(attachmentName, temporaryStream),
                      Parameter.with("message", "my myssage"));
</code>```

the post is created as expected. I can see a message and the published pictute under the message .

but when I want to do the same but on some pages wall instead the user wall by.

```<code>FacebookType publish = fc.publish(pageId + "/photos", FacebookType.class,
                      BinaryAttachment.with(attachmentName, temporaryStream),
                      Parameter.with("message", "my myssage"));
</code>```

the post is published, but I can see only text. Not the picture. The picture can be seen only when I click on the date of the post. I can also reach this photo by clicking on the photos on the top of the page and then "name of the page" photos tab.

Is there any way how to see the photo as the part of the post also when I post it on a page?

答:
Your Answer worked a treat and helped me untold amounts however i found with my solution I didn't need

```<code>FacebookType post =  fc.publish(pageid + "/feed", FacebookType.class,
        Parameter.with("message", "your message"),Parameter.with("type", "photo"),
        Parameter.with("link", photoLink.getLink()));
</code>```

as i would recive an error (that i should have copied to show you) but photoLink.getLink() returned null in my case.

so my updated solution ended up being

```<code>        FacebookType photo = client.publish(groupId + "/photos",
            FacebookType.class,
            BinaryAttachment.with(imageName),
                    imageAsBytes,
                    "image/png"),
            Parameter.with("message",
                    message));
</code>```

Just my 2 cents, Thanks again for your help!

EDIT

Also while playing around I noticed that in the solution I arrived at I was creating a FacebookType photo object and this object doesn't get used anywhere, your just calling the publish method of the client that's created further up in your program.

my final class is below, (my application is taking an image from the computer and posing to a groups wall)

```<code>    public void createImagePostInGroup(String message, String groupId, String imageFilePath){

    byte[] imageAsBytes = fetchBytesFromImage(imageFilePath);

    DefaultFacebookClient client =
        new DefaultFacebookClient(accessToken, Version.LATEST);

    client.publish(groupId + "/photos",
            FacebookType.class,
            BinaryAttachment.with(imageFilePath.substring(imageFilePath.length()-34),
                    imageAsBytes,
                    "image/png"),
            Parameter.with("message",
                    message));
}
</code>```

And my image is converted into a byte array in this method

```<code>private byte[] fetchBytesFromImage(String imageFile) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte fileContent[] = null;

    try{

        BufferedImage image = ImageIO.read(new File(imageFile));

        ImageIO.write(image, "png", baos);
        baos.flush();
        fileContent = baos.toByteArray();

    }catch (Exception e){
        e.printStackTrace();
    }
    return  fileContent;

}
</code>```

Again thanks for your help.

Body:
When I publish a picture to my wall by

FacebookType publish = fc.publish("me/photos", FacebookType.class,
                      BinaryAttachment.with(attachmentName, temporaryStream),
                      Parameter.with("message", "my myssage"));

the post is created as expected. I can see a message and the published pictute under the message .

but when I want to do the same but on some pages wall instead the user wall by.

FacebookType publish = fc.publish(pageId + "/photos", FacebookType.class,
                      BinaryAttachment.with(attachmentName, temporaryStream),
                      Parameter.with("message", "my myssage"));

the post is published, but I can see only text. Not the picture. The picture can be seen only when I click on the date of the post. I can also reach this photo by clicking on the photos on the top of the page and then "name of the page" photos tab.

Is there any way how to see the photo as the part of the post also when I post it on a page?

Body:
Your Answer worked a treat and helped me untold amounts however i found with my solution I didn't need

FacebookType post =  fc.publish(pageid + "/feed", FacebookType.class,
        Parameter.with("message", "your message"),Parameter.with("type", "photo"),
        Parameter.with("link", photoLink.getLink()));

as i would recive an error (that i should have copied to show you) but photoLink.getLink() returned null in my case.

so my updated solution ended up being

        FacebookType photo = client.publish(groupId + "/photos",
            FacebookType.class,
            BinaryAttachment.with(imageName),
                    imageAsBytes,
                    "image/png"),
            Parameter.with("message",
                    message));

Just my 2 cents, Thanks again for your help!

EDIT

Also while playing around I noticed that in the solution I arrived at I was creating a FacebookType photo object and this object doesn't get used anywhere, your just calling the publish method of the client that's created further up in your program.

my final class is below, (my application is taking an image from the computer and posing to a groups wall)

    public void createImagePostInGroup(String message, String groupId, String imageFilePath){

    byte[] imageAsBytes = fetchBytesFromImage(imageFilePath);

    DefaultFacebookClient client =
        new DefaultFacebookClient(accessToken, Version.LATEST);

    client.publish(groupId + "/photos",
            FacebookType.class,
            BinaryAttachment.with(imageFilePath.substring(imageFilePath.length()-34),
                    imageAsBytes,
                    "image/png"),
            Parameter.with("message",
                    message));
}

And my image is converted into a byte array in this method

private byte[] fetchBytesFromImage(String imageFile) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte fileContent[] = null;

    try{

        BufferedImage image = ImageIO.read(new File(imageFile));

        ImageIO.write(image, "png", baos);
        baos.flush();
        fileContent = baos.toByteArray();

    }catch (Exception e){
        e.printStackTrace();
    }
    return  fileContent;

}

Again thanks for your help.


问:
Serbian latin and Serbian Cyrillic in android
Is it possible to change programmatically Locale in the app to Serbian Latin in android app?
As i understand i can do it in this way:

```<code>Locale locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
</code>```

But it is available only in 21 API. But i have minsdk = 16

答:
Here's the answer to this question. With various forms for the newer versions of the OS. </p>

```<code>private static Locale serbianLatinLocale(){

    Locale locale = null;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        for (Locale checkLocale : Locale.getAvailableLocales()) {
            if (checkLocale.getISO3Language().equals("srp") && checkLocale.getCountry().equals("LATN") && checkLocale.getVariant().equals("")) {
                locale = checkLocale;
            }
        }
    } else {
        locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
    }

    return locale;
}
</code>```

Body:
Is it possible to change programmatically Locale in the app to Serbian Latin in android app?
As i understand i can do it in this way:

Locale locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();

But it is available only in 21 API. But i have minsdk = 16

Body:
Here's the answer to this question. With various forms for the newer versions of the OS.

private static Locale serbianLatinLocale(){

    Locale locale = null;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        for (Locale checkLocale : Locale.getAvailableLocales()) {
            if (checkLocale.getISO3Language().equals("srp") && checkLocale.getCountry().equals("LATN") && checkLocale.getVariant().equals("")) {
                locale = checkLocale;
            }
        }
    } else {
        locale = new Locale.Builder().setLanguage("sr").setRegion("RS").setScript("Latn").build();
    }

    return locale;
}


问:
`brew upgrade` hangs on El Capitan
I can't run brew upgrade without it hanging indefinitely. I'm using El Capitan OS. Here's the input/output:

```<code>>>$ brew upgrade
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core, homebrew/science).
==> Updated Formulae
artifactory         dovecot             node@4              scamper
chromedriver        node-build          openvpn
==> Deleted Formulae
pdksh

==> Upgrading 10 outdated packages, with result:
gcc 6.2.0, gdbm 1.12, libtiff 4.0.7, openssl 1.0.2j, pkg-config 0.29.1_2, python 2.7.12_2, homebrew/science/r 3.3.2, readline 7.0.1, sqlite 3.15.2, yara 3.5.0_1
==> Upgrading gcc
Warning: Building gcc from source:
  The bottle needs the Xcode CLT to be installed.
==> Using the sandbox
==> Downloading https://ftpmirror.gnu.org/gcc/gcc-6.2.0/gcc-6.2.0.tar.bz2
Already downloaded: /Users/r8t/Library/Caches/Homebrew/gcc-6.2.0.tar.bz2
==> Downloading https://raw.githubusercontent.com/Homebrew/formula-patches/e9e0e
Already downloaded: /Users/r8t/Library/Caches/Homebrew/gcc--patch-863957f90a934ee8f89707980473769cff47ca0663c3906992da6afb242fb220.patch
==> Patching
==> Applying 6.1.0-jit.patch
patching file gcc/jit/Make-lang.in
==> ../configure --build=x86_64-apple-darwin15.6.0 --prefix=/usr/local/Cellar/gc
==> make bootstrap
</code>```

And then nothing.

答:
It could be downloading something large and taking a long time. Try running the following so you can see the download progress:</p>

```<code>brew update --debug --verbose
</code>```

Title: `brew upgrade` hangs on El Capitan

Body:
I can't run brew upgrade without it hanging indefinitely. I'm using El Capitan OS. Here's the input/output:

>>$ brew upgrade
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core, homebrew/science).
==> Updated Formulae
artifactory         dovecot             node@4              scamper
chromedriver        node-build          openvpn
==> Deleted Formulae
pdksh

==> Upgrading 10 outdated packages, with result:
gcc 6.2.0, gdbm 1.12, libtiff 4.0.7, openssl 1.0.2j, pkg-config 0.29.1_2, python 2.7.12_2, homebrew/science/r 3.3.2, readline 7.0.1, sqlite 3.15.2, yara 3.5.0_1
==> Upgrading gcc
Warning: Building gcc from source:
  The bottle needs the Xcode CLT to be installed.
==> Using the sandbox
==> Downloading https://ftpmirror.gnu.org/gcc/gcc-6.2.0/gcc-6.2.0.tar.bz2
Already downloaded: /Users/r8t/Library/Caches/Homebrew/gcc-6.2.0.tar.bz2
==> Downloading https://raw.githubusercontent.com/Homebrew/formula-patches/e9e0e
Already downloaded: /Users/r8t/Library/Caches/Homebrew/gcc--patch-863957f90a934ee8f89707980473769cff47ca0663c3906992da6afb242fb220.patch
==> Patching
==> Applying 6.1.0-jit.patch
patching file gcc/jit/Make-lang.in
==> ../configure --build=x86_64-apple-darwin15.6.0 --prefix=/usr/local/Cellar/gc
==> make bootstrap

And then nothing.

Body:
It could be downloading something large and taking a long time. Try running the following so you can see the download progress:

brew update --debug --verbose


问:
How to explain funny behavior of call/cc in Racket?
combine must map reduce a list with the binary operator bin but must return exc if it finds any value that fails the predicate pred?, and if it finds any such value it must not perform any calculation on the list.

This is a simple continuation problem.

```<code>#lang racket

(define (id x)
  x)

(define (const x)
  (lambda (_) x))

(define (combine pred? bin zero exc)
  (call/cc
   (lambda (exit)
     (letrec
         ((f (lambda (xs)
               (if (empty? xs)
                   zero
                   (if (pred? (first xs))
                       (exit exc)
                       (bin (first xs) (f (rest xs))))))))
       f))))

(define product
  (combine zero?
           *
           1
           0))

(product '(1 2 3 0 4))
</code>```

The code almost works, but it has a very subtle error.

It raises the following exception:

```<code>define-values: assignment disallowed;
 cannot re-define a constant
  constant: product
</code>```

It is easy to make it work. Only a small change is needed:

```<code>(define (combine pred? bin un zero exc)
  (lambda (ys)
    (call/cc
     (lambda (exit)
       (letrec
           ((f (lambda (xs)
                 (if (empty? xs)
                     zero
                     (if (pred? (first xs))
                         (exit exc)
                         (bin (first xs) (f (rest xs))))))))
         (f ys))))))
</code>```

I see that the problem is that Racket the continuation of define is to define  a function, but can anyone give more details? What syntatic transformations involved, for example?

答:
Think of the order you have to have here:

```<code>(define product (combine ....))
</code>```

Here you first evaluate (combine ...) and the continuation is the rest of the program starting with storing the computed value as the name product. Calling the continuation from withing  f jumps right back to storing product all over again.

By calling (product '(1 2 3 0 4)) you are redefining product since it is the continuation of the program and call/cc captures the continuation.

In your second attempt you do a true refactoring of wrapping it in a lambda and call f with the same argument. It's just delaying when the call/cc happens and thus what is included in the continuation. In this version the continuation is whatever comes after the (product ...) and not the setting pf product in (define product ...)

Body:
combine must map reduce a list with the binary operator bin but must return exc if it finds any value that fails the predicate pred?, and if it finds any such value it must not perform any calculation on the list.

This is a simple continuation problem.

#lang racket

(define (id x)
  x)

(define (const x)
  (lambda (_) x))

(define (combine pred? bin zero exc)
  (call/cc
   (lambda (exit)
     (letrec
         ((f (lambda (xs)
               (if (empty? xs)
                   zero
                   (if (pred? (first xs))
                       (exit exc)
                       (bin (first xs) (f (rest xs))))))))
       f))))

(define product
  (combine zero?
           *
           1
           0))

(product '(1 2 3 0 4))

The code almost works, but it has a very subtle error.

It raises the following exception:

define-values: assignment disallowed;
 cannot re-define a constant
  constant: product

It is easy to make it work. Only a small change is needed:

(define (combine pred? bin un zero exc)
  (lambda (ys)
    (call/cc
     (lambda (exit)
       (letrec
           ((f (lambda (xs)
                 (if (empty? xs)
                     zero
                     (if (pred? (first xs))
                         (exit exc)
                         (bin (first xs) (f (rest xs))))))))
         (f ys))))))

I see that the problem is that Racket the continuation of define is to define  a function, but can anyone give more details? What syntatic transformations involved, for example?

Body:
Think of the order you have to have here:

(define product (combine ....))

Here you first evaluate (combine ...) and the continuation is the rest of the program starting with storing the computed value as the name product. Calling the continuation from withing  f jumps right back to storing product all over again.

By calling (product '(1 2 3 0 4)) you are redefining product since it is the continuation of the program and call/cc captures the continuation.

In your second attempt you do a true refactoring of wrapping it in a lambda and call f with the same argument. It's just delaying when the call/cc happens and thus what is included in the continuation. In this version the continuation is whatever comes after the (product ...) and not the setting pf product in (define product ...)


问:
Find multi-word terms in a tokenized text in Python
I have a text that I have tokenized, or in general a list of words is ok as well. For example:

```<code>   >>> from nltk.tokenize import word_tokenize
    >>> s = '''Good muffins cost $3.88\nin New York.  Please buy me
    ... two of them.\n\nThanks.'''
    >>> word_tokenize(s)
        ['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New', 'York', '.',
        'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
</code>```

If I have a Python dict that contains single word as well as multi-word keys, how can I efficiently and correctly check for their presence in the text? The ideal output would be key:location_in_text pairs, or something as convenient.
Thanks in advance!

P.S. To explain "correctly" - If I have "lease" in my dict, I do not wish Please marked. Also, recognizing plurals is required. I am wondering if this can be elegantly solved without many if-else clauses.

答:
If you already have a list of Multi-Word Expressions gazetteers, you can use MWETokenizer, e.g.:

```<code>>>> from nltk.tokenize import MWETokenizer
>>> from nltk import sent_tokenize, word_tokenize

>>> s = '''Good muffins cost $3.88\nin New York.  Please buy me
...     ... two of them.\n\nThanks.'''

>>> mwe = MWETokenizer([('New', 'York'), ('Hong', 'Kong')], separator='_')

>>> [mwe.tokenize(word_tokenize(sent)) for sent in sent_tokenize(s)]
[['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New_York', '.'], ['Please', 'buy', 'me', '...', 'two', 'of', 'them', '.'], ['Thanks', '.']]
</code>```

Body:
I have a text that I have tokenized, or in general a list of words is ok as well. For example:

   >>> from nltk.tokenize import word_tokenize
    >>> s = '''Good muffins cost $3.88\nin New York.  Please buy me
    ... two of them.\n\nThanks.'''
    >>> word_tokenize(s)
        ['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New', 'York', '.',
        'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']

If I have a Python dict that contains single word as well as multi-word keys, how can I efficiently and correctly check for their presence in the text? The ideal output would be key:location_in_text pairs, or something as convenient.
Thanks in advance!

P.S. To explain "correctly" - If I have "lease" in my dict, I do not wish Please marked. Also, recognizing plurals is required. I am wondering if this can be elegantly solved without many if-else clauses.

Body:
If you already have a list of Multi-Word Expressions gazetteers, you can use MWETokenizer, e.g.:

>>> from nltk.tokenize import MWETokenizer
>>> from nltk import sent_tokenize, word_tokenize

>>> s = '''Good muffins cost $3.88\nin New York.  Please buy me
...     ... two of them.\n\nThanks.'''

>>> mwe = MWETokenizer([('New', 'York'), ('Hong', 'Kong')], separator='_')

>>> [mwe.tokenize(word_tokenize(sent)) for sent in sent_tokenize(s)]
[['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New_York', '.'], ['Please', 'buy', 'me', '...', 'two', 'of', 'them', '.'], ['Thanks', '.']]