问:
Row_number over (Partition by xxx) in Linq?
I have a DataTable which has a structure and data:

```<code>id |   inst   |   name
------------------------
 1 |  guitar  |  john
 2 |  guitar  |  george
 3 |  guitar  |  paul
 4 |  drums   |  ringo
 5 |  drums   |  pete
</code>```

I can retrieve the records via:

```<code>IEnumerable <Beatle>...

class Beatle
{
  int id;
  string inst;
  string name;
}
</code>```

I'd like to get the internal order of those who play the different instruments.  In MSSQL I'd use

```<code>SELECT
    *
    ,Row_Number() OVER (PARTITION BY inst ORDER BY id) AS rn
FROM Beatles
</code>```

This query returns

```<code>id |   inst   |   name  | rn
-----------------------------
 1 |  guitar  |  john   | 1
 2 |  guitar  |  george | 2
 3 |  guitar  |  paul   | 3
 4 |  drums   |  ringo  | 1
 5 |  drums   |  pete   | 2
</code>```

Question:

How can I do that in Linq?

答:
B"H

I know this is old. But why isn't the solution simply?

```<code>var o = beatles.GroupBy(x => x.inst)
               .SelectMany(g =>
                   g.Select((j, i) => new { j.inst, j.name, rn = i + 1 })
               );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a DataTable which has a structure and data:

id |   inst   |   name
------------------------
 1 |  guitar  |  john
 2 |  guitar  |  george
 3 |  guitar  |  paul
 4 |  drums   |  ringo
 5 |  drums   |  pete

I can retrieve the records via:

IEnumerable <Beatle>...

class Beatle
{
  int id;
  string inst;
  string name;
}

I'd like to get the internal order of those who play the different instruments.  In MSSQL I'd use

SELECT
    *
    ,Row_Number() OVER (PARTITION BY inst ORDER BY id) AS rn
FROM Beatles

This query returns

id |   inst   |   name  | rn
-----------------------------
 1 |  guitar  |  john   | 1
 2 |  guitar  |  george | 2
 3 |  guitar  |  paul   | 3
 4 |  drums   |  ringo  | 1
 5 |  drums   |  pete   | 2

Question:

How can I do that in Linq?

Body:
B"H

I know this is old. But why isn't the solution simply?

var o = beatles.GroupBy(x => x.inst)
               .SelectMany(g =>
                   g.Select((j, i) => new { j.inst, j.name, rn = i + 1 })
               );


来源: stackexchange

问:
Forwarding keyboard events from one Windows control to another
In Delphi XE, I'm trying to implement an "instant search" feature - one that resembles Firefox's "search as you type" somewhat, but is better illustrated by a similar feature in an open source clipboard extender, Ditto:

There is a list of items that handles typical navigation events. However, any alphanumeric keys as well as navigation and editing commands (right/left arrows, shift+arrows, backspace, delete etc.) should be rerouted to the edit box below the list. An OnChange event of the edit box will trigger a refresh of the list.

The point of the UI is that user does not have to tab or shift-tab between the controls. The two controls (the list and the edit box) should 'feel" as if they were a single control. The behavior of the search UI should not be contingent on which control has focus.

It seems my best option is to forward certain keyboard events from the list control (I'm using TcxTreeList) to the edit box, and forward a handful of navigation keys from the edit box to the list. How can I achieve that?

Notes:

TcxTreeList supports incremental search of course, but this is not what I'm after. The search goes to an SQLite database and looks for substring matches. The list displays only the matching items from the db.

There is some overlap, e.g. both controls would normally handle VK_HOME and VK_END, but that's OK - in this case the keys would go to the list. I'll need to decide whether to forward each individual keypress, or handle it in the control that received it.

On Edit:
One obvious way seemed to be to invoke the respective KeyDown, KeyUp and KeyPress methods of the edit control, like so:

```<code>type
  THackEdit = class( TEdit );

procedure TMainForm.cxTreeList1KeyDown(Sender: TObject; var Key: Word;
    Shift: TShiftState);
begin
  THackEdit( edit1 ).KeyDown( Key, Shift );
end;
</code>```

Unfortunately, this has no effect. My guess is TEdit won't process key events unless it is focused. Using SendMessage( THackEdit( edit1 ).Handle, WM_KEYDOWN, Key, 0 ) has no effect, either.

答:
You can use the message handling capability of a VCL control and send the relevant messages to one another. I don't know about a 'TcxTreeList', but the following demonstrates the idea on an edit control and a memo control responding to keyboard events synchronously (whereever possible of course).

```<code>type
  TEdit = class(stdctrls.TEdit)
  private
    FMsgCtrl: TWinControl;
    FRecursing: Boolean;
    procedure WmChar(var Msg: TWMChar); message WM_CHAR;
    procedure WmKeyDown(var Msg: TWMKeyDown); message WM_KEYDOWN;
    procedure WmKeyUp(var Msg: TWMKeyUp); message WM_KEYUP;
  end;

  TMemo = class(stdctrls.TMemo)
  private
    FMsgCtrl: TWinControl;
    FRecursing: Boolean;
    procedure WmChar(var Msg: TWMChar); message WM_CHAR;
    procedure WmKeyDown(var Msg: TWMKeyDown); message WM_KEYDOWN;
    procedure WmKeyUp(var Msg: TWMKeyUp); message WM_KEYUP;
  end;

  TForm1 = class(TForm)
    Edit1: TEdit;
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
  private
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TEdit }

procedure TEdit.WmChar(var Msg: TWMChar);
begin
  if not FRecursing then begin
    inherited;

    // Insert test here to see if the message will be forwarded
    // exit/modify accordingly.

    if Assigned(FMsgCtrl) then begin
      FRecursing := True;
      try
        FMsgCtrl.Perform(Msg.Msg,
                         MakeWParam(Msg.CharCode, Msg.Unused), Msg.KeyData);
      finally
        FRecursing := False;
      end;
    end;
  end;
end;

procedure TEdit.WmKeyDown(var Msg: TWMKeyDown);
begin
  // exact same contents as in the above procedure
end;

procedure TEdit.WmKeyUp(var Msg: TWMKeyUp);
begin
  // same here
end;

{ TMemo }

procedure TMemo.WmChar(var Msg: TWMChar);
begin
  // same here
end;

procedure TMemo.WmKeyDown(var Msg: TWMKeyDown);
begin
  // same here
end;

procedure TMemo.WmKeyUp(var Msg: TWMKeyUp);
begin
  // same here
end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  Edit1.FMsgCtrl := Memo1;
  Memo1.FMsgCtrl := Edit1;
end;
</code>```

You might need to intervene additional messages but you get the idea.

If for one reason or another you cannot derive a new control or override message handling, you can consider sub-classing the controls. Answer to this question would show you how to do that.

ContentLicense: CC BY-SA 2.5

Body:
In Delphi XE, I'm trying to implement an "instant search" feature - one that resembles Firefox's "search as you type" somewhat, but is better illustrated by a similar feature in an open source clipboard extender, Ditto:

There is a list of items that handles typical navigation events. However, any alphanumeric keys as well as navigation and editing commands (right/left arrows, shift+arrows, backspace, delete etc.) should be rerouted to the edit box below the list. An OnChange event of the edit box will trigger a refresh of the list.

The point of the UI is that user does not have to tab or shift-tab between the controls. The two controls (the list and the edit box) should 'feel" as if they were a single control. The behavior of the search UI should not be contingent on which control has focus.

It seems my best option is to forward certain keyboard events from the list control (I'm using TcxTreeList) to the edit box, and forward a handful of navigation keys from the edit box to the list. How can I achieve that?

Notes:

TcxTreeList supports incremental search of course, but this is not what I'm after. The search goes to an SQLite database and looks for substring matches. The list displays only the matching items from the db.

There is some overlap, e.g. both controls would normally handle VK_HOME and VK_END, but that's OK - in this case the keys would go to the list. I'll need to decide whether to forward each individual keypress, or handle it in the control that received it.

On Edit:
One obvious way seemed to be to invoke the respective KeyDown, KeyUp and KeyPress methods of the edit control, like so:

type
  THackEdit = class( TEdit );

procedure TMainForm.cxTreeList1KeyDown(Sender: TObject; var Key: Word;
    Shift: TShiftState);
begin
  THackEdit( edit1 ).KeyDown( Key, Shift );
end;

Unfortunately, this has no effect. My guess is TEdit won't process key events unless it is focused. Using SendMessage( THackEdit( edit1 ).Handle, WM_KEYDOWN, Key, 0 ) has no effect, either.

Body:
You can use the message handling capability of a VCL control and send the relevant messages to one another. I don't know about a 'TcxTreeList', but the following demonstrates the idea on an edit control and a memo control responding to keyboard events synchronously (whereever possible of course).

type
  TEdit = class(stdctrls.TEdit)
  private
    FMsgCtrl: TWinControl;
    FRecursing: Boolean;
    procedure WmChar(var Msg: TWMChar); message WM_CHAR;
    procedure WmKeyDown(var Msg: TWMKeyDown); message WM_KEYDOWN;
    procedure WmKeyUp(var Msg: TWMKeyUp); message WM_KEYUP;
  end;

  TMemo = class(stdctrls.TMemo)
  private
    FMsgCtrl: TWinControl;
    FRecursing: Boolean;
    procedure WmChar(var Msg: TWMChar); message WM_CHAR;
    procedure WmKeyDown(var Msg: TWMKeyDown); message WM_KEYDOWN;
    procedure WmKeyUp(var Msg: TWMKeyUp); message WM_KEYUP;
  end;

  TForm1 = class(TForm)
    Edit1: TEdit;
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
  private
  public
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TEdit }

procedure TEdit.WmChar(var Msg: TWMChar);
begin
  if not FRecursing then begin
    inherited;

    // Insert test here to see if the message will be forwarded
    // exit/modify accordingly.

    if Assigned(FMsgCtrl) then begin
      FRecursing := True;
      try
        FMsgCtrl.Perform(Msg.Msg,
                         MakeWParam(Msg.CharCode, Msg.Unused), Msg.KeyData);
      finally
        FRecursing := False;
      end;
    end;
  end;
end;

procedure TEdit.WmKeyDown(var Msg: TWMKeyDown);
begin
  // exact same contents as in the above procedure
end;

procedure TEdit.WmKeyUp(var Msg: TWMKeyUp);
begin
  // same here
end;

{ TMemo }

procedure TMemo.WmChar(var Msg: TWMChar);
begin
  // same here
end;

procedure TMemo.WmKeyDown(var Msg: TWMKeyDown);
begin
  // same here
end;

procedure TMemo.WmKeyUp(var Msg: TWMKeyUp);
begin
  // same here
end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  Edit1.FMsgCtrl := Memo1;
  Memo1.FMsgCtrl := Edit1;
end;

You might need to intervene additional messages but you get the idea.

If for one reason or another you cannot derive a new control or override message handling, you can consider sub-classing the controls. Answer to this question would show you how to do that.


问:
TS2339: Property 'x' does not exist on type 'Y'. In class inheritance
Let say I have a class hierarchy like so:

```<code>// monorepo/src/package1/file1.ts
export class AbstractModel implements Hashable {

    assignFromHash(hash: Object): void {
        Object.assign(this, hash);
    }
}

// monorepo/src/package2/file2.ts
export abstract class Model extends AbstractModel {}

// monorepo/src/package2/file3.ts
export class ModelImpl extends Model {}

// monorepo/src/application/file4.ts somewhere in application.
// Here object `model`, because of the angular DI setup,
// is an instance of ModelImpl
(model: Model ) => {
    model.assignFromHash({});
}
</code>```

When compiling this with tsc -p . and the following tsconfig.json:

```<code>{
  "compilerOptions": {
  "allowSyntheticDefaultImports": true,
  "declaration": false,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "skipLibCheck": true,
  "noStrictGenericChecks": true,
  "lib": [
    "dom",
    "es2015"
  ],
  "module": "es2015",
  "moduleResolution": "node",
  "sourceMap": true,
  "target": "es5"
},
"include": [
  "./**/*.ts"
],
"exclude": [
  "node_modules"
],
"compileOnSave": false,
"atom": {
  "rewriteTsconfig": false
}
</code>```

}

I am getting:

```<code>error TS2339: Property 'assignFromHash' does not exist on type 'Model'.
</code>```

What am I missing? How to fix this?

Note:

The reason to have the intermediate class Model is to be able to use the DI functionality from Angular when registering providers. I can not use an interface due to obvious limitation with typescript interfaces and javascript. I can not use AbstractModel neither because it would be too general then.

The monorepo repository is handled with lerna

There was no syntax error. The dots was just a way to state that it was an object placeholder, real code there is a correctly defined object hash.

This issue, as usual, was due to incorrect understanding of what was happening under the hood. I will post results as an answer in order to stick to stack overflow ways.

Thanks in advance.

答:
Your presented code compiles without errors:

```<code>export interface Hashable { }
export class AbstractModel implements Hashable {
  assignFromHash(hash: Object): void {
    Object.assign(this, hash);
  }
}
export abstract class Model extends AbstractModel { }
export class ModelImpl extends Model { }
console.log((model: Model) => {
  model.assignFromHash({}); // No error
});
</code>```

Demo

More

If you manage to reproduce the error again, please open a new question.

ContentLicense: CC BY-SA 3.0

Body:
Let say I have a class hierarchy like so:

// monorepo/src/package1/file1.ts
export class AbstractModel implements Hashable {

    assignFromHash(hash: Object): void {
        Object.assign(this, hash);
    }
}

// monorepo/src/package2/file2.ts
export abstract class Model extends AbstractModel {}

// monorepo/src/package2/file3.ts
export class ModelImpl extends Model {}

// monorepo/src/application/file4.ts somewhere in application.
// Here object `model`, because of the angular DI setup,
// is an instance of ModelImpl
(model: Model ) => {
    model.assignFromHash({});
}

When compiling this with tsc -p . and the following tsconfig.json:

{
  "compilerOptions": {
  "allowSyntheticDefaultImports": true,
  "declaration": false,
  "emitDecoratorMetadata": true,
  "experimentalDecorators": true,
  "skipLibCheck": true,
  "noStrictGenericChecks": true,
  "lib": [
    "dom",
    "es2015"
  ],
  "module": "es2015",
  "moduleResolution": "node",
  "sourceMap": true,
  "target": "es5"
},
"include": [
  "./**/*.ts"
],
"exclude": [
  "node_modules"
],
"compileOnSave": false,
"atom": {
  "rewriteTsconfig": false
}

}

I am getting:

error TS2339: Property 'assignFromHash' does not exist on type 'Model'.

What am I missing? How to fix this?

Note:

The reason to have the intermediate class Model is to be able to use the DI functionality from Angular when registering providers. I can not use an interface due to obvious limitation with typescript interfaces and javascript. I can not use AbstractModel neither because it would be too general then.

The monorepo repository is handled with lerna

There was no syntax error. The dots was just a way to state that it was an object placeholder, real code there is a correctly defined object hash.

This issue, as usual, was due to incorrect understanding of what was happening under the hood. I will post results as an answer in order to stick to stack overflow ways.

Thanks in advance.

Body:
Your presented code compiles without errors:

export interface Hashable { }
export class AbstractModel implements Hashable {
  assignFromHash(hash: Object): void {
    Object.assign(this, hash);
  }
}
export abstract class Model extends AbstractModel { }
export class ModelImpl extends Model { }
console.log((model: Model) => {
  model.assignFromHash({}); // No error
});

Demo

More

If you manage to reproduce the error again, please open a new question.


问:
How can I check if a NSString is equal with a character at specific index in another NSString?
I tried so far:

```<code>if ([randomString isEqualToString:[anotherRandomString atIndex:1]]){
    stuff
}
</code>```

which returns this error:

error: instance method '-atIndex:' not found

and

```<code>[arg1 isEqualToString:[password2 characterAtIndex:1]]
</code>```

returns this error

error: cannot initialize a parameter of type 'NSString *' with an rvalue of type 'unichar'

答:
Get the desired substring from anotherRandomString and then compare that to randomString.

```<code>NSString *substring = [anotherRandomString substringWithRange:NSMakeRange(someIndex, 1)];
if ([randomString isEqualToString:substring]) {
}
</code>```

Body:
I tried so far:

if ([randomString isEqualToString:[anotherRandomString atIndex:1]]){
    stuff
}

which returns this error:

error: instance method '-atIndex:' not found

and

[arg1 isEqualToString:[password2 characterAtIndex:1]]

returns this error

error: cannot initialize a parameter of type 'NSString *' with an rvalue of type 'unichar'

Body:
Get the desired substring from anotherRandomString and then compare that to randomString.

NSString *substring = [anotherRandomString substringWithRange:NSMakeRange(someIndex, 1)];
if ([randomString isEqualToString:substring]) {
}


问:
Haskell - manipulating/extending an ADT that isn’t under your control
What is the best way to go about manipulating/extending an ADT that isn’t under your control? (ie from a dependency)

Here is the data type that relates to my problem:

I want to maintain the structure of the data, but add additional data (ie adding another type), but the structure itself is not under my control. Do I have to map the data over to my own version of this definition?

For example, for all the paragraphs in the structure, I would like Para to become Para [Inline] [String] where [String] is a list of words contained in the paragraph (as it's own data structure).

I am serving this data up as JSON via an endpoint, I thought one way I could get around this would be to define my own ToJSON instance, and perform this translation on Para there, however I am unable to override the instance as it is already defined! I am willing to accept a solution that does not actually touch the Para type itself, I just need a way to couple more data to Para without losing any of the structure of full Pandoc document.

答:
Yes I think defining your own JSON serializer is probably the best way to go.  You can define JSON serializers without using the typeclass mechanism, because Aeson is well-designed (thanks @bos), just define a function from Block ->Value.  Unfortunately it seems like you will have to traverse every case manually, at least the cases with nested Blocks such as BlockQuote, OrderedList, etc.  For the others you can just forward to ToJSON:

```<code>serialize :: Block -> Value
serialize (BlockQuote bs) = object
   [ "type" .= "blockquote"       -- or whatever the encoding is
   , "blocks" .= map serailize bs
   ]
...  -- implement this for every constructor with recursive Blocks
serialize b = toJSON b
</code>```

It's not great, since you might have to directly rewrite things that have been written.  I don't see a way around it given pandoc's design, though (often ASTs are parameterized over a type of annotations, e.g. haskell-src-exts, or use some open-fixedpoint design, which would allow something more clever).

A rather crude way would be to serialize using toJSON, find just the parts of the JSON structure you want to annotate, deserialize just that part and compute the annotation, reserialize, then add your computed annotation.  Very ugly, but you don't have to reimplement any serializers, I think.  If pandoc had a lot of recursive constructors, or very complex serialization, I might consider this, but as it stands I would probably just bite the bullet and reimplement the recursive cases.

Body:
Yes I think defining your own JSON serializer is probably the best way to go.  You can define JSON serializers without using the typeclass mechanism, because Aeson is well-designed (thanks @bos), just define a function from Block ->Value.  Unfortunately it seems like you will have to traverse every case manually, at least the cases with nested Blocks such as BlockQuote, OrderedList, etc.  For the others you can just forward to ToJSON:

serialize :: Block -> Value
serialize (BlockQuote bs) = object
   [ "type" .= "blockquote"       -- or whatever the encoding is
   , "blocks" .= map serailize bs
   ]
...  -- implement this for every constructor with recursive Blocks
serialize b = toJSON b

It's not great, since you might have to directly rewrite things that have been written.  I don't see a way around it given pandoc's design, though (often ASTs are parameterized over a type of annotations, e.g. haskell-src-exts, or use some open-fixedpoint design, which would allow something more clever).

A rather crude way would be to serialize using toJSON, find just the parts of the JSON structure you want to annotate, deserialize just that part and compute the annotation, reserialize, then add your computed annotation.  Very ugly, but you don't have to reimplement any serializers, I think.  If pandoc had a lot of recursive constructors, or very complex serialization, I might consider this, but as it stands I would probably just bite the bullet and reimplement the recursive cases.


问:
JQuery Bracket plugin - init property from a function result
I'm trying to initialize the render object with the result of a JS function that returns a query from a REST service

JS function that returns a query from a REST service

This is the function that initializes the object:

Function that initializes the object

In the console log I have this result:

Console log result

The expected result would be this :(

Expected result

答: The problem was in assigning a variable within an asynchronous call. I moved a call from the object's startup function to the success of the function calling the service and it worked.</p>


问:
c# linq GroupBy and Sum up only the lowerest in each group
This is the problem:
I have a long list of objects with properties

```<code>1) int Book (B)
2) int Chapter (C)
3) int Paragraph (P)
4) int TimesRead (nx)
</code>```

each book is the sum of all it's chapters and each chapter is the sum of all it's paragraphs. Obviously only if you have read all the chapters of a book it counts for having read the whole book. The same is true for a chapter; all paragraphs have to be read to count the chapter as read.

The list of references that looks like this

```<code>B1 - C1 - P1 - 3x
B1 - C1 - P2 - 3x
B1 - C1 - P3 - 4x
B1 - C2 - P1 - 5x
B1 - C2 - P2 - 2x
B1 - C2 - P3 - 2x
B1 - C2 - P4 - 9x
B2 - C1 - P1 - 3x
...tens of thousands of them
</code>```

B1C1 counts only as 3x read. B1C2 counts as 2x read because each of the paragraphs have been read 3x and 2x respectively. What I want to count is only the minimum.
I want the sum of all the chapters how often they have been read through completely. But how do I go about summing up only the lowerest TimesRead for each chapter;

```<code>B1C1 + B1C2 + B2C1
 3   +   2  +   3
</code>```

using linq or a loop (I'd prefer linq).

This is as far as I get but it's not correct. How do I get only the groups with the lowest TimesRead for each pair x.Book-x.Chapter?

```<code>SumTotalChaptersRead = listBookChapterParagraph
    .Where(x => x.TimesRead >= 1)
    .GroupBy(x => new Tuple<string, int>($"{x.Book}-{x.Chapter}", x.TimesRead))
    .ToList()
    .Where(x => x.TimesRead[.Min])
    .Sum(s => s.Key.Item2);
</code>```

Somehow there must be a TimesRead.Min somewhere in this.

答:
Can’t check this out right now, but wouldn’t something similar to this work?</p>

```<code>SumTotalChaptersRead =
   listBookChapterParagraph.Where(x => x.TimesRead >= 1)
                           .GroupBy(x => $"{x.Book}-{x.Chapter}")
                           .Select(g => g.OrderBy(x => x.TimesRead).First())
                           .Sum(x => x.TimesRead);
</code>```

Body:
This is the problem:
I have a long list of objects with properties

1) int Book (B)
2) int Chapter (C)
3) int Paragraph (P)
4) int TimesRead (nx)

each book is the sum of all it's chapters and each chapter is the sum of all it's paragraphs. Obviously only if you have read all the chapters of a book it counts for having read the whole book. The same is true for a chapter; all paragraphs have to be read to count the chapter as read.

The list of references that looks like this

B1 - C1 - P1 - 3x
B1 - C1 - P2 - 3x
B1 - C1 - P3 - 4x
B1 - C2 - P1 - 5x
B1 - C2 - P2 - 2x
B1 - C2 - P3 - 2x
B1 - C2 - P4 - 9x
B2 - C1 - P1 - 3x
...tens of thousands of them

B1C1 counts only as 3x read. B1C2 counts as 2x read because each of the paragraphs have been read 3x and 2x respectively. What I want to count is only the minimum.
I want the sum of all the chapters how often they have been read through completely. But how do I go about summing up only the lowerest TimesRead for each chapter;

B1C1 + B1C2 + B2C1
 3   +   2  +   3

using linq or a loop (I'd prefer linq).

This is as far as I get but it's not correct. How do I get only the groups with the lowest TimesRead for each pair x.Book-x.Chapter?

SumTotalChaptersRead = listBookChapterParagraph
    .Where(x => x.TimesRead >= 1)
    .GroupBy(x => new Tuple<string, int>($"{x.Book}-{x.Chapter}", x.TimesRead))
    .ToList()
    .Where(x => x.TimesRead[.Min])
    .Sum(s => s.Key.Item2);

Somehow there must be a TimesRead.Min somewhere in this.

Body:
Can’t check this out right now, but wouldn’t something similar to this work?

SumTotalChaptersRead =
   listBookChapterParagraph.Where(x => x.TimesRead >= 1)
                           .GroupBy(x => $"{x.Book}-{x.Chapter}")
                           .Select(g => g.OrderBy(x => x.TimesRead).First())
                           .Sum(x => x.TimesRead);


问:
MATLAB uicontrol callback return matrix
Original post: MATLAB scrolling plot

I got a second part in my problem now.
As before, I have a 19*1000*134 matrix that I'm plotting thanks to the nicely answer from Aero Engy on the last post.

I would like to create in my workspace a vector called clean that will have a 134 length.

By default, the value for clean(i) (with i between 1 and 134) will be 1 -- but, if I press a button on the UI interface, the value must get to 0.

My code bellow, just don't give me any ouput. The button seems to work, but when I close the figure, I don't get the vector clean.

```<code>function cleanData(data);
% data = rand(19,1000,134);
global clean
clean = ones(1,size(data,3));
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,clean,s});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
viewI = round(s.Value);
disp(['Current Epoch: ' num2str(viewI)]) %console print
xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])

function notClean(c,evtData,clean,s)
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print
</code>```

What am I doing wrong ?

Bonus: It would be nice if

When I press the button "Not clean", the slider change values and increment aswell (Currently, I have to press the button, then the right Arrow of the slider to go to the next 2 secs of data).

Once I check "Clean" or "not clean" for one channel (one of the 19 rows of the matrix), for the next one, it will skip the "not clean" data (i.e. with a 0 in the clean matrix corresponding to the epoch number).

Thanks for the help, I'm quite new at MATLAB, and even if I improve quickly, I'm far from fully understanding this code.

答:
Modified code working with second part too:</p>

```<code>function cleanData(data);
% data = rand(19,1000,134);
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,s,a});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
global clean
viewI = round(s.Value);
if clean(viewI) == 0
    s.Value = s.Value+1;
    sliderChange(s,[],a)
else
    disp(['Current Epoch: ' num2str(viewI)]) %console print
    xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])
end

function notClean(c,evtData,s,a)
global clean %Call the global
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print
%Advance to the next slider position.
s.Value = num+1;
sliderChange(s,[],a)
</code>```

Title: MATLAB uicontrol callback return matrix

Body:
Original post: MATLAB scrolling plot

I got a second part in my problem now.
As before, I have a 19*1000*134 matrix that I'm plotting thanks to the nicely answer from Aero Engy on the last post.

I would like to create in my workspace a vector called clean that will have a 134 length.

By default, the value for clean(i) (with i between 1 and 134) will be 1 -- but, if I press a button on the UI interface, the value must get to 0.

My code bellow, just don't give me any ouput. The button seems to work, but when I close the figure, I don't get the vector clean.

function cleanData(data);
% data = rand(19,1000,134);
global clean
clean = ones(1,size(data,3));
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,clean,s});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
viewI = round(s.Value);
disp(['Current Epoch: ' num2str(viewI)]) %console print
xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])

function notClean(c,evtData,clean,s)
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print

What am I doing wrong ?

Bonus: It would be nice if

When I press the button "Not clean", the slider change values and increment aswell (Currently, I have to press the button, then the right Arrow of the slider to go to the next 2 secs of data).

Once I check "Clean" or "not clean" for one channel (one of the 19 rows of the matrix), for the next one, it will skip the "not clean" data (i.e. with a 0 in the clean matrix corresponding to the epoch number).

Thanks for the help, I'm quite new at MATLAB, and even if I improve quickly, I'm far from fully understanding this code.

Body:
Modified code working with second part too:

function cleanData(data);
% data = rand(19,1000,134);
f = figure('Units','Normalized','Position',[0.25 0.25 0.5 0.5]);
a =   axes('Units','Normalized','Position',[0.05 0.15, 0.75 0.75]);
s =   uicontrol(f, 'Style','Slider', 'Units','Normalized','Position',[0.05 0.025, 0.75 0.05],...
                   'Min',1,'Max',size(data,3),'Value',1, 'Callback',{@sliderChange,a});
l =   uicontrol(f, 'Style','listbox','Units','Normalized','Position',[0.85 0.15, 0.1, 0.75],...
                   'String',cellstr(num2str([1:size(data,1)]')),'Callback',{@changeChannel,a,s,data});
c = uicontrol(f, 'Style','pushbutton','Units','Normalized','String','Not clean',...
                   'Position',[0.85 0.025 0.1 0.05],'Callback',{@notClean,s,a});

stepSize = 1/(s.Max - s.Min);
s.SliderStep = [stepSize 2*stepSize];
changeChannel(l,[],a,s,data)

function changeChannel(l,evtData,a,s,data)
cla(a);
chanNum = str2double(l.String{l.Value});
sR = 500;  %500Hz
tempData = reshape(data(chanNum,:,:),[],size(data,3)); %Reshape each epoch into a column
tempTime = [0:1/sR:(size(data,2)-1)/sR]' + (0:1:size(data,3)-1)*2; %Build time array
plot(a,tempTime,tempData) %plot all the lines
s.Value = 1; %Rest Slider Position

function sliderChange(s,evtData,a)
global clean
viewI = round(s.Value);
if clean(viewI) == 0
    s.Value = s.Value+1;
    sliderChange(s,[],a)
else
    disp(['Current Epoch: ' num2str(viewI)]) %console print
    xlim(a,[(viewI-1)*2 viewI*2] + [-.1 .1])
end

function notClean(c,evtData,s,a)
global clean %Call the global
num = round(s.Value);
clean(num) = 0;
disp(['Epoch ' num2str(num) ' not clean']) %console print
%Advance to the next slider position.
s.Value = num+1;
sliderChange(s,[],a)


问:
Is it possible to programmatically modify TFS 2008/2010 work item type?
Is there a way to programmatically modify a work item type on a TFS server?

The background on this is that we use a custom field similar to VSTS.Build.FoundIn and would like to have it populated with build numbers from a global list. For a single project it is not a problem - it's enough to manually specify the SUGGESTEDVALUES rule with the name of the global list. The problem with this approach is that it cannot be applied to a template that we reuse across multiple projects - there is no way to specify a placeholder for the project name in the global list reference. Hence, every time we create a TFS project we need to manually modify the global list name, like from
<GLOBALLIST name="Builds - [ProjectName]" /> to <GLOBALLIST name="Builds - Project1" />

It seems that TFS has a hardcoded mechanism for creating these rules for the FoundIn and IntegrationBuild properties (see this answer) and I was considering creating a handler for a TFS event to mimic this logic for our custom fields as well.

答:
You could subscribe to ProjectCreatedEvent on the team foundation server and then use Shai Raig's post for working with global lists to create your global list after the project is created.

http://blogs.microsoft.co.il/blogs/shair/archive/2010/03/08/tfs-api-part-23-create-global-list-xml-way.aspx

Martin Hinshelwood has a good post on subscribing to server events here:
http://blog.hinshelwood.com/archive/2010/09/16/team-foundation-server-2010-event-handling-with-subscribers.aspx

EDIT:
You can use the Team Foundation Server Power Tools to edit work items, and also to modify the Project Templates so that work items will have the new field.

UPDATE 1/20/2011:
I found this question which answers how to import and export work items:
TFS Client APIs for creating workitem templates?


问:
How do i use Switch for inline keyboard and replykeyboard at the same time #PHP
here is a php telegram webhook script:

```<code>//calling telegram api after setting $access_token with the bot api
$api = 'https://api.telegram.org/bot' . $access_token;
$output = json_decode(file_get_contents('php://input'), TRUE);

                //setting variables from telegram api
                $chat_id = $output['message']['chat']['id'];
                $first_name = $output['message']['chat']['first_name'];
                $last_name  = $output["message"]["chat"]["last_name"];
                $message = $output['message']['text'];
                $callback_query = $output['callback_query'];
                $data = $callback_query['data'];
                $message_id = ['callback_query']['message']['message_id'];
                $chat_id_in = $callback_query['message']['chat']['id'];
                 switch($message) {
                     case '/start':
                     $inline_button1 = array("text"=>"Website","url"=>"http://google.com");
                     $inline_button2 = array("text"=>"test","callback_data"=>'/test');
                     $inline_keyboard = [[$inline_button1,$inline_button2]];
                     $keyboard=array("inline_keyboard"=>$inline_keyboard);
                     $replyMarkup = json_encode($keyboard);
                      sendMessage($chat_id, "hello", $replyMarkup);
                     break;
                     case '/help':
                     sendMessage($chat_id,"you need help?",$replyMarkup);
                     break;
                     default:
                     sendMessage($chat_id,"thank you",$replyMarkup);
                 }
                switch($data){
                    case '/test':
                    sendMessage($chat_id_in, "Coming Soon .....");
                    break;
                }
    //the sendMessage function
                function sendMessage($chat_id, $message, $replyMarkup) {
                  file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' . $replyMarkup);
                }
</code>```

The Code above works fine for me with inline keyboard on telegram, but i like to add replykeyboard along with some command but am having issue with it see below . I think its the curl function i need to get right, what is your thought guys .

How can you help me?

```<code>        $api = 'https://api.telegram.org/bot' . $access_token;
        $output = json_decode(file_get_contents('php://input'), TRUE);
        $chat_id = $output['message']['chat']['id'];
        $first_name = $output['message']['chat']['first_name'];
        $last_name  = $output["message"]["chat"]["last_name"];
        $message = $output['message']['text'];
        $callback_query = $output['callback_query'];
        $data = $callback_query['data'];
        $message_id = ['callback_query']['message']['message_id'];
        $chat_id_in = $callback_query['message']['chat']['id'];
         switch($message) {
             case '/start':
             $inline_button1 = array("text"=>"Website","url"=>"http://google.com");
             $inline_button2 = array("text"=>"test","callback_data"=>'/test');
             $inline_keyboard = [[$inline_button1,$inline_button2]];
             $keyboard=array("inline_keyboard"=>$inline_keyboard);
             $replyMarkup = json_encode($keyboard);
              sendMessage($chat_id, "Hello", $replyMarkup);
             break;
             case '/help':
             $keyboard1 = array("text"=>"Button 1","text"=>"Button 1","resize_keyboard"=>'true',"one_time_keyboard"=>'true');
             $keyboard2 = array("text"=>"Button 2","text"=>"Button 2","resize_keyboard"=>'true',"one_time_keyboard"=>'true');
             $keyboardset = [[$keyboard1,$keyboard2]];
             $keyboard=array("KeyboardButton"=>$keyboardset)
             $replyMarkup = json_encode($keyboard);
             sendMessage($chat_id,"$you need help",$replyMarkup);
             break;
             default:
             sendMessage($chat_id,"$Thanks",$replyMarkup);
         }
        switch($data){
            case '/test':
            sendMessage($chat_id_in, "Coming Soon .....");
            break;
        }

//call the curl $ch = curl_init($api . 'sendMessage');
        curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch,
        CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($data)); curl_setopt($ch,
        CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch);
        curl_close($ch);

            function sendMessage($chat_id, $message, $replyMarkup) {
              file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' .
        $replyMarkup);
            }
</code>```

Thanks in advance

答:
Here is a complete code

```<code> $api = 'https://api.telegram.org/bot' . $access_token;
        $output = json_decode(file_get_contents('php://input'), TRUE);
        $chat_id = $output['message']['chat']['id'];
        $first_name = $output['message']['chat']['first_name'];
        $last_name  = $output["message"]["chat"]["last_name"];
        $message = $output['message']['text'];
        $callback_query = $output['callback_query'];
        $data = $callback_query['data'];
        $message_id = ['callback_query']['message']['message_id'];
        $chat_id_in = $callback_query['message']['chat']['id'];
         switch($message) {
             case '/start':
             $inline_button1 = array("text"=>"Website","url"=>"http://google.com");
             $inline_button2 = array("text"=>"test","callback_data"=>'/test');
             $inline_keyboard = [[$inline_button1,$inline_button2]];
             $keyboard=array("inline_keyboard"=>$inline_keyboard);
             $replyMarkup = json_encode($keyboard);
              sendMessage($chat_id, "Hello", $replyMarkup);
             break;
             case '/help':
             $keyboard = array(array("Cancel","Go Ahead","test"));
   $resp = array("keyboard" => $keyboard,"resize_keyboard" => true,"one_time_keyboard" => true);
   $reply_ = json_encode($resp);
             break;
             default:
             sendMessage($chat_id,"$Thanks",$replyMarkup);
         }
        switch($data){
            case '/test':
            sendMessage($chat_id_in, "Coming Soon .....");
            break;
        }
</code>```

Thanks

Body:
here is a php telegram webhook script:

//calling telegram api after setting $access_token with the bot api
$api = 'https://api.telegram.org/bot' . $access_token;
$output = json_decode(file_get_contents('php://input'), TRUE);

                //setting variables from telegram api
                $chat_id = $output['message']['chat']['id'];
                $first_name = $output['message']['chat']['first_name'];
                $last_name  = $output["message"]["chat"]["last_name"];
                $message = $output['message']['text'];
                $callback_query = $output['callback_query'];
                $data = $callback_query['data'];
                $message_id = ['callback_query']['message']['message_id'];
                $chat_id_in = $callback_query['message']['chat']['id'];
                 switch($message) {
                     case '/start':
                     $inline_button1 = array("text"=>"Website","url"=>"http://google.com");
                     $inline_button2 = array("text"=>"test","callback_data"=>'/test');
                     $inline_keyboard = [[$inline_button1,$inline_button2]];
                     $keyboard=array("inline_keyboard"=>$inline_keyboard);
                     $replyMarkup = json_encode($keyboard);
                      sendMessage($chat_id, "hello", $replyMarkup);
                     break;
                     case '/help':
                     sendMessage($chat_id,"you need help?",$replyMarkup);
                     break;
                     default:
                     sendMessage($chat_id,"thank you",$replyMarkup);
                 }
                switch($data){
                    case '/test':
                    sendMessage($chat_id_in, "Coming Soon .....");
                    break;
                }
    //the sendMessage function
                function sendMessage($chat_id, $message, $replyMarkup) {
                  file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' . $replyMarkup);
                }

The Code above works fine for me with inline keyboard on telegram, but i like to add replykeyboard along with some command but am having issue with it see below . I think its the curl function i need to get right, what is your thought guys .

How can you help me?

        $api = 'https://api.telegram.org/bot' . $access_token;
        $output = json_decode(file_get_contents('php://input'), TRUE);
        $chat_id = $output['message']['chat']['id'];
        $first_name = $output['message']['chat']['first_name'];
        $last_name  = $output["message"]["chat"]["last_name"];
        $message = $output['message']['text'];
        $callback_query = $output['callback_query'];
        $data = $callback_query['data'];
        $message_id = ['callback_query']['message']['message_id'];
        $chat_id_in = $callback_query['message']['chat']['id'];
         switch($message) {
             case '/start':
             $inline_button1 = array("text"=>"Website","url"=>"http://google.com");
             $inline_button2 = array("text"=>"test","callback_data"=>'/test');
             $inline_keyboard = [[$inline_button1,$inline_button2]];
             $keyboard=array("inline_keyboard"=>$inline_keyboard);
             $replyMarkup = json_encode($keyboard);
              sendMessage($chat_id, "Hello", $replyMarkup);
             break;
             case '/help':
             $keyboard1 = array("text"=>"Button 1","text"=>"Button 1","resize_keyboard"=>'true',"one_time_keyboard"=>'true');
             $keyboard2 = array("text"=>"Button 2","text"=>"Button 2","resize_keyboard"=>'true',"one_time_keyboard"=>'true');
             $keyboardset = [[$keyboard1,$keyboard2]];
             $keyboard=array("KeyboardButton"=>$keyboardset)
             $replyMarkup = json_encode($keyboard);
             sendMessage($chat_id,"$you need help",$replyMarkup);
             break;
             default:
             sendMessage($chat_id,"$Thanks",$replyMarkup);
         }
        switch($data){
            case '/test':
            sendMessage($chat_id_in, "Coming Soon .....");
            break;
        }

//call the curl $ch = curl_init($api . 'sendMessage');
        curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch,
        CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($data)); curl_setopt($ch,
        CURLOPT_SSL_VERIFYPEER, false); $result = curl_exec($ch);
        curl_close($ch);

            function sendMessage($chat_id, $message, $replyMarkup) {
              file_get_contents($GLOBALS['api'] . '/sendMessage?chat_id=' . $chat_id . '&text=' . urlencode($message) . '&reply_markup=' .
        $replyMarkup);
            }

Thanks in advance

Body:
Here is a complete code

 $api = 'https://api.telegram.org/bot' . $access_token;
        $output = json_decode(file_get_contents('php://input'), TRUE);
        $chat_id = $output['message']['chat']['id'];
        $first_name = $output['message']['chat']['first_name'];
        $last_name  = $output["message"]["chat"]["last_name"];
        $message = $output['message']['text'];
        $callback_query = $output['callback_query'];
        $data = $callback_query['data'];
        $message_id = ['callback_query']['message']['message_id'];
        $chat_id_in = $callback_query['message']['chat']['id'];
         switch($message) {
             case '/start':
             $inline_button1 = array("text"=>"Website","url"=>"http://google.com");
             $inline_button2 = array("text"=>"test","callback_data"=>'/test');
             $inline_keyboard = [[$inline_button1,$inline_button2]];
             $keyboard=array("inline_keyboard"=>$inline_keyboard);
             $replyMarkup = json_encode($keyboard);
              sendMessage($chat_id, "Hello", $replyMarkup);
             break;
             case '/help':
             $keyboard = array(array("Cancel","Go Ahead","test"));
   $resp = array("keyboard" => $keyboard,"resize_keyboard" => true,"one_time_keyboard" => true);
   $reply_ = json_encode($resp);
             break;
             default:
             sendMessage($chat_id,"$Thanks",$replyMarkup);
         }
        switch($data){
            case '/test':
            sendMessage($chat_id_in, "Coming Soon .....");
            break;
        }

Thanks


问:
How to remove space between elements in a string using xslt 1.0
I am trying to remove space between 2 elements in an XML using xslt. I initially converted my xml to string using content-as-a-string() function. This helped me to remove the indentation of the xml. However there are single spaces between each element as given below. The requirement is to remove the spaces between
> <.

```<code><Employee> <EmployeeName>ABC</EmployeeName> <EmployeeID>123</EmployeeID> <EmployeeDate>11/13/2015</EmployeeDate> </Employee>
</code>```

The output i need is as below:

```<code><Employee><EmployeeName>ABC</EmployeeName><EmployeeID>123</EmployeeID><EmployeeDate>11/13/2015</EmployeeDate></Employee>
</code>```

Any help in getting the correct XSLT is appreciated. Also I can use only xslt 1.0 version.
Regards
Anooja

答:
A simple identity transform plus a template that matches text nodes and applies normalize-space():

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="text()"><xsl:value-of select="normalize-space(.)"/> </xsl:template>
</xsl:stylesheet>
</code>```

Note that this will normalize spaces in ALL text nodes.

Body:
I am trying to remove space between 2 elements in an XML using xslt. I initially converted my xml to string using content-as-a-string() function. This helped me to remove the indentation of the xml. However there are single spaces between each element as given below. The requirement is to remove the spaces between
> <.

<Employee> <EmployeeName>ABC</EmployeeName> <EmployeeID>123</EmployeeID> <EmployeeDate>11/13/2015</EmployeeDate> </Employee>

The output i need is as below:

<Employee><EmployeeName>ABC</EmployeeName><EmployeeID>123</EmployeeID><EmployeeDate>11/13/2015</EmployeeDate></Employee>

Any help in getting the correct XSLT is appreciated. Also I can use only xslt 1.0 version.
Regards
Anooja

Body:
A simple identity transform plus a template that matches text nodes and applies normalize-space():

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="text()"><xsl:value-of select="normalize-space(.)"/> </xsl:template>
</xsl:stylesheet>

Note that this will normalize spaces in ALL text nodes.


问:
Centos6 - Apache | Subdomains Not Working
Ok, so I'm having some trouble with apache on my CentOS 6 (64bit) Webserver.

Whenever I load http://myserver.com/sub, it works perfectly and loads the page in /var/www/html/sub.

For some reason, when loading http://sub.myserver.com, it loads the page in /var/www/html, rather than /var/www/html/sub.

Also, my DNS name servers are ran on the same vps. Here are the records in the zone file:

```<code>; Mapping

@               IN  A               127.0.0.1
www             IN  A               127.0.0.1
</code>```

Is there a problem with my setup or do I need to edit some configurations?

Thanks.

答:
On my server, I have set a virtual host to get subdomains to work. I believe that apache doesn't know where to send the subdomain.domain.tld request if you don't have the virtual host set up for it so it just sends it to the same place as primarydomainl.tld requests are going.

You have to set up virtual hosts in your apache configuration files. There are several way to do it, but I personally decided to just put it into the httpd.conf file.

If you're on centos then it will be in /etc/httpd/conf/httpd.conf
On ubuntu it's in /etc/apache2/ somewhere, though I'm not completely sure of the whole path and don't have an ubuntu machine spun up atm to check.

Here's an example of what's currently working properly on my server:

```<code><VirtualHost *:80>
        ServerName primarydomain.tld
        ServerAlias www.primarydomain.tld
        DocumentRoot /var/www/html
        <Directory "/var/www/html">
                allow from all
                Options +Indexes
        </Directory>
</VirtualHost>

<VirtualHost *:80>
        ServerName      subdomain.primarydomain.tld
        DocumentRoot    /var/www/subdomain
        <Directory "/var/www/subdomain">
                allow from all
                Options +Indexes
        </Directory>
</VirtualHost>
</code>```

You'll also need to make sure you have A and CNAME records setup:

A subdomain.primarydomain.tld ipaddress
CNAME *.subdomain.primarydomain.tld subdomain.primarydomain.tld

Body:
Ok, so I'm having some trouble with apache on my CentOS 6 (64bit) Webserver.

Whenever I load http://myserver.com/sub, it works perfectly and loads the page in /var/www/html/sub.

For some reason, when loading http://sub.myserver.com, it loads the page in /var/www/html, rather than /var/www/html/sub.

Also, my DNS name servers are ran on the same vps. Here are the records in the zone file:

; Mapping

@               IN  A               127.0.0.1
www             IN  A               127.0.0.1

Is there a problem with my setup or do I need to edit some configurations?

Thanks.

Body:
On my server, I have set a virtual host to get subdomains to work. I believe that apache doesn't know where to send the subdomain.domain.tld request if you don't have the virtual host set up for it so it just sends it to the same place as primarydomainl.tld requests are going.

You have to set up virtual hosts in your apache configuration files. There are several way to do it, but I personally decided to just put it into the httpd.conf file.

If you're on centos then it will be in /etc/httpd/conf/httpd.conf
On ubuntu it's in /etc/apache2/ somewhere, though I'm not completely sure of the whole path and don't have an ubuntu machine spun up atm to check.

Here's an example of what's currently working properly on my server:

<VirtualHost *:80>
        ServerName primarydomain.tld
        ServerAlias www.primarydomain.tld
        DocumentRoot /var/www/html
        <Directory "/var/www/html">
                allow from all
                Options +Indexes
        </Directory>
</VirtualHost>

<VirtualHost *:80>
        ServerName      subdomain.primarydomain.tld
        DocumentRoot    /var/www/subdomain
        <Directory "/var/www/subdomain">
                allow from all
                Options +Indexes
        </Directory>
</VirtualHost>

You'll also need to make sure you have A and CNAME records setup:

A subdomain.primarydomain.tld ipaddress
CNAME *.subdomain.primarydomain.tld subdomain.primarydomain.tld


问:
how to make rails external database calls?
So i'd like to be able to add an external database to my config/database.yml   Then model one table from it.

Is this possible? I haven't been able to figure out how.

"Connection to multiple databases in different models

Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection. For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection and Course and all of its subclasses will use this connection instead.

This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool. "

答:
First, define the connection information in database.yml:

```<code>my_external_db:
  adapter: mysql
  username: ...
  ....
</code>```

Then, create the model and connect it to the external db

```<code>class MyExternalModel < ActiveRecord::Base
  establish_connection(:my_external_db)
  set_table_name 'my_external_table'
end
</code>```

Body:
First, define the connection information in database.yml:

my_external_db:
  adapter: mysql
  username: ...
  ....

Then, create the model and connect it to the external db

class MyExternalModel < ActiveRecord::Base
  establish_connection(:my_external_db)
  set_table_name 'my_external_table'
end


问:
Partitioning Data in 'R' based on data size
I'm currently working on a program that analyzes leaf area and compares that to the position of the leaf within the cluster (i.e. is it the first leaf, 3rd, last. etc.) and am analyzing the relationship between the position, area, mass, and more. I have a database of approximately 5,000 leaves, and 1,000 clusters and that's where the problem arises.

Clusters come in different numbers, most have 5 leaves, but some have 2, 8, or anywhere in-between. I need a way to separate the clusters by number in the cluster so that the program isn't treating clusters with 3 leaves the same as clusters with 7. My .csv has each leaf individually entered so simply manually input different sets isn't possible.

I'm rather new at 'R' so I might be missing an obvious skill here but any help would be greatly appreciated. I also understand this is rather confusing so please feel free to reply with clarifying questions.

Thanks in advance.

答:
If I understand the question correctly, it sounds like you want to calculate things based on some defined group (in your case clusterPosition?). One way to do this with dplyr is to use group_by with summarize or mutate.  The later keeps all the rows in your original data set and simply adds a new column to it, the former aggregates like rows and returns a summary statistic for each unique grouped variable.

As an example, if your data looks something like this:

df <- data.frame(leafArea = c(2.0, 3.0, 4.0, 5.0, 6.0),
 cluster = c(1, 2, 1, 2, 3), clusterPosition = c(1, 1, 2, 2, 1))

To get the mean and standard deviation for each unique clusterPosition you would do something like the below, this returns one row for each unique clusterPosition.

```<code>library(dplyr)
df %>% group_by(clusterPosition) %>% summarize(meanArea = mean(leafArea), sdArea = sd(leafArea))
</code>```

If you want to compare each unique leaf to some characteristic of it's clusterPosition, ie you want to preserve all the individual rows in your original dataset, you can use mutate instead of summarize.

```<code>library(dplyr)
df %>% group_by(clusterPosition) %>% mutate(meanPositionArea = mean(leafArea), diffMean = leafArea - meanPositionArea)
</code>```

Body:
If I understand the question correctly, it sounds like you want to calculate things based on some defined group (in your case clusterPosition?). One way to do this with dplyr is to use group_by with summarize or mutate.  The later keeps all the rows in your original data set and simply adds a new column to it, the former aggregates like rows and returns a summary statistic for each unique grouped variable.

As an example, if your data looks something like this:

df <- data.frame(leafArea = c(2.0, 3.0, 4.0, 5.0, 6.0),
 cluster = c(1, 2, 1, 2, 3), clusterPosition = c(1, 1, 2, 2, 1))

To get the mean and standard deviation for each unique clusterPosition you would do something like the below, this returns one row for each unique clusterPosition.

library(dplyr)
df %>% group_by(clusterPosition) %>% summarize(meanArea = mean(leafArea), sdArea = sd(leafArea))

If you want to compare each unique leaf to some characteristic of it's clusterPosition, ie you want to preserve all the individual rows in your original dataset, you can use mutate instead of summarize.

library(dplyr)
df %>% group_by(clusterPosition) %>% mutate(meanPositionArea = mean(leafArea), diffMean = leafArea - meanPositionArea)


问:
Virtual Device Configuration: "A system image must be selected to continue"
I have installed the newer Android Studio on my new Asus computer, but
when I try to run the emulator via the android virtual device manager
and create a virtual device, I get an error every time like this:

答:
I had a similar problem.

Make sure you are connected to the internet.

When you select a System Image, press enter (click or double-click
didn't work for me). Wait for Android Studio to download missing
components.

Now, if you select the System Image the next button would be active. Click on next to continue creating your virtual device

Please note that the download could take a very long time. You may wish to try using HTTP by unchecking use secure connection like this

File->Settings->Appearance and Behavior->System Settings->Updates->then click on Use Secure Connection


问:
Mock DataAccess methods that uses Enterprise Library to return IDataReader
I was given a task to rewrite an Api and corresponding unit tests. I am still quite new to unit testing and so I am struggling to write the test code for a data access class that uses Enterprise Library. Here is the code:

```<code>namespace TOS_Landside_BL.Classes {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using Microsoft.Practices.EnterpriseLibrary.Data;
  using Interfaces;

  public class DataAccess : IDataAccess {
    private readonly Database yasDB;

    public DataAccess () {
      DatabaseProviderFactory factory = new DatabaseProviderFactory ();
      DatabaseFactory.SetDatabaseProviderFactory (factory, false);
      yasDB = factory.Create ("AutomationDB");
    }

    // caller is responsible for closing the reader.
    public IDataReader ExecuteReaderForStoredProcedure (string cmdName, List<DbParameter> parameters = null) {
      DbCommand cmd = yasDB.GetStoredProcCommand (cmdName);
      if (parameters != null)
        cmd.Parameters.AddRange (parameters.ToArray ());

      return yasDB.ExecuteReader (cmd);
    }

    public IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List <DbParameter> parameters = null) {
      DbCommand cmd = yasDB.GetSqlStringCommand (cmdScript);
      if (parameters != null) {
        cmd.Parameters.AddRange(parameters.ToArray());
      }

      return yasDB.ExecuteReader (cmd);
    }
  }
}
</code>```

Here is the interface IDataAccess:

```<code>namespace TOS_Landside_BL.Interfaces {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;

  public interface IDataAccess {
    IDataReader ExecuteReaderForStoredProcedure (string cmdName, List<DbParameter> parameters = null);
    IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List <DbParameter> parameters = null);
  }
}
</code>```

And here is a sample on how I would call it:

```<code>namespace TOS_Landside_BL.Data {
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using System.Data.SqlClient;
  using System.Linq;
  using Classes;
  using Enums;
  using Factories;
  using Interfaces;

  public class LandsideTransactionDataProvider {
    private readonly IDataAccess _dataAccess;

    public LandsideTransactionDataProvider (IDataAccess dataAccess = null)
    {
      _dataAccess = dataAccess ?? new DataAccess ();
    }

    public LandsideTransaction GetLandsideTransaction (string keyword, bool isKioskID = false)
    {
      var strCmd = isKioskID ? "proc_get_landside_transaction_by_kiosk_id" : "[LandSide].[GetLandsideTransactionDetail]";
      var parameters = new List <DbParameter> () {
        new SqlParameter ("@keyword", SqlDbType.NVarChar, 11) {Value = keyword}
      };

      using (var reader = _dataAccess.ExecuteReaderForStoredProcedure (strCmd, parameters)) {
        return reader.Read () ? reader.CreateLandSideTransaction () : null;
      }
    }
  }
</code>```

In the SetUp method of my test class, I tried this:

```<code>var dataAccess = new Mock<IDataAccess>();
dataAccess.SetUp(d => d.ExecuteReaderFromStoredProcedure(null, null)).Returns(IDataReader);
</code>```

but it won't accept IDataReader or any concrete data reader classes.

Please advise as to what I'm doing wrong, and any suggestion would really be appreciated.  Thank you.

答:
You can create a mock for the IDataReader and set it up for the test as well.

```<code>var reader = new Mock<IDataReader>();
//..Setup the reader as expected for the test.
//Like reader.Read(), etc.

var dataAccess = new Mock<IDataAccess>();
dataAccess
    .Setup(_ => _.ExecuteReaderForStoredProcedure(It.IsAny<string>(), It.IsAny<List<DbParameter>>()))
    .Returns(reader.Object);//return mocked reader.
</code>```

Body:
I was given a task to rewrite an Api and corresponding unit tests. I am still quite new to unit testing and so I am struggling to write the test code for a data access class that uses Enterprise Library. Here is the code:

namespace TOS_Landside_BL.Classes {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using Microsoft.Practices.EnterpriseLibrary.Data;
  using Interfaces;

  public class DataAccess : IDataAccess {
    private readonly Database yasDB;

    public DataAccess () {
      DatabaseProviderFactory factory = new DatabaseProviderFactory ();
      DatabaseFactory.SetDatabaseProviderFactory (factory, false);
      yasDB = factory.Create ("AutomationDB");
    }

    // caller is responsible for closing the reader.
    public IDataReader ExecuteReaderForStoredProcedure (string cmdName, List<DbParameter> parameters = null) {
      DbCommand cmd = yasDB.GetStoredProcCommand (cmdName);
      if (parameters != null)
        cmd.Parameters.AddRange (parameters.ToArray ());

      return yasDB.ExecuteReader (cmd);
    }

    public IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List <DbParameter> parameters = null) {
      DbCommand cmd = yasDB.GetSqlStringCommand (cmdScript);
      if (parameters != null) {
        cmd.Parameters.AddRange(parameters.ToArray());
      }

      return yasDB.ExecuteReader (cmd);
    }
  }
}

Here is the interface IDataAccess:

namespace TOS_Landside_BL.Interfaces {
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;

  public interface IDataAccess {
    IDataReader ExecuteReaderForStoredProcedure (string cmdName, List<DbParameter> parameters = null);
    IDataReader ExecuteReaderForSqlStringCommand (string cmdScript, List <DbParameter> parameters = null);
  }
}

And here is a sample on how I would call it:

namespace TOS_Landside_BL.Data {
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Common;
  using System.Data.SqlClient;
  using System.Linq;
  using Classes;
  using Enums;
  using Factories;
  using Interfaces;

  public class LandsideTransactionDataProvider {
    private readonly IDataAccess _dataAccess;

    public LandsideTransactionDataProvider (IDataAccess dataAccess = null)
    {
      _dataAccess = dataAccess ?? new DataAccess ();
    }

    public LandsideTransaction GetLandsideTransaction (string keyword, bool isKioskID = false)
    {
      var strCmd = isKioskID ? "proc_get_landside_transaction_by_kiosk_id" : "[LandSide].[GetLandsideTransactionDetail]";
      var parameters = new List <DbParameter> () {
        new SqlParameter ("@keyword", SqlDbType.NVarChar, 11) {Value = keyword}
      };

      using (var reader = _dataAccess.ExecuteReaderForStoredProcedure (strCmd, parameters)) {
        return reader.Read () ? reader.CreateLandSideTransaction () : null;
      }
    }
  }

In the SetUp method of my test class, I tried this:

var dataAccess = new Mock<IDataAccess>();
dataAccess.SetUp(d => d.ExecuteReaderFromStoredProcedure(null, null)).Returns(IDataReader);

but it won't accept IDataReader or any concrete data reader classes.

Please advise as to what I'm doing wrong, and any suggestion would really be appreciated.  Thank you.

Body:
You can create a mock for the IDataReader and set it up for the test as well.

var reader = new Mock<IDataReader>();
//..Setup the reader as expected for the test.
//Like reader.Read(), etc.

var dataAccess = new Mock<IDataAccess>();
dataAccess
    .Setup(_ => _.ExecuteReaderForStoredProcedure(It.IsAny<string>(), It.IsAny<List<DbParameter>>()))
    .Returns(reader.Object);//return mocked reader.


问:
Is it possible to optimize the query in which nodes have an optional relationship?
There are organizations and applications within the software system. User actions generate log records. Log records (green) do belong to organizations (red) and may belong to applications (pink).

Trying to filter the nodes by application and organization (both params are optional), I created the following query:

```<code>MATCH
(log0:Log)-[:GENERATED_IN]->(org:Organization),
(app:Application)<-[:GENERATED_IN]-(log1:Log)-[:GENERATED_IN]->(org:Organization)
WHERE ($orgID IS NULL
    OR ID(org)=$orgID)
AND ($appID IS NULL
    OR ID(app)=$appID)
RETURN DISTINCT
    CASE $appID
        WHEN null THEN log0
        ELSE log1
    END
    CASE $appID
    WHEN null then log1
    ELSE null
    END
</code>```

I use 2 CASE expressions because Cypher returns only nodes which do not have relationship to :Organization as log0 (though I expected all :Log nodes to be returned) and because there is no possibility to return several variables from the CASE, i. e.

```<code>RETURN DISTINCT
    CASE $appID
        WHEN null THEN log0, log1
        ELSE log1
</code>```

This seems not to be a nicely readable and maintainable code (esp. keeping in mind there are a lot of other filtering params I currently excluded for simplicity), so is there any possibility to optimize this query?

答:
Your query can return a map containing 1 or 2 Log nodes, like this:

```<code>MATCH
  (log0:Log)-[:GENERATED_IN]->(org:Organization),
  (app:Application)<-[:GENERATED_IN]-(log1:Log)-[:GENERATED_IN]->(org)
WHERE ($orgID IS NULL OR ID(org)=$orgID)
  AND ($appID IS NULL OR ID(app)=$appID)
RETURN DISTINCT
  CASE $appID WHEN NULL
    THEN {a: log0, b: log1}
    ELSE {a: log1}
  END AS result;
</code>```

Body:
There are organizations and applications within the software system. User actions generate log records. Log records (green) do belong to organizations (red) and may belong to applications (pink).

Trying to filter the nodes by application and organization (both params are optional), I created the following query:

MATCH
(log0:Log)-[:GENERATED_IN]->(org:Organization),
(app:Application)<-[:GENERATED_IN]-(log1:Log)-[:GENERATED_IN]->(org:Organization)
WHERE ($orgID IS NULL
    OR ID(org)=$orgID)
AND ($appID IS NULL
    OR ID(app)=$appID)
RETURN DISTINCT
    CASE $appID
        WHEN null THEN log0
        ELSE log1
    END
    CASE $appID
    WHEN null then log1
    ELSE null
    END

I use 2 CASE expressions because Cypher returns only nodes which do not have relationship to :Organization as log0 (though I expected all :Log nodes to be returned) and because there is no possibility to return several variables from the CASE, i. e.

RETURN DISTINCT
    CASE $appID
        WHEN null THEN log0, log1
        ELSE log1

This seems not to be a nicely readable and maintainable code (esp. keeping in mind there are a lot of other filtering params I currently excluded for simplicity), so is there any possibility to optimize this query?

Body:
Your query can return a map containing 1 or 2 Log nodes, like this:

MATCH
  (log0:Log)-[:GENERATED_IN]->(org:Organization),
  (app:Application)<-[:GENERATED_IN]-(log1:Log)-[:GENERATED_IN]->(org)
WHERE ($orgID IS NULL OR ID(org)=$orgID)
  AND ($appID IS NULL OR ID(app)=$appID)
RETURN DISTINCT
  CASE $appID WHEN NULL
    THEN {a: log0, b: log1}
    ELSE {a: log1}
  END AS result;


问:
generic call of class in c#
```<code>SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
</code>```

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

```<code>if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...
</code>```

i want to make something like

```<code>(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...
</code>```

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.

答: You should make an ISearchQueryManager interface with implementations for each language, then use a Dictionary<string, ISearchQueryManager> to get the implementation for the desired language.

Title: generic call of class in c#

Body:
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);

is it possible to get SlovenianSearchQueryManager class by concatinating HttpContext.Current.Session["lang_name"] and "SearchQueryManager";

HttpContext.Current.Session["lang_name"] is Slovenian so together is SlovenianSearchQueryManager

next time

HttpContext.Current.Session["lang_name"] is German so together is
GermanSearchQueryManager

i try to make this generic instead of making

if (HttpContext.Current.Session["lang_name"] == "Slovenian)
{
SlovenianSearchQueryManager.ApplySloveniaQueries(rawQuery, page, pageSize, orderBy, out count);
}
else ...

i want to make something like

(HttpContext.Current.Session["lang_name"] + "SearchQueryManager").ApplySloveniaQueries(...

is this even possible to make something like this and the type SlovenianSearchQueryManager for example exists, it's in a different class library.


问:
How to get rid of missing directories in SVN commit?
When I try to commit SVN reports about 10 old directories as missing.

I've deleted these directories quite a while ago. I've tried to create the same directory again but then SVN reports them as "obstructed" and I can't delete them.

These directories are not in the repository either. They are not affecting my commits directly but TortoiseSVN showing these folders in commit dialog. For sake for keeping my commit dialog clean to see other changes easily I want to get rid of these missing directories.

Is there anyway to solve this other than a clean checkout?

--
It's in the comments of accepted answer for future reference this is the solution which worked for me:

I've created the directory first locally then force to delete and it resolves the problem.

答:
I ran into similar problem and wanted to share my experience.

I used Tortoise SVN.

I had a folder that I deleted and that wasn't on the SVN either, but was showing up when I try to commit the folder was showing up in the list marked as missing and it's subfolders and subfiles were also showing up as deleted or missing.

I did the following:

create a new folder where the original folder was

give the folder the same name as the folder that was marked as missing

right click on that folder and then TortoiseSVN -> Undo Add

And, the problem was gone.


答:
I would recommend making two changes.

First, make all of your "SearchQueryManager" instances derive from a common interface (or base class), such as ISearchQueryManager.

Second, make a Dictionary<string, ISearchQueryManager>, and use it to lookup the appropriate one based on your type.

You could then do:

```<code> ISearchQueryManager manager;
 if (!managers.TryGetValue(HttpContext.Current.Session["lang_name"], out manager))
 {
     // Unknown language - handle this!
 }
 else
 {
       manager.ApplyQuery(...);
 }
</code>```

Title: generic call of class in c#

Body:
I would recommend making two changes.

First, make all of your "SearchQueryManager" instances derive from a common interface (or base class), such as ISearchQueryManager.

Second, make a Dictionary<string, ISearchQueryManager>, and use it to lookup the appropriate one based on your type.

You could then do:

 ISearchQueryManager manager;
 if (!managers.TryGetValue(HttpContext.Current.Session["lang_name"], out manager))
 {
     // Unknown language - handle this!
 }
 else
 {
       manager.ApplyQuery(...);
 }


问:
SAS: What's the optimal way to find the sum of a column by another column?
I want to find out the best way to perform a group-by in SAS so I can perform some benchmarks. The simplest two ways I can think of is Proc SQL and Proc means. Here is the example in proc sql

    proc sql noprint; /* took 6 mins */
    create table summ as select
            id,
            sum(val)
        from
            randint
        group by
            id
        ;
    quit;

I think there are ways to make this run fast

use sasfile command to load the data into memory first

create an index on id

Are there any other options I can use? Any SAS options I should turn on to make this run as fast as possible? I am not tied to proc sql nor proc means, so if there are faster ways then I would love to know about it!!!

My set up code is as below

```<code>options macrogen;
options obs=max sortsize=max source2 FULLSTIMER;
options minoperator SASTRACE=',,,d' SASTRACELOC=SASLOG;
options compress = binary NOSTSUFFIX;
options noxwait noxsync;
options LRECL=32767;

proc fcmp outlib=work.myfunc.sample;
    function RandBetween(min, max);
        return (min + floor((1 + max - min) * rand("uniform")));
    endsub;
run;

options cmplib=work.myfunc;

data RandInt;
    do i = 1 to 250000000;
        id = RandBetween(1, 2500000);
        val = rand("uniform");
        output;
    end;
    drop i;
run;
</code>```

My SAS comparison macros are as below

```<code>%macro sasbench(dosql = N); %macro _; %mend;
    %if &dosql. = Y %then %do;
        proc sql noprint; /* took 6 mins */
            create table summ as select
                id,
                sum(val)
            from
                randint
            group by
                id
            ;
        quit;
    %end;

    proc means data=randint  sum noprint;
        var val ;
        class id;
        output out = summmeans(drop=_type_ _freq_) sum = /autoname;
    run;
%mend;

%sasbench();
/**/
/*sasfile randint load;*/
/*%sasbench();*/
/*sasfile randint close;*/

proc datasets lib=work;
    modify randint;
    INDEX CREATE id / nomiss;
run;

%sasbench();
</code>```

答:
The best answer varies dramatically by the application.  In your example, PROC SQL at least on my machine significantly outperforms PROC MEANS, but there are plenty of cases where it will not do so.  It's able to in this case because it's building hash tables behind the scenes, more than likely, which are quite fast - a single pass through the data is all that's needed.

You certainly could speed things up by putting your full dataset into memory with SASFILE, if you have room to store the whole thing.  You would have to have it in memory to begin with, though, more than likely; just reading it into memory for this purpose alone wouldn't really help since you're doing that read anyway.

As Richard notes, there are a bunch of ways to do this.  I think PROC SQL will often be the fastest or similar to the fastest in simple cases, both because it's multithreaded (as opposed to data step being single threaded) and because it's got a fast hash table backend.

PROC MEANS is also usually going to be competitive, the case you show in the example is almost a worst case for it since it's got a huge number of class variables so I think it may be creating a temporary table on disk.  It's also multithreaded. Reduce the class variable categories to 2500 instead of 2,500,000 and you get PROC MEANS a bit faster than PROC SQL (but within the margin of error).

Data step accumulation, either in a hash table or a DoW loop, will sometimes outperform both of the above, and sometimes not, again depending on the data.  Here it does outperform slightly.  The code for data step accumulation tends to be a bit more complex, which is why I'd usually discourage it unless the savings is substantial (having more code to maintain is worse, typically).  PROC MEANS and PROC SQL require less maintenance and less to understand.  But in applications where performance is critical and these solutions happen to be superior, it may be worth it to go this route, especially if the data step is helpful.  Of course, the hash table method is limited to fitting the results in memory, though usually that's manageable.

Ultimately, I would encourage you to use whatever method is easiest to maintain but still gives sufficient performance; and when possible try to be self consistent with other code.  If most of your code is in SQL, that is probably fine.  SASFILE and indexes probably won't be needed, unless you're doing more complicated things than you present above.  Summation is actually more work than I/O in many cases.  Don't overcomplicate it, ultimately: programmer hours and difficulty of QA is something that should trump basic performance, unless you're talking several hours' difference.  And if you are, then just run tests on your actual use case and see what works best.

Body:
I want to find out the best way to perform a group-by in SAS so I can perform some benchmarks. The simplest two ways I can think of is Proc SQL and Proc means. Here is the example in proc sql

    proc sql noprint; /* took 6 mins */
    create table summ as select
            id,
            sum(val)
        from
            randint
        group by
            id
        ;
    quit;

I think there are ways to make this run fast

use sasfile command to load the data into memory first

create an index on id

Are there any other options I can use? Any SAS options I should turn on to make this run as fast as possible? I am not tied to proc sql nor proc means, so if there are faster ways then I would love to know about it!!!

My set up code is as below

options macrogen;
options obs=max sortsize=max source2 FULLSTIMER;
options minoperator SASTRACE=',,,d' SASTRACELOC=SASLOG;
options compress = binary NOSTSUFFIX;
options noxwait noxsync;
options LRECL=32767;

proc fcmp outlib=work.myfunc.sample;
    function RandBetween(min, max);
        return (min + floor((1 + max - min) * rand("uniform")));
    endsub;
run;

options cmplib=work.myfunc;

data RandInt;
    do i = 1 to 250000000;
        id = RandBetween(1, 2500000);
        val = rand("uniform");
        output;
    end;
    drop i;
run;

My SAS comparison macros are as below

%macro sasbench(dosql = N); %macro _; %mend;
    %if &dosql. = Y %then %do;
        proc sql noprint; /* took 6 mins */
            create table summ as select
                id,
                sum(val)
            from
                randint
            group by
                id
            ;
        quit;
    %end;

    proc means data=randint  sum noprint;
        var val ;
        class id;
        output out = summmeans(drop=_type_ _freq_) sum = /autoname;
    run;
%mend;

%sasbench();
/**/
/*sasfile randint load;*/
/*%sasbench();*/
/*sasfile randint close;*/

proc datasets lib=work;
    modify randint;
    INDEX CREATE id / nomiss;
run;

%sasbench();


问:
MSBuild - Get a list of projects by a condition
I have the following MSBuild task which runs the "CustomBuildTask" task for every referenced project in parallel:

```<code><Target Name="CustomBuild" AfterTargets="Build">
    <ItemGroup>
      <CustomProjectReferences Include="@(ProjectReference)" />
    </ItemGroup>
    <MSBuild
      Targets="CustomBuildTask"
      BuildInParallel="$(BuildInParallel)"
      Projects="@(CustomProjectReferences)"
      Condition="'@(CustomProjectReferences)' != ''"
      ContinueOnError="true">
    </MSBuild>
</Target>
</code>```

This seems to work fine. However is there a way I can improve this by filtering "CustomProjectReferences" on some condition. For example only select the projects which have the "CustomBuildTask" task defined or only select the ones with some property defined.

I'd appreciate the help as I'm looking to improve my build time. Thanks

答: As @stijn points out in his comment, the project files represented by the ProjectReference items would each have to be evaluated by MSBuild in order to know all of the targets and properties defined therein. This would likely not be worth the performance expense. However, you may be able to get the data you need without a huge performance hit by using the XmlPeek task. Depending on your needs, this might be sufficiently reliable for the scenario you suggest where you are checking for the presence a target, but only if that target would never be incorporated via an Import nor ever have a Condition attribute. The property scenario would be much more dicey, only working if you know the property will never be defined via an Import, never defined or updated inside a Target, and never have a Condition attribute. If you go down this road, a helpful piece of the puzzle will be Item Functions, e.g. WithMetadataValue.

Body:
I have the following MSBuild task which runs the "CustomBuildTask" task for every referenced project in parallel:

<Target Name="CustomBuild" AfterTargets="Build">
    <ItemGroup>
      <CustomProjectReferences Include="@(ProjectReference)" />
    </ItemGroup>
    <MSBuild
      Targets="CustomBuildTask"
      BuildInParallel="$(BuildInParallel)"
      Projects="@(CustomProjectReferences)"
      Condition="'@(CustomProjectReferences)' != ''"
      ContinueOnError="true">
    </MSBuild>
</Target>

This seems to work fine. However is there a way I can improve this by filtering "CustomProjectReferences" on some condition. For example only select the projects which have the "CustomBuildTask" task defined or only select the ones with some property defined.

I'd appreciate the help as I'm looking to improve my build time. Thanks


问:
Directing all mobile traffic to AMP pages on WordPress
I'm building a WooCommerce website and I'd like to know if I can force a redirect of all mobile traffic to the AMP pages of the shop. This is kind of a test as I have about 11 client websites running on regular responsive templates.

Would it be possible to force a redirect to AMP on mobile? And how can I exclude the checkout pages while doing this because I understand they're not converted at the moment

答:
This bit of htaccess code should do the trick for you.</p>

```<code>RewriteEngine On
RewriteCond %{REQUEST_URI} !/amp$ [NC]
RewriteCond %{HTTP_USER_AGENT} (android|blackberry|googlebot\-mobile|iemobile|iphone|ipod|\#opera\ mobile|palmos|webos) [NC]
RewriteRule ^([a-zA-Z0-9-]+)([\/]*)$ https://example.com/$1/amp [L,R=302]
</code>```

Body:
This bit of htaccess code should do the trick for you.

RewriteEngine On
RewriteCond %{REQUEST_URI} !/amp$ [NC]
RewriteCond %{HTTP_USER_AGENT} (android|blackberry|googlebot\-mobile|iemobile|iphone|ipod|\#opera\ mobile|palmos|webos) [NC]
RewriteRule ^([a-zA-Z0-9-]+)([\/]*)$ https://example.com/$1/amp [L,R=302]


问:
Get argument expression before evaluation
I'm trying to create an assert method in Javascript.  I've been struggling with arguments.callee.caller and friends for a while, but I can't find a way to reliably get the full text of the calling function and find which match in that text called the current function.

I want to be able to use my function like this:

```<code>var four = 5;
function calculate4() { return 6; }

assert(4 == 2 + 3);
assert(4 == four);
assert(4 == calculate4());
assert(4 != 3 && 2 < 1)
</code>```

and get output like this:

Assertion 4 == 2 + 3 failed.
Assertion 4 == four failed.
Assertion 4 == calculate4() failed.
Assertion 4 != 3 && 2

Right now, I can't get much beyond Assertion false failed. which isn't very useful...

I'd like to avoid passing in extra parameters (such as this) because I want to keep the assert code as clean as possible and because it will be typed many, many times. I don't really mind making it a string, but I'm concerned about issues of scoping when trying to eval() that string.  If I have no other options, or if my concerns are ill-founded, please say so.

I'm running this in an .hta application on Windows, so it's really jscript and I have full access to the filesystem, ActiveX etc. so system specific solutions are fine (as long as they don't require Firebug etc.).  However, I'd prefer a general solution.

答:
I ended up using the following function, which allows me to optionally duplicate the text of the assertion as a second argument.  It seemed simplest.

```<code>function assert(expression, message)
{
    if (!expression) {
        if (message + "" != "undefined" && message + "" != "") {
            document.write("<h2>Assertion ```" +
                            message +
                           "``` failed.</h2><br>");
        } else {
            document.write("<h2>Assertion failed.</h2><br>");
        }
    }
}
</code>```

Maybe that helps someone.  There are probably better methods available, but this worked for me.

Note that I've only been programming in Javascript for three days, so there's probably a number of improvements that could be made.

Body:
I'm trying to create an assert method in Javascript.  I've been struggling with arguments.callee.caller and friends for a while, but I can't find a way to reliably get the full text of the calling function and find which match in that text called the current function.

I want to be able to use my function like this:

var four = 5;
function calculate4() { return 6; }

assert(4 == 2 + 3);
assert(4 == four);
assert(4 == calculate4());
assert(4 != 3 && 2 < 1)

and get output like this:

Assertion 4 == 2 + 3 failed.
Assertion 4 == four failed.
Assertion 4 == calculate4() failed.
Assertion 4 != 3 && 2

Right now, I can't get much beyond Assertion false failed. which isn't very useful...

I'd like to avoid passing in extra parameters (such as this) because I want to keep the assert code as clean as possible and because it will be typed many, many times. I don't really mind making it a string, but I'm concerned about issues of scoping when trying to eval() that string.  If I have no other options, or if my concerns are ill-founded, please say so.

I'm running this in an .hta application on Windows, so it's really jscript and I have full access to the filesystem, ActiveX etc. so system specific solutions are fine (as long as they don't require Firebug etc.).  However, I'd prefer a general solution.

Body:
I ended up using the following function, which allows me to optionally duplicate the text of the assertion as a second argument.  It seemed simplest.

function assert(expression, message)
{
    if (!expression) {
        if (message + "" != "undefined" && message + "" != "") {
            document.write("<h2>Assertion <pre>" +
                            message +
                           "</pre> failed.</h2><br>");
        } else {
            document.write("<h2>Assertion failed.</h2><br>");
        }
    }
}

Maybe that helps someone.  There are probably better methods available, but this worked for me.

Note that I've only been programming in Javascript for three days, so there's probably a number of improvements that could be made.


问:
How to check if its a digit and repeat when its not
The code below just loops infinitely even with the break;. I'm trying to make it so if the user types something other than a number it asks again.

```<code>int x,y;
while(1)
{
    printf("x: ");
    scanf("%d",&x);
    printf("y: ");
    scanf("%d",&y);
    if(isdigit(x)&&isdigit(y))
    {
        break;
    }
}
printf("X: %d Y: %d",x,y);
</code>```

答: x and y will never be digits, because digits range from 0x30 to 0x39 (in the case of ascii encoding). You are reading them with the %d modifier, use the %c modifier instead.</p>

Body:
The code below just loops infinitely even with the break;. I'm trying to make it so if the user types something other than a number it asks again.

int x,y;
while(1)
{
    printf("x: ");
    scanf("%d",&x);
    printf("y: ");
    scanf("%d",&y);
    if(isdigit(x)&&isdigit(y))
    {
        break;
    }
}
printf("X: %d Y: %d",x,y);


问:
How to animate a Bootstrap toggle in Angular 2?
As you may now, Bootstrap toggles just change display: none to display: block and vice-versa. I've been reading the Angular 2 Animation Guide but it all seems to depend on a changing property on the component, when I just want to change based on the element's style.display property.

Am I thinking about this the wrong way, or how would I do this?

答:
As described in Angular Docs, you can use the void and * states to define transitions that animate the entering and leaving of elements:

Enter: void => *

  Leave: * => void

```<code>animations: [
   trigger('myAwesomeAnimation', [
      transition('void => *', [
        style({ opacity: 0 }),
        animate(1000)
      ]),
      transition('* => void', [
        animate(1000, style({opacity: 100}))
      ])
  ])
]
</code>```

HTML

```<code><ul>
  <li  @myAwesomeAnimation *ngFor="let i of list">
   {{ i }}
  </li>
</ul>
</code>```

Demo Punkr

Body:
As described in Angular Docs, you can use the void and * states to define transitions that animate the entering and leaving of elements:

Enter: void => *

  Leave: * => void

animations: [
   trigger('myAwesomeAnimation', [
      transition('void => *', [
        style({ opacity: 0 }),
        animate(1000)
      ]),
      transition('* => void', [
        animate(1000, style({opacity: 100}))
      ])
  ])
]

HTML

<ul>
  <li  @myAwesomeAnimation *ngFor="let i of list">
   {{ i }}
  </li>
</ul>

Demo Punkr


问:
java.lang.NoSuchFieldError: USE_DEFAULTS
So while writing and testing the trial code(Java) of twilio for sending the SMS iam getting the above error. here is the code below:

```<code>import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class Sms {
    public static final String ACCOUNT_SID = "ACb519b651243a021f900be0b0d387edc9";
    public static final String AUTH_TOKEN = "I_CAN'T_SHARE";

    public static void main(String[] args) {

        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        Message message = Message.creator(new PhoneNumber("+19916022xxx"),
                new PhoneNumber("+18082010XXX"),
                "Sent from a Twilio Trial Account").create(); // the number in the from phone number field is provided by twilio

        System.out.println(message.getSid());
    }

}
</code>```

exception stack trace:-

```<code>Exception in thread "main" java.lang.NoSuchFieldError: USE_DEFAULTS
    at com.fasterxml.jackson.annotation.JsonInclude$Value.<clinit>(JsonInclude.java:247)
    at com.fasterxml.jackson.databind.cfg.ConfigOverrides.<init>(ConfigOverrides.java:53)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:564)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:480)
    at com.twilio.http.TwilioRestClient.<init>(TwilioRestClient.java:31)
    at com.twilio.http.TwilioRestClient.<init>(TwilioRestClient.java:6)
    at com.twilio.http.TwilioRestClient$Builder.build(TwilioRestClient.java:104)
    at com.twilio.Twilio.getRestClient(Twilio.java:122)
    at com.twilio.base.Creator.create(Creator.java:45)
    at sms.Sms.main(Sms.java:17)
</code>```

答:
Twilio developer evangelist here.

The Twilio Java library is usable without maven you just have to ensure you have the correct dependencies. The documentation lists two ways of using the jar without a build tool.

You can either download a jar with the dependencies included, called twilio-7.x.x-with-dependencies.jar, from the maven repo.

Or, you can get it without dependencies by downloading twilio-7.x.x.jar and getting the dependencies which are listed in the projects pom.xml file.

Let me know if that helps at all.

Body:
So while writing and testing the trial code(Java) of twilio for sending the SMS iam getting the above error. here is the code below:

import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;

public class Sms {
    public static final String ACCOUNT_SID = "ACb519b651243a021f900be0b0d387edc9";
    public static final String AUTH_TOKEN = "I_CAN'T_SHARE";

    public static void main(String[] args) {

        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);

        Message message = Message.creator(new PhoneNumber("+19916022xxx"),
                new PhoneNumber("+18082010XXX"),
                "Sent from a Twilio Trial Account").create(); // the number in the from phone number field is provided by twilio

        System.out.println(message.getSid());
    }

}

exception stack trace:-

Exception in thread "main" java.lang.NoSuchFieldError: USE_DEFAULTS
    at com.fasterxml.jackson.annotation.JsonInclude$Value.<clinit>(JsonInclude.java:247)
    at com.fasterxml.jackson.databind.cfg.ConfigOverrides.<init>(ConfigOverrides.java:53)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:564)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:480)
    at com.twilio.http.TwilioRestClient.<init>(TwilioRestClient.java:31)
    at com.twilio.http.TwilioRestClient.<init>(TwilioRestClient.java:6)
    at com.twilio.http.TwilioRestClient$Builder.build(TwilioRestClient.java:104)
    at com.twilio.Twilio.getRestClient(Twilio.java:122)
    at com.twilio.base.Creator.create(Creator.java:45)
    at sms.Sms.main(Sms.java:17)