问:
Generic cloneable/movable parameter as function argument
For an arbitrary struct that implements Clone, I would like to have a single generic function that takes either:

a &MyStruct in which case it can be conditionally cloned by the function

a MyStruct in which case the clone is unnecessary since it can be moved

I've implemented this on my own:

```<code>use std::clone::Clone;

#[derive(Debug)]
struct MyStruct {
    value: u64,
}

impl Clone for MyStruct {
    fn clone(&self) -> Self {
        println!("cloning {:?}", self);
        MyStruct { value: self.value }
    }
}

trait TraitInQuestion<T> {
    fn clone_or_no_op(self) -> T;
}

impl TraitInQuestion<MyStruct> for MyStruct {
    fn clone_or_no_op(self) -> MyStruct {
        self
    }
}

impl<'a> TraitInQuestion<MyStruct> for &'a MyStruct {
    fn clone_or_no_op(self) -> MyStruct {
        self.clone()
    }
}

fn test<T: TraitInQuestion<MyStruct>>(t: T) {
    let owned = t.clone_or_no_op();
}

fn main() {
    let a = MyStruct { value: 8675309 };

    println!("borrowing to be cloned");
    test(&a);

    println!("moving");
    test(a);
}
</code>```

and the output is as expected:

borrowing to be cloned
cloning MyStruct { value: 8675309 }
moving
```

<p>Is this functionality already derived somehow by implementing <code>Clone</code>? If not, <code>std::borrow::ToOwned</code> sounds like what I want, but I can't get it to work:</p>

```use std::clone::Clone;
use std::borrow::Borrow;

#[derive(Debug)]
struct MyStruct {
    value: u64,
}

impl Clone for MyStruct {
    fn clone(&self) -> Self {
        println!("cloning {:?}", self);
        MyStruct { value: self.value }
    }
}

fn test<T: ToOwned<Owned = MyStruct>>(a: T) {
    let owned = a.to_owned();
}

fn main() {
    let a = MyStruct { value: 8675309 };

    println!("borrowing to be cloned");
    test(&a);

    println!("moving");
    test(a);
}
```

<p>Compiler output:</p>

<pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `MyStruct: std::borrow::Borrow<T>` is not satisfied
  --> src/main.rs:16:1
   |
16 | / fn test<T: ToOwned<Owned = MyStruct>>(a: T) {
17 | |     let owned = a.to_owned();
18 | | }
   | |_^ the trait `std::borrow::Borrow<T>` is not implemented for `MyStruct`
   |
   = help: consider adding a `where MyStruct: std::borrow::Borrow<T>` bound
   = note: required by `std::borrow::ToOwned`
</code>```

Doing what the compiler suggests by changing test:

```<code>fn test<T: ToOwned<Owned = MyStruct>>(a: T) -> ()
where
    MyStruct: Borrow<T>,
{
    let owned = a.to_owned();
}
</code>```

And the resulting error:

error[E0308]: mismatched types
  --> src/main.rs:27:10
   |
27 |     test(&a);
   |          ^^ expected struct `MyStruct`, found &MyStruct
   |
   = note: expected type `MyStruct`
              found type `&MyStruct`
```

<p>If I try to implement <code>ToOwned</code> for <code>&MyStruct</code></p>

```impl<'a> ToOwned for &'a MyStruct {
    type Owned = MyStruct;

    fn to_owned(&self) -> Self::Owned {
        self.clone()
    }
}
```

<p>I get the following error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0119]: conflicting implementations of trait `std::borrow::ToOwned` for type `&MyStruct`:
  --> src/main.rs:16:1
   |
16 | / impl<'a> ToOwned for &'a MyStruct {
17 | |     type Owned = MyStruct;
18 | |
19 | |     fn to_owned(&self) -> Self::Owned {
20 | |         self.clone()
21 | |     }
22 | | }
   | |_^
   |
   = note: conflicting implementation in crate `alloc`
</code>```

答:
As @Shepmaster pointed out there is Cow; but you'd need to manually create the Cow::Borrowed(&a) or Cow::Owned(a) instances, and the wrapped (Owned) type must always implement Clone (for T: ToOwned<Owned=T>).

(The Clone for ToOwned::Owned might not be strictly necessary with custom ToOwned implementations; but .borrow().to_owned() acts like a .clone(), so there is no reason to hide it.)

Your own trait is a nice start for an alternative, although you should use generic implementations.  That way you don't require a type to implement Clone as long as you don't pass a reference:

Playground

```<code>trait CloneOrNoOp<T> {
    fn clone_or_no_op(self) -> T;
}

impl<T> CloneOrNoOp<T> for T {
    fn clone_or_no_op(self) -> T {
        self
    }
}

impl<'a, T: Clone> CloneOrNoOp<T> for &'a T {
    fn clone_or_no_op(self) -> T {
        self.clone()
    }
}

struct MyStructNoClone;

#[derive(Debug)]
struct MyStruct {
    value: u64,
}

impl Clone for MyStruct {
    fn clone(&self) -> Self {
        println!("cloning {:?}", self);
        MyStruct { value: self.value }
    }
}

fn test<T: CloneOrNoOp<MyStruct>>(t: T) {
    let _owned = t.clone_or_no_op();
}

// if `I` implement `Clone` this takes either `&I` or `I`; if `I` doesn't
// implement `Clone` it still will accept `I` (but not `&I`).
fn test2<I, T: CloneOrNoOp<I>>(t: T) {
    let _owned: I = t.clone_or_no_op();
}

fn main() {
    let a = MyStruct { value: 8675309 };

    println!("borrowing to be cloned");
    test(&a);
    // cannot infer `I`, could be `&MyStruct` or `MyStruct`:
    // test2(&a);
    test2::<MyStruct,_>(&a);
    test2::<&MyStruct,_>(&a);

    println!("moving");
    test(a);

    let a = MyStructNoClone;
    test2(&a);
    // the previous line is inferred as ("cloning" the reference):
    test2::<&MyStructNoClone,_>(&a);
    // not going to work (because it can't clone):
    // test2::<MyStructNoClone,_>(&a);

    test2(a);
}
</code>```

Sadly it seems impossible for now to base CloneOrNoOp on ToOwned (instead of Clone) like this:

```<code>impl<'a, B> CloneOrNoOp<B::Owned> for &'a B
where
    B: ToOwned,
{
    fn clone_or_no_op(self) -> B::Owned {
        self.to_owned()
    }
}
</code>```

The compiler sees conflicting implementations of "CloneOrNoOp<&_> for type &_" (someone crazy might implement ToOwned for Foo { type Owned = &'static Foo; ... }; traits can't distinguish implementations based on lifetime differences).

But similar to ToOwned you can implement specific customizations, like:

```<code>impl<'a> CloneOrNoOp<String> for &'a str {
    fn clone_or_no_op(self) -> String {
        self.to_owned()
    }
}
</code>```

Now you can pass any of &str, &String or String if you want to get a String:

```<code>test2::<String,_>("abc");
test2::<String,_>(&String::from("abc"));
test2::<String,_>(String::from("abc"));
</code>```

Body:
For an arbitrary struct that implements Clone, I would like to have a single generic function that takes either:

a &MyStruct in which case it can be conditionally cloned by the function

a MyStruct in which case the clone is unnecessary since it can be moved

I've implemented this on my own:

use std::clone::Clone;

#[derive(Debug)]
struct MyStruct {
    value: u64,
}

impl Clone for MyStruct {
    fn clone(&self) -> Self {
        println!("cloning {:?}", self);
        MyStruct { value: self.value }
    }
}

trait TraitInQuestion<T> {
    fn clone_or_no_op(self) -> T;
}

impl TraitInQuestion<MyStruct> for MyStruct {
    fn clone_or_no_op(self) -> MyStruct {
        self
    }
}

impl<'a> TraitInQuestion<MyStruct> for &'a MyStruct {
    fn clone_or_no_op(self) -> MyStruct {
        self.clone()
    }
}

fn test<T: TraitInQuestion<MyStruct>>(t: T) {
    let owned = t.clone_or_no_op();
}

fn main() {
    let a = MyStruct { value: 8675309 };

    println!("borrowing to be cloned");
    test(&a);

    println!("moving");
    test(a);
}

and the output is as expected:

borrowing to be cloned
cloning MyStruct { value: 8675309 }
moving

Is this functionality already derived somehow by implementing Clone? If not, std::borrow::ToOwned sounds like what I want, but I can't get it to work:

use std::clone::Clone;
use std::borrow::Borrow;

#[derive(Debug)]
struct MyStruct {
    value: u64,
}

impl Clone for MyStruct {
    fn clone(&self) -> Self {
        println!("cloning {:?}", self);
        MyStruct { value: self.value }
    }
}

fn test<T: ToOwned<Owned = MyStruct>>(a: T) {
    let owned = a.to_owned();
}

fn main() {
    let a = MyStruct { value: 8675309 };

    println!("borrowing to be cloned");
    test(&a);

    println!("moving");
    test(a);
}

Compiler output:

error[E0277]: the trait bound `MyStruct: std::borrow::Borrow<T>` is not satisfied
  --> src/main.rs:16:1
   |
16 | / fn test<T: ToOwned<Owned = MyStruct>>(a: T) {
17 | |     let owned = a.to_owned();
18 | | }
   | |_^ the trait `std::borrow::Borrow<T>` is not implemented for `MyStruct`
   |
   = help: consider adding a `where MyStruct: std::borrow::Borrow<T>` bound
   = note: required by `std::borrow::ToOwned`

Doing what the compiler suggests by changing test:

fn test<T: ToOwned<Owned = MyStruct>>(a: T) -> ()
where
    MyStruct: Borrow<T>,
{
    let owned = a.to_owned();
}

And the resulting error:

error[E0308]: mismatched types
  --> src/main.rs:27:10
   |
27 |     test(&a);
   |          ^^ expected struct `MyStruct`, found &MyStruct
   |
   = note: expected type `MyStruct`
              found type `&MyStruct`

If I try to implement ToOwned for &MyStruct

impl<'a> ToOwned for &'a MyStruct {
    type Owned = MyStruct;

    fn to_owned(&self) -> Self::Owned {
        self.clone()
    }
}

I get the following error:

error[E0119]: conflicting implementations of trait `std::borrow::ToOwned` for type `&MyStruct`:
  --> src/main.rs:16:1
   |
16 | / impl<'a> ToOwned for &'a MyStruct {
17 | |     type Owned = MyStruct;
18 | |
19 | |     fn to_owned(&self) -> Self::Owned {
20 | |         self.clone()
21 | |     }
22 | | }
   | |_^
   |
   = note: conflicting implementation in crate `alloc`

Body:
As @Shepmaster pointed out there is Cow; but you'd need to manually create the Cow::Borrowed(&a) or Cow::Owned(a) instances, and the wrapped (Owned) type must always implement Clone (for T: ToOwned<Owned=T>).

(The Clone for ToOwned::Owned might not be strictly necessary with custom ToOwned implementations; but .borrow().to_owned() acts like a .clone(), so there is no reason to hide it.)

Your own trait is a nice start for an alternative, although you should use generic implementations.  That way you don't require a type to implement Clone as long as you don't pass a reference:

Playground

trait CloneOrNoOp<T> {
    fn clone_or_no_op(self) -> T;
}

impl<T> CloneOrNoOp<T> for T {
    fn clone_or_no_op(self) -> T {
        self
    }
}

impl<'a, T: Clone> CloneOrNoOp<T> for &'a T {
    fn clone_or_no_op(self) -> T {
        self.clone()
    }
}

struct MyStructNoClone;

#[derive(Debug)]
struct MyStruct {
    value: u64,
}

impl Clone for MyStruct {
    fn clone(&self) -> Self {
        println!("cloning {:?}", self);
        MyStruct { value: self.value }
    }
}

fn test<T: CloneOrNoOp<MyStruct>>(t: T) {
    let _owned = t.clone_or_no_op();
}

// if `I` implement `Clone` this takes either `&I` or `I`; if `I` doesn't
// implement `Clone` it still will accept `I` (but not `&I`).
fn test2<I, T: CloneOrNoOp<I>>(t: T) {
    let _owned: I = t.clone_or_no_op();
}

fn main() {
    let a = MyStruct { value: 8675309 };

    println!("borrowing to be cloned");
    test(&a);
    // cannot infer `I`, could be `&MyStruct` or `MyStruct`:
    // test2(&a);
    test2::<MyStruct,_>(&a);
    test2::<&MyStruct,_>(&a);

    println!("moving");
    test(a);

    let a = MyStructNoClone;
    test2(&a);
    // the previous line is inferred as ("cloning" the reference):
    test2::<&MyStructNoClone,_>(&a);
    // not going to work (because it can't clone):
    // test2::<MyStructNoClone,_>(&a);

    test2(a);
}

Sadly it seems impossible for now to base CloneOrNoOp on ToOwned (instead of Clone) like this:

impl<'a, B> CloneOrNoOp<B::Owned> for &'a B
where
    B: ToOwned,
{
    fn clone_or_no_op(self) -> B::Owned {
        self.to_owned()
    }
}

The compiler sees conflicting implementations of "CloneOrNoOp<&_> for type &_" (someone crazy might implement ToOwned for Foo { type Owned = &'static Foo; ... }; traits can't distinguish implementations based on lifetime differences).

But similar to ToOwned you can implement specific customizations, like:

impl<'a> CloneOrNoOp<String> for &'a str {
    fn clone_or_no_op(self) -> String {
        self.to_owned()
    }
}

Now you can pass any of &str, &String or String if you want to get a String:

test2::<String,_>("abc");
test2::<String,_>(&String::from("abc"));
test2::<String,_>(String::from("abc"));


来源: stackexchange

问:
Control docker-compose in Java
I created a fairly amount of docker-compose scripts which spawn up several services. I now want to control docker-compose in the JVM. Basically, I want to be able to execute up and down, ideally with -p <project name> parameter, so I can spawn multiple instances at the same time.

Is this possible in Java?

答:
Docker Compose is a python utility that talks directly to the same Docker API as the all the other Docker clients. There's nothing fundamentally different about the commands it sends, but it does manage a lot of Docker container life cycle for you inside it's code.

Compose is based on the docker python module which is just another python Docker API client.

It would probably take a lot to reimplement the same in Java, here is the up method. Maybe try pulling that in with Jython if you really need to do it from the JVM or stick with executing the docker-compose commands from Java.

ContentLicense: CC BY-SA 3.0

Title: Control docker-compose in Java


问:
Getting error in api calling in retrofit 1.9.0
My api call is like this

```<code>@FormUrlEncoded
    @POST("/dealer/index.php")
    void getDealersPacks(
            @Query("r") String query,
            @Field("cd_dealer_id")
                    String cd_dealer_id,
            @Field("country_code")
                    String country_code,
            @Field("business_type")
                    String business_type, Callback<String> cb);
</code>```

And i am getting this error

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_STRING but was OBJECT at line 1 column 59 path $.
</code>```

答: The error says the method "getDealersPacks" is expecting a string value. But what you are sending as a parameter is an Object. So it is throwing syntax exception. Please properly check the data type of input params that you are sending.</p>

Body:
My api call is like this

@FormUrlEncoded
    @POST("/dealer/index.php")
    void getDealersPacks(
            @Query("r") String query,
            @Field("cd_dealer_id")
                    String cd_dealer_id,
            @Field("country_code")
                    String country_code,
            @Field("business_type")
                    String business_type, Callback<String> cb);

And i am getting this error

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_STRING but was OBJECT at line 1 column 59 path $.


问:
isMemberOfClass in Swift
The keyword is is equivalent to isKindOfClass.

But I am unable to find what is equivalent of isMemberOfClass in swift.

Note:
My question is not about the difference between isKindOfClass or isMemberofclass rather the question is about what is the equivalent of isMemberofClass in Swift

somebody please clarify

答:
In case of optional variable type(of:) returns the type from initialization.

Example:

```<code>class Animal {}
class Cat : Animal {}

var c: Animal?
c = Cat()

type(of: c) // _expr_63.Animal>.Type
type(of: c) == Cat?.self // false
type(of: c) == Animal?.self // true
</code>```

My class was inherited from NSObject, so I used its variable classForCoder and it worked for me.

```<code>class Animal : NSObject {}
class Cat : Animal {}

var c: Animal?
c = Cat()
c?.classForCoder == Cat.self // true
</code>```

Title: isMemberOfClass in Swift

Body:
In case of optional variable type(of:) returns the type from initialization.

Example:

class Animal {}
class Cat : Animal {}

var c: Animal?
c = Cat()

type(of: c) // _expr_63.Animal>.Type
type(of: c) == Cat?.self // false
type(of: c) == Animal?.self // true

My class was inherited from NSObject, so I used its variable classForCoder and it worked for me.

class Animal : NSObject {}
class Cat : Animal {}

var c: Animal?
c = Cat()
c?.classForCoder == Cat.self // true


问:
c++ Genetic Algorithm Mutation error
I Have a problem with the mutation function within my genetic Algorithm. I can't quite see what I am doing wrong either. I've looked at this code for a while and I think the logic is correct, it's just not producing the results i want.

The problem
When i output the Binary array located in the Child Struct, If mutation has occured on any of the bits, then a random number will be changed, and not the one that should be.

for example

0000000 is the binary string

mutation has occured on the second
bit

0001000 would be the result

This section is located within the main.

```<code>for (int Child = 0; Child < ParentNumberInit; Child++)
{
    cout << endl;
    mutation(child[Child],Child);
}
</code>```

This is the mutation function

```<code>void mutation(struct Parent Child1,int childnumber)
{
    int mutation; // will be the random number generated

    cout << endl << "Child " << (childnumber+1) << endl;

    //loop through every bit in the binary string
    for (int z = 0; z < Binscale; z++)
    {
        mutation = 0;   // set mutation at 0 at the start of every loop
        mutation = rand()%100;      //create a random number

        cout << "Generated number = " << mutation << endl;

        //if variable mutation is smaller, mutation occurs
        if (mutation < MutationRate)
        {
            if(Child1.binary_code[z] == '0')
                Child1.binary_code[z] = '1';
            else if(Child1.binary_code[z] == '1')
                Child1.binary_code[z] = '0';
        }
    }
}
</code>```

It's being outputted in the main like this

```<code>    for (int childnumber = 0; childnumber < ParentNumberInit; childnumber++)
    {
        cout<<"Child "<<(childnumber+1)<<" Binary code = ";
        for (int z = 0; z < Binscale; z ++)
        {
        cout<<child[childnumber].binary_code[z];
        }
        cout<<endl;
     }
</code>```

答:
try this:</p>

```<code>void mutation(Parent& Child1,int childnumber)
</code>```

ContentLicense: CC BY-SA 2.5

Title: c++ Genetic Algorithm Mutation error

Body:
I Have a problem with the mutation function within my genetic Algorithm. I can't quite see what I am doing wrong either. I've looked at this code for a while and I think the logic is correct, it's just not producing the results i want.

The problem
When i output the Binary array located in the Child Struct, If mutation has occured on any of the bits, then a random number will be changed, and not the one that should be.

for example

0000000 is the binary string

mutation has occured on the second
bit

0001000 would be the result

This section is located within the main.

for (int Child = 0; Child < ParentNumberInit; Child++)
{
    cout << endl;
    mutation(child[Child],Child);
}

This is the mutation function

void mutation(struct Parent Child1,int childnumber)
{
    int mutation; // will be the random number generated

    cout << endl << "Child " << (childnumber+1) << endl;

    //loop through every bit in the binary string
    for (int z = 0; z < Binscale; z++)
    {
        mutation = 0;   // set mutation at 0 at the start of every loop
        mutation = rand()%100;      //create a random number

        cout << "Generated number = " << mutation << endl;

        //if variable mutation is smaller, mutation occurs
        if (mutation < MutationRate)
        {
            if(Child1.binary_code[z] == '0')
                Child1.binary_code[z] = '1';
            else if(Child1.binary_code[z] == '1')
                Child1.binary_code[z] = '0';
        }
    }
}

It's being outputted in the main like this

    for (int childnumber = 0; childnumber < ParentNumberInit; childnumber++)
    {
        cout<<"Child "<<(childnumber+1)<<" Binary code = ";
        for (int z = 0; z < Binscale; z ++)
        {
        cout<<child[childnumber].binary_code[z];
        }
        cout<<endl;
     }

Body:
try this:

void mutation(Parent& Child1,int childnumber)


问:
Read file from FTP to memory in C#
I want to read a file from a FTP server without downloading it to a local file. I wrote a function but it does not work:</p>

```<code>private string GetServerVersion()
{
    WebClient request = new WebClient();

    string url = FtpPath + FileName;
    string version = "";

    request.Credentials = new NetworkCredential(ftp_user, ftp_pas);

    try
    {
        byte[] newFileData = request.DownloadData(new Uri(FtpPath)+FileName);
        string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
    }
    catch (WebException e)
    {
    }
    return version;
}
</code>```

答:
Small binary file

If the file is small, the easiest way is using WebClient.DownloadData:

```<code>WebClient client = new WebClient();
string url = "ftp://ftp.example.com/remote/path/file.zip";
client.Credentials = new NetworkCredential("username", "password");
byte[] contents = client.DownloadData(url);
</code>```

Small text file

If the small file is a text file, use WebClient.DownloadString:

```<code>string contents = client.DownloadString(url);
</code>```

It assumes that the file contents is in UTF-8 encoding (a plain ASCII file will do too). If you need to use a different encoding, use WebClient.Encoding property.

Large binary file

If the file is large, so that you need to process it in chunks, instead of loading it to memory whole, use FtpWebRequest:

```<code>FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream stream = request.GetResponse().GetResponseStream())
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        // process the chunk in "buffer"
    }
}
</code>```

You can also simplify the code by using WebClient.OpenRead.

Large text file

If the large file is a text file and you want to process it by lines, instead of by chunks of a fixed size, use StreamReader:

```<code>FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream stream = request.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        // process the line
        Console.WriteLine(line);
    }
}
</code>```

Again, this assumes UTF-8 encoding. If you want to use another encoding, use an overload of StreamReader constructor that takes also Encoding.

As previously, you can simplify the code by using WebClient.OpenRead.

Stream interface

Though, in many cases, you will want to use the downloaded data in some API that uses the Stream interface. In that case, instead of using any of the solutions above, directly use the stream returned by request.GetResponse().GetResponseStream() or WebClient.OpenRead in the API.

For an example, see Transferring files from FTP directly to Azure Blob storage in C#.

Title: Read file from FTP to memory in C#

Body:
I want to read a file from a FTP server without downloading it to a local file. I wrote a function but it does not work:

private string GetServerVersion()
{
    WebClient request = new WebClient();

    string url = FtpPath + FileName;
    string version = "";

    request.Credentials = new NetworkCredential(ftp_user, ftp_pas);

    try
    {
        byte[] newFileData = request.DownloadData(new Uri(FtpPath)+FileName);
        string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
    }
    catch (WebException e)
    {
    }
    return version;
}

Body:
Small binary file

If the file is small, the easiest way is using WebClient.DownloadData:

WebClient client = new WebClient();
string url = "ftp://ftp.example.com/remote/path/file.zip";
client.Credentials = new NetworkCredential("username", "password");
byte[] contents = client.DownloadData(url);

Small text file

If the small file is a text file, use WebClient.DownloadString:

string contents = client.DownloadString(url);

It assumes that the file contents is in UTF-8 encoding (a plain ASCII file will do too). If you need to use a different encoding, use WebClient.Encoding property.

Large binary file

If the file is large, so that you need to process it in chunks, instead of loading it to memory whole, use FtpWebRequest:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream stream = request.GetResponse().GetResponseStream())
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        // process the chunk in "buffer"
    }
}

You can also simplify the code by using WebClient.OpenRead.

Large text file

If the large file is a text file and you want to process it by lines, instead of by chunks of a fixed size, use StreamReader:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream stream = request.GetResponse().GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        // process the line
        Console.WriteLine(line);
    }
}

Again, this assumes UTF-8 encoding. If you want to use another encoding, use an overload of StreamReader constructor that takes also Encoding.

As previously, you can simplify the code by using WebClient.OpenRead.

Stream interface

Though, in many cases, you will want to use the downloaded data in some API that uses the Stream interface. In that case, instead of using any of the solutions above, directly use the stream returned by request.GetResponse().GetResponseStream() or WebClient.OpenRead in the API.

For an example, see Transferring files from FTP directly to Azure Blob storage in C#.

ContentLicense: CC BY-SA 4.0


问:
SharePoint send email with javascript on add list item
I like to send an email to the administrator when a user adds a item to my List. I already changed the NewForm for the list and execute the add item with:

```<code>SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
</code>```

Now in my SharePoint the email notification on Lists has been disabled by the company. So I'd like some code to send an email automatically after the user added an item.
I already have the username of the person who added the item.

```<code>var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
</code>```

The email has to be send to an address of the companies outlook server. An SMTP can be used.

Marco

答:
Here is a little code snippet to send email using javascript.

```<code>function getUserEmail(){
 $.ajax({
   url:spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid("+_spPageContextInfo.userId+")?$select=Email",
   headers:{"Accept": "application/json;odata=verbose","content-type": "application/json;odata=verbose"},
   success:function(result){
      var email = result.d.Email;
      sendEmail("xxxx@email.com", email, "body", "subject");
   }
  });
}

function sendEmail(from, to, body, subject) {

    var siteurl = _spPageContextInfo.webServerRelativeUrl;
    var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': {
                    'type': 'SP.Utilities.EmailProperties'
                },
                'From': from,
                'To': {
                    'results': [to]
                },
                'Body': body,
                'Subject': subject
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            console.log(data);
        },
        error: function (err) {
            console.error(err);
        }
    });
}
</code>```

But it also depends on your scenario. Can you give us more details about:

I already changed the NewForm for the list and execute the add item with:

How did you proceed?
Are you working on on-premise or online instance?

Body:
I like to send an email to the administrator when a user adds a item to my List. I already changed the NewForm for the list and execute the add item with:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);

Now in my SharePoint the email notification on Lists has been disabled by the company. So I'd like some code to send an email automatically after the user added an item.
I already have the username of the person who added the item.

var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

The email has to be send to an address of the companies outlook server. An SMTP can be used.

Marco

Body:
Here is a little code snippet to send email using javascript.

function getUserEmail(){
 $.ajax({
   url:spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid("+_spPageContextInfo.userId+")?$select=Email",
   headers:{"Accept": "application/json;odata=verbose","content-type": "application/json;odata=verbose"},
   success:function(result){
      var email = result.d.Email;
      sendEmail("xxxx@email.com", email, "body", "subject");
   }
  });
}

function sendEmail(from, to, body, subject) {

    var siteurl = _spPageContextInfo.webServerRelativeUrl;
    var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
    $.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: "POST",
        data: JSON.stringify({
            'properties': {
                '__metadata': {
                    'type': 'SP.Utilities.EmailProperties'
                },
                'From': from,
                'To': {
                    'results': [to]
                },
                'Body': body,
                'Subject': subject
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            console.log(data);
        },
        error: function (err) {
            console.error(err);
        }
    });
}

But it also depends on your scenario. Can you give us more details about:

I already changed the NewForm for the list and execute the add item with:

How did you proceed?
Are you working on on-premise or online instance?


问:
Positioning divs on top of an image that's utilizing the flex CSS property
For a web application, I'm to position an animated emoji along with some text in a div. These elements are to remain separated in a fully responsive way. Behold:

I'm using flex to accomplish this. That ensures that even if the screen size becomes extremely small, separation is still kept by stacking these one on top of the other.

To accomplish it, the whole outer div is wrapped in:

```<code>.act{
  display: flex;
  flex-wrap: wrap;
  background-color: #E1F5FE;
  padding: 10px;
  border-radius: 10px;
  align-items: center;
}
</code>```

Next, the animated image inside the div is wrapped in:

```<code>.anim {
  flex: 1 1;
  min-width: 64px;
  text-align: center;

}

.anim > img {
  width: 100%;
  height: auto;
  max-width: 50px;
}
</code>```

Lastly, the text along with the image is wrapped in:

```<code>.txt {
  flex: 1 1 180px;
  text-align: center;
}
</code>```

Did you notice the tear drops on the emoji? Those are separate from the image, and are to be animated in html5.

I can't figure out how to ensure those tear drops stay precisely around the eyes of the emoji. I have tried using a z-index alongwith position:absolute (e.g. see the following):

```<code>    <div class="anim">
          <div class="tear" style="z-index:2;position:absolute;margin-top: 30px;margin-left: 110px;"></div>
          <div class="tear" style="z-index:2;position:absolute;margin-top: 30px;margin-left: 84px;"></div>
          <img src="sad.png">
    </div>
</code>```

This isn't responsive at all.

Moreover, If I try usingposition:relative, that makes it impossible to overlap the tear shape over the emoji, regardless of what z-index I set.

Please help me fix this situation. Ideally, I want to stick to using flex because otherwise, it's perfect for my needs.

Note: Answers to a similar SO question don't help since I've already included what they're suggesting.

答:
To accomplish that you need a wrapper around the image and text, that take the size of the image.

Here is a sample code, where I added an extra wrapper, image, around the anim, and then made the anim display as inline block.

Here the image wrapper become the flex item instead, and will allow the anim to behave and be sized as the image, and create the boundaries you need to be able to place the eyes at a fixed position on top the image.

Stack snippet

.act {
  display: flex;
  flex-wrap: wrap;
  background-color: #E1F5FE;
  padding: 10px;
  border-radius: 10px;
  align-items: center;
}

.image {
  flex: 1 1;
  min-width: 64px;
  text-align: center;
}

.anim {
  display: inline-block;
  position: relative;
}

.anim>img {
  width: 100%;
  max-width: 50px;
}

.txt {
  flex: 1 1 180px;
  text-align: center;
}

.tear {
  position:absolute;
  top: 10px;
  left: 30px;
  width: 10px;
  height: 10px;
  background: blue;
}
.tear:first-child {
  left: 10px;"
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="act">

  <div class="image">
    <div class="anim">
      <div class="tear"></div>
      <div class="tear"></div>
      <img src="http://placehold.it/150">
    </div>
  </div>

  <div class="txt">
    Some text
  </div>

</div></code>```

Body:
For a web application, I'm to position an animated emoji along with some text in a div. These elements are to remain separated in a fully responsive way. Behold:

I'm using flex to accomplish this. That ensures that even if the screen size becomes extremely small, separation is still kept by stacking these one on top of the other.

To accomplish it, the whole outer div is wrapped in:

.act{
  display: flex;
  flex-wrap: wrap;
  background-color: #E1F5FE;
  padding: 10px;
  border-radius: 10px;
  align-items: center;
}

Next, the animated image inside the div is wrapped in:

.anim {
  flex: 1 1;
  min-width: 64px;
  text-align: center;

}

.anim > img {
  width: 100%;
  height: auto;
  max-width: 50px;
}

Lastly, the text along with the image is wrapped in:

.txt {
  flex: 1 1 180px;
  text-align: center;
}

Did you notice the tear drops on the emoji? Those are separate from the image, and are to be animated in html5.

I can't figure out how to ensure those tear drops stay precisely around the eyes of the emoji. I have tried using a z-index alongwith position:absolute (e.g. see the following):

This isn't responsive at all.

Moreover, If I try usingposition:relative, that makes it impossible to overlap the tear shape over the emoji, regardless of what z-index I set.

Please help me fix this situation. Ideally, I want to stick to using flex because otherwise, it's perfect for my needs.

Note: Answers to a similar SO question don't help since I've already included what they're suggesting.

Body:
To accomplish that you need a wrapper around the image and text, that take the size of the image.

Here is a sample code, where I added an extra wrapper, image, around the anim, and then made the anim display as inline block.

Here the image wrapper become the flex item instead, and will allow the anim to behave and be sized as the image, and create the boundaries you need to be able to place the eyes at a fixed position on top the image.

Stack snippet

.act {
  display: flex;
  flex-wrap: wrap;
  background-color: #E1F5FE;
  padding: 10px;
  border-radius: 10px;
  align-items: center;
}

.image {
  flex: 1 1;
  min-width: 64px;
  text-align: center;
}

.anim {
  display: inline-block;
  position: relative;
}

.anim>img {
  width: 100%;
  max-width: 50px;
}

.txt {
  flex: 1 1 180px;
  text-align: center;
}

.tear {
  position:absolute;
  top: 10px;
  left: 30px;
  width: 10px;
  height: 10px;
  background: blue;
}
.tear:first-child {
  left: 10px;"
}

<div class="act">

  <div class="image">
    <div class="anim">
      <div class="tear"></div>
      <div class="tear"></div>
      <img src="http://placehold.it/150">
    </div>
  </div>

  <div class="txt">
    Some text
  </div>

</div>


问:
Downsampling audio in javascript
I want to downsample an audio buffer in javascript. I am using OfflineAudioContext, but the output audio quality is significantly worse than the original audio (at 44100Hz). Is there any solution for higher quality audio resampling in javascript than this:</p>

```<code>var sampleRate = 44100;
var outSampleRate = 16000;
var durationInSamples = audioBuffer441k.length;
var o = new OfflineAudioContext(1, durationInSamples*outSampleRate/sampleRate, outSampleRate);
var b = o.createBuffer(1, durationInSamples, sampleRate);

var buf = b.getChannelData(0);
for (var i = 0; i < durationInSamples; i++) {
   buf[i] = audioBuffer441k[i];
}

var source = o.createBufferSource();
source.buffer = b;
source.connect(o.destination);
source.start(0);
o.startRendering();
o.oncomplete = function(audiobuffer16k) {
  console.log("done resampling!!");
  console.log(audiobuffer16k.renderedBuffer);
  //do something with resampled audio
}
</code>```

答:
Direct interpolation algorithms are not enough to achieve qualified/lossless conversions. Linear interpolation is nearly killing the waveform. It's like downcasting an object. You need a resampler supporting sine/cosine curving
 nonlinear interpolation but it's now so difficult to find a pure js solution for it unless anyone implement o strong solution and share.

Try to capture your data at the frequency you desire. Resampling it always reduces the quality (especially in pure javascript code)

take a look at for linear-weight based interpolation resampling in XAudioJS:
https://stackoverflow.com/a/30032095/5896342

Title: Downsampling audio in javascript

Body:
I want to downsample an audio buffer in javascript. I am using OfflineAudioContext, but the output audio quality is significantly worse than the original audio (at 44100Hz). Is there any solution for higher quality audio resampling in javascript than this:

var sampleRate = 44100;
var outSampleRate = 16000;
var durationInSamples = audioBuffer441k.length;
var o = new OfflineAudioContext(1, durationInSamples*outSampleRate/sampleRate, outSampleRate);
var b = o.createBuffer(1, durationInSamples, sampleRate);

var buf = b.getChannelData(0);
for (var i = 0; i < durationInSamples; i++) {
   buf[i] = audioBuffer441k[i];
}

var source = o.createBufferSource();
source.buffer = b;
source.connect(o.destination);
source.start(0);
o.startRendering();
o.oncomplete = function(audiobuffer16k) {
  console.log("done resampling!!");
  console.log(audiobuffer16k.renderedBuffer);
  //do something with resampled audio
}


问:
Show more and less with respective height or content
Hi i was trying to create a dynamic table, it has to display only 2 item(rows) and other rows need to be hidden, on click showmore remaining rows has to display.

Thanks

```<code><table class="table borderless">
  <thead>
    <tr>
      <th></th>
      <th>Thead1</th>
      <th>Thead2</th>
    </tr>
  </thead>
  <tbody class="tbodySpace">
    <tr>
      <td>Row 1 - heading</td>
      <td>
        data1
      </td>
      <td>
        data2
      </td>
    </tr>
    <tr>
      <td>Row 2 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
    <tr>
      <td>Row 3 - heading</td>
      <td>
        data3
      </td>
      <td>
        data4
      </td>
    </tr>
  </tbody>
</table>
<button class="button">Show more</button>
</code>```

Jsfiddle is here

答:
Try this jquery

```<code>$('.button').on('click',function(){
  if($(this).text()=='Show more') {
     $('.tbodySpace tr').each(function(){
      $(this).show();
     });
     $(this).text('Show Less');
  }
  else {
    $('.tbodySpace tr').each(function(i,e){
     if(i>=2)
      $(this).hide();
    });
    $(this).text('Show more');
  }
});
$('.tbodySpace tr').each(function(i,e){
    if(i>=2)
    $(this).hide();
});
</code>```

Working fiddle

Body:
Hi i was trying to create a dynamic table, it has to display only 2 item(rows) and other rows need to be hidden, on click showmore remaining rows has to display.

Thanks

      Thead1
      Thead2

      Row 1 - heading

        data1

        data2

      Row 2 - heading

        data3

        data4

      Row 3 - heading

        data3

        data4

<button class="button">Show more</button>

Jsfiddle is here

Body:
Try this jquery

$('.button').on('click',function(){
  if($(this).text()=='Show more') {
     $('.tbodySpace tr').each(function(){
      $(this).show();
     });
     $(this).text('Show Less');
  }
  else {
    $('.tbodySpace tr').each(function(i,e){
     if(i>=2)
      $(this).hide();
    });
    $(this).text('Show more');
  }
});
$('.tbodySpace tr').each(function(i,e){
    if(i>=2)
    $(this).hide();
});

Working fiddle


问:
Android Custom Tab - Text Scrolling
I am trying to implement a custom TabHost with colored tabs.  I've been following stackoverflow member Josh Clemm's excellent example.  The coloring works great.  In the default out of the box TabHost, if the text to be displayed in the tab doesn't fit it, it does this nice scrolling of the text inside the tab itself.  It only does this on the active tab and seems to be on a timer where it will pause and the rescroll the text a few times.

Now with the custom tabs I've lost that.  Has anyone else run into this and solved this problem already?

答: Use android:ellipsize="marquee" and related attributes on your TextView.

Title: Android Custom Tab - Text Scrolling


问:
what did is difference between java and kotlin about visibility modifiers?

This is what the official document says. But when I do something like this:

```<code>var human : Human? = null
</code>```

and decompile it into java code, I find it actually was

```<code>@Nullable
private Human human;
</code>```

and it's no use to write this

```<code>public var human : Human? = null
</code>```

but when I write this:

```<code>lateinit var human : Human
</code>```

it become public this time

```<code>@NotNull
public Human human;
</code>```

it was a big problem when I use Dagger2

in Dagger2  the property be injected must be public, but if i write var human : Human? = null
it will fail to build.

答:
I slove my problem by myself.

Actually , what kotlin's public mean is private + getter and setter , private is jsut private has no getter and setter.  The official document didn't explain that clearly.

So , it add some explain at the chapter Calling Kotlin from Java  it means  if you want your properties is public , you can use
@JvmField or
lateinit var

It's my fault , i didn't  reading the document carefullly

Body:
This is what the official document says. But when I do something like this:

var human : Human? = null

and decompile it into java code, I find it actually was

@Nullable
private Human human;

and it's no use to write this

public var human : Human? = null

but when I write this:

lateinit var human : Human

it become public this time

@NotNull
public Human human;

it was a big problem when I use Dagger2

in Dagger2  the property be injected must be public, but if i write var human : Human? = null
it will fail to build.


问:
Assigning ID to a Row in an Android ListView
I have a ListView. When an item on the ListView is tapped, it loads a SubView. I want to assign an ID to each row of the ListView, so I can pass that ID along to the SubView. How do I assign a specific ID to each row in the ListView?

Here is how I am currently loading the ListView:

```<code>setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mArrayList));
</code>```

答:
After spending hours on this, this easiest way I found was to override bindView of the adapter and set a tag value containing the row's _id on the item - in my case, it was a button in the ListView row.</p>

```<code>SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.note, cursor, fromColumns, toViews, 0) {

    @Override
    // add the _id field value to the button's tag
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView(view, context, cursor);
        Integer index = cursor.getColumnIndex("_id");
        Integer row_id = cursor.getInt(index);
        Button button = (Button) view.findViewById(R.id.button_delete_record);
        button.setTag(row_id);
    }
};
</code>```

Body:
I have a ListView. When an item on the ListView is tapped, it loads a SubView. I want to assign an ID to each row of the ListView, so I can pass that ID along to the SubView. How do I assign a specific ID to each row in the ListView?

Here is how I am currently loading the ListView:

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, mArrayList));

Body:
After spending hours on this, this easiest way I found was to override bindView of the adapter and set a tag value containing the row's _id on the item - in my case, it was a button in the ListView row.

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
        R.layout.note, cursor, fromColumns, toViews, 0) {

    @Override
    // add the _id field value to the button's tag
    public void bindView(View view, Context context, Cursor cursor) {
        super.bindView(view, context, cursor);
        Integer index = cursor.getColumnIndex("_id");
        Integer row_id = cursor.getInt(index);
        Button button = (Button) view.findViewById(R.id.button_delete_record);
        button.setTag(row_id);
    }
};


问:
create-react-app npm run build fail to minify watson node sdk
I am new to React and I am trying to build a react app using create-react-app and Watson node-sdk. Everything works fine in development mode after running npm start. But when I try to build a production package using npm run build and below is the error I receive.

```<code>e:\Microsoft\Workspace\React\myapp>npm run build

> myapp@0.1.0 build e:\Microsoft\Workspace\React\myapp
> react-scripts build

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

    ./node_modules/watson-developer-cloud/lib/helper.js:31

Read more here: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myapp@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yk\AppData\Roaming\npm-cache\_logs\2017-09-
20T09_40_36_144Z-debug.log
</code>```

The line that giving error is let missing; and seems like the let is causing the issue. Is there anything I can do with this?

答:
Encountered this problem today. the doc suggests some solutions:

Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled.

Fork the package and publish a corrected version yourself.

If the dependency is small enough, copy it to your src/ folder and treat it as application code.

Read more here: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify

Body:
I am new to React and I am trying to build a react app using create-react-app and Watson node-sdk. Everything works fine in development mode after running npm start. But when I try to build a production package using npm run build and below is the error I receive.

e:\Microsoft\Workspace\React\myapp>npm run build

> myapp@0.1.0 build e:\Microsoft\Workspace\React\myapp
> react-scripts build

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

    ./node_modules/watson-developer-cloud/lib/helper.js:31

Read more here: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! myapp@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\yk\AppData\Roaming\npm-cache\_logs\2017-09-
20T09_40_36_144Z-debug.log

The line that giving error is let missing; and seems like the let is causing the issue. Is there anything I can do with this?


问:
How to show only 7 days in a calender from current date to next 6 days
i'm developing android app which requires calender with Only 7 days from current date : if Today is Wed day, so results will be wed -- till tuesday i need to show in view of my calender.</p>

```<code>Calendar instance = Calendar.getInstance();
widget.setSelectedDate(instance.getTime());
Calendar instance1 = Calendar.getInstance();
instance1.set(instance1.get(Calendar.YEAR), Calendar.JANUARY, 1);
Calendar instance2 = Calendar.getInstance();
instance2.set(instance2.get(Calendar.YEAR), Calendar.DECEMBER, 31);
widget.state().edit()
        .setMinimumDate(instance1.getTime())
        .setMaximumDate(instance2.getTime())
        .commit();
widget.addDecorators(
        new MySelectorDecorator(this),
        new HighlightWeekendsDecorator(),
        oneDayDecorator);
</code>```

答:
If you use CalendarView or DatePickerDialog, you can set min date = today and set max date = today + 7.

```<code>CalendarView calendarView = (CalendarView) findViewById(R.id.cl);
long currentTime = System.currentTimeMillis();
long maxTime = currentTime + 1000 * 60 * 60 * 24 * 7;
calendarView.setMinDate(currentTime);
calendarView.setMaxDate(maxTime);
</code>```

Hope it can help you.

Body:
i'm developing android app which requires calender with Only 7 days from current date : if Today is Wed day, so results will be wed -- till tuesday i need to show in view of my calender.

Calendar instance = Calendar.getInstance();
widget.setSelectedDate(instance.getTime());
Calendar instance1 = Calendar.getInstance();
instance1.set(instance1.get(Calendar.YEAR), Calendar.JANUARY, 1);
Calendar instance2 = Calendar.getInstance();
instance2.set(instance2.get(Calendar.YEAR), Calendar.DECEMBER, 31);
widget.state().edit()
        .setMinimumDate(instance1.getTime())
        .setMaximumDate(instance2.getTime())
        .commit();
widget.addDecorators(
        new MySelectorDecorator(this),
        new HighlightWeekendsDecorator(),
        oneDayDecorator);

Body:
If you use CalendarView or DatePickerDialog, you can set min date = today and set max date = today + 7.

CalendarView calendarView = (CalendarView) findViewById(R.id.cl);
long currentTime = System.currentTimeMillis();
long maxTime = currentTime + 1000 * 60 * 60 * 24 * 7;
calendarView.setMinDate(currentTime);
calendarView.setMaxDate(maxTime);

Hope it can help you.


问:
Android Studio 3.0: Unable to resolve module dependency
I have a one main project and second project (module).

After I import the module project as a module dependency into app project and try to sync everything, I get the following error:

```<code>Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :module.
Could not resolve project :module.
Required by: project :app
Unable to find a matching configuration of project :module:
 - Configuration 'debugApiElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found compatible value 'java-api'.
 - Configuration 'debugMetadataElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Metadata'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' but no value provided.
 - Configuration 'debugRuntimeElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found incompatible value 'java-runtime'.
 - Configuration 'releaseApiElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found compatible value 'java-api'.
 - Configuration 'releaseMetadataElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Metadata'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' but no value provided.
 - Configuration 'releaseRuntimeElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found incompatible value 'java-runtime'.
</code>```

My dependency in main app.gradle:

```<code>compile project(':module')
</code>```

I found out that if I change it to the following:

```<code>compile project(path: ':module', configuration:'default')
</code>```

Then the project synchronizes and builds.

However in main project class files I am unable to import any files from the module project.

Spent already couple hours searching for answers and nothing I've found so far helps. Went as far as to reinstalling Android Studio 3.0 but it didn't help.

答:
Solved my problem.

I created test module using  apply plugin: 'com.android.application' when it should be using apply plugin: 'com.android.library'.

While you can have multiple application modules in a project, you cannot have application modules depend on other application modules.

Body:
I have a one main project and second project (module).

After I import the module project as a module dependency into app project and try to sync everything, I get the following error:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve project :module.
Could not resolve project :module.
Required by: project :app
Unable to find a matching configuration of project :module:
 - Configuration 'debugApiElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found compatible value 'java-api'.
 - Configuration 'debugMetadataElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Metadata'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' but no value provided.
 - Configuration 'debugRuntimeElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found compatible value 'debug'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'debug' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found incompatible value 'java-runtime'.
 - Configuration 'releaseApiElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found compatible value 'java-api'.
 - Configuration 'releaseMetadataElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Metadata'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' but no value provided.
 - Configuration 'releaseRuntimeElements':
     - Required com.android.build.api.attributes.BuildTypeAttr 'debug' and found incompatible value 'release'.
     - Required com.android.build.gradle.internal.dependency.AndroidTypeAttr 'Aar' and found incompatible value 'Apk'.
     - Found com.android.build.gradle.internal.dependency.VariantAttr 'release' but wasn't required.
     - Required org.gradle.api.attributes.Usage 'java-api' and found incompatible value 'java-runtime'.

My dependency in main app.gradle:

compile project(':module')

I found out that if I change it to the following:

compile project(path: ':module', configuration:'default')

Then the project synchronizes and builds.

However in main project class files I am unable to import any files from the module project.

Spent already couple hours searching for answers and nothing I've found so far helps. Went as far as to reinstalling Android Studio 3.0 but it didn't help.


问:
Adding animation to my images with JQuery
Here is my home page:

```<code><%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">
<table id="home" style="margin-left: auto; margin-right:auto;">
    <td id="homeLinks">
        <div style="padding-left:35px;" id="homeListing" class="containerMid">
            <div id="homeView">
                <table style="margin-left: auto; margin-right:auto;">
                    <tr>
                        <tr>
                            <td id="btnIcOld" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />
                            </td>
                            <td id="btnIc" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />
                            </td>
                            <td id="btnPricing" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnSheets" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />
                            </td>
                            <td id="btnPort" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />
                            </td>
                            <td id="btnAdmin" style="text-align:center;cursor:pointer;">
                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />
                            </td>
                        </tr>
                        <tr>
                            <td id="Td1">
                                <b>Indications Calculator | </b>
                            </td>
                            <td id="lblIc">
                                <b>Indications Calculator - Beta | </b>
                            </td>
                            <td id="lblPricing">
                                <b>Managing Pricing Triggers | </b>
                            </td>
                            <td id="lblSheets">
                                <b>Creating Pricing Sheets | </b>
                            </td>
                            <td id="lblPort">
                                <b>Portfolio Analysis | </b>
                            </td>
                            <td id="lblAdmin">
                                <b>Administration</b>
                            </td>
                        </tr>
                    </tr>
                </table>
            </div>
        </div>
    </td>
</table>

<div id="pageMessage"></div>

<script>
    $(document).ready(function () {

        $('#btnIc').live('click', function () {
            window.location.href = "<%=Url.Action("Indications") %>";
        });

        $('#btnIcOld').live('click', function () {
            window.location.href = 'https://extranetint/swap';
        });

        $('#btnPricing').live('click', function () {
            //window.location.href = "<%=Url.Action("Triggers") %>";
        });

        $('#btnSheets').live('click', function () {
            //window.location.href = "<%=Url.Action("Sheets") %>";
        });

        $('#btnPort').live('click', function () {
            //window.location.href = "<%=Url.Action("Analysis") %>";
        });

        $('#btnAdmin').live('click', function () {
            //window.location.href = "<%=Url.Action("Admin") %>";
        });

    });
</script>
</asp:Content>
</code>```

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!

答:
I actually think your main problem was with using .btnIc instead of #btnIc. Also, you are targeting the td instead of the img inside it. Here's a working example with divs instead of a td and an img: http://jsfiddle.net/zyKde/

If you want it to work on your code, you should change $('#btnIc .img') to $('#btnIc img') in the javascript code.

(Edit) also, make sure you set the correct position: relative and position: absolute on your td and img, if you want to use top and left.

Body:
Here is my home page:

<%@ Page Language="C#" MasterPageFile="~/Views/Home/Home.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content2" ContentPlaceHolderID="IndicationContentPlaceHolder" runat="server">

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Load.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Bar_Chart.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Pie_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Line_Chart_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Modify_disabled.png")%>" />

                                <img src="<%= VirtualPathUtility.ToAbsolute("~/img/chic/Profile_disabled.png")%>" />

                                Indications Calculator |

                                Indications Calculator - Beta |

                                Managing Pricing Triggers |

                                Creating Pricing Sheets |

                                Portfolio Analysis |

                                Administration

</asp:Content>

How can I, with JQuery (or really anything), achieve a mouse-over effect on my images where they will grow a little bit as you hover over them? I tried using JQuery animate but for some reason I couldn't get it to work.

Thanks!


问:
Junit test for Exception
I try to test my Exception JUnit and the test doesn't pass I have this error trace :

```<code>org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnitAndHigherRunnerImpl.java:37)
</code>```

and

```<code>org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
</code>```

and here is my code :

```<code>PatientEntityFacade pef = new PatientEntityFacade();
Mockito.when(pef.findByNumber(5555)).thenReturn(patientEntity);

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldThrow() throws PatientNotFoundException
{
    thrown.expect(PatientNotFoundException.class);
    thrown.expectMessage("personalized exception no patient found");

    try {
        pef.findByNumber(5555);
    } catch (com.patient.facade.PatientNotFoundException e) {
        e.printStackTrace();
    }
 }
</code>```

答:
If you watn to test your Exception, then do it the right way.

Define when Exception should be thrown.

in @BeforeClass if every Method should

in @Test-method if only this Method should throw it.

Notice, that you can use any(X.class) if other methods got other values for it.

Don´t try-catch in unit-tests.
Catch it this way and if there is no Exception, the test will fail.

```<code>@Test(expected = PatientNotFoundException.class)
public void shouldThrow()
    pef.findByNumber(5555);
}
</code>```

Title: Junit test for Exception

Body:
I try to test my Exception JUnit and the test doesn't pass I have this error trace :

org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnitAndHigherRunnerImpl.java:37)

and

org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)

and here is my code :

PatientEntityFacade pef = new PatientEntityFacade();
Mockito.when(pef.findByNumber(5555)).thenReturn(patientEntity);

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldThrow() throws PatientNotFoundException
{
    thrown.expect(PatientNotFoundException.class);
    thrown.expectMessage("personalized exception no patient found");

    try {
        pef.findByNumber(5555);
    } catch (com.patient.facade.PatientNotFoundException e) {
        e.printStackTrace();
    }
 }

Body:
If you watn to test your Exception, then do it the right way.

Define when Exception should be thrown.

in @BeforeClass if every Method should

in @Test-method if only this Method should throw it.

Notice, that you can use any(X.class) if other methods got other values for it.

Don´t try-catch in unit-tests.
Catch it this way and if there is no Exception, the test will fail.

@Test(expected = PatientNotFoundException.class)
public void shouldThrow()
    pef.findByNumber(5555);
}


问:
How to Pretty Print HTML to a file, with indentation
I am using lxml.html to generate some HTML. I want to pretty print (with indentation) my final result into an html file. How do I do that?

This is what I have tried and got till now

```<code>import lxml.html as lh
from lxml.html import builder as E
sliderRoot=lh.Element("div", E.CLASS("scroll"), style="overflow-x: hidden; overflow-y: hidden;")
scrollContainer=lh.Element("div", E.CLASS("scrollContainer"), style="width: 4340px;")
sliderRoot.append(scrollContainer)
print lh.tostring(sliderRoot, pretty_print = True, method="html")
</code>```

As you can see I am using the pretty_print=True attribute. I thought that would give indented code, but it doesn't really help. This is the output :

答:
If you store the HTML as an unformatted string, in a variable html_string, it can be done using beautifulsoup4 as follows:

```<code>from bs4 import BeautifulSoup
print(BeautifulSoup(html_string, 'html.parser').prettify())
</code>```

Body:
I am using lxml.html to generate some HTML. I want to pretty print (with indentation) my final result into an html file. How do I do that?

This is what I have tried and got till now

import lxml.html as lh
from lxml.html import builder as E
sliderRoot=lh.Element("div", E.CLASS("scroll"), style="overflow-x: hidden; overflow-y: hidden;")
scrollContainer=lh.Element("div", E.CLASS("scrollContainer"), style="width: 4340px;")
sliderRoot.append(scrollContainer)
print lh.tostring(sliderRoot, pretty_print = True, method="html")

As you can see I am using the pretty_print=True attribute. I thought that would give indented code, but it doesn't really help. This is the output :

Body:
If you store the HTML as an unformatted string, in a variable html_string, it can be done using beautifulsoup4 as follows:

from bs4 import BeautifulSoup
print(BeautifulSoup(html_string, 'html.parser').prettify())


问:
Global structure in Header files
i have a question regarding structure in c and there declaration in header file.
i am writing a code in which there are 3 variables which have another two variables linked with it. so i decided to declare a structure. below i'm writing a Pseudo-code

```<code>//----------registers.h---------
#ifndef __REG__H__
#define __REG__H__

struct ADE_reg_type
{
    unsigned int i : 4;
    unsigned int j : 4;
};

extern struct ADE_reg_type AIRMS_reg;
extern struct ADE_reg_type BIRMS_reg;
extern struct ADE_reg_type CIRMS_reg;
#endif

//-----------registers.c-------------------
#include "registers.h"

struct ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};  //initializing
struct ADE_reg_type BIRMS_reg = {.i = 3,.j = 4};  //initializing
struct ADE_reg_type CIRMS_reg = {.i = 1,.j = 9};  //initializing

//-----------main.c-------------------
#include "registers.h"

int main()
{
   display_numbers(AIRMS_reg);  //display_numbers(struct ADE_reg_type) has
                              //defined in another .c file which also includes
                              // registers.h
}
</code>```

What i'm want is that i should have a variable which i can access in any .c file. scope of variable should be global. so is it a right way to use a global structure or i'm making some mistake here ?

答:
Array approach:
for example:

```<code>ADE_reg_type RegType_Array[3];
ADE_reg_type* ADE_reg_type(char index)
{
    return &RegType_Array[index];
}
</code>```

Variable approach:

```<code>ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};
ADE_reg_type* AIRMS_reg()
{
    return &AIRMS_reg
}
</code>```

Title: Global structure in Header files

Body:
i have a question regarding structure in c and there declaration in header file.
i am writing a code in which there are 3 variables which have another two variables linked with it. so i decided to declare a structure. below i'm writing a Pseudo-code

//----------registers.h---------
#ifndef __REG__H__
#define __REG__H__

struct ADE_reg_type
{
    unsigned int i : 4;
    unsigned int j : 4;
};

extern struct ADE_reg_type AIRMS_reg;
extern struct ADE_reg_type BIRMS_reg;
extern struct ADE_reg_type CIRMS_reg;
#endif

//-----------registers.c-------------------
#include "registers.h"

struct ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};  //initializing
struct ADE_reg_type BIRMS_reg = {.i = 3,.j = 4};  //initializing
struct ADE_reg_type CIRMS_reg = {.i = 1,.j = 9};  //initializing

//-----------main.c-------------------
#include "registers.h"

int main()
{
   display_numbers(AIRMS_reg);  //display_numbers(struct ADE_reg_type) has
                              //defined in another .c file which also includes
                              // registers.h
}

What i'm want is that i should have a variable which i can access in any .c file. scope of variable should be global. so is it a right way to use a global structure or i'm making some mistake here ?

Body:
Array approach:
for example:

ADE_reg_type RegType_Array[3];
ADE_reg_type* ADE_reg_type(char index)
{
    return &RegType_Array[index];
}

Variable approach:

ADE_reg_type AIRMS_reg = {.i = 4,.j = 5};
ADE_reg_type* AIRMS_reg()
{
    return &AIRMS_reg
}


问:
Is there a tool to analyse if a C# and WPF project can be ported to Silverlight?
I have a WPF and C# application, and I want to know if it can be ported to silverlight. Is there a tool to analyse the dependencies and tell me what I can't use, and what I can ?

Thanks.

答: I have not seen such tool, but there is WPF compatibility list on MSDN which i use.</p>


问:
How to pass parameters from angular 4 to access REST API data
I have created the service to access the REST API data but when i hit the url from the Angular application end then it gives me this error in the console.

```<code>Failed to load http://<SERVER.URL.FROM.SERVER>/api/invoice-details/121: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.
</code>```

So for that the backend guy gave some authentication parameters like

So he is telling me to pass the parameters For Authentication to access the data in my Angular application. Otherwise i can get the same error like CORS.

So my question is how to pass the parameters from my end. I have written the code like this in the user.service.ts where all my services are there.

```<code>import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class UserService {

    private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
    private options = new RequestOptions({ headers: this.headers, withCredentials: true });

    constructor(private http: Http, private config: AppConfig) {}

getSupplierBasicInfo(){
        return this.http.get(this.config.apiUrl + 'api/supplier-basic-info/121')
        .map(response => response.json());
    }
}
</code>```

In the component i am calling the service like this:

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

@Component({
  selector: 'app-invoice',
  templateUrl: './invoice.component.html',
  styleUrls: ['./invoice.component.css']
})
export class InvoiceComponent implements OnInit {
  invoiceDetails: any[];
  constructor(private _userService: UserService) {
    console.log('Invoice Details loaded!');
  }

  ngOnInit() {
    this._userService.getInvoiceDetails()
    .subscribe(data => this.invoiceDetails = data);
  }
}
</code>```

Data binding is like this:

```<code><table class="table table-striped">
    <thead class="thead-dark">
      <tr style="background-color:#55555A; color:#ffffff">
        <th scope="col">Req ID</th>
        <th scope="col">Date</th>
        <th scope="col">Category</th>
        <th scope="col">Details</th>
        <th scope="col">Status</th>
        <th scope="col">View</th>
        <th scope="col">Download</th>
      </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of orderDetails">
            <td>{{ item.title }}</td>
            <td>{{ item.field_date }}</td>
            <td>{{ item.field_date }}</td>
            <td>{{ item.field_first_name }}</td>
            <td>{{ item.field_upload_invoice }}</td>
            <td><i class="fa fa-eye" aria-hidden="true"></i></td>
            <td><span class="glyphicon glyphicon-download"></span></td>
        </tr>
    </tbody>
  </table>
</code>```

So can anybody help me that how to pass the parameters to get the data in my application.

答:
Imports:

```<code>import { Http, Headers, URLSearchParams, RequestOptions } from '@angular/http';
</code>```

Headers:

```<code>    private headers = new Headers([
            { 'credentials': 'same-origin' },
            { 'Access-Control-Allow-Origin': '*' },
            //instead of * you can specify your host
            { 'Access-Control-Allow-Credentials': 'true' },
        ]);
        //private params: URLSearchParams = new URLSearchParams();
        private options: RequestOptions = new RequestOptions({ headers: this.headers,
withCredentials: true
});
</code>```

Request:

```<code>this.options.search = this.params;
this.http.get(`${this.host}${this.url}`, this.options)
            .map(result => result.json());
</code>```

You can also specyfi CORS on web api configuration file to add headers to every request.

Body:
I have created the service to access the REST API data but when i hit the url from the Angular application end then it gives me this error in the console.

Failed to load http://<SERVER.URL.FROM.SERVER>/api/invoice-details/121: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

So for that the backend guy gave some authentication parameters like

So he is telling me to pass the parameters For Authentication to access the data in my Angular application. Otherwise i can get the same error like CORS.

So my question is how to pass the parameters from my end. I have written the code like this in the user.service.ts where all my services are there.

import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class UserService {

    private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
    private options = new RequestOptions({ headers: this.headers, withCredentials: true });

    constructor(private http: Http, private config: AppConfig) {}

getSupplierBasicInfo(){
        return this.http.get(this.config.apiUrl + 'api/supplier-basic-info/121')
        .map(response => response.json());
    }
}

In the component i am calling the service like this:

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

@Component({
  selector: 'app-invoice',
  templateUrl: './invoice.component.html',
  styleUrls: ['./invoice.component.css']
})
export class InvoiceComponent implements OnInit {
  invoiceDetails: any[];
  constructor(private _userService: UserService) {
    console.log('Invoice Details loaded!');
  }

  ngOnInit() {
    this._userService.getInvoiceDetails()
    .subscribe(data => this.invoiceDetails = data);
  }
}

Data binding is like this:

        Req ID
        Date
        Category
        Details
        Status
        View
        Download

            {{ item.title }}
            {{ item.field_date }}
            {{ item.field_date }}
            {{ item.field_first_name }}
            {{ item.field_upload_invoice }}

So can anybody help me that how to pass the parameters to get the data in my application.

Body:
Imports:

import { Http, Headers, URLSearchParams, RequestOptions } from '@angular/http';

Headers:

    private headers = new Headers([
            { 'credentials': 'same-origin' },
            { 'Access-Control-Allow-Origin': '*' },
            //instead of * you can specify your host
            { 'Access-Control-Allow-Credentials': 'true' },
        ]);
        //private params: URLSearchParams = new URLSearchParams();
        private options: RequestOptions = new RequestOptions({ headers: this.headers,
withCredentials: true
});

Request:

this.options.search = this.params;
this.http.get(`${this.host}${this.url}`, this.options)
            .map(result => result.json());

You can also specyfi CORS on web api configuration file to add headers to every request.


问:
How to display the workHr that comes as json data in table format using vue js?
My json data is

```<code>{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}
</code>```

Currently I am displaying data as

```<code> <p><i class="fa fa-map-marker" aria-hidden="true"></I>{{data.place}}, {{data.city}}, {{data.pincode}}</p><br>
</code>```

I need to display {{data.workHr}} in the form of a table

My table is as

```<code> <table class="table">
  <thead>
    <tr>
      <th>Sunday</th>
      <th>Monday</th>
      <th>Tuesday</th>
      <th>Wednesday</th>
      <th>Thursday</th>
      <th>Friday</th>
      <th>Saturday</th>
    </tr>
  </thead>
  <tbody>
    <tr>

      <td></td>
       <td></td>
        <td></td>
         <td></td>
          <td></td>
           <td></td>
            <td></td>
    </tr>
  </tbody>
</table>
</code>```

I need to display the corresponding working hours that come from json data under each day? Can please anybody help me to solve the issue??

答:
You can also make two column table for day and time

var app = new Vue({
    el: "#vue-instance",
    data: {
    formData:{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}

    },
    methods:{
      getWorkHrs: function(){
        var workhrs = {};
        this.formData.data.workHr.split(",").map(function(e){
          var temp = e.split(" :");
          var tempObj = {};
          workhrs[temp[0]] = temp[1];
          //workhrs.push(tempObj);
        });
        return workhrs;
      },
    },
    components: {
    },
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
  <table>
    <tr><th>Day</th><th>Time</th></tr>
    <tr v-for="(time,day) in getWorkHrs()"><td>{{day}}</td><td>{{time}}</td></tr>
  </table>
</div></code>```

Body:
My json data is

{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}

Currently I am displaying data as

{{data.place}}, {{data.city}}, {{data.pincode}}

I need to display {{data.workHr}} in the form of a table

My table is as

      Sunday
      Monday
      Tuesday
      Wednesday
      Thursday
      Friday
      Saturday

I need to display the corresponding working hours that come from json data under each day? Can please anybody help me to solve the issue??

Body:
You can also make two column table for day and time

var app = new Vue({
    el: "#vue-instance",
    data: {
    formData:{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon@gmail.com", "contactOfficeAddress": "college of Eng", "contactNumber": "1236547859", "contactOfficeNumber": "8947123658", "state": "Kerala", "city": "Koy", "place": "Kly", "pincode": 686514, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}

    },
    methods:{
      getWorkHrs: function(){
        var workhrs = {};
        this.formData.data.workHr.split(",").map(function(e){
          var temp = e.split(" :");
          var tempObj = {};
          workhrs[temp[0]] = temp[1];
          //workhrs.push(tempObj);
        });
        return workhrs;
      },
    },
    components: {
    },
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.1/vue.js"></script>
<div id="vue-instance">
  <table>
    <tr><th>Day</th><th>Time</th></tr>
    <tr v-for="(time,day) in getWorkHrs()"><td>{{day}}</td><td>{{time}}</td></tr>
  </table>
</div>


问:
How to prevent a database search from running on an empty string?
With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?</p>

```<code>    <form action="search.php" method="POST">
        <input type="text" name="search" placeholder="search site">
        <button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
    </form>

    <?php
        if (isset($_POST['submit-search'])){
            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
            $result = mysqli_query($conn, $sql);
            $queryResult = mysqli_num_rows($result);

            if ($queryResult > 0){
                echo $queryResult . " results found";

                while ($row = mysqli_fetch_assoc($result)){
                    echo "<div class='articleItem'>
                        <h2>".$row['title']."</h2>
                        <p>".$row['abstract']."</p>
                        <a href=".$row['link']." target='_blank'>".$row['link']."</a>
                    </div>";
                }
            }
            else {
                echo "There are no results matching your search.";
            }
        }
    ?>
</code>```

答:
You can check string length with strlen. A trim can be additionally used to remove white spece search also.</p>

```<code>$hasResult = false ; //default mark no result.
if (isset($_POST['submit-search']) && strlen(trim($_POST['submit-search'])) > 0) {
    $search = mysqli_real_escape_string($conn, $_POST['search']);
    $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
    $result = mysqli_query($conn, $sql);
    $queryResult = mysqli_num_rows($result);

    if ($queryResult > 0) {
        $hasResult = true ;  //mark result found
        echo $queryResult . " results found";

        while ($row = mysqli_fetch_assoc($result)) {
            echo "<div class='articleItem'>
                        <h2>" . $row['title'] . "</h2>
                        <p>" . $row['abstract'] . "</p>
                        <a href=" . $row['link'] . " target='_blank'>" . $row['link'] . "</a>
                    </div>";
        }
    }
}

if( ! $hasResult  ) { //Move to a common section
    echo "There are no results matching your search.";
}
</code>```

Body:
With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?

    <form action="search.php" method="POST">
        <input type="text" name="search" placeholder="search site">
        <button type="submit" name="submit-search"></button>
    </form>

    <?php
        if (isset($_POST['submit-search'])){
            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
            $result = mysqli_query($conn, $sql);
            $queryResult = mysqli_num_rows($result);

            if ($queryResult > 0){
                echo $queryResult . " results found";

                while ($row = mysqli_fetch_assoc($result)){
                    echo "

".$row['title']."

".$row['abstract']."

                        ".$row['link']."

";
                }
            }
            else {
                echo "There are no results matching your search.";
            }
        }
    ?>

Body:
You can check string length with strlen. A trim can be additionally used to remove white spece search also.

$hasResult = false ; //default mark no result.
if (isset($_POST['submit-search']) && strlen(trim($_POST['submit-search'])) > 0) {
    $search = mysqli_real_escape_string($conn, $_POST['search']);
    $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
    $result = mysqli_query($conn, $sql);
    $queryResult = mysqli_num_rows($result);

    if ($queryResult > 0) {
        $hasResult = true ;  //mark result found
        echo $queryResult . " results found";

        while ($row = mysqli_fetch_assoc($result)) {
            echo "<div class='articleItem'>
                        <h2>" . $row['title'] . "</h2>
                        <p>" . $row['abstract'] . "</p>
                        <a href=" . $row['link'] . " target='_blank'>" . $row['link'] . "</a>
                    </div>";
        }
    }
}

if( ! $hasResult  ) { //Move to a common section
    echo "There are no results matching your search.";
}


问:
Using personas in software development
We are using personas at work. However, is the use of quotes from the imaginary user a good thing to add?</p>

答:
For creating a Persona, you can review the web site that SAP UX build for software builders at https://sapcsr.build.me/splashapp/learningDetail/644

There it is explicitely stated to:

Create a short quote - real or pieced together from various real quotes - that illustrates the user's goals or motivations.

Title: Using personas in software development


问:
ng test fail after adding 'ng2-dateime '
I have added ng2-datetime module in my Angular 4 project.

Now problem I am facing with ng test.

Currently it throws error like below.

```<code>'Cannot find name 'jQuery'
'Cannot find name '$'
</code>```

EDIT:

I did tried same way as most of answer below which is adding below lines in typings.d.ts

```<code>declare var jQuery: any;
declare var $: any;
</code>```

this will start 'ng test' but it will throw error while making build using ng build --prod.

```<code>Cannot redeclare block-scoped variable 'jQuery'
Cannot redeclare block-scoped variable '$'
</code>```

TIA

答:
Try to add this on your typings.d.ts :

```<code>declare jQuery: any;
</code>```

The variable will be available in all your app

But if you can, try to avoid plugins that uses jQuery

Body:
I have added ng2-datetime module in my Angular 4 project.

Now problem I am facing with ng test.

Currently it throws error like below.

'Cannot find name 'jQuery'
'Cannot find name '$'

EDIT:

I did tried same way as most of answer below which is adding below lines in typings.d.ts

declare var jQuery: any;
declare var $: any;

this will start 'ng test' but it will throw error while making build using ng build --prod.

Cannot redeclare block-scoped variable 'jQuery'
Cannot redeclare block-scoped variable '$'

TIA

Body:
Try to add this on your typings.d.ts :

declare jQuery: any;

The variable will be available in all your app

But if you can, try to avoid plugins that uses jQuery


问:
Apache Mina TCP session tracking from client
I have created a TCP client using Apache Mina. I have added a while loop to constantly check the liveness of the port. Once the connection is up on the server side, the loop is broken and the connection is made. i get the session from future and use it to communicate.
Is there a better way to do this. instead of loop can i ask the connection to wait till its up.

```<code> while(true){
   try {
 ConnectFuture future = ioConnector.connect(new InetSocketAddress(Port),
            new TriggerReceiverHandler(), SOCKET_CONFIG);
    System.out.println("Message Receiver started and listening on port "+ Port);
Thread.sleep(1000);
                session = future.getSession();
                if(session != null)
                    break;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch(Exception ce){
                if(ce.getCause() instanceof ConnectException)
                System.out.println("Retrying connection");
            }
        }
</code>```

Another question is, If the server is down and I want the server to keep waiting for the connection till its up, what should i do?

答: The answer is, As of now its not possible, as the connection state is known only when we attempt to connect. One modification is instead of the Thread.sleep(1000); we can add future.join() in version 1.0+ or add a listener for the future in case of 2.0+

Body:
I have created a TCP client using Apache Mina. I have added a while loop to constantly check the liveness of the port. Once the connection is up on the server side, the loop is broken and the connection is made. i get the session from future and use it to communicate.
Is there a better way to do this. instead of loop can i ask the connection to wait till its up.

 while(true){
   try {
 ConnectFuture future = ioConnector.connect(new InetSocketAddress(Port),
            new TriggerReceiverHandler(), SOCKET_CONFIG);
    System.out.println("Message Receiver started and listening on port "+ Port);
Thread.sleep(1000);
                session = future.getSession();
                if(session != null)
                    break;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch(Exception ce){
                if(ce.getCause() instanceof ConnectException)
                System.out.println("Retrying connection");
            }
        }

Another question is, If the server is down and I want the server to keep waiting for the connection till its up, what should i do?