问:
Django test(django.test.client) put call, with many headers don't work

Django (2.0)

Python 3.5.2

Without REMOTE_ADDR it works very well:

```<code>client = Client()

response = client.put('/api/v1/person/address/',{},
    HTTP_API_KEY=self.model_login_director.token)
</code>```

With REMOTE_ADDR in a put() call doesn't work (but works for GET and POST requests).

```<code>client = Client()

response = client.put('/api/v1/person/address/',{},
    REMOTE_ADDR='127.0.0.8',
    HTTP_API_KEY=self.model_login_director.token)
</code>```

Message error

```<code>Traceback (most recent call last):
      File "/home/wborba/project/willcode/sofia/api/test/testsControllerPersonAddress.py", line 577, in test_person_address_update_address_id_missing
        HTTP_API_KEY=self.model_login_director.token)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 548, in put
        response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 366, in put
        secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 404, in generic
        return self.request(**r)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 485, in request
        raise exc_value
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner
        response = get_response(request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 69, in view
        return self.dispatch(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 89, in dispatch
        return handler(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
        return view_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 62, in _wrapper
        return bound_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/home/wborba/project/willcode/sofia/api/Business/Auth.py", line 145, in wrap
        return function(request, model_login, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 58, in bound_func
        return func.__get__(self, type(self))(*args2, **kwargs2)
    TypeError: put() takes 2 positional arguments but 3 were given
</code>```

答:
You should pass header information when instantiating the Client()

From the docs:

class Client(enforce_csrf_checks=False, **defaults)

It requires no
  arguments at time of construction. However, you can use keywords
  arguments to specify some default headers. For example, this will send
  a User-Agent HTTP header in each request:

c = Client(HTTP_USER_AGENT='Mozilla/5.0')

As such, you should pass the REMOTE_ADDR header when creating the Client:

```<code>client = Client(REMOTE_ADDR='127.0.0.8')

response = client.put('/api/v1/person/address/',{},
    HTTP_API_KEY=self.model_login_director.token)
</code>```

Body:
Django (2.0)

Python 3.5.2

Without REMOTE_ADDR it works very well:

client = Client()

response = client.put('/api/v1/person/address/',{},
    HTTP_API_KEY=self.model_login_director.token)

With REMOTE_ADDR in a put() call doesn't work (but works for GET and POST requests).

client = Client()

response = client.put('/api/v1/person/address/',{},
    REMOTE_ADDR='127.0.0.8',
    HTTP_API_KEY=self.model_login_director.token)

Message error

Traceback (most recent call last):
      File "/home/wborba/project/willcode/sofia/api/test/testsControllerPersonAddress.py", line 577, in test_person_address_update_address_id_missing
        HTTP_API_KEY=self.model_login_director.token)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 548, in put
        response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 366, in put
        secure=secure, **extra)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 404, in generic
        return self.request(**r)
      File "/usr/local/lib/python3.5/dist-packages/django/test/client.py", line 485, in request
        raise exc_value
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner
        response = get_response(request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 69, in view
        return self.dispatch(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/generic/base.py", line 89, in dispatch
        return handler(request, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
        return view_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 62, in _wrapper
        return bound_func(*args, **kwargs)
      File "/usr/lib/python3.5/contextlib.py", line 30, in inner
        return func(*args, **kwds)
      File "/home/wborba/project/willcode/sofia/api/Business/Auth.py", line 145, in wrap
        return function(request, model_login, *args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/utils/decorators.py", line 58, in bound_func
        return func.__get__(self, type(self))(*args2, **kwargs2)
    TypeError: put() takes 2 positional arguments but 3 were given

Body:
You should pass header information when instantiating the Client()

From the docs:

class Client(enforce_csrf_checks=False, **defaults)

It requires no
  arguments at time of construction. However, you can use keywords
  arguments to specify some default headers. For example, this will send
  a User-Agent HTTP header in each request:

c = Client(HTTP_USER_AGENT='Mozilla/5.0')

As such, you should pass the REMOTE_ADDR header when creating the Client:

client = Client(REMOTE_ADDR='127.0.0.8')

response = client.put('/api/v1/person/address/',{},
    HTTP_API_KEY=self.model_login_director.token)


来源: stackexchange

问:
angular 4 how to http put with If-Match
My script that shall do the work:

```<code>updateTask(task:Task){
    const body = task;
    var headers = new HttpHeaders();
    headers.set('Content-Type', 'application/javascript');
    headers.set('If-Match', task.etag);
    return this.httpc.put(this.resources+'/'+task.id, body, { headers: headers });
}
</code>```

Could anyone take a look at it and tell me if I did something wrong here please? Never tried it before, actually I am beginner to angular :S ( Back-end is not mine so I can't share with you guys :/ )

httpc is a HttpClient :)
Thanks your time and answers in advance! ^^.

Edit 1:

Response >
{"error":"If-Match header is missing or invalid"}

Edit2:

Request header

```<code>PUT /app/data/schedule/tasks/42615 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 438
Accept: application/json, text/plain, */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Content-Type: application/json
Referer: http://localhost:3000/portal/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: sid=f5eb691a56bfa7b6db05083023c5f4caf044db47c2f29f644bc80d7bb7dcf1f3
</code>```

答:
Summarizing the great amount of comments to solve this question.
The backend does not accept an HTTP PUT command because the headers are not properly setting. So, to fix this problem, you should add both headers properly in your code. There is several ways. I proposed one, based on constructor, but there is more.

Based on constructor:

const header =
new HttpHeaders({'Content-Type': 'application/javascript', 'If-Match' : task.etag});
```

<p>Using append method (as this question suggests):</p>

<pre class="lang-js prettyprint-override"><code>const headers = new HttpHeaders();
headers.append('Content-Type', 'application/javascript');
headers.append('If-Match', task.etag);
</code>```

Note the change made in the declaration of header. I propose const instead var.

ContentLicense: CC BY-SA 3.0

Title: angular 4 how to http put with If-Match

Body:
My script that shall do the work:

updateTask(task:Task){
    const body = task;
    var headers = new HttpHeaders();
    headers.set('Content-Type', 'application/javascript');
    headers.set('If-Match', task.etag);
    return this.httpc.put(this.resources+'/'+task.id, body, { headers: headers });
}

Could anyone take a look at it and tell me if I did something wrong here please? Never tried it before, actually I am beginner to angular :S ( Back-end is not mine so I can't share with you guys :/ )

httpc is a HttpClient :)
Thanks your time and answers in advance! ^^.

Edit 1:

Response >
{"error":"If-Match header is missing or invalid"}

Edit2:

Request header

PUT /app/data/schedule/tasks/42615 HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 438
Accept: application/json, text/plain, */*
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
Content-Type: application/json
Referer: http://localhost:3000/portal/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: sid=f5eb691a56bfa7b6db05083023c5f4caf044db47c2f29f644bc80d7bb7dcf1f3

Body:
Summarizing the great amount of comments to solve this question.
The backend does not accept an HTTP PUT command because the headers are not properly setting. So, to fix this problem, you should add both headers properly in your code. There is several ways. I proposed one, based on constructor, but there is more.

Based on constructor:

const header =
new HttpHeaders({'Content-Type': 'application/javascript', 'If-Match' : task.etag});

Using append method (as this question suggests):

const headers = new HttpHeaders();
headers.append('Content-Type', 'application/javascript');
headers.append('If-Match', task.etag);

Note the change made in the declaration of header. I propose const instead var.


问:
XCode doesn't finish test build while at "Run Script" phase
When trying to build the unit tests created using the default XCode Unit Test bundle target, it looks like it's stuck on the "Run custom shell script 'Run Script'" phase.

I also notice a high cpu usage on process "otest" to the point where the fans kick in within seconds.

The only useful message I see when expanding the line is

/Developer/Tools/RunPlatformUnitTests.include:419: note: Running tests for architecture 'i386' (GC OFF)
  Couldn't open shared capabilities memory GSCapabilities (No such file or directory)

The only option I have at that time is to stop the build.

Have to say I was running unit tests perfectly fine up to this moment but can't say for sure what I did to cause that.

That's on XCode 3.2.4

After updating to 3.2.5 now the run script does fail with an error

Test rig '/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/Developer/usr/bin/otest' exited abnormally with code 138 (it may have crashed).

Guess they problem is related?
Did find some answers on SO about how exception handling now works differently when using NSInvocation (which otest seems to use) but not really a solution to this.

答: I had this happen to me. I made it go away by scrapping my old testing target profile, creating a new one, and pointing all my tests to it. I was too frustrated to compare the profiles line by line to figure out what had changed.</p>

ContentLicense: CC BY-SA 2.5


问:
Capture repeated characters and split using Python
I need to split a string by using repeated characters.

For example:

My string is "howhowhow"

I need output as 'how,how,how'.

I cant use 'how' directly in my reg exp. because my input varies. I should check the string whether it is repeating the character and need to split that characters.

答:
```<code>lengthofRepeatedChar = 3
str1 = 'howhowhow'
HowmanyTimesRepeated = int(len(str1)/lengthofRepeatedChar)
((str1[:lengthofRepeatedChar]+',')*HowmanyTimesRepeated)[:-1]
'how,how,how'
</code>```

Works When u know the length of repeated characters

Body:
lengthofRepeatedChar = 3
str1 = 'howhowhow'
HowmanyTimesRepeated = int(len(str1)/lengthofRepeatedChar)
((str1[:lengthofRepeatedChar]+',')*HowmanyTimesRepeated)[:-1]
'how,how,how'

Works When u know the length of repeated characters


问:
Shortest unique substrings of a vector
Say I have a character vector of some length,

```<code>vec <- c("man lives to work", "man works to live")
</code>```

Starting from the beginning, I'd now like to find the shortest unique substrings (of complete words) in this vector.
In other words, I'm not looking for the shortest substring overall, but I'd like crop the string after the word where it becomes unique, in this case after work and lives, respectively.

So the result should be, in this case:

```<code>[1] "man lives" "man works"
</code>```

The strings should be cropped after lives/works because that's the earliest point at which they become unique (in this context).
Including to would be redundant, because they are already unique.
Including only man would not be enough, because c("man", "man") is not unique.

(I want to use this to automatically generate valid R names, and base::make.names() will do the rest).

How do I do this?

I figured, there has to be a package out there which already does this, but couldn't find it.

答:
```<code>df %>%  unnest_tokens(word ,words) %>%
  mutate(bigram = substr(word,1,2),
         trigram = ifelse (nchar(word) >= 3,substr(word,1,3),NA) ,
         four_gram  = ifelse (nchar(word) >= 4, substr(word,1,4), NA),
         five_gram  = ifelse (nchar(word) >= 5, substr(word,1,5), NA)) %>%
  group_by(bigram) %>%
  mutate(count_bigram = n()) %>%
  ungroup() %>%
  group_by(trigram) %>%
  mutate(count_trigram = n()) %>%
  ungroup() %>%
  group_by(four_gram) %>%
  mutate(count_four_gram = n()) %>%
  ungroup() %>%
  group_by(five_gram) %>%
  mutate(count_five_gram = n()) %>%
  ungroup()   %>%
  summarise_each(funs(((function(x) {sum(x == 1)})(.))),
                 count_bigram, count_trigram,
                 count_four_gram, count_five_gram)

# # A tibble: 1 × 4
#    count_bigram count_trigram count_four_gram count_five_gram
#          <int>         <int>           <int>           <int>
#1            0             0               0               2
</code>```

Title: Shortest unique substrings of a vector

Body:
Say I have a character vector of some length,

vec <- c("man lives to work", "man works to live")

Starting from the beginning, I'd now like to find the shortest unique substrings (of complete words) in this vector.
In other words, I'm not looking for the shortest substring overall, but I'd like crop the string after the word where it becomes unique, in this case after work and lives, respectively.

So the result should be, in this case:

[1] "man lives" "man works"

The strings should be cropped after lives/works because that's the earliest point at which they become unique (in this context).
Including to would be redundant, because they are already unique.
Including only man would not be enough, because c("man", "man") is not unique.

(I want to use this to automatically generate valid R names, and base::make.names() will do the rest).

How do I do this?

I figured, there has to be a package out there which already does this, but couldn't find it.


问:
Joining two tables when dates mismatch
I have Two tables Customer and Customer Address. Join criteria is on CustomerNo and Date. When date is not matching or not available on Customer Address table, I want to join with latest date available on the Customer Address

```<code>   Customer Table              Customer Address Table
    CustomerNo    Date        CustomerNo      Date       Addr
    123          1/1/2017     123            1/1/2017   sample1
    123          2/1/2017     123            2/1/2017   sample2
    123          2/11/2017
    123          3/1/2017
</code>```

Expected output

```<code>         Final Table

CustomerNo       Date      Addr
123             1/1/2017   sample1
123             2/1/2017   sample2
122             2/11/2017  sample2
123             3/1/2017   sample2
</code>```

When Dates are not available in Customer Address , match with last available date.

Thanks in advance.

答:
Here is a solution. I haven't tested as I can't find a teradata compiler online.

Basically, the query gets the MAX record in the subquery and uses the Addr from max record if there isnt one already there for the date (See the COALESCE).

```<code>SELECT C.CustomerNo,
       C.Date,
       COALESCE(CA.Addr, CMax.Addr) AS Addr
  FROM Customer C,
       LEFT JOIN Customer_Address CA
              ON (C.CustomerNo = CA.CustomerNo AND
                  C.Date = CA.Date)
       LEFT JOIN (SELECT CustomerNo, Addr,
                         ROW_NUMBER() OVER (PARTITION BY CustomerNo ORDER BY Date Desc) AS r_num
                    FROM Customer_Address
                   GROUP BY CustomerNo) CMax
              ON (C.CustomerNo = CMax.CustomerNo AND
                  CMax.r_num = 1);
</code>```

Title: Joining two tables when dates mismatch

Body:
I have Two tables Customer and Customer Address. Join criteria is on CustomerNo and Date. When date is not matching or not available on Customer Address table, I want to join with latest date available on the Customer Address

   Customer Table              Customer Address Table
    CustomerNo    Date        CustomerNo      Date       Addr
    123          1/1/2017     123            1/1/2017   sample1
    123          2/1/2017     123            2/1/2017   sample2
    123          2/11/2017
    123          3/1/2017

Expected output

         Final Table

CustomerNo       Date      Addr
123             1/1/2017   sample1
123             2/1/2017   sample2
122             2/11/2017  sample2
123             3/1/2017   sample2

When Dates are not available in Customer Address , match with last available date.

Thanks in advance.

Body:
Here is a solution. I haven't tested as I can't find a teradata compiler online.

Basically, the query gets the MAX record in the subquery and uses the Addr from max record if there isnt one already there for the date (See the COALESCE).

SELECT C.CustomerNo,
       C.Date,
       COALESCE(CA.Addr, CMax.Addr) AS Addr
  FROM Customer C,
       LEFT JOIN Customer_Address CA
              ON (C.CustomerNo = CA.CustomerNo AND
                  C.Date = CA.Date)
       LEFT JOIN (SELECT CustomerNo, Addr,
                         ROW_NUMBER() OVER (PARTITION BY CustomerNo ORDER BY Date Desc) AS r_num
                    FROM Customer_Address
                   GROUP BY CustomerNo) CMax
              ON (C.CustomerNo = CMax.CustomerNo AND
                  CMax.r_num = 1);


问:
Wcf Rest Service Return Number Conversion Error
I am consuming Wcf Rest Service into Angular JS Application . I am trying to display single record based on account number in input filed. But when i click the submit button to display the record then i got following errors in Google Chrome Network Tap.

The server encountered an error processing the request. The exception message is 'Conversion failed when converting the nvarchar value '{Account_Number}15' to data type int.'. See server logs for more details. The exception stack trace is:

And its returns 400 Bad Request on Post Method Operation .

Here is the interface .

```<code> [OperationContract]
       [WebInvoke(Method = "POST",
       RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "/GetAccountDetails/{Account_Number}")]
        string  GetAccountDetails(string Account_Number);
</code>```

Here is the Implementation.

```<code> public string GetAccountDetails(string Account_Number)
        {
            List<object> customers = new List<object>();
            string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Number = @Account_Number";
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    cmd.Parameters.AddWithValue("@Account_Number", Account_Number);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            customers.Add(new
                            {
                                Tittle = sdr["Tittle"],
                                Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                                Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                                Account_Holder_DOB = sdr["Account_Holder_DOB"],
                                Account_Holder_House_No = sdr["Account_Holder_House_No"],
                                Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                                Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],

                                Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                                Account_Number = sdr["Account_Number"]

                            });
                        }
                    }
                    conn.Close();
                }

                return (new JavaScriptSerializer().Serialize(customers));
            }

        }
</code>```

Here is the Script code.

```<code>var app = angular.module("WebClientModule", [])
    .controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
        var Account_Number = $scope.Account_Number;
        $scope.search = function (Account_Number) {
            var promisePostSingle = myService.postbyId(Account_Number);

        promisePostSingle.then(function (pl) {
            var res = pl.data;
            $scope.Account_Number = res.Account_Number;
            $scope.Account_Creation_Date = res.Account_Creation_Date;
            $scope.Account_Type = res.Account_Type;
            $scope.Branch_Sort_Code = res.Branch_Sort_Code;
            $scope.Account_Fees = res.Account_Fees;
            $scope.Account_Balance = res.Account_Balance;
            $scope.Over_Draft_Limit = res.Over_Draft_Limit;

            //   $scope.IsNewRecord = 0;
        },
            function (errorPl) {
                console.log('failure loading Employee', errorPl);
            });
    }
    }]);

app.service("myService", function ($http) {

    this.postbyId = function (Id) {
        return $http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
    };
   })
</code>```

Here is the HTML .

```<code>@{
    Layout = null;
}

<!DOCTYPE html>

<html ng-app="WebClientModule">
<head>
    <meta name="viewport" content="width=device-width" />

    <title>AccountBalance</title>
    <script src="~/Scripts/angular.min.js"></script>

    <script src="~/RegistrationScript/AccountBalance.js"></script>
</head>
<body>
    <div data-ng-controller="Web_Client_Controller">
        Enter Account_Number: <input type="text" ng-model="Account_Number" />
        <input type="button"  value="search" ng-click="search(Account_Number)" />

            <table id="tblContainer">
                <tr>
                    <td>
                        <table style="border: solid 2px Green; padding: 5px;">
                            <tr style="height: 30px; background-color: skyblue; color: maroon;">
                                <th></th>
                                <th>Account Number</th>
                                <th>Account Creation Date</th>
                                <th>Account Type</th>
                                <th>Branch Sort Code</th>
                                <th>Account Fees</th>
                                <th>Account Balance</th>
                                <th>Over Draft Limit</th>

                                <th></th>
                                <th></th>
                            </tr>
                            <tbody data-ng-repeat="user in Users">
                                <tr>
                                    <td></td>
                                    <td><span>{{user.Account_Number}}</span></td>
                                    <td><span>{{user.Account_Creation_Date}}</span></td>
                                    <td><span>{{user.Account_Type}}</span></td>
                                    <td><span>{{user.Branch_Sort_Code}}</span></td>

                                    <td><span>{{user.Account_Fees}}</span></td>
                                    <td><span>{{user.Account_Balance}}</span></td>
                                    <td><span>{{user.Over_Draft_Limit}}</span></td>
                                    <td>

                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td></td>
                </tr>
                <tr>
                    <td>

                        <div style="color: red;">{{Message}}</div>

                    </td>
                </tr>
            </table>
        </div>
        </body>

</html>
</code>```

Here is the Screen Shot on Debugging mode on Wcf Service .

Here is the result on Google Chrome Console Windows .

答:
You should change it;

```<code>$http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
</code>```

to

```<code>$http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails?Account_Number=" + Id);
</code>```

You are sending the parameter as {Account_Number}15. It should be 15.

Body:
I am consuming Wcf Rest Service into Angular JS Application . I am trying to display single record based on account number in input filed. But when i click the submit button to display the record then i got following errors in Google Chrome Network Tap.

The server encountered an error processing the request. The exception message is 'Conversion failed when converting the nvarchar value '{Account_Number}15' to data type int.'. See server logs for more details. The exception stack trace is:

And its returns 400 Bad Request on Post Method Operation .

Here is the interface .

 [OperationContract]
       [WebInvoke(Method = "POST",
       RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "/GetAccountDetails/{Account_Number}")]
        string  GetAccountDetails(string Account_Number);

Here is the Implementation.

 public string GetAccountDetails(string Account_Number)
        {
            List<object> customers = new List<object>();
            string sql = "SELECT * FROM Current_Account_Holder_Details WHERE Account_Number = @Account_Number";
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(sql))
                {
                    cmd.Parameters.AddWithValue("@Account_Number", Account_Number);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {

                            customers.Add(new
                            {
                                Tittle = sdr["Tittle"],
                                Account_Holder_First_Name = sdr["Account_Holder_First_Name"],
                                Account_Holder_Last_Name = sdr["Account_Holder_Last_Name"],
                                Account_Holder_DOB = sdr["Account_Holder_DOB"],
                                Account_Holder_House_No = sdr["Account_Holder_House_No"],
                                Account_Holder_Street_Name = sdr["Account_Holder_Street_Name"],
                                Account_Holder_Post_Code = sdr["Account_Holder_Post_Code"],

                                Account_Holder_Occupation = sdr["Account_Holder_Occupation"],
                                Account_Number = sdr["Account_Number"]

                            });
                        }
                    }
                    conn.Close();
                }

                return (new JavaScriptSerializer().Serialize(customers));
            }

        }

Here is the Script code.

var app = angular.module("WebClientModule", [])
    .controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
        var Account_Number = $scope.Account_Number;
        $scope.search = function (Account_Number) {
            var promisePostSingle = myService.postbyId(Account_Number);

        promisePostSingle.then(function (pl) {
            var res = pl.data;
            $scope.Account_Number = res.Account_Number;
            $scope.Account_Creation_Date = res.Account_Creation_Date;
            $scope.Account_Type = res.Account_Type;
            $scope.Branch_Sort_Code = res.Branch_Sort_Code;
            $scope.Account_Fees = res.Account_Fees;
            $scope.Account_Balance = res.Account_Balance;
            $scope.Over_Draft_Limit = res.Over_Draft_Limit;

            //   $scope.IsNewRecord = 0;
        },
            function (errorPl) {
                console.log('failure loading Employee', errorPl);
            });
    }
    }]);

app.service("myService", function ($http) {

    this.postbyId = function (Id) {
        return $http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);
    };
   })

Here is the HTML .

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />

    <title>AccountBalance</title>

        Enter Account_Number: <input type="text" ng-model="Account_Number" />
        <input type="button"  value="search" ng-click="search(Account_Number)" />

                                Account Number
                                Account Creation Date
                                Account Type
                                Branch Sort Code
                                Account Fees
                                Account Balance
                                Over Draft Limit

                                    {{user.Account_Number}}
                                    {{user.Account_Creation_Date}}
                                    {{user.Account_Type}}
                                    {{user.Branch_Sort_Code}}

                                    {{user.Account_Fees}}
                                    {{user.Account_Balance}}
                                    {{user.Over_Draft_Limit}}

{{Message}}

Here is the Screen Shot on Debugging mode on Wcf Service .

Here is the result on Google Chrome Console Windows .

Body:
You should change it;

$http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails/{Account_Number}" + Id);

to

$http.post("http://localhost:52098/HalifaxIISService.svc/GetAccountDetails?Account_Number=" + Id);

You are sending the parameter as {Account_Number}15. It should be 15.


问:
Java Swing Assigning a variable to a URL
Hello I'm developing a swing chat application where the chat history is being stored in an xml file.
I am able to fetch the xml file and display it in a table when done in the NetBeans project

But when converted to a jar file I am unable to use the xml file.
I've tried various things such as the getClass().getResource() method but it retrieves a URL rather than a string and if converted to a string using toString() method it cant be used as a valid path in order to parse the xml file.

Below is the code-->

ServerFrame.java

```<code>     public class ServerFrame extends javax.swing.JFrame {

        public String historyFile;
        public HistoryFrame historyFrame;
        public History hist;  }

        public ServerFrame() {
           historyFile=this.getClass().getResource("History.xml").toString();}

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

            hist = new History(historyFile);
            historyFrame = new HistoryFrame(hist);
            historyFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            historyFrame.setLocation(this.getLocation());
            historyFrame.setVisible(true);
    }
</code>```

History.java

```<code>public class History {

    public String filePath;

    public History(String filePath){

        this.filePath = filePath;
    }

    public void addMessage(Message msg, String time){

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filePath);

            Node data = doc.getFirstChild();

            Element message = doc.createElement("message");
            Element _sender = doc.createElement("sender"); _sender.setTextContent(msg.sender);
            Element _content = doc.createElement("content"); _content.setTextContent(msg.content);
            Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(msg.recipient);
            Element _time = doc.createElement("time"); _time.setTextContent(time);

            message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
            data.appendChild(message);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);

       }
           catch(Exception ex){
        System.out.println("Exceptionmodify xml");
       }
    }

    public void FillTable(HistoryFrame frame){

        DefaultTableModel model = (DefaultTableModel) frame.jTable1.getModel();

        try{
            File fXmlFile = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("message");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    model.addRow(new Object[]{getTagValue("sender", eElement), getTagValue("content", eElement), getTagValue("recipient", eElement), getTagValue("time", eElement)});
                }
            }
        }
        catch(Exception ex){
            System.out.println("Filling Exception");
        }
    }
</code>```

I have put the xml file in the src folder of Project directory.The problem seems to be in the docBuilder.parse() since everytime an exception is being generated in the function and it accepts only strings not urls since the system path of the file is different from javapath of the file.

I just need someway to access the xml file within the jar during execution. By access I mean just right filepath of xml file in the jar file and no need of file content.

答:
When running from an IDE you will not actually create a jar file and therefore you can get a resource from the directory structure. When packaging the application you will create jar file and resources are suddenly relative to a zip file. Reading from such a resource is possible but writing should not be done as it would change your package.

what you might need is to configure a specific location outside your jar location where you retrieve and write your xml file.

Body:
Hello I'm developing a swing chat application where the chat history is being stored in an xml file.
I am able to fetch the xml file and display it in a table when done in the NetBeans project

But when converted to a jar file I am unable to use the xml file.
I've tried various things such as the getClass().getResource() method but it retrieves a URL rather than a string and if converted to a string using toString() method it cant be used as a valid path in order to parse the xml file.

Below is the code-->

ServerFrame.java

     public class ServerFrame extends javax.swing.JFrame {

        public String historyFile;
        public HistoryFrame historyFrame;
        public History hist;  }

        public ServerFrame() {
           historyFile=this.getClass().getResource("History.xml").toString();}

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

            hist = new History(historyFile);
            historyFrame = new HistoryFrame(hist);
            historyFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            historyFrame.setLocation(this.getLocation());
            historyFrame.setVisible(true);
    }

History.java

public class History {

    public String filePath;

    public History(String filePath){

        this.filePath = filePath;
    }

    public void addMessage(Message msg, String time){

        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filePath);

            Node data = doc.getFirstChild();

            Element message = doc.createElement("message");
            Element _sender = doc.createElement("sender"); _sender.setTextContent(msg.sender);
            Element _content = doc.createElement("content"); _content.setTextContent(msg.content);
            Element _recipient = doc.createElement("recipient"); _recipient.setTextContent(msg.recipient);
            Element _time = doc.createElement("time"); _time.setTextContent(time);

            message.appendChild(_sender); message.appendChild(_content); message.appendChild(_recipient); message.appendChild(_time);
            data.appendChild(message);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filePath));
            transformer.transform(source, result);

       }
           catch(Exception ex){
        System.out.println("Exceptionmodify xml");
       }
    }

    public void FillTable(HistoryFrame frame){

        DefaultTableModel model = (DefaultTableModel) frame.jTable1.getModel();

        try{
            File fXmlFile = new File(filePath);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("message");

            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    model.addRow(new Object[]{getTagValue("sender", eElement), getTagValue("content", eElement), getTagValue("recipient", eElement), getTagValue("time", eElement)});
                }
            }
        }
        catch(Exception ex){
            System.out.println("Filling Exception");
        }
    }

I have put the xml file in the src folder of Project directory.The problem seems to be in the docBuilder.parse() since everytime an exception is being generated in the function and it accepts only strings not urls since the system path of the file is different from javapath of the file.

I just need someway to access the xml file within the jar during execution. By access I mean just right filepath of xml file in the jar file and no need of file content.


问:
Android intent-filter to be notified of an attempt to view a CSV file in the Download Manager
What's the required magic incantation to register your app to be notified that a user is trying to view a CSV file they've previously downloaded via the Download manager. I've had a brief play and the following filter will happily intercept notifications generated by: Dropbox, Box, Google Drive, Sky Drive, Chrome..... and offer itself to open the files, but my App isn't getting anything when a user attempts to view a file via the Download Manager.

```<code>        <intent-filter>
            <action android:name="com.my.testImportApp.LAUNCH" />
            <action android:name="android.intent.action.SEND" />
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.EDIT" />
            <action android:name="android.intent.action.PASTE" />
            <action android:name="android.intent.action.OPEN_DOCUMENT" />
            <action android:name="android.intent.action.GET_CONTENT" />
            <action android:name="android.intent.action.INSERT" />
            <action android:name="android.intent.action.INSERT_OR_EDIT" />
            <action android:name="android.intent.action.SENDTO" />
            <action android:name="android.intent.action.SEND_MULTIPLE" />
            <action android:name="android.intent.action.PICK" />
            <category android:name="android.intent.category.CATEGORY_BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:scheme="ftp" />
            <data android:scheme="file" />
            <data android:scheme="data" />
            <data android:scheme="info" />
            <data android:scheme="data" />
            <data android:scheme="smb" />
            <data android:scheme="nfs" />
            <data android:scheme="android.resource" />
            <data android:mimeType="text/comma-separated-values"/>
            <data android:mimeType="text/csv"/>
            <data android:mimeType="text/plain"/>
        </intent-filter>
</code>```

答:
You don't need really to play, here is a quick roundtrip to find out what you need.

Grep logcat for "ActivityManager: START u0"

Place your file in Downloads

Open Download App

Open your file by click on it

Check logcat you should find a line like: {act=android.intent.action.VIEW dat=content://com.android.providers.downloads.documents/document/2183 typ=text/csv flg=0x3 ...

This means your scheme is "content" and your mime type is "text/csv". As a hint when you see the dialog "open with" leave it open and do a ./gradlew installDebug with your new filter settings and it will immediately appear when you hit the filter conditions in your manifest set.

Body:
What's the required magic incantation to register your app to be notified that a user is trying to view a CSV file they've previously downloaded via the Download manager. I've had a brief play and the following filter will happily intercept notifications generated by: Dropbox, Box, Google Drive, Sky Drive, Chrome..... and offer itself to open the files, but my App isn't getting anything when a user attempts to view a file via the Download Manager.

        <intent-filter>
            <action android:name="com.my.testImportApp.LAUNCH" />
            <action android:name="android.intent.action.SEND" />
            <action android:name="android.intent.action.VIEW" />
            <action android:name="android.intent.action.EDIT" />
            <action android:name="android.intent.action.PASTE" />
            <action android:name="android.intent.action.OPEN_DOCUMENT" />
            <action android:name="android.intent.action.GET_CONTENT" />
            <action android:name="android.intent.action.INSERT" />
            <action android:name="android.intent.action.INSERT_OR_EDIT" />
            <action android:name="android.intent.action.SENDTO" />
            <action android:name="android.intent.action.SEND_MULTIPLE" />
            <action android:name="android.intent.action.PICK" />
            <category android:name="android.intent.category.CATEGORY_BROWSABLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.LAUNCHER" />
            <data android:scheme="http" />
            <data android:scheme="https" />
            <data android:scheme="ftp" />
            <data android:scheme="file" />
            <data android:scheme="data" />
            <data android:scheme="info" />
            <data android:scheme="data" />
            <data android:scheme="smb" />
            <data android:scheme="nfs" />
            <data android:scheme="android.resource" />
            <data android:mimeType="text/comma-separated-values"/>
            <data android:mimeType="text/csv"/>
            <data android:mimeType="text/plain"/>
        </intent-filter>

ContentLicense: CC BY-SA 4.0


问:
How do i make a WPF tab control's tab area smaller than the control?
I have a scenario where i have two buttons in the top right of my application, and i have a tab control that spans the entire application's screen. (Basically the two buttons are on the same horizontal line as the tabs in the tab control). The problem is that when i have multiple tabs open, the buttons and the tabs overlap. I don't want to have to specify the grid row/column numbers so that the buttons are above the tabs.

Is there any way to specify to the Tab control a certain area that it has to open tab controls before it automatically starts a second row of tabs?

In other words, if my tab control has a width of X, how can i tell the area that displays the actual tabs that it should only occupy say, x-15 amount of space.

Thanks!

答:
You'll have to supply the ControlTemplate for the TabControl to do that.  Here is an example where 100 pixels is reserved to the right of the header panel:

```<code><Grid>
    <TabControl>
        <TabControl.Template>
            <ControlTemplate TargetType="{x:Type TabControl}">
                <Grid KeyboardNavigation.TabNavigation="Local"
                      SnapsToDevicePixels="true"
                      ClipToBounds="true">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition x:Name="ColumnDefinition0"/>
                        <ColumnDefinition x:Name="ColumnDefinition1"
                                          Width="100"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition x:Name="RowDefinition0"
                                       Height="Auto"/>
                        <RowDefinition x:Name="RowDefinition1"
                                       Height="*"/>
                    </Grid.RowDefinitions>
                    <TabPanel x:Name="HeaderPanel"
                              Panel.ZIndex ="1"
                              KeyboardNavigation.TabIndex="1"
                              Grid.Column="0"
                              Grid.Row="0"
                              Margin="2,2,2,0"
                              IsItemsHost="true"/>
                    <Border x:Name="ContentPanel"
                            Background="{TemplateBinding Background}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            KeyboardNavigation.TabNavigation="Local"
                            KeyboardNavigation.DirectionalNavigation="Contained"
                            KeyboardNavigation.TabIndex="2"
                            Grid.Column="0"
                            Grid.Row="1"
                            Grid.ColumnSpan="2">
                        <ContentPresenter x:Name="PART_SelectedContentHost"
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                          Margin="{TemplateBinding Padding}"
                                          ContentSource="SelectedContent"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </TabControl.Template>
        <TabItem Header="Item1"/>
        <TabItem Header="Item2"/>
        <TabItem Header="Item3"/>
        <TabItem Header="Item4"/>
    </TabControl>
</Grid>
</code>```

Resize the window to see it in action.

Body:
You'll have to supply the ControlTemplate for the TabControl to do that.  Here is an example where 100 pixels is reserved to the right of the header panel:

<Grid>
    <TabControl>
        <TabControl.Template>
            <ControlTemplate TargetType="{x:Type TabControl}">
                <Grid KeyboardNavigation.TabNavigation="Local"
                      SnapsToDevicePixels="true"
                      ClipToBounds="true">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition x:Name="ColumnDefinition0"/>
                        <ColumnDefinition x:Name="ColumnDefinition1"
                                          Width="100"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition x:Name="RowDefinition0"
                                       Height="Auto"/>
                        <RowDefinition x:Name="RowDefinition1"
                                       Height="*"/>
                    </Grid.RowDefinitions>
                    <TabPanel x:Name="HeaderPanel"
                              Panel.ZIndex ="1"
                              KeyboardNavigation.TabIndex="1"
                              Grid.Column="0"
                              Grid.Row="0"
                              Margin="2,2,2,0"
                              IsItemsHost="true"/>
                    <Border x:Name="ContentPanel"
                            Background="{TemplateBinding Background}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            KeyboardNavigation.TabNavigation="Local"
                            KeyboardNavigation.DirectionalNavigation="Contained"
                            KeyboardNavigation.TabIndex="2"
                            Grid.Column="0"
                            Grid.Row="1"
                            Grid.ColumnSpan="2">
                        <ContentPresenter x:Name="PART_SelectedContentHost"
                                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                          Margin="{TemplateBinding Padding}"
                                          ContentSource="SelectedContent"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </TabControl.Template>
        <TabItem Header="Item1"/>
        <TabItem Header="Item2"/>
        <TabItem Header="Item3"/>
        <TabItem Header="Item4"/>
    </TabControl>
</Grid>

Resize the window to see it in action.


问:
I can access jquery from developer console but not from inside a component in angular 2
I have a script bundle that already includes jquery amont other things. I just want to use it. When trying to us it from a component it fails saying ERROR ReferenceError: $ is not defined. But when I go to console type $('body') for example it works correctly. What am I doing wrong?

Edit

I forgot to mention of course that the top of the page includes this:
declare var $ : any;

This is an angular-cli project and the bundle is already included in .angular-cli.json

答:
Angular-cli builds the project with webpack under the hood.

Now webpack tree-shakes everything that is not imported and bundle the whole thing into an isolated scope, hence if you don't have any reference to jquery, than it won't be available to your units

So just do in your ts file:

```<code>import * as $ from 'jquery'
</code>```

maybe you also need to add the jquery package via npm:

```<code>npm install -S jquery
</code>```

That -S stands for --save

plnkr demo here : https://plnkr.co/edit/y272nspAjnHy2wsTqzdh?p=preview

Some food for thought :

I strongly suggest not to use JQuery in your Angular 2+ projects, natives like querySelector and addEventListener with angular's bindings make jQuery obsolete.

Body:
Angular-cli builds the project with webpack under the hood.

Now webpack tree-shakes everything that is not imported and bundle the whole thing into an isolated scope, hence if you don't have any reference to jquery, than it won't be available to your units

So just do in your ts file:

import * as $ from 'jquery'

maybe you also need to add the jquery package via npm:

npm install -S jquery

That -S stands for --save

plnkr demo here : https://plnkr.co/edit/y272nspAjnHy2wsTqzdh?p=preview

Some food for thought :

I strongly suggest not to use JQuery in your Angular 2+ projects, natives like querySelector and addEventListener with angular's bindings make jQuery obsolete.


问:
How to change the active chat in web whatsapp via selenium or javascript with Python 3
I am steering web whatsapp via selenium via Python, i was wondering if it is possible to change the active (top chat. If a message is recieved, the chat won't be set as active, it will always remain in the background.

In Javascript, one can see a list of all chat in the consoles via:

```<code>Store.chat.models
</code>```

The active chat is stored at position zero, however overwriting the position zero with another chat will not make the chat active.

I have found out that there is a variable called "x_active" which changes if a chat is clicked on and view to true (and all others have it as false).

e.g.:

```<code>Store.Chat.models[0].__x_active
</code>```

However setting the variable or true or false in the chrome Console tab did not change anything in the UI, so how can I achieve such behaviour?

答:
You'll need to use selenium to click on the contact in the left pane to make it active.  You can easily find the place to click using the CSS selector like this:

```<code>driver.find_element_by_css_selector('span[title="Contact Name"]').click()
</code>```

To easily identify which contacts have unread messages, you can use your JavaScript Store.chat.models list, and find objects in the list with the variable __x_hasUnread = True, and the value of the variable __x_formattedTitle to find the contact name to use for the find above.

Body:
I am steering web whatsapp via selenium via Python, i was wondering if it is possible to change the active (top chat. If a message is recieved, the chat won't be set as active, it will always remain in the background.

In Javascript, one can see a list of all chat in the consoles via:

Store.chat.models

The active chat is stored at position zero, however overwriting the position zero with another chat will not make the chat active.

I have found out that there is a variable called "x_active" which changes if a chat is clicked on and view to true (and all others have it as false).

e.g.:

Store.Chat.models[0].__x_active

However setting the variable or true or false in the chrome Console tab did not change anything in the UI, so how can I achieve such behaviour?

Body:
You'll need to use selenium to click on the contact in the left pane to make it active.  You can easily find the place to click using the CSS selector like this:

driver.find_element_by_css_selector('span[title="Contact Name"]').click()

To easily identify which contacts have unread messages, you can use your JavaScript Store.chat.models list, and find objects in the list with the variable __x_hasUnread = True, and the value of the variable __x_formattedTitle to find the contact name to use for the find above.


问:
Database structure and source control - best practice
Background

I came from several years working in a company where all the database objects were stored in source control, one file per object.  We had a list of all the objects that was maintained when new items were added (to allow us to have scripts run in order and handle dependencies) and a VB script that ran to create one big script for running against the database.

All the tables were 'create if not exists' and all the SP's etc. were drop and recreate.

Up to the present and I am now working in a place where the database is the master and there is no source control for DB objects, but we do use redgate's tools for updating our production database (SQL compare), which is very handy, and requires little work.

Question

How do you handle your DB objects?  I like to have them under source control (and, as we're using GIT, I'd like to be able to handle merge conflicts in the scripts, rather than the DB), but I'm going to be pressed to get past the ease of using SQL compare to update the database.

I don't really want to have us updating scripts in GIT and then using SQL compare to update the production database from our DEV DB, as I'd rather have 'one version of the truth', but I don't really want to get into re-writing a custom bit of software to bundle the whole lot of scripts together.

I think that visual studio database edition may do something similar to this, but I'm not sure if we will have the budget for it.

I'm sure that this has been asked to death, but I can't find anything that seems to quite have the answer I'm looking for.
Similar to this, but not quite the same:

What are the best practices for database scripts under code control

Started a bounty, as I'm interested in canvassing for a few more opinions - the answers here are sound, but I feel that there should really be an easier way.

Thanks for all the great answers - all have their merits, so I'm going to take the highest vote, but cheers for all the input.

答:
Using a 3rd party SSMS add-in ApexSQL Source Control, database objects can be automatically scripted and pushed to a remote Git repository, or even to a cloned local one, if you prefer working with local repository.

ApexSQL Source Control support Git source control system out of the box. That means you don’t need any additional Git client installed. Besides this, Branching and Merging are integrated and available through the add-in UI.


问:
SQL select only those group for which other column has only Nulls
I have SQL query with GROUP BY.
I want to select only this groups which have only Nulls in other column.

```<code>Select HH, TT from TABLE join TABLE... where XX GROUP BY HH

HH | TT
1  | Null
2  | Null
2  | Test
3  | Null
3  | Null
</code>```

I want to have only those:

```<code> HH | TT
 1  | Null
 3  | Null
</code>```

I'm on Oracle.

答:
nvl2 is such a nice function that helps us for both null and not null values :

```<code>select hh, 'Null' tt
  from mytable
 group by hh
 having sum(nvl2(tt,1,0))=0;
</code>```

Body:
I have SQL query with GROUP BY.
I want to select only this groups which have only Nulls in other column.

Select HH, TT from TABLE join TABLE... where XX GROUP BY HH

HH | TT
1  | Null
2  | Null
2  | Test
3  | Null
3  | Null

I want to have only those:

 HH | TT
 1  | Null
 3  | Null

I'm on Oracle.

Body:
nvl2 is such a nice function that helps us for both null and not null values :

select hh, 'Null' tt
  from mytable
 group by hh
 having sum(nvl2(tt,1,0))=0;


问:
Combine streams of array and single value
I have a scenario I would like help with figuring out how to implement it in rxjs.

Source Observables:

single: emits single values with an id field

many: emits array of values of the same type as single

Stream Requirements:

Overview: the final result of the stream is an array of values representing the latest value emitted from many overwritten by the values emitted by single since the last emit from many.

nothing is emitted till many emits at least once

the values emitted by single accumulate and overwrite the corresponding values (by id) previously emitted by many

when many emits the accumulated single values are cleared

Practical Scenario:

I have a filterable data-table component that has child components that represent each filter for each column. A list of filter settings corresponding to each column (many) can be pushed down into the component from its parent. The child filter components can emit filter changes (single) for themselves. The settings from the parent component have priority over the child filter components.

What I've Tried

console.clear();
const many = Rx.Observable.create(o => {
  setTimeout(() => {
    o.next([
      { id: 1, value: 'a' },
      { id: 2, value: 'b' },
      { id: 3, value: 'c' }
    ]);
  }, 1000);
  setTimeout(() => {
    o.next([
      { id: 1, value: 'x' },
      { id: 2, value: 'y' },
      { id: 3, value: 'z' }
    ]);
  }, 4000);
});

const single = Rx.Observable.create(o => {
  o.next({ id: 1, value: 'd' });
  setTimeout(() => { o.next({ id: 2, value: 'e' }); }, 2000);
  setTimeout(() => { o.next({ id: 3, value: 'f' }); }, 3000);
  setTimeout(() => { o.next({ id: 1, value: 'g' }); }, 5000);
});

single
  .scan((acc, x) => {
    return [...acc.filter(y => y.id !== x.id), x];
  }, [])
  .startWith([])
  .combineLatest(many)
  .map(x => {
    const s = x[0];
    const m = x[1];
    return [...m.filter(y => !s.some(z => z.id === y.id)), s];
  })
  .subscribe(x => { console.log(JSON.stringify(x)); });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script></code>```

What this code doesn't do reset the accumulated single values when many emits.

Question

How do you implement the afore mentioned scenario in rxjs?

Edit

I found a solution (posted bellow) but I'll accept a better implementation. Thanks!

答:
Blaaah... I realized what I did wrong soon after posting. I just needed to reverse the order. Here is my solution but I'm open to better options.

const many = new Rx.Subject();
const single = new Rx.Subject();

// create the stream
const stream = many
  .switchMap(m => {
    return single
      .scan((acc, x) => {
        return [...acc.filter(y => y.id !== x.id), x];
      }, [])
      .startWith([])
      .map(s => {
        return [...m.filter(y => !s.some(z => z.id === y.id)), ...s];
      });
  })
  .subscribe(x => { console.log(JSON.stringify(x)); });

// send the data
single.next({ id: 1, value: 'd' });
setTimeout(() => {
  many.next([
    { id: 1, value: 'a' },
    { id: 2, value: 'b' },
    { id: 3, value: 'c' }
  ]);
}, 1000);
setTimeout(() => { single.next({ id: 2, value: 'e' }); }, 2000);
setTimeout(() => { single.next({ id: 3, value: 'f' }); }, 3000);
setTimeout(() => {
  many.next([
    { id: 1, value: 'x' },
    { id: 2, value: 'y' },
    { id: 3, value: 'z' }
  ]);
}, 4000);
setTimeout(() => { single.next({ id: 1, value: 'g' }); }, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script></code>```

Body:
I have a scenario I would like help with figuring out how to implement it in rxjs.

Source Observables:

single: emits single values with an id field

many: emits array of values of the same type as single

Stream Requirements:

Overview: the final result of the stream is an array of values representing the latest value emitted from many overwritten by the values emitted by single since the last emit from many.

nothing is emitted till many emits at least once

the values emitted by single accumulate and overwrite the corresponding values (by id) previously emitted by many

when many emits the accumulated single values are cleared

Practical Scenario:

I have a filterable data-table component that has child components that represent each filter for each column. A list of filter settings corresponding to each column (many) can be pushed down into the component from its parent. The child filter components can emit filter changes (single) for themselves. The settings from the parent component have priority over the child filter components.

What I've Tried

console.clear();
const many = Rx.Observable.create(o => {
  setTimeout(() => {
    o.next([
      { id: 1, value: 'a' },
      { id: 2, value: 'b' },
      { id: 3, value: 'c' }
    ]);
  }, 1000);
  setTimeout(() => {
    o.next([
      { id: 1, value: 'x' },
      { id: 2, value: 'y' },
      { id: 3, value: 'z' }
    ]);
  }, 4000);
});

const single = Rx.Observable.create(o => {
  o.next({ id: 1, value: 'd' });
  setTimeout(() => { o.next({ id: 2, value: 'e' }); }, 2000);
  setTimeout(() => { o.next({ id: 3, value: 'f' }); }, 3000);
  setTimeout(() => { o.next({ id: 1, value: 'g' }); }, 5000);
});

single
  .scan((acc, x) => {
    return [...acc.filter(y => y.id !== x.id), x];
  }, [])
  .startWith([])
  .combineLatest(many)
  .map(x => {
    const s = x[0];
    const m = x[1];
    return [...m.filter(y => !s.some(z => z.id === y.id)), s];
  })
  .subscribe(x => { console.log(JSON.stringify(x)); });

What this code doesn't do reset the accumulated single values when many emits.

Question

How do you implement the afore mentioned scenario in rxjs?

Edit

I found a solution (posted bellow) but I'll accept a better implementation. Thanks!

Body:
Blaaah... I realized what I did wrong soon after posting. I just needed to reverse the order. Here is my solution but I'm open to better options.

const many = new Rx.Subject();
const single = new Rx.Subject();

// create the stream
const stream = many
  .switchMap(m => {
    return single
      .scan((acc, x) => {
        return [...acc.filter(y => y.id !== x.id), x];
      }, [])
      .startWith([])
      .map(s => {
        return [...m.filter(y => !s.some(z => z.id === y.id)), ...s];
      });
  })
  .subscribe(x => { console.log(JSON.stringify(x)); });

// send the data
single.next({ id: 1, value: 'd' });
setTimeout(() => {
  many.next([
    { id: 1, value: 'a' },
    { id: 2, value: 'b' },
    { id: 3, value: 'c' }
  ]);
}, 1000);
setTimeout(() => { single.next({ id: 2, value: 'e' }); }, 2000);
setTimeout(() => { single.next({ id: 3, value: 'f' }); }, 3000);
setTimeout(() => {
  many.next([
    { id: 1, value: 'x' },
    { id: 2, value: 'y' },
    { id: 3, value: 'z' }
  ]);
}, 4000);
setTimeout(() => { single.next({ id: 1, value: 'g' }); }, 5000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.5/Rx.min.js"></script>


问:
QMake appending to DEFINE without respecting conditional
I created an empty Qt Project to illustrate my issue.  There is NOTHING in the project whatsoever except for this QMake code in a in pro file.  The project/build configuration is just the defaults.

This Qmake code ALWAYS executes the $$system() function, but it does it "behind the scenes".  There is some mystery process in which contains( DEFINES, anything ) ALWAYS evaluates to true and fires off the subsequent code.  Note that you can literally use any value where I've used something and anything.

```<code>CONFIG( something ){ DEFINES+=anything }
contains( DEFINES, anything ){
    message( anything! )
    stdOut=$$system( echo x > test.txt )
}
else{
    message( nothing! )
}
</code>```

Every time this is run (I'm just saving the file in QtCreator to kick it off btw - NOT running QMake), this General Message appears:

Project MESSAGE: nothing!

A second later, the test.txt file appears in the project directory.

Adding to the oddity, if you use the CONFIG() directly as the condition to control the file writing, then this does NOT happen.  Further, if you remove that CONFIG() line this does NOT happen.

It seems that there is a mysterious background process which evaluates this and ALWAYS executes DEFINES+=anything and then continues to process whatever logic is present.

I know that if you add source files to the project conditionally, they will always appear in the file browsing tree, even if they are not compiled.  That is an example where Qt Creator ignores conditionals and executes the QMake for it's own purposes.  Is this the same mechanism at play?

答:
I wasted a couple of hours fighting this, and then arrived at an answer just after posting my question.  I often find that the act of simply explaining my issue in detail seems to clarify how to solve it!

Anyway, I'm pretty sure that my guess is correct about what is happening under the hood.  Qt Creator performs a pass of the code where it ignores all conditionals in order to create the defines (for whatever private purpose...).

One solution would be to not a set define value, and just use a QMake variable like this:

```<code>CONFIG( something ){ IS_SOMETHING=true } else { IS_SOMETHING=false }
$$IS_SOMETHING{
    message( anything! )
    stdOut=$$system( echo x > test.txt )
}
else{
    message( nothing! )
}
</code>```

That's fine if you only need to use a subsequent conditional within the QMake.  The weakness of that, however, is you don't have the logic cascade down into your C++.  So, I found a better solution:

```<code>defineReplace( hideFromIdeParser ){ return( $$1 ) }

CONFIG( something ){ DEFINES+=$$hideFromIdeParser(anything) }
contains( DEFINES, anything ){
    message( anything! )
    stdOut=$$system( echo x > test.txt )
}
else{
    message( nothing! )
}
</code>```

Apparently, the blackbox parser does not resolve function results, so this trick makes everything work as desired!

Body:
I created an empty Qt Project to illustrate my issue.  There is NOTHING in the project whatsoever except for this QMake code in a in pro file.  The project/build configuration is just the defaults.

This Qmake code ALWAYS executes the $$system() function, but it does it "behind the scenes".  There is some mystery process in which contains( DEFINES, anything ) ALWAYS evaluates to true and fires off the subsequent code.  Note that you can literally use any value where I've used something and anything.

CONFIG( something ){ DEFINES+=anything }
contains( DEFINES, anything ){
    message( anything! )
    stdOut=$$system( echo x > test.txt )
}
else{
    message( nothing! )
}

Every time this is run (I'm just saving the file in QtCreator to kick it off btw - NOT running QMake), this General Message appears:

Project MESSAGE: nothing!

A second later, the test.txt file appears in the project directory.

Adding to the oddity, if you use the CONFIG() directly as the condition to control the file writing, then this does NOT happen.  Further, if you remove that CONFIG() line this does NOT happen.

It seems that there is a mysterious background process which evaluates this and ALWAYS executes DEFINES+=anything and then continues to process whatever logic is present.

I know that if you add source files to the project conditionally, they will always appear in the file browsing tree, even if they are not compiled.  That is an example where Qt Creator ignores conditionals and executes the QMake for it's own purposes.  Is this the same mechanism at play?

Body:
I wasted a couple of hours fighting this, and then arrived at an answer just after posting my question.  I often find that the act of simply explaining my issue in detail seems to clarify how to solve it!

Anyway, I'm pretty sure that my guess is correct about what is happening under the hood.  Qt Creator performs a pass of the code where it ignores all conditionals in order to create the defines (for whatever private purpose...).

One solution would be to not a set define value, and just use a QMake variable like this:

CONFIG( something ){ IS_SOMETHING=true } else { IS_SOMETHING=false }
$$IS_SOMETHING{
    message( anything! )
    stdOut=$$system( echo x > test.txt )
}
else{
    message( nothing! )
}

That's fine if you only need to use a subsequent conditional within the QMake.  The weakness of that, however, is you don't have the logic cascade down into your C++.  So, I found a better solution:

defineReplace( hideFromIdeParser ){ return( $$1 ) }

CONFIG( something ){ DEFINES+=$$hideFromIdeParser(anything) }
contains( DEFINES, anything ){
    message( anything! )
    stdOut=$$system( echo x > test.txt )
}
else{
    message( nothing! )
}

Apparently, the blackbox parser does not resolve function results, so this trick makes everything work as desired!