问:
How send parameter to a url without using form in php?
dear all,
I need to send parameters to a URL without using form in php and get value from that page.We can easily send parameters using form like this:

```<code><html>
    <form action="http://..../abc.php" method="get">
    <input name="id" type="text" />
    <input name="name" type="text"/>
    <input  type="submit" value="press" />
    </form>
</html>
</code>```

But i already have value like this

```<code>     <?php
       $id="123";
       $name="blahblah";
      ?>
</code>```

Now i need to send values to http://..../abc.php without using form.when the 2 value send to abc.php link then it's show a value OK.Now i have to collect the "OK" msg from abc.php and print on my current page.
i need to auto execute the code.when user enter into the page those value automatically send to a the url.So i can't use form or href. because form and href need extra one click.

Is their any kind heart who can help me to solve this issue?

答:
```<code><?php

$base = 'http://example.com/abc.php';
$id="123";
$name="blahblah";

$data = array(
    'id' => $id,
    'name' => $name,
);

$url = $base . '?' . http_build_query($data);

header("Location: $url");
exit;
</code>```

Body:
dear all,
I need to send parameters to a URL without using form in php and get value from that page.We can easily send parameters using form like this:

    <form action="http://..../abc.php" method="get">
    <input name="id" type="text" />
    <input name="name" type="text"/>
    <input  type="submit" value="press" />
    </form>

But i already have value like this

     <?php
       $id="123";
       $name="blahblah";
      ?>

Now i need to send values to http://..../abc.php without using form.when the 2 value send to abc.php link then it's show a value OK.Now i have to collect the "OK" msg from abc.php and print on my current page.
i need to auto execute the code.when user enter into the page those value automatically send to a the url.So i can't use form or href. because form and href need extra one click.

Is their any kind heart who can help me to solve this issue?


来源: stackexchange

问:
Repeating background image
I want to put my picture in the background to take the entire screen but image is not repeating.

Screenshot

```<code><div id="backgrounddiv">
  <img id="background" src="http://i.imgur.com/nhQAcos.jpg">
</div>

#background {
    width:100%;
    height:100%;
    image-repeat: repeat;
}

#backgrounddiv {
    position: absolute;
    z-index:0;
    left:0;
    top:0;
    width:100%;
    height:100%
}
</code>```

答:
What you want to be using is background-repeat

The css syntax:

background-repeat: repeat|repeat-x|repeat-y|no-repeat|initial|inherit;

So it should look like this:

div {
    background-image:url(http://i.imgur.com/nhQAcos.jpg);
    background-repeat:initial;
}```
</div>
</div>
</p>

<p>or if you want it to repeat vertically...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
    background-image:url(http://i.imgur.com/nhQAcos.jpg);
    background-repeat:repeat-y;
}</code>```

ContentLicense: CC BY-SA 4.0

Title: Repeating background image

Body:
I want to put my picture in the background to take the entire screen but image is not repeating.

Screenshot

#background {
    width:100%;
    height:100%;
    image-repeat: repeat;
}

#backgrounddiv {
    position: absolute;
    z-index:0;
    left:0;
    top:0;
    width:100%;
    height:100%
}

Body:
What you want to be using is background-repeat

The css syntax:

background-repeat: repeat|repeat-x|repeat-y|no-repeat|initial|inherit;

So it should look like this:

div {
    background-image:url(http://i.imgur.com/nhQAcos.jpg);
    background-repeat:initial;
}

or if you want it to repeat vertically...

div {
    background-image:url(http://i.imgur.com/nhQAcos.jpg);
    background-repeat:repeat-y;
}

ContentLicense: CC BY-SA 3.0


问:
Webpack when to use `NoErrorsPlugin`?
After read the NoErrorsPlugin docs.

When there are errors while compiling this plugin skips the emitting phase (and recording phase), so there are no assets emitted that include errors.

Still, don't understand. How to use it?

I made a syntax error, but it seems there is nothing different before I enable NoErrorsPlugin.

答:
Since the webpack documentation concerning this remains sparse, let's look at the source code, https://github.com/webpack/webpack/tree/master/lib/NoErrorsPlugin.js:

let deprecationReported = false;

class NoErrorsPlugin {
 apply(compiler) {
  compiler.plugin("should-emit", (compilation) => {
   if(!deprecationReported) {
    compilation.warnings.push("webpack: Using NoErrorsPlugin is deprecated.\n" +
     "Use NoEmitOnErrorsPlugin instead.\n");
    deprecationReported = true;
   }
   if(compilation.errors.length > 0)
    return false;
  });
  compiler.plugin("compilation", (compilation) => {
   compilation.plugin("should-record", () => {
    if(compilation.errors.length > 0)
     return false;
   });
  });
 }
}

module.exports = NoErrorsPlugin;```

Ignore the deprecation aspect for now. This code is a webpack plugin as documented here: https://webpack.js.org/api/plugins. It uses the event hooks should-emit and compilation, which are documented here: https://webpack.js.org/api/plugins/compiler/#event-hooks. I could not find the should-record hook, but it seems to be about this: https://webpack.js.org/api/plugins/compilation/#record-compilation-records-.

So we can summarize: if there are errors, the plugin suppresses the emission of target code, and the "storing of info about the compilation". I verified this with a React app, by toggling the plugin in the webpack configuration and monitoring the time stamp of the output bundle.

About the deprecation: in the same GitHub directory, there is also a "NoEmitOnErrorsPlugin.js", which looks like "NoErrorsPlugin.js", only with no deprecation. So, if we want to suppress code emission, we should use the new plugin.

Title: Webpack when to use `NoErrorsPlugin`?

Body:
Since the webpack documentation concerning this remains sparse, let's look at the source code, https://github.com/webpack/webpack/tree/master/lib/NoErrorsPlugin.js:

let deprecationReported = false;

class NoErrorsPlugin {
 apply(compiler) {
  compiler.plugin("should-emit", (compilation) => {
   if(!deprecationReported) {
    compilation.warnings.push("webpack: Using NoErrorsPlugin is deprecated.\n" +
     "Use NoEmitOnErrorsPlugin instead.\n");
    deprecationReported = true;
   }
   if(compilation.errors.length > 0)
    return false;
  });
  compiler.plugin("compilation", (compilation) => {
   compilation.plugin("should-record", () => {
    if(compilation.errors.length > 0)
     return false;
   });
  });
 }
}

module.exports = NoErrorsPlugin;

Ignore the deprecation aspect for now. This code is a webpack plugin as documented here: https://webpack.js.org/api/plugins. It uses the event hooks should-emit and compilation, which are documented here: https://webpack.js.org/api/plugins/compiler/#event-hooks. I could not find the should-record hook, but it seems to be about this: https://webpack.js.org/api/plugins/compilation/#record-compilation-records-.

So we can summarize: if there are errors, the plugin suppresses the emission of target code, and the "storing of info about the compilation". I verified this with a React app, by toggling the plugin in the webpack configuration and monitoring the time stamp of the output bundle.

About the deprecation: in the same GitHub directory, there is also a "NoEmitOnErrorsPlugin.js", which looks like "NoErrorsPlugin.js", only with no deprecation. So, if we want to suppress code emission, we should use the new plugin.


问:
How can I programmatically change the background in Mac OS X?
How would I go about programmatically changing the desktop background in Mac OS X?  I'd like to use python, but I'm interested in any way possible.  Could I hook up to Terminal and call a certain command?</p>

答:
To add to Matt Miller's response: you can use subprocess.call() to execute a shell command as so:</p>

```<code>import subprocess
subprocess.call(["defaults", "write", "com.apple.Desktop", "background", ...])
</code>```

OwnerDisplayName: stalepretzel

Body:
To add to Matt Miller's response: you can use subprocess.call() to execute a shell command as so:

import subprocess
subprocess.call(["defaults", "write", "com.apple.Desktop", "background", ...])

OwnerDisplayName: Adam Rosenfield

ContentLicense: CC BY-SA 2.5


问:
Low speed network with high risk of disconnection
I have some computers on a network, the network is somehow serial, I mean computers are connected to each other via radio transmitters and in a line, if a radio transmitter goes off or face some problems other computers are not accessible.
the architecture would be something like this:

RT = radio transmitters

Computer#1<-RT#1->Computer#2<-RT#2->Computer#3<-RT#3->....<-RT#(N-1)->Computer#N

Distances between computers are about 20 to 30 kilometers and network speed varies between 0 and 10Kbps. computers are running windows XP and a very high loaded program (2GB of ram, 90% CPU Usage) are always running on them, all computers IP addresses are known and static.

I'm going to write a program which is going to run on every computer and get commands or packages to run or install and update on that computer. because of the low speed network and high risk of disconnection sending data between computers should have resume capability. the question is how should I implement that? using .NET remoting or use simple network sockets and TCP? which one is better? feel free to explain your suggestion or approaches you think suites this solution.

答:
I used to develop on a terrible connection.

I had packets returning literally hours (3-6 hours IIRC) later.

Thanks goodness that contract is over  :)

Have fun! I feel your pain.


问:
C++ interface inheritance with a Factory
I'm using a library which have an interface for a certain functionality, and a few implementation of the functionality. The library also provides a Factory object that instantiates the correct functionality's implementation.

I need to extend a functionality in question by adding new methods to the object, and I wanted to do this by creating a new interface which inherits from the library's interface and roll my own implementations.

For example :

```<code>class IFromLibrary
{
  virtual void LibraryMethod(void) = 0;
}

class IMyInterface : public IFromLibrary
{
  virtual void MyMethod(void) = 0;
  int SomeValue;
}

class TMyImplementation : public IMyInterface
{
  void LibraryMethod(void) { ... }
  void MyMethod(void) { ... }
}
</code>```

The problem I'm facing is with the creation of an instance of TMyImplementation. Like I said, the library hides the constructors of the implementations as private members and uses Factory static methods to construct the objects.

Example :

```<code>static IFromLibrary * createFromLibrary(int whatever) { ... }
</code>```

Since it's the paradigm of the library, I'm trying to do it as well by creating my own create in my implementation class :

```<code>static IMyInterface * createMyImplementation(int whatever) { ... }
</code>```

The problem I have is that I'd wish that my newly instantiated object would be constructed using the values provided by the library's Factory :

```<code>static IMyInterface * createMyImplementation(int whatever)
{
  IMyInterface * newObject = createFromLibrary(whatever); // this doesn't compile, evidently.
  newObject->SomeValue = SomeOtherValue; // init the parts of the object that belong to my interface
}
</code>```

I'm trying to avoid the adapter pattern (i.e. wrapping a IFromLibrary pointer inside my TMyImplementation class and forward all the method calls that are inherited from IFromLibrary). That would indeed work, but from my point of view, I find it strange, architecturally speaking, that I simultaneously inherit from and wrap a class. I also want to avoid all that forwarding boiler plate code, if at all possible.

Can this be done in any way?

EDIT :

Added the fact that the private constructors are for the implementations only (sorry @NirFriedman for the confusion).

Specified why I want (if possible) to avoid the Adapter pattern (thanks @immibis for the pattern name).

答:
It would be great if you could find implementation of "createFromLibrary" and use it in your "createMyImplementation", if it's not possible:

```<code>static IMyInterface * createMyImplementation(int whatever)
{
    IFromLibrary* newLibraryObject = createFromLibrary(whatever);
    IMyInterface* newObject = (IMyInterface*)malloc(sizeof(IMyInterface));
    memcpy(newObject, newLibraryObject, sizeof(IFromLibrary));
    newObject->SomeValue = SomeOtherValue;
    return newObject;
}
</code>```

It is not guaranteed to work, if the library keeps the trace of it's objects, this way it will loose connection with "newObject" that can lead to undefined behavior.

If your library has something like "ReleaseFromLibrary(IFromLibrary* pObj)" try to call it when you finished with "newObject" or "newLibraryObject" or both!
 (any of them can lead to undefined behavior).

Anyway I don't like this kind of solutions, but nothing better came to my mind!

Body:
I'm using a library which have an interface for a certain functionality, and a few implementation of the functionality. The library also provides a Factory object that instantiates the correct functionality's implementation.

I need to extend a functionality in question by adding new methods to the object, and I wanted to do this by creating a new interface which inherits from the library's interface and roll my own implementations.

For example :

class IFromLibrary
{
  virtual void LibraryMethod(void) = 0;
}

class IMyInterface : public IFromLibrary
{
  virtual void MyMethod(void) = 0;
  int SomeValue;
}

class TMyImplementation : public IMyInterface
{
  void LibraryMethod(void) { ... }
  void MyMethod(void) { ... }
}

The problem I'm facing is with the creation of an instance of TMyImplementation. Like I said, the library hides the constructors of the implementations as private members and uses Factory static methods to construct the objects.

Example :

static IFromLibrary * createFromLibrary(int whatever) { ... }

Since it's the paradigm of the library, I'm trying to do it as well by creating my own create in my implementation class :

static IMyInterface * createMyImplementation(int whatever) { ... }

The problem I have is that I'd wish that my newly instantiated object would be constructed using the values provided by the library's Factory :

static IMyInterface * createMyImplementation(int whatever)
{
  IMyInterface * newObject = createFromLibrary(whatever); // this doesn't compile, evidently.
  newObject->SomeValue = SomeOtherValue; // init the parts of the object that belong to my interface
}

I'm trying to avoid the adapter pattern (i.e. wrapping a IFromLibrary pointer inside my TMyImplementation class and forward all the method calls that are inherited from IFromLibrary). That would indeed work, but from my point of view, I find it strange, architecturally speaking, that I simultaneously inherit from and wrap a class. I also want to avoid all that forwarding boiler plate code, if at all possible.

Can this be done in any way?

EDIT :

Added the fact that the private constructors are for the implementations only (sorry @NirFriedman for the confusion).

Specified why I want (if possible) to avoid the Adapter pattern (thanks @immibis for the pattern name).

Body:
It would be great if you could find implementation of "createFromLibrary" and use it in your "createMyImplementation", if it's not possible:

static IMyInterface * createMyImplementation(int whatever)
{
    IFromLibrary* newLibraryObject = createFromLibrary(whatever);
    IMyInterface* newObject = (IMyInterface*)malloc(sizeof(IMyInterface));
    memcpy(newObject, newLibraryObject, sizeof(IFromLibrary));
    newObject->SomeValue = SomeOtherValue;
    return newObject;
}

It is not guaranteed to work, if the library keeps the trace of it's objects, this way it will loose connection with "newObject" that can lead to undefined behavior.

If your library has something like "ReleaseFromLibrary(IFromLibrary* pObj)" try to call it when you finished with "newObject" or "newLibraryObject" or both!
 (any of them can lead to undefined behavior).

Anyway I don't like this kind of solutions, but nothing better came to my mind!


问:
Android Studio Firebase Storage getting Url error
I have looked into every single possible solution but I still don't seem to get what I am doing wrong or what the "user" should be.

Here is my code:

```<code>mStorage = FirebaseStorage.getInstance().getReference();
mStorage.child("kana@kana.ee.jpeg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Picasso.with(MyProfile.this).load(uri).into(viewImage);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Toast.makeText(MyProfile.this, "failed", Toast.LENGTH_SHORT).show();
        }
    });
</code>```

This is the file in firebase storage.

From all the articles I have read it says that something like this is necessary:

```<code>storageRef.child("users/me/profile.png").getDownloadUrl().getResult();
</code>```

I tried it with "users" and "me" and both of them alone but nothing seems to work. What should I do or what should I replace "users" with.

答:
```<code>storageRef.child("users/me/profile.png").getDownloadUrl().getResult();
</code>```

This code means get inside users folder then me folder then get the download url for profile.png.
But if your file is in not inside any directory then you can just use this

```<code>storageRef.child("profile.png").getDownloadUrl().getResult();
</code>```

But in your case your file is "profile.jpeg" but you are trying to download "profile.jpeg"
That is why it is not finding any child.

Body:
I have looked into every single possible solution but I still don't seem to get what I am doing wrong or what the "user" should be.

Here is my code:

mStorage = FirebaseStorage.getInstance().getReference();
mStorage.child("kana@kana.ee.jpeg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            Picasso.with(MyProfile.this).load(uri).into(viewImage);
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Toast.makeText(MyProfile.this, "failed", Toast.LENGTH_SHORT).show();
        }
    });

This is the file in firebase storage.

From all the articles I have read it says that something like this is necessary:

storageRef.child("users/me/profile.png").getDownloadUrl().getResult();

I tried it with "users" and "me" and both of them alone but nothing seems to work. What should I do or what should I replace "users" with.

Body:
storageRef.child("users/me/profile.png").getDownloadUrl().getResult();

This code means get inside users folder then me folder then get the download url for profile.png.
But if your file is in not inside any directory then you can just use this

storageRef.child("profile.png").getDownloadUrl().getResult();

But in your case your file is "profile.jpeg" but you are trying to download "profile.jpeg"
That is why it is not finding any child.


问:
Declaring array in Header file
I am trying to optimize a life game.
I need to change this code from the header file:

```<code>  #define MASK(col) (0x80 >> ((col) & 7))
</code>```

(The variable "col" is a variable that will save the column, it goes from 0 to 8)

To something like this:

```<code>int array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
  #define MASK(col) (array[col])

(((0) & 7) = 0, ((1) & 7) = 64, ((2) & 7) = 32, ((3) & 16)...)
</code>```

The error I am getting with this code is the following:

```<code>"#10010 errors encountered during linking "life.out" not built"
"#10056 "array" redefined: first defined in './lifelib.obj', redefined in
'./life.obj'"
</code>```

(Ps.: I've changed the name of the array to something like: "OKDPSAdiahodakDSA" and I still got the same error)

PS: This error only happens when I make this change. The entire code is working fine.

答:
The problem is that you're using a macro.

C macros are processed by the C preprocessor, which runs before your code compiles. So macros don't know anything about variables, which only exist as named entities during compilation. You are trying to use your MASK macro as if it knew the variables array and col exist, but macros don't know anything about arrays - they just do literal text substitution.

So if you do something like

int x = MASK(9);

the text

int x = array[9];

gets injected into your code. This is why you're seeing errors related to array even if you change the name of your array.

The easiest way to solve this would be to change the name of your array into something that you know will never be used, like __life_mask_array.

So you could change your code to something like:

```<code>int __life_mask_array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
#define MASK(col) (__life_mask_array[col])
</code>```

Which would make a name collision less likely.

Of course, unless using a macro for this is sorely needed, you could do away with the macro altogether and just access your array. C macros tend to be more trouble than they are worth, because they do text substitution, which may cause stuff to behave unexpectedly if a macro uses a name that exists in its enclosing scope. It is a usual practice to prefix variable names used in macros with underscores in order to avoid name collisions, but there is no surefire way to guarantee you won't run into trouble.

Title: Declaring array in Header file

Body:
I am trying to optimize a life game.
I need to change this code from the header file:

  #define MASK(col) (0x80 >> ((col) & 7))

(The variable "col" is a variable that will save the column, it goes from 0 to 8)

To something like this:

int array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
  #define MASK(col) (array[col])

(((0) & 7) = 0, ((1) & 7) = 64, ((2) & 7) = 32, ((3) & 16)...)

The error I am getting with this code is the following:

"#10010 errors encountered during linking "life.out" not built"
"#10056 "array" redefined: first defined in './lifelib.obj', redefined in
'./life.obj'"

(Ps.: I've changed the name of the array to something like: "OKDPSAdiahodakDSA" and I still got the same error)

PS: This error only happens when I make this change. The entire code is working fine.

Body:
The problem is that you're using a macro.

C macros are processed by the C preprocessor, which runs before your code compiles. So macros don't know anything about variables, which only exist as named entities during compilation. You are trying to use your MASK macro as if it knew the variables array and col exist, but macros don't know anything about arrays - they just do literal text substitution.

So if you do something like

int x = MASK(9);

the text

int x = array[9];

gets injected into your code. This is why you're seeing errors related to array even if you change the name of your array.

The easiest way to solve this would be to change the name of your array into something that you know will never be used, like __life_mask_array.

So you could change your code to something like:

int __life_mask_array[9] = { 0, 64, 32, 16, 8, 4, 2, 1};
#define MASK(col) (__life_mask_array[col])

Which would make a name collision less likely.

Of course, unless using a macro for this is sorely needed, you could do away with the macro altogether and just access your array. C macros tend to be more trouble than they are worth, because they do text substitution, which may cause stuff to behave unexpectedly if a macro uses a name that exists in its enclosing scope. It is a usual practice to prefix variable names used in macros with underscores in order to avoid name collisions, but there is no surefire way to guarantee you won't run into trouble.


问:
Extracting list-elements that appear more than once
I have the following list:

```<code>tmp <- list(c(1,2,1,2,11,29),
            c(2,3,2,3,20,21),
            c(10,11,12,13,14,15))

names(tmp) <- c("ID1","ID2","ID3")
</code>```

If we write out each of the 5 vectors of this list, we then have

```<code>(1,2,10)
(2,3,11)
(1,2,12)
(2,3,13)
(11,20,14)
(29,21,15)
</code>```

Note that the combination (1,2,X) and (2,3,Y) appear twice, both of them. I would like to extract those vectors, where the first two elements appear n times. So for n=2 we would get

```<code>(1,2,10)
(1,2,12)
</code>```

and

```<code>(2,3,11)
(2,3,13)
</code>```

答:
Suppose the requirement is for n = 2.

Create an artificial variable summarizing the two vectors (use sep="\b" to be more confident of uniqueness)

```<code>idx = paste(tmp[["ID1"]], tmp[["ID2"]], sep="\b")
</code>```

Create a table summarizing the occurrence of each label, select the elements of the table that satisfy the condition, and get their names

```<code>nms = names(which(table(idx) == n))
</code>```

Determine which elements you'd like to keep, then subset each element of tmp

```<code>keep = idx %in% nms
lapply(tmp, `[`, keep)
</code>```

As a function with a little generality

```<code>fun = function(lst, n, op = `==`, key = 1:2) {
    idx = paste(lst[[ key[1] ]], lst[[ key[2] ]], sep="\b")
    keep = idx %in% names(which(op(table(idx), n)))
    lapply(lst, `[`, keep)
}
</code>```

Body:
I have the following list:

tmp <- list(c(1,2,1,2,11,29),
            c(2,3,2,3,20,21),
            c(10,11,12,13,14,15))

names(tmp) <- c("ID1","ID2","ID3")

If we write out each of the 5 vectors of this list, we then have

(1,2,10)
(2,3,11)
(1,2,12)
(2,3,13)
(11,20,14)
(29,21,15)

Note that the combination (1,2,X) and (2,3,Y) appear twice, both of them. I would like to extract those vectors, where the first two elements appear n times. So for n=2 we would get

(1,2,10)
(1,2,12)

and

(2,3,11)
(2,3,13)

Body:
Suppose the requirement is for n = 2.

Create an artificial variable summarizing the two vectors (use sep="\b" to be more confident of uniqueness)

idx = paste(tmp[["ID1"]], tmp[["ID2"]], sep="\b")

Create a table summarizing the occurrence of each label, select the elements of the table that satisfy the condition, and get their names

nms = names(which(table(idx) == n))

Determine which elements you'd like to keep, then subset each element of tmp

keep = idx %in% nms
lapply(tmp, `[`, keep)

As a function with a little generality

fun = function(lst, n, op = `==`, key = 1:2) {
    idx = paste(lst[[ key[1] ]], lst[[ key[2] ]], sep="\b")
    keep = idx %in% names(which(op(table(idx), n)))
    lapply(lst, `[`, keep)
}


问:
custom elements and class decorators
custom elements act differently on class decorators?

Example:

index.html

```<code><test-2></test-2>
<script src="test2.js"></script>
</code>```

test2.ts => test2.js (target:es2017)

```<code>function defineClass(tagname: string) {
  return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    console.log("Define: " + constructor.name)
    window.customElements.define(tagname, constructor)
    return class extends constructor {
        newProperty = "decorator";
        hello = "decorator";
    }
  }
}

@defineClass('test-2')
class Greeter2 extends HTMLElement{
  property = 'property2'
  hello = 'hello2'
  constructor() {
    super()
    console.log(this.hello)
  }
  connectedCallback() { }
  disconnectedCallback() { }
  attributeChangedCallback(name: string, oldValue: string, newValue: string) { }
  adoptedCallback() { }
}
console.log('test-2: ', document.querySelector('test-2').hello)

@defineClass('test-3')
class Greeter3 {
  property = 'property3'
  hello = 'hello3'
  constructor() {
    console.log(this.hello)
  }
}
console.log('test-3: ', new Greeter3());
</code>```

Output:

```<code>Define: Greeter2
hello2
test-2:  hello2 <= expected "decorator" like Greeter3 does

Define: Greeter3
hello3
test-3: Object {property: "property3", hello: "decorator", newProperty: "decorator"}
</code>```

Is this the way it's suppose to be working? If so why?

答:
Credit goes to https://github.com/rictic for finding the solution, asked if he had time to answer it on stack, but don't think he has account so I paste it instead.</p>

```<code>function defineClass(tagname: string) {
  return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    console.log("Define: " + constructor.name)
    const generated = class extends constructor {
        newProperty = "decorator";
        hello = "decorator";
    }
    window.customElements.define(tagname, generated)
    return generated;
  }
}
</code>```

Title: custom elements and class decorators

Body:
custom elements act differently on class decorators?

Example:

index.html

<test-2></test-2>

test2.ts => test2.js (target:es2017)

function defineClass(tagname: string) {
  return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    console.log("Define: " + constructor.name)
    window.customElements.define(tagname, constructor)
    return class extends constructor {
        newProperty = "decorator";
        hello = "decorator";
    }
  }
}

@defineClass('test-2')
class Greeter2 extends HTMLElement{
  property = 'property2'
  hello = 'hello2'
  constructor() {
    super()
    console.log(this.hello)
  }
  connectedCallback() { }
  disconnectedCallback() { }
  attributeChangedCallback(name: string, oldValue: string, newValue: string) { }
  adoptedCallback() { }
}
console.log('test-2: ', document.querySelector('test-2').hello)

@defineClass('test-3')
class Greeter3 {
  property = 'property3'
  hello = 'hello3'
  constructor() {
    console.log(this.hello)
  }
}
console.log('test-3: ', new Greeter3());

Output:

Define: Greeter2
hello2
test-2:  hello2 <= expected "decorator" like Greeter3 does

Define: Greeter3
hello3
test-3: Object {property: "property3", hello: "decorator", newProperty: "decorator"}

Is this the way it's suppose to be working? If so why?

Body:
Credit goes to https://github.com/rictic for finding the solution, asked if he had time to answer it on stack, but don't think he has account so I paste it instead.

function defineClass(tagname: string) {
  return function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
    console.log("Define: " + constructor.name)
    const generated = class extends constructor {
        newProperty = "decorator";
        hello = "decorator";
    }
    window.customElements.define(tagname, generated)
    return generated;
  }
}


问:
Class not being added to parent div which contains an id beginning with x
I've been trying to add a class to a parent container when the child element has the class 'hidden', if not it should add a different class.

function tagMissions() {
  if ($('span[id^="mission_participant_new"]').hasClass('hidden')) {
    $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
  } else {
    $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case');
  }
}

tagMissions();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mission_474453321" mission_id="474453321" mission_type_id="239" class="missionSideBarEntry" latitude="48.464928" longitude="11.929025" target_latitude="null" target_longitude="null">
  <!-- this is the parent div i am trying to assign the class to -->
  <div id="mission_panel_474453321" class="panel panel-default">
    <div id="mission_panel_heading_474453321" class="panel-heading">
         Alarm
        <span id="mission_participant_474453321" class="glyphicon glyphicon-user"></span>
        <!-- this is the span element with the id beginning with mission_participant_new_ -->
        <span id="mission_participant_new_474453321" class="glyphicon glyphicon-asterisk hidden"></span>
        Verkehrsunfall mit Linienbus</div>
    <div
      class="panel-body">
      <div class="row">
        <div class="col-xs-1"><img src="/Bus_rot.png?1484350177" id="mission_vehicle_state_474453321" class="mission_vehicle_state"></div>
        <div class="col-xs-11">
          <div id="mission_bar_outer_474453321" class="progress progress-striped mission_progress">
            <div id="mission_bar_474453321" class="progress-bar progress-bar-danger" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"></div>
          </div>
          <div id="mission_missing_474453321" class="alert alert-danger">Zusätzlich benötigte Fahrzeuge: 1 FwK</div>
          <ul id="mission_patients_474453321"></ul>
          <ul class="mission_prisoners" id="mission_prisoners_474453321"></ul>
        </div>
      </div>
  </div>
</div>
</div></code>```

So when a span element with an id beginning with mission_participant_new has a class called hidden, it should add a class to the parent div whose id begins with mission_panel called lss_new_case_in_progress. If the class hidden is not given, it should add lss_new_case.

This
 is given many times within the DOM.
Can you guys help me out? I cannot seem to find the mistake.

答:
You're not calling tagMissions in the context of a DOM element, so this defaults to the window object, and $(window).closest(...) doesn't find anything.

It looks like you meant to loop over all the mission_participant_new_XXX elements, so you need to use .each() for this. It sets this to the current element of the iteration.

function tagMissions() {
  $('span[id^="mission_participant_new"]').each(function() {
      if ($(this).hasClass('hidden')) {
        $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
      } else {
        $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case');
      }
    }
  });
}

tagMissions();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mission_474453321" mission_id="474453321" mission_type_id="239" class="missionSideBarEntry" latitude="48.464928" longitude="11.929025" target_latitude="null" target_longitude="null">
  <!-- this is the parent div i am trying to assign the class to -->
  <div id="mission_panel_474453321" class="panel panel-default">
    <div id="mission_panel_heading_474453321" class="panel-heading">
       Alarm
      <span id="mission_participant_474453321" class="glyphicon glyphicon-user"></span>
      <!-- this is the span element with the id beginning with mission_participant_new_ -->
      <span id="mission_participant_new_474453321" class="glyphicon glyphicon-asterisk hidden"></span>
      Verkehrsunfall mit Linienbus</div>
    <div class="panel-body">
      <div class="row">
        <div class="col-xs-1"><img src="/Bus_rot.png?1484350177" id="mission_vehicle_state_474453321" class="mission_vehicle_state"></div>
        <div class="col-xs-11">
          <div id="mission_bar_outer_474453321" class="progress progress-striped mission_progress">
            <div id="mission_bar_474453321" class="progress-bar progress-bar-danger" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"></div>
          </div>
          <div id="mission_missing_474453321" class="alert alert-danger">Zusätzlich benötigte Fahrzeuge: 1 FwK</div>
          <ul id="mission_patients_474453321"></ul>
          <ul class="mission_prisoners" id="mission_prisoners_474453321"></ul>
        </div>
      </div>
    </div>
  </div>
</div></code>```

You can also do it without looping, just using two selectors:

```<code>$('span[id^="mission_participant_new"].hidden').closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
$('span[id^="mission_participant_new"]:not(.hidden)').closest('div[id^="mission_panel"]').addClass('lss_new_case');
</code>```

I also recommend you avoid using ID prefixes like this in selectors. Give all the elements with the same prefix a class, so you can just use $('.mission_participant_new') to find them.

Body:
I've been trying to add a class to a parent container when the child element has the class 'hidden', if not it should add a different class.

function tagMissions() {
  if ($('span[id^="mission_participant_new"]').hasClass('hidden')) {
    $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
  } else {
    $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case');
  }
}

tagMissions();

         Alarm

        Verkehrsunfall mit Linienbus

Zusätzlich benötigte Fahrzeuge: 1 FwK

So when a span element with an id beginning with mission_participant_new has a class called hidden, it should add a class to the parent div whose id begins with mission_panel called lss_new_case_in_progress. If the class hidden is not given, it should add lss_new_case.

This
 is given many times within the DOM.
Can you guys help me out? I cannot seem to find the mistake.

Body:
You're not calling tagMissions in the context of a DOM element, so this defaults to the window object, and $(window).closest(...) doesn't find anything.

It looks like you meant to loop over all the mission_participant_new_XXX elements, so you need to use .each() for this. It sets this to the current element of the iteration.

function tagMissions() {
  $('span[id^="mission_participant_new"]').each(function() {
      if ($(this).hasClass('hidden')) {
        $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
      } else {
        $(this).closest('div[id^="mission_panel"]').addClass('lss_new_case');
      }
    }
  });
}

tagMissions();

<div id="mission_474453321" mission_id="474453321" mission_type_id="239" class="missionSideBarEntry" latitude="48.464928" longitude="11.929025" target_latitude="null" target_longitude="null">
  <!-- this is the parent div i am trying to assign the class to -->
  <div id="mission_panel_474453321" class="panel panel-default">
    <div id="mission_panel_heading_474453321" class="panel-heading">
      <a href="/missions/474453321" class="btn btn-default btn-xs lightbox-open" id="alarm_button_474453321"> Alarm</a>
      <span id="mission_participant_474453321" class="glyphicon glyphicon-user"></span>
      <!-- this is the span element with the id beginning with mission_participant_new_ -->
      <span id="mission_participant_new_474453321" class="glyphicon glyphicon-asterisk hidden"></span>
      <a href="" id="mission_caption_474453321" class="map_position_mover" target_latitude="null" target_longitude="null" data-latitude="48.464928" data-longitude="11.929025">Verkehrsunfall mit Linienbus</a></div>
    <div class="panel-body">
      <div class="row">
        <div class="col-xs-1"><img src="/Bus_rot.png?1484350177" id="mission_vehicle_state_474453321" class="mission_vehicle_state"></div>
        <div class="col-xs-11">
          <div id="mission_bar_outer_474453321" class="progress progress-striped mission_progress">
            <div id="mission_bar_474453321" class="progress-bar progress-bar-danger" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"></div>
          </div>
          <div id="mission_missing_474453321" class="alert alert-danger">Zusätzlich benötigte Fahrzeuge: 1 FwK</div>
          <ul id="mission_patients_474453321"></ul>
          <ul class="mission_prisoners" id="mission_prisoners_474453321"></ul>
        </div>
      </div>
    </div>
  </div>
</div>

You can also do it without looping, just using two selectors:

$('span[id^="mission_participant_new"].hidden').closest('div[id^="mission_panel"]').addClass('lss_new_case_in_progress');
$('span[id^="mission_participant_new"]:not(.hidden)').closest('div[id^="mission_panel"]').addClass('lss_new_case');

I also recommend you avoid using ID prefixes like this in selectors. Give all the elements with the same prefix a class, so you can just use $('.mission_participant_new') to find them.


问:
I can not change src of imageview from inside non-activity class in Android
I'm trying to change src of ImageView from inside non-activity class and display Error dialog message at the same time, the dialog message is appeared but without any changes on the src of ImageView this is my code by using inflater, I don't know what is the problem.

```<code> LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_fragment, null );

        ImageView imgView = (ImageView)view.findViewById(R.id.okimg);
        imgView.setImageResource(R.drawable.clear);
</code>```

Updated: Complete class

```<code>public class AddressControl extends AddressControlTask {

private View anchorView;

// You must send a context
public static void run(Context context, View anchorView, String zipCode, String houseNumber) {
    new AddressControl(context, anchorView).execute(zipCode, houseNumber);
}

private AddressControl(Context context, View anchorView) {
    super(context);
    this.anchorView = anchorView;
}

@Override
public Class<? extends AbstractTask> getTaskClass() {
    return getClass();
}

@Override
protected void onPostExecute(final List<Address> result) {
    if (result.size() == 0) {
        result.add(null);

        destroyDialog();

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_address_fragment, null );

        ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

        okaddress.setImageResource(R.drawable.clear);

        final CustomAlertDialog alertDialog = new CustomAlertDialog(getContext());
        alertDialog.setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setTitle("Wrong");

        alertDialog.setText("Address is not correct");
        alertDialog.show();
        super.onPostExecute(result);
    } if(result.size() == 1) {
        super.onPostExecute(result);
    } else {
        destroyDialog();
        Context context = getContext();
        CustomSelectDialog dialog = new CustomSelectDialog(context, anchorView);
        dialog.setOnItemSelectListener(new CustomSelectDialog.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String text, Object value) {
                List<Address> addressList = new ArrayList<>();
                addressList.add((Address) value);
                onPostExecute(addressList);
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onPostExecute(new ArrayList<Address>());
            }
        });
        for(Address address : result) {
            dialog.addItem(StringUtils.getAddressText(address), address);
        }
        dialog.setTitle("Enter true address, please");
        dialog.show();
    }
}
}
</code>```

答: I solved my problem by change source of ImageView from Fragment not from non-activity class, but until now need to know why we can not change ImageView by the previous way ( from normal class)?</p>

Body:
I'm trying to change src of ImageView from inside non-activity class and display Error dialog message at the same time, the dialog message is appeared but without any changes on the src of ImageView this is my code by using inflater, I don't know what is the problem.

 LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_fragment, null );

        ImageView imgView = (ImageView)view.findViewById(R.id.okimg);
        imgView.setImageResource(R.drawable.clear);

Updated: Complete class

public class AddressControl extends AddressControlTask {

private View anchorView;

// You must send a context
public static void run(Context context, View anchorView, String zipCode, String houseNumber) {
    new AddressControl(context, anchorView).execute(zipCode, houseNumber);
}

private AddressControl(Context context, View anchorView) {
    super(context);
    this.anchorView = anchorView;
}

@Override
public Class<? extends AbstractTask> getTaskClass() {
    return getClass();
}

@Override
protected void onPostExecute(final List<Address> result) {
    if (result.size() == 0) {
        result.add(null);

        destroyDialog();

        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View view = inflater.inflate( R.layout.control_address_fragment, null );

        ImageView okaddress = (ImageView)view.findViewById(R.id.address_ok);

        okaddress.setImageResource(R.drawable.clear);

        final CustomAlertDialog alertDialog = new CustomAlertDialog(getContext());
        alertDialog.setPositiveButton("Ok", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        alertDialog.setTitle("Wrong");

        alertDialog.setText("Address is not correct");
        alertDialog.show();
        super.onPostExecute(result);
    } if(result.size() == 1) {
        super.onPostExecute(result);
    } else {
        destroyDialog();
        Context context = getContext();
        CustomSelectDialog dialog = new CustomSelectDialog(context, anchorView);
        dialog.setOnItemSelectListener(new CustomSelectDialog.OnItemSelectedListener() {
            @Override
            public void onItemSelected(String text, Object value) {
                List<Address> addressList = new ArrayList<>();
                addressList.add((Address) value);
                onPostExecute(addressList);
            }
        });
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                onPostExecute(new ArrayList<Address>());
            }
        });
        for(Address address : result) {
            dialog.addItem(StringUtils.getAddressText(address), address);
        }
        dialog.setTitle("Enter true address, please");
        dialog.show();
    }
}
}


问:
How do I change my iPhone App binary filename
I get the following error when I try to upload the application on iTunes Connect:

"Binary file names cannot contain a space. Please rename your binary file and try again."

If I try to Validate the Application in XCode, I get:
"My Application.ipa: filename may not contain whitespace"

So I guess I have to find a way to rename this .ipa file. I don't want to change my product name which has to stay "My Application". How can I do that?

Thanks!

答:
This works very well (taken from here: http://developer.appcelerator.com/question/82971/filename-may-not-contain-whitespace-in-xcode-325-is-back):

1) In Xcode Organizer right click on the build date of the app and select "Reveal Archived App in Finder"

2) Open ArchiveInfo.plist in a text editor (i used Coda)

3) For me at line 12 it was creating the application with a space:

```<code>  <key>XCApplicationName</key>
  <string>Example Name</string>
</code>```

Change that to ExampleName and save the file.

4) Once you get back to Xcode Organizer, you should be able to go through fine.

Body:
This works very well (taken from here: http://developer.appcelerator.com/question/82971/filename-may-not-contain-whitespace-in-xcode-325-is-back):

1) In Xcode Organizer right click on the build date of the app and select "Reveal Archived App in Finder"

2) Open ArchiveInfo.plist in a text editor (i used Coda)

3) For me at line 12 it was creating the application with a space:

  <key>XCApplicationName</key>
  <string>Example Name</string>

Change that to ExampleName and save the file.

4) Once you get back to Xcode Organizer, you should be able to go through fine.


问:
How to log incoming and outgoing XML from WCF requests
I have a basic WCF hosted in a console app, and a basic console WCF client. How do you look at the requests sent between the two apps (over localhost)?

Should I use something like 'Wireshark' or would it be possible to log out the incoming and outgoing response objects in visual Studio?

I'm already creating an log.svclog file by the system.diagnostics directive in the App.config file, but can't find the actual request and response xml:

```<code><diagnostics>
  <messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
</diagnostics>

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
      <listeners>
        <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\log\log.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>
</code>```

Which I got from Stack Overflow (I can't remember where)

答: You need to configure message logging, which is separate from just WCF tracing, which is what you have configured above. See https://msdn.microsoft.com/en-us/library/ms730064(v=vs.110).aspx.</p>

Body:
I have a basic WCF hosted in a console app, and a basic console WCF client. How do you look at the requests sent between the two apps (over localhost)?

Should I use something like 'Wireshark' or would it be possible to log out the incoming and outgoing response objects in visual Studio?

I'm already creating an log.svclog file by the system.diagnostics directive in the App.config file, but can't find the actual request and response xml:

<diagnostics>
  <messageLogging logEntireMessage="true" logMalformedMessages="true" logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
</diagnostics>

<system.diagnostics>
  <sources>
    <source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
      <listeners>
        <add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="C:\log\log.svclog" />
      </listeners>
    </source>
  </sources>
</system.diagnostics>

Which I got from Stack Overflow (I can't remember where)


问:
Datatables self reference loop detected Entity framework and JSON
See comments for what was my solution

I am new with ASP.net and i'm currently making a website.

This site is creating with MVC in mind. I have created a database containing a few tables.

As you can see are Shipments referenced in processOrder ( 1 --* ) and there are a few more references like this (Mandator and Customer). I think this is no problem?

At the client side i'm using jquery datatables to show my data:

I had no trouble before but since i started server side processing of my data (For optimization purpose) i have some trouble accessing my data. I created a method so the datatable can receive the data in json format:

Since then I keep having self referencing problems in processOrder for shipment type. I tried a few things in this post: JSON.NET Error Self referencing loop detected for type but the closest I got was with fix 2 of the second answer. The only problem with that solution is the "$ref" that my datatable cant understand.

I hope someone can get me back on the right track with a solution or tip

EDIT: Added the entity ProcessOrder. It is auto generated from the database.
`

```<code>namespace ICT.ControlTower.Domain.Entities
{
    using System;
    using System.Collections.Generic;

    public partial class ProcessOrder
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public ProcessOrder()
        {
            this.Shipment = new HashSet<Shipment>();
            this.StockItem = new HashSet<StockItem>();
        }

        public int Id { get; set; }
        public System.DateTime InsertedAt { get; set; }
        public int CustomerId { get; set; }
        public int OrderStatus { get; set; }
        public int MandatorId { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Shipment> Shipment { get; set; }
        public virtual Customer Customer { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<StockItem> StockItem { get; set; }
        public virtual Mandator Mandator { get; set; }
    }
}
</code>```

`

```<code>namespace ICT.ControlTower.Domain.Entities
{
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Customer()
        {
            this.ProcessOrder = new HashSet<ProcessOrder>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProcessOrder> ProcessOrder { get; set; }
    }
}
</code>```

答:
Couple of thoughts - it's hard to determine which entity or entities are the culprit in your case based on what you shared, but I'll take a shot. I would suggest posting what your entity classes look like for ProcessOrder and ShipmentType so we can provide suggestions.

That being said, this tends to come up when you have Lazy Loading enabled in your DbContext (which is the default) and you have entities that reference one another with virtual properties. The virtual keyword will instruct EF to Lazy Load that type, which if that has virtual properties, it will lazy load those and so the circular reference continues until WebAPI throws an exception.

If you would like to disable LazyLoading for a query, set this value on your context to prevent that behavior. Keep in mind if you do this, you'll have to explicitly Include or Load navigation properties that are required:

```<code>DbContext.Configuration.LazyLoadingEnabled = false;
</code>```

Another thing you can try is if you can find the property that is creating the circular reference and you do not need it in the UI, you can apply the [JsonIgnore] attribute to that property and it won't be serialized

If your eventual solution is returning $refs from WebAPI, you can either create a client side function to remap the objects together (something I haven't had to do personally) or if it's a specific entity you want to always serialize the object you can add the following attribute to the class:

```<code>[JsonObject(IsReference = false)]
</code>```

Lots of words - maybe you can look into one of the suggestions above and find a solution for yourself :)

Body:
See comments for what was my solution

I am new with ASP.net and i'm currently making a website.

This site is creating with MVC in mind. I have created a database containing a few tables.

As you can see are Shipments referenced in processOrder ( 1 --* ) and there are a few more references like this (Mandator and Customer). I think this is no problem?

At the client side i'm using jquery datatables to show my data:

I had no trouble before but since i started server side processing of my data (For optimization purpose) i have some trouble accessing my data. I created a method so the datatable can receive the data in json format:

Since then I keep having self referencing problems in processOrder for shipment type. I tried a few things in this post: JSON.NET Error Self referencing loop detected for type but the closest I got was with fix 2 of the second answer. The only problem with that solution is the "$ref" that my datatable cant understand.

I hope someone can get me back on the right track with a solution or tip

EDIT: Added the entity ProcessOrder. It is auto generated from the database.
`

namespace ICT.ControlTower.Domain.Entities
{
    using System;
    using System.Collections.Generic;

    public partial class ProcessOrder
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public ProcessOrder()
        {
            this.Shipment = new HashSet<Shipment>();
            this.StockItem = new HashSet<StockItem>();
        }

        public int Id { get; set; }
        public System.DateTime InsertedAt { get; set; }
        public int CustomerId { get; set; }
        public int OrderStatus { get; set; }
        public int MandatorId { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Shipment> Shipment { get; set; }
        public virtual Customer Customer { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<StockItem> StockItem { get; set; }
        public virtual Mandator Mandator { get; set; }
    }
}

`

namespace ICT.ControlTower.Domain.Entities
{
    using System;
    using System.Collections.Generic;

    public partial class Customer
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Customer()
        {
            this.ProcessOrder = new HashSet<ProcessOrder>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ProcessOrder> ProcessOrder { get; set; }
    }
}

Body:
Couple of thoughts - it's hard to determine which entity or entities are the culprit in your case based on what you shared, but I'll take a shot. I would suggest posting what your entity classes look like for ProcessOrder and ShipmentType so we can provide suggestions.

That being said, this tends to come up when you have Lazy Loading enabled in your DbContext (which is the default) and you have entities that reference one another with virtual properties. The virtual keyword will instruct EF to Lazy Load that type, which if that has virtual properties, it will lazy load those and so the circular reference continues until WebAPI throws an exception.

If you would like to disable LazyLoading for a query, set this value on your context to prevent that behavior. Keep in mind if you do this, you'll have to explicitly Include or Load navigation properties that are required:

DbContext.Configuration.LazyLoadingEnabled = false;

Another thing you can try is if you can find the property that is creating the circular reference and you do not need it in the UI, you can apply the [JsonIgnore] attribute to that property and it won't be serialized

If your eventual solution is returning $refs from WebAPI, you can either create a client side function to remap the objects together (something I haven't had to do personally) or if it's a specific entity you want to always serialize the object you can add the following attribute to the class:

[JsonObject(IsReference = false)]

Lots of words - maybe you can look into one of the suggestions above and find a solution for yourself :)


问:
Remove row dynamically from table in templates js
I have a page in which rows will be added dynamically using an add button (there is a java script function to add rows to the table on the page), these rows have to be deleted by clicking on a delete image which is a  value in one of the row
 that needs to be removed. I have done something like below, but 'onclick' is not working. The event is not getting triggered. What am I doing wrong here? Thanks.

```<code>function addRow(){
...
...
var deleteRow = "'deleteRowfun(\"rowNumber_"+(rowCount)+"\"); return false;'";

        var someName = "<tr id='rowNumber_" + (rowCount) + "' class = ' " + colorClass + " '><td valign='top' class='value'><label id='contactLastName_" +
            rowCount + "'>" + lastName + "</label></td>
            <td id='deleteContactAction_" + rowCount + "'>" +
            "<input type='image' src='/Projectname/plugins/folder/images/custom/delete-icon.jpg' id='contactDelete_" + rowCount + "'" +
            "title='Delete Contact' name='contactDelete' class='actionsIcon' " +
            "onclick="+ deleteRow + "/></td></tr>";

        $("#contactsTBL tbody").append(someName);
...
...

};

function deleteRowfun(itemId) {
        if (!confirm('Delete?')) {
            return false;
        }
        itemRowId = "#" + itemId
        $(itemRowId).remove();
    }
</code>```

答:
Since you are already using jQuery library, I'd suggest to take advantage from it by defining click event listeners as follows:

```<code>// click handler for existing and new IMG tags
$(document).on('click', 'img', function(e) {
    $(e.target).closest('tr').remove();
});
</code>```

Note that this click event listeners is going to be applied to every existing img tag and to every new one that is going to be added later.

Also note note that once we identify the clicked img tag (e.target) we look for the closest tr (row) in order to remove it

See this working JSfiddle sample

Body:
I have a page in which rows will be added dynamically using an add button (there is a java script function to add rows to the table on the page), these rows have to be deleted by clicking on a delete image which is a  value in one of the row
 that needs to be removed. I have done something like below, but 'onclick' is not working. The event is not getting triggered. What am I doing wrong here? Thanks.

function addRow(){
...
...
var deleteRow = "'deleteRowfun(\"rowNumber_"+(rowCount)+"\"); return false;'";

        var someName = "
" + lastName + "
            " +
            "<input type='image' src='/Projectname/plugins/folder/images/custom/delete-icon.jpg' id='contactDelete_" + rowCount + "'" +
            "title='Delete Contact' name='contactDelete' class='actionsIcon' " +
            "onclick="+ deleteRow + "/>
";

        $("#contactsTBL tbody").append(someName);
...
...

};

function deleteRowfun(itemId) {
        if (!confirm('Delete?')) {
            return false;
        }
        itemRowId = "#" + itemId
        $(itemRowId).remove();
    }

Body:
Since you are already using jQuery library, I'd suggest to take advantage from it by defining click event listeners as follows:

// click handler for existing and new IMG tags
$(document).on('click', 'img', function(e) {
    $(e.target).closest('tr').remove();
});

Note that this click event listeners is going to be applied to every existing img tag and to every new one that is going to be added later.

Also note note that once we identify the clicked img tag (e.target) we look for the closest tr (row) in order to remove it

See this working JSfiddle sample


问:
PHP DOM parsing text between
 tags
I am trying to parse some HTML to get the text between two
 tags using DOM with PHP but I don't get any output when I pass in hr into getElementsByTagName:

```<code><?php
    $dom = new DOMDocument();
    $dom->loadHTML("<hr>Text<hr>");
    $hr = $dom->getElementsByTagName("hr");
    for ($i=0; $i<$hr->length; $i++) {
        echo "[". $i . "]" . $hr->item($i)->nodeValue . "</br>";
    }
?>
</code>```

When I run this code, it doesn't output anything however, if I change "hr" to "*" then it outputs:

```<code>[0]Text
[1]Text
[2]
[3]
</code>```

(Why four lines of results?)

I run this code on a webserver which has PHP version 7.1.3 running. I can't use functions such as file_get_html or str_get_html because it returns an error about Undefined call to function ...

Why doesn't the hr tag produce results?

答:
This happens, because the
 has no child nodes (text are also childs).
To get the text between the
 nodes, you have to iterate over all nodes on the same level and check if the current node is a text node (nodeType == 3), the previous sibling must be a HR node and the next sibling must be a HR node too.

```<code><?php
    $dom = new DOMDocument();
    $dom->loadHTML("<hr>Text<hr>");

    foreach ($dom->childNodes as $childNode) {
        if (3 !== $childNode->nodeType) {
            continue;
        }

        if (!$childNode->previousSibling || ('HR' !== $childNode->previousSibling->nodeName)) {
            continue;
        }

        if (!$childNode->nextSibling || ('HR' !== $childNode->nextSibling->nodeName)) {
            continue;
        }

        echo "{$childNode->nodeValue}\n";
    }
</code>```

But if you want to get anything between the hr nodes it will be more complicated.

Title: PHP DOM parsing text between <hr> tags

Body:
I am trying to parse some HTML to get the text between two
 tags using DOM with PHP but I don't get any output when I pass in hr into getElementsByTagName:

<?php
    $dom = new DOMDocument();
    $dom->loadHTML("
Text
");
    $hr = $dom->getElementsByTagName("hr");
    for ($i=0; $i<$hr->length; $i++) {
        echo "[". $i . "]" . $hr->item($i)->nodeValue . "
";
    }
?>

When I run this code, it doesn't output anything however, if I change "hr" to "*" then it outputs:

[0]Text
[1]Text
[2]
[3]

(Why four lines of results?)

I run this code on a webserver which has PHP version 7.1.3 running. I can't use functions such as file_get_html or str_get_html because it returns an error about Undefined call to function ...

Why doesn't the hr tag produce results?

Body:
This happens, because the <hr> has no child nodes (text are also childs).
To get the text between the <hr> nodes, you have to iterate over all nodes on the same level and check if the current node is a text node (nodeType == 3), the previous sibling must be a HR node and the next sibling must be a HR node too.

<?php
    $dom = new DOMDocument();
    $dom->loadHTML("<hr>Text<hr>");

    foreach ($dom->childNodes as $childNode) {
        if (3 !== $childNode->nodeType) {
            continue;
        }

        if (!$childNode->previousSibling || ('HR' !== $childNode->previousSibling->nodeName)) {
            continue;
        }

        if (!$childNode->nextSibling || ('HR' !== $childNode->nextSibling->nodeName)) {
            continue;
        }

        echo "{$childNode->nodeValue}\n";
    }

But if you want to get anything between the hr nodes it will be more complicated.


问:
Warning frame for "Navigation bar" will be different at run time appears in Xcode 8 Swift 3
Before I've upgraded to Xcode 8 I haven't seen this error in such case. I have different Navigation Controllers. For all of them I see an error Frame for "Navigation bar" will be different at the run time. Navigation bar "Expected: width=384, Actual: width=375. In reality these Navigation Controllers doesn't have Navigation bar. Navigation bar exists for subviews. Anyway I could solve it by tick and untick the checkbox Shows navigation bar in Attributes inspector. But unfortunately every time I reopen Main.storyboard this warning appears again. Also if I click on yellow triangle and then on update frames nothing happen.

答:
I tried all the above suggestions but it didn't seem to work.  I think it might be a more serious bug.

I have logged a bug with Apple Bug Reporter( link: https://bugreport.apple.com/logon) - if you want to do the same, then please reference bug : 31355220 so that Apple can tie it together.  The more people that report it - the more information they will have to fix this annoyance.


问:
Postulating namespaces in Coq
I would like to have signatures such that I can postulate inhabitants for them. In Agda it looks like this:

```<code>record Foo (A : Set) : Set where
  field
    bar : A
    baz : A → A

postulate assumeFoo : Foo ℕ
open Foo assumeFoo
</code>```

The advantage of this technique is that we can conveniently assemble and parameterize large bundles of postulated theories.

In Coq, I can open modules as namespaces and postulate inhabitants of records, but don't know how to do both for either. Is that possible?

答:
There is no exact analog of this feature in Coq. The closest you can get is to use a typeclass. This solves the parameterization issue, but does not provide the same namespace features. Your example would become:

```<code>Class Foo (A : Type) := {
  bar : A;
  baz : A -> A
}.
</code>```

This declares a record with two fields bar and baz. What's special about the Class command is that Coq has a mechanism for filling in implicit arguments when their type was declared as a class. For instance, here is how we would postulate that nat has an instance of Foo:

```<code>Section MySection.

Context {fooNat : Foo nat}.

Check bar.

Check baz bar.

End MySection.
</code>```

Any definitions inside the section would then get an extra fooNat parameter once you leave the section.

You can refer to the Coq manual for more references on typeclasses.

Title: Postulating namespaces in Coq

Body:
I would like to have signatures such that I can postulate inhabitants for them. In Agda it looks like this:

record Foo (A : Set) : Set where
  field
    bar : A
    baz : A → A

postulate assumeFoo : Foo ℕ
open Foo assumeFoo

The advantage of this technique is that we can conveniently assemble and parameterize large bundles of postulated theories.

In Coq, I can open modules as namespaces and postulate inhabitants of records, but don't know how to do both for either. Is that possible?

Body:
There is no exact analog of this feature in Coq. The closest you can get is to use a typeclass. This solves the parameterization issue, but does not provide the same namespace features. Your example would become:

Class Foo (A : Type) := {
  bar : A;
  baz : A -> A
}.

This declares a record with two fields bar and baz. What's special about the Class command is that Coq has a mechanism for filling in implicit arguments when their type was declared as a class. For instance, here is how we would postulate that nat has an instance of Foo:

Section MySection.

Context {fooNat : Foo nat}.

Check bar.

Check baz bar.

End MySection.

Any definitions inside the section would then get an extra fooNat parameter once you leave the section.

You can refer to the Coq manual for more references on typeclasses.


问:
How many attributes in one arff file that python-weka-wrapper can support when clustering?
I want to know if there's any limitations of dataset for python-weka-wrapper.

I'm doing the ClusterEvaluation(with weka.clusterers.HierarchicalClusterer) via python-weka-wrapper 0.3.8.
And I can get the final clustering results with smaller dataset (62 attributes) successfully. But with a larger dataset (264 attributes), it stuck about 2 days without any output debugging message with python-weka-wrapper.
Using the same arff(264 attributes), it can run correctly with WEKA.

I want to know if there's any limitation of dataset for python-weka-wrapper.
Or is there any setting I should check first for larger dataset?

Thanks!

答: python-weka-wrapper has the same limitations as Weka, as it just wraps around a Weka process running inside a JVM. However, you might have to increase the heap size used for the JVM. Use the max_heap_size parameter to set a different memory limit when starting the JVM (see documentation).


问:
Google Smart Lock across multiple apps
I've been trying to get Google's Smart Lock to work between two apps that I have (unfortunately with different keystores), but not having any luck.

It's straightforward to save a password in Smart Lock for one app (APP 1) doing something like:

```<code>Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .build();
Auth.CredentialsApi.save(mCredentialsApiClient, credential).setResultCallback(...
</code>```

However, when I try to make a CredentialRequest in APP 2 it's not able to read the same credentials saved from APP 1.
I've tried setting the accountType to the same identifier between them like:

```<code>Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .setAccountType(ACCOUNT_TYPE)
            .build();
Auth.CredentialsApi.save(mCredentialsApiClient, credential).setResultCallback(...
...
CredentialRequest request = new CredentialRequest.Builder()
            .setAccountTypes(ACCOUNT_TYPE)
            .build();

Auth.CredentialsApi.request(mCredentialsApiClient, request).setResultCallback(...
</code>```

But I get an exception stating you can't set both the password and accountType on the same credential (which matches what the documentation says).

Anyone tried something similar between two apps?
I should note, I'm unable to tie my credentials from the apps up with my website sign in at the moment, so can't use the Digital Asset Links mechanism.

答:
For security reasons, the digit asset linking is the only way to associate multiple apps with different package names and signing certificates for password retreival with Smart Lock.

If you can't support credentials from the website yet, then simply exclude the "web" target from the digital asset links file and credentials will only be shared between the apps (but you still have to host the file somewhere and include a link to this file in both app manifests).

Title: Google Smart Lock across multiple apps

Body:
I've been trying to get Google's Smart Lock to work between two apps that I have (unfortunately with different keystores), but not having any luck.

It's straightforward to save a password in Smart Lock for one app (APP 1) doing something like:

Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .build();
Auth.CredentialsApi.save(mCredentialsApiClient, credential).setResultCallback(...

However, when I try to make a CredentialRequest in APP 2 it's not able to read the same credentials saved from APP 1.
I've tried setting the accountType to the same identifier between them like:

Credential credential = new Credential.Builder(email)
            .setPassword(password)
            .setAccountType(ACCOUNT_TYPE)
            .build();
Auth.CredentialsApi.save(mCredentialsApiClient, credential).setResultCallback(...
...
CredentialRequest request = new CredentialRequest.Builder()
            .setAccountTypes(ACCOUNT_TYPE)
            .build();

Auth.CredentialsApi.request(mCredentialsApiClient, request).setResultCallback(...

But I get an exception stating you can't set both the password and accountType on the same credential (which matches what the documentation says).

Anyone tried something similar between two apps?
I should note, I'm unable to tie my credentials from the apps up with my website sign in at the moment, so can't use the Digital Asset Links mechanism.


问:
Get SUM of values in a column after query is ran
This is my SQL statement which pulls back all the fills I've had in a certain time frame.  Is there a way to get the list to come up and also pull the SUM of all of them?</p>

```<code>SELECT customerName, date, gallons
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
ORDER BY CONVERT(DATE, date) ASC
</code>```

答:
sums of fills per customer since '3-3-2015'

```<code> SELECT customerName, date, sum(gallons)
 FROM addFill
 WHERE date >= CONVERT(datetime, '3-3-2015' )
 GROUP BY customerName
</code>```

sum of fills for all customers since '3-3-2015'

```<code>SELECT sum(gallons)
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
</code>```

Body:
This is my SQL statement which pulls back all the fills I've had in a certain time frame.  Is there a way to get the list to come up and also pull the SUM of all of them?

SELECT customerName, date, gallons
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )
ORDER BY CONVERT(DATE, date) ASC

Body:
sums of fills per customer since '3-3-2015'

 SELECT customerName, date, sum(gallons)
 FROM addFill
 WHERE date >= CONVERT(datetime, '3-3-2015' )
 GROUP BY customerName

sum of fills for all customers since '3-3-2015'

SELECT sum(gallons)
FROM addFill
WHERE date >= CONVERT(datetime, '3-3-2015' )


问:
RegEx for at least 1 number, 1 lower case and 1 upper case letter
Currently, I'm using one that I found with a length restriction:

```<code><input #password="ngModel" type="password" name="password"  minlength="5" maxlength="30" pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})" required ngModel>
</code>```

It works, but I don't want the length restriction at the end. I don't know much about regular expressions, so I assumed that removing {6,20} at the end would get the job done, but I was wrong.

So my question is: How do I make this regex work without the length restriction? Thanks!

答:
You are using an HTML5 pattern attribute that anchors a regex by default (it actually wraps the pattern with ^(?: and )$). That means the pattern must match the entire string. This is the reason why you can't just take out .{6,20} and keep the lookaheads.

You need to use the lookaheads at the beginning, and .* (to allow 0 or more chars in the input) or .+ (to disallow empty input) at the end (as the consuming pattern part):

```<code>pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*"
</code>```

This will be successfully translated into /^(?:(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*)$/ and will work as expected:

^ - start of string

(?: - start of the non-capturing group

(?=.*\d) - 1 digit after any 0+ chars from the current position is required

(?=.*[a-z])  - 1 lowercase letter after any 0+ chars from the current position is required

(?=.*[A-Z])  - 1 uppercase letter after any 0+ chars from the current position is required

.*  - any 0 or more chars

) - end of the non-capturing group

$ - end of string.

Body:
Currently, I'm using one that I found with a length restriction:

<input #password="ngModel" type="password" name="password"  minlength="5" maxlength="30" pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})" required ngModel>

It works, but I don't want the length restriction at the end. I don't know much about regular expressions, so I assumed that removing {6,20} at the end would get the job done, but I was wrong.

So my question is: How do I make this regex work without the length restriction? Thanks!

Body:
You are using an HTML5 pattern attribute that anchors a regex by default (it actually wraps the pattern with ^(?: and )$). That means the pattern must match the entire string. This is the reason why you can't just take out .{6,20} and keep the lookaheads.

You need to use the lookaheads at the beginning, and .* (to allow 0 or more chars in the input) or .+ (to disallow empty input) at the end (as the consuming pattern part):

pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*"

This will be successfully translated into /^(?:(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*)$/ and will work as expected:

^ - start of string

(?: - start of the non-capturing group

(?=.*\d) - 1 digit after any 0+ chars from the current position is required

(?=.*[a-z])  - 1 lowercase letter after any 0+ chars from the current position is required

(?=.*[A-Z])  - 1 uppercase letter after any 0+ chars from the current position is required

.*  - any 0 or more chars

) - end of the non-capturing group

$ - end of string.


问:
How can I make the data open in the same form
i want to transfer values from one form to another...

This is the code for the MainPage

```<code>    Public Property StringPass As String
    Public Property NumPass As String
    Private Sub MainPage_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label7.Text = StringPass
    TextBox3.Text = NumPass

    End Sub
</code>```

This is the code for the SecondPage

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim OBJ As New MainPage
  Dim NUM As New MainPage
  OBJ.StringPass = TextBox1.Text
  NUM.NumPass = TextBox6.Text
  OBJ.Show()
  NUM.Show()
  Me.Hide()
End Sub
</code>```

How can OBJ and NUM pass values to their respective textboxes but open in the same MainPage?

答:
You are creating 2 forms and you only need one.
If you want to pass data to the next form you can assign those values just like you would with a normal class.

Make sure you have saved all forms as well.

Your naming convention is not the best here just FYI.

Here is an example with your code.

This is the code for the SecondPage

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim OBJ As New MainPage
  OBJ.Label7.Text = TextBox1.Text
  OBJ.TextBox3.Text = TextBox6.Text
  OBJ.Show()
  Me.Hide()
End Sub
</code>```

Body:
i want to transfer values from one form to another...

This is the code for the MainPage

    Public Property StringPass As String
    Public Property NumPass As String
    Private Sub MainPage_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label7.Text = StringPass
    TextBox3.Text = NumPass

    End Sub

This is the code for the SecondPage

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim OBJ As New MainPage
  Dim NUM As New MainPage
  OBJ.StringPass = TextBox1.Text
  NUM.NumPass = TextBox6.Text
  OBJ.Show()
  NUM.Show()
  Me.Hide()
End Sub

How can OBJ and NUM pass values to their respective textboxes but open in the same MainPage?

Body:
You are creating 2 forms and you only need one.
If you want to pass data to the next form you can assign those values just like you would with a normal class.

Make sure you have saved all forms as well.

Your naming convention is not the best here just FYI.

Here is an example with your code.

This is the code for the SecondPage

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  Dim OBJ As New MainPage
  OBJ.Label7.Text = TextBox1.Text
  OBJ.TextBox3.Text = TextBox6.Text
  OBJ.Show()
  Me.Hide()
End Sub


问:
Populating DropDownList of MVC Application Using Entity Framework and NUGET PageList
I need to provide two distinct filters in my MVC 5 application (one via text box control and the other via drop down list), which uses the Entity Framework.  Having difficulty populating the control with selected values from the table.  While I was initially worried about multiple values (in the list control) because I joined a table with multiple values into one with single items, I haven’t gotten beyond step 1.  I should point out that I am using a paged list control, which may be complicating things more.

MODEL
(Fairly straightforward with not much to see here)

CONTROLLER

Fairly straightforward with a sort and name filter

```<code>if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var employees = from s in db.tblEmployeeADPs.Include(s => s.tblDepartmentFuncADP)
                            .Where(s => s.Status == "Active")
                            select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                employees = employees.Where(s => s.LastName.Contains(searchString)
                                              || s.FirstName.Contains(searchString));

            }

            if (!String.IsNullOrEmpty(DepartmentFunction))
            {
                employees = employees.Where(s => s.HomeDepartmentDesc == DepartmentFunction);

            }

int pageSize = 30;
int pageNumber = (page ?? 1);
return View(employees.ToPagedList(pageNumber, pageSize));
</code>```

VIEW

```<code>@using (Html.BeginForm("Index","Employee", FormMethod.Get))
{
<p>
   Find by name:  @Html.TextBox("searchString", ViewBag.currentFilter as     String)
    <input type="submit" value="Search" />

   <img style="5px"/>

   XMan-Filter: @Html.DropDownListFor(m => m.FunctionName, new SelectList(ViewBag.DepartmentFunc, "FunctionName", "FunctionNAme"), "-- Select One --")
 </p>
}

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of    @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
new { sortOrder = ViewBag.CurrentSort, currentFilter =     ViewBag.CurrentFilter, page, PlaceHolderForVariable}))
</code>```

When I attempt to use the m => m.valuename lambda syntax to test anything out of the collection, I get an error:

PagedList.IPagedList' does not contain a definition for 'FunctionName' and no extension method 'FunctionName' accepting a first argument of type 'PagedList.IPagedList' could

答:
EDIT:

```<code>@Html.DropDownListFor(m => m.FunctionName, new SelectList(ViewBag.DepartmentFunc, "FunctionName", "FunctionNAme"), "-- Select One --")
</code>```

Edit this line to

```<code>@Html.DropDownListFor(model => model.FirstOrDefault().FunctionName, new SelectList(ViewBag.DepartmentFunc, "FunctionName", "FunctionName"), "-- Select One --")
</code>```

It should work.

Body:
I need to provide two distinct filters in my MVC 5 application (one via text box control and the other via drop down list), which uses the Entity Framework.  Having difficulty populating the control with selected values from the table.  While I was initially worried about multiple values (in the list control) because I joined a table with multiple values into one with single items, I haven’t gotten beyond step 1.  I should point out that I am using a paged list control, which may be complicating things more.

MODEL
(Fairly straightforward with not much to see here)

CONTROLLER

Fairly straightforward with a sort and name filter

if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var employees = from s in db.tblEmployeeADPs.Include(s => s.tblDepartmentFuncADP)
                            .Where(s => s.Status == "Active")
                            select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                employees = employees.Where(s => s.LastName.Contains(searchString)
                                              || s.FirstName.Contains(searchString));

            }

            if (!String.IsNullOrEmpty(DepartmentFunction))
            {
                employees = employees.Where(s => s.HomeDepartmentDesc == DepartmentFunction);

            }

int pageSize = 30;
int pageNumber = (page ?? 1);
return View(employees.ToPagedList(pageNumber, pageSize));

VIEW

@using (Html.BeginForm("Index","Employee", FormMethod.Get))
{

   Find by name:  @Html.TextBox("searchString", ViewBag.currentFilter as     String)
    <input type="submit" value="Search" />

   XMan-Filter: @Html.DropDownListFor(m => m.FunctionName, new SelectList(ViewBag.DepartmentFunc, "FunctionName", "FunctionNAme"), "-- Select One --")

}

Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of    @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
new { sortOrder = ViewBag.CurrentSort, currentFilter =     ViewBag.CurrentFilter, page, PlaceHolderForVariable}))

When I attempt to use the m => m.valuename lambda syntax to test anything out of the collection, I get an error:

PagedList.IPagedList' does not contain a definition for 'FunctionName' and no extension method 'FunctionName' accepting a first argument of type 'PagedList.IPagedList' could

Body:
EDIT:

@Html.DropDownListFor(m => m.FunctionName, new SelectList(ViewBag.DepartmentFunc, "FunctionName", "FunctionNAme"), "-- Select One --")

Edit this line to

@Html.DropDownListFor(model => model.FirstOrDefault().FunctionName, new SelectList(ViewBag.DepartmentFunc, "FunctionName", "FunctionName"), "-- Select One --")

It should work.


问:
Resolve a standalone string/file using typesafe config
I'm looking for a way to say:

```<code>val c: Config = ConfigFactory.parseString("a=fox,b=dog")
val s: String = """This is a "quick" brown ${a}.\nThat is a lazy, lazy ${b}."""
println(c.resolveString(s))

// Should print:
// > This is a "quick" brown fox.
// > That is a lazy lazy dog.
</code>```

My two ideas:

Just find the placeholders with regex and replace from config one by one

convert s to config with single value and use resolveWith - but it seems quoting can be really tricky

Maybe there is an easier way?

答:
I have a similar situation where I automatically push elastic search index definitions before
I launch the job which uses those index definitions.

In my case the string which contains variable references is the
JSON index/template definition, which ALSO comes from the typesafe config.
(see es.template_or_index.json, below.)

I resolve these refs using the utility method I wrote on top
of apache.commons StrSubstitutor.

(see: VariableReferenceResolver.resolveReferences(String template), below)

Below is a sample of my config.  Note how the property 'es.animal' is injected into the index/template json.
This can't be done with out-of-the-box features of the typesafe config library  (but I think this would
be a wonderful feature for them to add !)

```<code> es {
      // user and password credentials should not be checked in to git. deployer is expected to
      // set these parameters into the their environment in whatever way is convenient -- .bashrc or whatever.
      user = dummy
      user = ${?ES_USER}
      password = dummy.passwd
      password = ${?ES_PASSWORD}
      hostPort = "localhost:9200"
      hostPort = ${?ES_HOST_PORT}
      protocol = http
      protocol = ${?ES_PROTOCOL}

      animal = horse            // This gets injected into the configuration property es.template_or_index.json

      // Note: for template json there is a second round of interpolation performed so the json can reference any defined
      // property of this configuration file (or anything it includes)
      template_or_index {
        name = test_template
        json = """
      {
          "template": "${es.animal}_sql-*",
          "settings": {
            "number_of_shards": 50,
            "number_of_replicas": 2
          },
          "mappings": {
                 "test_results" : {
                     "date_detection": false,
                     "properties" : {
                         "timestamp" : { "type" : "date"},
                         "yyyymmdd" : { "type" : "string", "index" : "not_analyzed"}
                     }
                 }
          }
        }
        """
      }
 }

package com.foo

import com.typesafe.config.Config;
import org.apache.commons.lang.text.StrLookup;
import org.apache.commons.lang.text.StrSubstitutor;

public class VariableReferenceResolver {
    final StrSubstitutor substitutor;

    static class ConfigStrLookup extends StrLookup {
          private final Config config;

          ConfigStrLookup(Config config) {
              this.config = config;
          }

          public String lookup(String key) {
              return config.getString(key);
          }
      }

    public VariableReferenceResolver (Config config) {
        substitutor=new StrSubstitutor(new ConfigStrLookup(config));

    }

    public String resolveReferences(String template) {
        return substitutor.replace(template);
    }
}

public class OtherClass {
    private static void getIndexConfiguration(String path) throws IOException {
        System.setProperty("config.file", path);
        Config config = ConfigFactory.load();
        String user =  config.getString("es.user");
        String password =  config.getString("es.password");
        String protocol =  config.getString("es.protocol");
        String hostPort =  config.getString("es.hostPort");
        String indexOrTemplateJson = config.getString("es.template_or_index.json");
        String indexOrTemplateName = config.getString("es.template_or_index.name");
        VariableReferenceResolver resolver = new VariableReferenceResolver(config);
        String resolvedIndexOrTemplateJson = resolver.resolveReferences(indexOrTemplateJson);

        File jsonFile = File.createTempFile("index-or-template-json", indexOrTemplateName);
        Files.write(Paths.get(jsonFile.getAbsolutePath()), resolvedIndexOrTemplateJson.getBytes());

        curlIndexOrTemplateCreateCommand =
                String.format(
                        "curl  -XPUT  -k -u %s:%s %s://%s/_template/%s -d @%s",
                        user, password, protocol, hostPort, indexOrTemplateName,  jsonFile.getAbsolutePath());
    }

            ....
}
</code>```

Body:
I'm looking for a way to say:

val c: Config = ConfigFactory.parseString("a=fox,b=dog")
val s: String = """This is a "quick" brown ${a}.\nThat is a lazy, lazy ${b}."""
println(c.resolveString(s))

// Should print:
// > This is a "quick" brown fox.
// > That is a lazy lazy dog.

My two ideas:

Just find the placeholders with regex and replace from config one by one

convert s to config with single value and use resolveWith - but it seems quoting can be really tricky

Maybe there is an easier way?

Body:
I have a similar situation where I automatically push elastic search index definitions before
I launch the job which uses those index definitions.

In my case the string which contains variable references is the
JSON index/template definition, which ALSO comes from the typesafe config.
(see es.template_or_index.json, below.)

I resolve these refs using the utility method I wrote on top
of apache.commons StrSubstitutor.

(see: VariableReferenceResolver.resolveReferences(String template), below)

Below is a sample of my config.  Note how the property 'es.animal' is injected into the index/template json.
This can't be done with out-of-the-box features of the typesafe config library  (but I think this would
be a wonderful feature for them to add !)

 es {
      // user and password credentials should not be checked in to git. deployer is expected to
      // set these parameters into the their environment in whatever way is convenient -- .bashrc or whatever.
      user = dummy
      user = ${?ES_USER}
      password = dummy.passwd
      password = ${?ES_PASSWORD}
      hostPort = "localhost:9200"
      hostPort = ${?ES_HOST_PORT}
      protocol = http
      protocol = ${?ES_PROTOCOL}

      animal = horse            // This gets injected into the configuration property es.template_or_index.json

      // Note: for template json there is a second round of interpolation performed so the json can reference any defined
      // property of this configuration file (or anything it includes)
      template_or_index {
        name = test_template
        json = """
      {
          "template": "${es.animal}_sql-*",
          "settings": {
            "number_of_shards": 50,
            "number_of_replicas": 2
          },
          "mappings": {
                 "test_results" : {
                     "date_detection": false,
                     "properties" : {
                         "timestamp" : { "type" : "date"},
                         "yyyymmdd" : { "type" : "string", "index" : "not_analyzed"}
                     }
                 }
          }
        }
        """
      }
 }

package com.foo

import com.typesafe.config.Config;
import org.apache.commons.lang.text.StrLookup;
import org.apache.commons.lang.text.StrSubstitutor;

public class VariableReferenceResolver {
    final StrSubstitutor substitutor;

    static class ConfigStrLookup extends StrLookup {
          private final Config config;

          ConfigStrLookup(Config config) {
              this.config = config;
          }

          public String lookup(String key) {
              return config.getString(key);
          }
      }

    public VariableReferenceResolver (Config config) {
        substitutor=new StrSubstitutor(new ConfigStrLookup(config));

    }

    public String resolveReferences(String template) {
        return substitutor.replace(template);
    }
}

public class OtherClass {
    private static void getIndexConfiguration(String path) throws IOException {
        System.setProperty("config.file", path);
        Config config = ConfigFactory.load();
        String user =  config.getString("es.user");
        String password =  config.getString("es.password");
        String protocol =  config.getString("es.protocol");
        String hostPort =  config.getString("es.hostPort");
        String indexOrTemplateJson = config.getString("es.template_or_index.json");
        String indexOrTemplateName = config.getString("es.template_or_index.name");
        VariableReferenceResolver resolver = new VariableReferenceResolver(config);
        String resolvedIndexOrTemplateJson = resolver.resolveReferences(indexOrTemplateJson);

        File jsonFile = File.createTempFile("index-or-template-json", indexOrTemplateName);
        Files.write(Paths.get(jsonFile.getAbsolutePath()), resolvedIndexOrTemplateJson.getBytes());

        curlIndexOrTemplateCreateCommand =
                String.format(
                        "curl  -XPUT  -k -u %s:%s %s://%s/_template/%s -d @%s",
                        user, password, protocol, hostPort, indexOrTemplateName,  jsonFile.getAbsolutePath());
    }

            ....
}


问:
Add namespace and schemaLocation to specific nodes using XSLT
I have this input xml:

```<code><root>
<someElement>
    <otherNode>blabla</otherNode>
</someElement>
</root>
</code>```

And I want this output xml:

```<code><root xmlns="http://www.blabla.com/foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<someElement xmlns="http://www.blabla.com/foo"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.blabla.com/foo/some.xsd">
    <otherNode>blabla</otherNode>
</someElement>
</root>
</code>```

Can I do that in one XSLT or I need two steps to do that? I´ve obtained putting namespace on root node but I can´t put the attributes of secondary node.

Thanks in advance.

Sergio

答: The two namespace declarations on the someElement element in your desired output are redundant because they are already present on the root element. There is no way to force an XSLT processor to output redundant namespace declarations.

Body:
I have this input xml:

<root>
<someElement>
    <otherNode>blabla</otherNode>
</someElement>
</root>

And I want this output xml:

<root xmlns="http://www.blabla.com/foo" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<someElement xmlns="http://www.blabla.com/foo"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.blabla.com/foo/some.xsd">
    <otherNode>blabla</otherNode>
</someElement>
</root>

Can I do that in one XSLT or I need two steps to do that? I´ve obtained putting namespace on root node but I can´t put the attributes of secondary node.

Thanks in advance.

Sergio