问:
How to convert a dictionary of strings into a block of text with python
I have a dictionary full of string-valued k-v pairs, and I want each to be separated by ==>& then printed to a newline.

I use an array to mediate the transformation, which seems unnecessary & inelegant. I'd like to do this in 1 line if possible.

Here's what I have:

```<code>foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)
</code>```

this will print:

```<code>b ==> 2
c ==> 3
a ==> 1
</code>```

the order doesn't matter (otherwise I'd just use OrderedDict.) What matters is that all k-v pairs get printed in the correct format.

答:
While other answers here have provided good ways of formatting your regular dictionary, if you have many cases where you need this functionality, you may want to consider creating a custom dictionary object by inheriting from collections.UserDict, and overriding its default __repr__():

```<code>>>> from collections import UserDict
>>>
>>> class custom_dict(UserDict):
...     def __repr__(self):
...         return '\n'.join('{} ==> {}'.format(k, v) for k, v in self.data.items())
...
>>> foo_dict = {
...     'a' : '1',
...     'b' : '2',
...     'c' : '3',
...     }
>>>
>>> new_dict = custom_dict(foo_dict)
>>> new_dict
a ==> 1
b ==> 2
c ==> 3
>>>
</code>```

Body:
I have a dictionary full of string-valued k-v pairs, and I want each to be separated by ==>& then printed to a newline.

I use an array to mediate the transformation, which seems unnecessary & inelegant. I'd like to do this in 1 line if possible.

Here's what I have:

foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)

this will print:

b ==> 2
c ==> 3
a ==> 1

the order doesn't matter (otherwise I'd just use OrderedDict.) What matters is that all k-v pairs get printed in the correct format.

Body:
While other answers here have provided good ways of formatting your regular dictionary, if you have many cases where you need this functionality, you may want to consider creating a custom dictionary object by inheriting from collections.UserDict, and overriding its default __repr__():

>>> from collections import UserDict
>>>
>>> class custom_dict(UserDict):
...     def __repr__(self):
...         return '\n'.join('{} ==> {}'.format(k, v) for k, v in self.data.items())
...
>>> foo_dict = {
...     'a' : '1',
...     'b' : '2',
...     'c' : '3',
...     }
>>>
>>> new_dict = custom_dict(foo_dict)
>>> new_dict
a ==> 1
b ==> 2
c ==> 3
>>>


来源: stackexchange

问:
Upload File from Rest client to codeigniter
I know it could be a duplicate but i need a bit more help in that.
I have started working on making api for an android application in codeigniter. And currently working on making api for uploading an image.. I am using  https://github.com/chriskacerguis/codeigniter-restserver
using postman to upload images to test my API but
but i am getting something like

'------WebKitFormBoundaryXkKFa0QV2XVs0EoK
Content-Disposition:_form-data;_name' => string '"filesss"; filename="17264394_1739947152983817_1705887364349350305_n.jpg"
Content-Type: image/jpeg
�����JFIF����������Photoshop 3.0�8BIM������g�Vnlfejt43YHm4REx3e4k(�bFBMD01000abe0300002f19000082320000643300004b3400002f4d0000c46f0000d3750000b8780000b07b000096cd0000��ICC_PROFILE���lcms��mntrRGB XYZ

Now can any one help me how to be able to save the image on my server
below is my code

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . './libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Update_image extends REST_Controller{
    function __construct(){
        parent::__construct();
            $models[] = 'Quiz_model';
            $models[] = 'Users_model';
        $this->load->model($models);
            $libs[] =  'form_validation';
            $libs[] =  'image_lib';
            $libs[] =  'email';
            //$libs[] =  'rest';
        $this->load->library($libs);

            $helpers[] = 'file';
            $helpers[] = 'security';
            $helpers[] = 'url';
            $helpers[] = 'string';
        $this->load->helper($helpers);

    }

    function index_post(){

            $users_id = $this->input->post('users_id');
            $users_id = 6;

            $config['upload_path']   = './public/user_images/';
            $config['allowed_types'] = 'jpg|png';
            $config['max_size']      = ; // for 5mb file
            $config['max_width']     = 5000;
            $config['max_height']    = 5000;
            $this->load->library('upload', $config);

            if(!$this->upload->do_upload('users_image')){
                $error = array('error' => $this->upload->display_errors('<span>','<span>'));
                $data['msg'] = error('Please Fix the errors below');
                $data['file_upload_error'] = formErrorParse($this->upload->display_errors());
                $this->form_validation->set_message('quiz_image', implode('<br/>', $error));

                $response['status'] = 0;
                $response['msg'] = strip_tags($this->upload->display_errors());

            }else{

                $uploadStat = $this->upload->data();
                $img_config['image_library'] = 'gd2';
                $img_config['source_image'] = './public/uploads/user_images/'.$uploadStat['file_name'];
                $img_config['new_image'] = './public/uploads/user_images/thumbnail/'.$uploadStat['file_name'];
                //$img_config['create_thumb'] = TRUE;
                $img_config['maintain_ratio'] = TRUE;
                $img_config['width']     = 150;
                $img_config['height']   = 150;
                $this->image_lib->clear();
                $this->image_lib->initialize($img_config);
                $this->image_lib->resize();

                $updates['users_images'] = $uploadStat['file_name'];
                $cond['users_id'] = $users_id;
                $this->db->update('users', $updates, $cond);

                $response['status'] = 1;
                $response['msg'] = 'Image Uploaded';
            }
            $this->response($response, 200);
    }

}
</code>```

答: Make sure your php version is 5.6 or above,i had the same problem and solved it by switching to php version 7.</p>

ContentLicense: CC BY-SA 3.0

Body:
I know it could be a duplicate but i need a bit more help in that.
I have started working on making api for an android application in codeigniter. And currently working on making api for uploading an image.. I am using  https://github.com/chriskacerguis/codeigniter-restserver
using postman to upload images to test my API but
but i am getting something like

'------WebKitFormBoundaryXkKFa0QV2XVs0EoK
Content-Disposition:_form-data;_name' => string '"filesss"; filename="17264394_1739947152983817_1705887364349350305_n.jpg"
Content-Type: image/jpeg
�����JFIF����������Photoshop 3.0�8BIM������g�Vnlfejt43YHm4REx3e4k(�bFBMD01000abe0300002f19000082320000643300004b3400002f4d0000c46f0000d3750000b8780000b07b000096cd0000��ICC_PROFILE���lcms��mntrRGB XYZ

Now can any one help me how to be able to save the image on my server
below is my code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . './libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class Update_image extends REST_Controller{
    function __construct(){
        parent::__construct();
            $models[] = 'Quiz_model';
            $models[] = 'Users_model';
        $this->load->model($models);
            $libs[] =  'form_validation';
            $libs[] =  'image_lib';
            $libs[] =  'email';
            //$libs[] =  'rest';
        $this->load->library($libs);

            $helpers[] = 'file';
            $helpers[] = 'security';
            $helpers[] = 'url';
            $helpers[] = 'string';
        $this->load->helper($helpers);

    }

    function index_post(){

            $users_id = $this->input->post('users_id');
            $users_id = 6;

            $config['upload_path']   = './public/user_images/';
            $config['allowed_types'] = 'jpg|png';
            $config['max_size']      = ; // for 5mb file
            $config['max_width']     = 5000;
            $config['max_height']    = 5000;
            $this->load->library('upload', $config);

            if(!$this->upload->do_upload('users_image')){
                $error = array('error' => $this->upload->display_errors('',''));
                $data['msg'] = error('Please Fix the errors below');
                $data['file_upload_error'] = formErrorParse($this->upload->display_errors());
                $this->form_validation->set_message('quiz_image', implode('
', $error));

                $response['status'] = 0;
                $response['msg'] = strip_tags($this->upload->display_errors());

            }else{

                $uploadStat = $this->upload->data();
                $img_config['image_library'] = 'gd2';
                $img_config['source_image'] = './public/uploads/user_images/'.$uploadStat['file_name'];
                $img_config['new_image'] = './public/uploads/user_images/thumbnail/'.$uploadStat['file_name'];
                //$img_config['create_thumb'] = TRUE;
                $img_config['maintain_ratio'] = TRUE;
                $img_config['width']     = 150;
                $img_config['height']   = 150;
                $this->image_lib->clear();
                $this->image_lib->initialize($img_config);
                $this->image_lib->resize();

                $updates['users_images'] = $uploadStat['file_name'];
                $cond['users_id'] = $users_id;
                $this->db->update('users', $updates, $cond);

                $response['status'] = 1;
                $response['msg'] = 'Image Uploaded';
            }
            $this->response($response, 200);
    }

}


问:
How do I get the standard file extension given a MIME type in Delphi?
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the easiest and most general way to implement a function that would be called like this:

```<code>fileExt := GetExtension('text/xml');
</code>```

答:
Indy's IndyProtocols package has a TIdMimeTable class and standalone GetMIMETypeFromFile() and GetMIMEDefaultFileExt() wrapper functions in the IdGlobalProtocols unit, eg:

```<code>uses
  ..., IdGlobalProtocols;

function GetExtension(const AMIMEType: string);
begin
  Result := GetMIMEDefaultFileExt(AMIMEType);
end
</code>```

Just know that internally, GetMIMEDefaultFileExt() creates and destroys a TIdMimeTable object, and that object re-builds its list of known extensions and MIME types every time it is created.  If you are going to be querying MIME extensions frequently, it would be worth creating your own TIdMimeTable object (or TIdThreadSafeMimeTable if you need to share the table across multiple threads) and reuse it each time:

```<code>uses
  ..., IdGlobalProtocols;

var
  MimeTable: TIdMimeTable = nil;

function GetExtension(const AMIMEType: string);
begin
  if MimeTable = nil then
    MimeTable := TIdMimeTable.Create;
  Result := MimeTable.GetDefaultFileExt(AMIMEType);
end;

initialization
finalization
  MimeTable.Free;
</code>```

```<code>uses
  ..., IdGlobalProtocols, IdCustomHTTPServer;

var
  MimeTable: TIdThreadSafeMimeTable = nil;

function GetExtension(const AMIMEType: string);
begin
  if MimeTable = nil then
    MimeTable := TIdThreadSafeMimeTable.Create;
  Result := MimeTable.GetDefaultFileExt(AMIMEType);
end;

initialization
finalization
  MimeTable.Free;
</code>```

Body:
Is there a built-in way to get the standard extension of a given MIME type in Delphi (XE7)?

I'm looking for the easiest and most general way to implement a function that would be called like this:

fileExt := GetExtension('text/xml');

Body:
Indy's IndyProtocols package has a TIdMimeTable class and standalone GetMIMETypeFromFile() and GetMIMEDefaultFileExt() wrapper functions in the IdGlobalProtocols unit, eg:

uses
  ..., IdGlobalProtocols;

function GetExtension(const AMIMEType: string);
begin
  Result := GetMIMEDefaultFileExt(AMIMEType);
end

Just know that internally, GetMIMEDefaultFileExt() creates and destroys a TIdMimeTable object, and that object re-builds its list of known extensions and MIME types every time it is created.  If you are going to be querying MIME extensions frequently, it would be worth creating your own TIdMimeTable object (or TIdThreadSafeMimeTable if you need to share the table across multiple threads) and reuse it each time:

uses
  ..., IdGlobalProtocols;

var
  MimeTable: TIdMimeTable = nil;

function GetExtension(const AMIMEType: string);
begin
  if MimeTable = nil then
    MimeTable := TIdMimeTable.Create;
  Result := MimeTable.GetDefaultFileExt(AMIMEType);
end;

initialization
finalization
  MimeTable.Free;

uses
  ..., IdGlobalProtocols, IdCustomHTTPServer;

var
  MimeTable: TIdThreadSafeMimeTable = nil;

function GetExtension(const AMIMEType: string);
begin
  if MimeTable = nil then
    MimeTable := TIdThreadSafeMimeTable.Create;
  Result := MimeTable.GetDefaultFileExt(AMIMEType);
end;

initialization
finalization
  MimeTable.Free;


问:
Formatting output to a fixed precision in Python
I would like to have always 5 numbers after coma.

Example :
My data is like 105.56565  105. 165.54......

I want the same length like this: 105.56565 105.00000 165.54000....

script :

```<code>from pylab import*
from rtlsdr import*
from bluetooth import*
import sys

#configure device
sdr= RtlSdr()
sdr.sample_rate=double(sys.argv[3])
sdr.gain=double(sys.argv[2])
sdr.center_freq=double(sys.argv[1])

#Bluetooth connection

server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port=server_sock.getsockname()[1]
uuid="94f39d29-7d6d-437d-973b-fba39e49d4ee"
client_sock,client_info=server_sock.accept()

while(1):
        samples=sdr.read_samples(256*1024)
        result=psd(samples,NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq*1e6/1e6)
        freq=result[1]/1e6
        value_freq=str(freq)[1:-1]
        print format(freq, '%5f') // he do not work
</code>```

答:
The format language used by the format builtin (and str.format) is not quite the same as the printf style formatting used by the % operator. You should read the docs for the details on the language.

For your specific case, I suspect you want format(freq, ".5f"). This will always give your five digits after the decimal point.

Body:
I would like to have always 5 numbers after coma.

Example :
My data is like 105.56565  105. 165.54......

I want the same length like this: 105.56565 105.00000 165.54000....

script :

from pylab import*
from rtlsdr import*
from bluetooth import*
import sys

#configure device
sdr= RtlSdr()
sdr.sample_rate=double(sys.argv[3])
sdr.gain=double(sys.argv[2])
sdr.center_freq=double(sys.argv[1])

#Bluetooth connection

server_sock=BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port=server_sock.getsockname()[1]
uuid="94f39d29-7d6d-437d-973b-fba39e49d4ee"
client_sock,client_info=server_sock.accept()

while(1):
        samples=sdr.read_samples(256*1024)
        result=psd(samples,NFFT=1024, Fs=sdr.sample_rate/1e6, Fc=sdr.center_freq*1e6/1e6)
        freq=result[1]/1e6
        value_freq=str(freq)[1:-1]
        print format(freq, '%5f') // he do not work


问:
Is the .git/ folder only supposed to be located in the project's root location?
Does git allow (i.e., is there a valid use case) a .git/ folder inside subfolders?

Or is the .git/ folder supposed to be only in one place and that is in the project's root location?

答: In general, the .git folder should only be at the project's root location (by design). However, the repository may be set up to use git submodules, and this could result in subdirectories having their own .git folder.


问:
Excel Crashes When Opening Trusted Document With Macros Or Enabling Macros
As the title says, I am unable to open a trusted document with macros - Excel crashes immediately. Making a copy of the document allows it to open (because the copy is untrusted), and I can inspect the macros in the VB Editor, but enabling macros causes another crash. Why is this happening and what can I do to fix it?

I experienced a similar situation today where a "Can't find project or library" dialog box displays before a crash as well, even though no projects or libraries are actually missing.

答:
This is caused by a macro with a compile error. To fix it, use the following steps (all credit to alulla at Ozgrid, whose directions I've lightly adapted for clarity):

Open a new Excel workbook, not your crashing workbook

Go to the Developer Tab and click “Macro Security” in the Code section of the Ribbon

Click the bullet option entitled “Disable all macros with notification”

Go to the Trusted Locations tab on the left and check the “Disable all Trusted Locations” box at the bottom

Go to Trusted Documents and check the “Disable all Trusted Documents” box

Click OK and close the new workbook

Open your Excel file that was crashing

Do not click "Enable Macros" - instead go to the Developer Tab and
  open the Visual Basic Editor

In the VB Editor, save the project and then click Debug > Compile VBAProject

Correct any compile errors that occur

Save the VB project again and then save the Excel workbook

Revert any changes you made to Macro Security in steps 3-5

Close Excel, re-open the previously crashing workbook, and Enable Macros

I experienced today that this can also resolve "Can't find project or library" crashes where no reference is actually missing and Excel crashes before you can even get to the reference dialog in the first place.

ContentLicense: CC BY-SA 4.0


问:
How to set image alpha back to normal
I am trying to have an image of a check mark or an image of a cross appear whether the user got something wrong or right. I then want the image to fade, which I have done to a level that I like, but the problem is, is the image doesn't re-appear after it fades. The code in question is below:

```<code>private void aniCross(){
    cross.setVisibility(View.VISIBLE);
    cross.animate().alpha(0).setDuration(1000);
}
</code>```

Here I call an animate cross method that will set the visibility to visible (I set the image to be invisible at the start of the onCreate), and then it will animate the image. The animation takes the alpha to a value of 0 in a time interval of 1000ms. After the cross becomes invisible, I want it to be able to be displayed again and again for as long as it needs to, but still fading out after each time it is displayed.

I have tried doing things like cross.setAlpha(255) but that didn't seem to help the problem.

答: Don't like answering my own question, but I was able to fix this problem. Use cross.setAlpha(1f) instead of cross.setAlpha(255). I guess setAlpha takes a float form 0 to 1 instead of 0 to 255.

Title: How to set image alpha back to normal

Body:
I am trying to have an image of a check mark or an image of a cross appear whether the user got something wrong or right. I then want the image to fade, which I have done to a level that I like, but the problem is, is the image doesn't re-appear after it fades. The code in question is below:

private void aniCross(){
    cross.setVisibility(View.VISIBLE);
    cross.animate().alpha(0).setDuration(1000);
}

Here I call an animate cross method that will set the visibility to visible (I set the image to be invisible at the start of the onCreate), and then it will animate the image. The animation takes the alpha to a value of 0 in a time interval of 1000ms. After the cross becomes invisible, I want it to be able to be displayed again and again for as long as it needs to, but still fading out after each time it is displayed.

I have tried doing things like cross.setAlpha(255) but that didn't seem to help the problem.


问:
Use Scanner for many different methods
I'm new to Java so I'm practicing with some simple code. I want to create some methods and use Scanner for all of them, but I don't want to declare Scanner every time I create other new methods.

So here is my code. Is this correct? Are there better ways to do this?

```<code>import java.util.*;

public class TripPlanner {

    public static final Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        Greeting();
    }

    public static void Greeting() {
        System.out.println("Welcome to Vacation Planner");
        System.out.print("What is your name? ");
        String  name = input.nextLine();
        System.out.print("Nice to meet you " + name +", where are you travelling to? ");
        String place = input.nextLine();
        System.out.println("Great! " + place + " sounds like a great trip" );
        System.out.println("************");
        System.out.println("\n");
    }
}
</code>```

答:
Yes, that will work for different methods in the same thread.

It is important to note, however, that unless you synchronize access to the scanner, you cannot use it in different threads

If you need it in different threads then make one for each thread

Title: Use Scanner for many different methods

Body:
I'm new to Java so I'm practicing with some simple code. I want to create some methods and use Scanner for all of them, but I don't want to declare Scanner every time I create other new methods.

So here is my code. Is this correct? Are there better ways to do this?

import java.util.*;

public class TripPlanner {

    public static final Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        Greeting();
    }

    public static void Greeting() {
        System.out.println("Welcome to Vacation Planner");
        System.out.print("What is your name? ");
        String  name = input.nextLine();
        System.out.print("Nice to meet you " + name +", where are you travelling to? ");
        String place = input.nextLine();
        System.out.println("Great! " + place + " sounds like a great trip" );
        System.out.println("************");
        System.out.println("\n");
    }
}


问:
AngularJS Router and .NET backend - getting redirect on templateUrl
I'm trying to write Angular application with $routeProvider. I have .NET on backend that is serving htmls for my app (prepared with permissions and roles). On some action backend calls for RedirectToAction that means 302 HTTP to another url and that means my templateUrl inside router gets another html that it should with that route. I must catch this 302 HTTP somehow, and change route to another (or just use another controller).

Propably the best option is to rewrite backend and use API requests that would check if I need this redirection, but what to do when I can't change it?

I tried to use interceptor in $httpProvider but that response has HTTP 200 and just data of redirected site.

答:
I think it should not be the best way, but think about returning an http 200 and an object with a fild that tells the angular to redirect.

Some like:

```<code>{ location: "/my-new-location" }
</code>```

And then, do the redirection in the application instead of doing in the backend!

Body:
I think it should not be the best way, but think about returning an http 200 and an object with a fild that tells the angular to redirect.

Some like:

{ location: "/my-new-location" }

And then, do the redirection in the application instead of doing in the backend!


问:
Where can i download .NET MVC 2.0 runtime?
I am looking for MVC 2.0 runtime for .NET.
Anybody have the link?

Thanks

答:
Are you looking for the source?  You can download it here: http://aspnet.codeplex.com/releases/view/41742

HTH.

ContentLicense: CC BY-SA 2.5


问:
asp grid takes two click to sort the data
I am trying to apply sorting on my grid but its takes two click to sort the data when the page loads. So when page loads.
First click on any column) -> No sorting but i see page refreshing

Second Click on any column will sort the data.And then it will work for any number of click once page is reloaded again.

Aspx:

```<code>  <asp:GridView id="SubGrid" runat="server" AutoGenerateColumns="False"
            CellPadding="15" AllowPaging="True" PageSize="20" AllowSorting="True"
            EmptyDataText="There are now submission to display."
            ShowHeaderWhenEmpty="True" DataKeyNames="SubmissionID,Abstract,info,upload,finalized,Submitter"
            OnRowCreated="SubGrid_RowCreated" OnRowDataBound="SubGrid_RowDataBound" DataSourceID="SqlDataSource1">

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringTest %>" SelectCommand="sb_Getvelue" SelectCommandType="StoredProcedure">
        <SelectParameters>
</code>```

Code Behind:

In code behind i  have two method

```<code>  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

Protected Sub SubGrid_RowCreated(sender As Object, e As GridViewRowEventArgs)
----Some Custom Code to add a extra line on top of the grid.
End Sub

 Protected Sub SubGrid_RowDataBound(sender As Object, e As
GridViewRowEventArgs)
----- Some code to add tool tip ----
End Sub
</code>```

答:
I found the solutions of this issue.Here are my thoughts and logic behind it. Let me know if i am wrong.

Data are bound with SqlDataSource and my SelectCommandType is stored procedure. My stored procedure return the result which is already sorted  by ID(which is my first column). Now what i found is sorting works fine for all the columns at a first try expect "ID" column. Also when i click on column to sort the data  myGrid.SortExpression alwasy return blank value. So i thought grid is already sorted in ASC order by ID through Stored Procedure,when i click on ID column for the first time it again sort the grid in ASC order because its not initialized and sort order is blank.

SO i added this code in the page_load

```<code>If IsPostBack = False Then

            If String.IsNullOrEmpty(myGrid.SortExpression) Then
                myGrid.Sort("SubmissionID", SortDirection.Ascending)
            End If
        End If
</code>```

this will initialize the grid in ASC order when the page loads and now when i click on the ID column for the first time it sort the grid in DESC order. so initializing grid sort order on page load worked for me.

Body:
I am trying to apply sorting on my grid but its takes two click to sort the data when the page loads. So when page loads.
First click on any column) -> No sorting but i see page refreshing

Second Click on any column will sort the data.And then it will work for any number of click once page is reloaded again.

Aspx:

  <asp:GridView id="SubGrid" runat="server" AutoGenerateColumns="False"
            CellPadding="15" AllowPaging="True" PageSize="20" AllowSorting="True"
            EmptyDataText="There are now submission to display."
            ShowHeaderWhenEmpty="True" DataKeyNames="SubmissionID,Abstract,info,upload,finalized,Submitter"
            OnRowCreated="SubGrid_RowCreated" OnRowDataBound="SubGrid_RowDataBound" DataSourceID="SqlDataSource1">

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringTest %>" SelectCommand="sb_Getvelue" SelectCommandType="StoredProcedure">
        <SelectParameters>

Code Behind:

In code behind i  have two method

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

Protected Sub SubGrid_RowCreated(sender As Object, e As GridViewRowEventArgs)
----Some Custom Code to add a extra line on top of the grid.
End Sub

 Protected Sub SubGrid_RowDataBound(sender As Object, e As
GridViewRowEventArgs)
----- Some code to add tool tip ----
End Sub

Body:
I found the solutions of this issue.Here are my thoughts and logic behind it. Let me know if i am wrong.

Data are bound with SqlDataSource and my SelectCommandType is stored procedure. My stored procedure return the result which is already sorted  by ID(which is my first column). Now what i found is sorting works fine for all the columns at a first try expect "ID" column. Also when i click on column to sort the data  myGrid.SortExpression alwasy return blank value. So i thought grid is already sorted in ASC order by ID through Stored Procedure,when i click on ID column for the first time it again sort the grid in ASC order because its not initialized and sort order is blank.

SO i added this code in the page_load

If IsPostBack = False Then

            If String.IsNullOrEmpty(myGrid.SortExpression) Then
                myGrid.Sort("SubmissionID", SortDirection.Ascending)
            End If
        End If

this will initialize the grid in ASC order when the page loads and now when i click on the ID column for the first time it sort the grid in DESC order. so initializing grid sort order on page load worked for me.


问:
Get value of SelectedIndex in a dynamically created RadioButtonList added to a dynamically created table
I have an array of RadioButtonLists.

```<code>RadioButtonList[] r = new RadioButtonList[20];
</code>```

On clicking a view button, my program creates a dynamic table and adds an image and a RadioButtonList to each cell:

```<code>tcell.Controls.Add(r[i])
</code>```

On clicking a submit button, I’m trying to access the value of SelectedIndex on all RadioButtonLists; however, it’s showing up as null.

```<code>var value = r[i].SelectedValue;
</code>```

I found some answers on how to get the value of RadioButtons created dynamically using .FindControl, but since my table is also dynamic, when I give Table1.rows, it results in null.

答:
Dynamically created controls lose their state, when they are posted back, so you will have to re-create it yourself - outside the

if(!IsPostBack)

block in Page_Load (or somewhere similar).

Body:
I have an array of RadioButtonLists.

RadioButtonList[] r = new RadioButtonList[20];

On clicking a view button, my program creates a dynamic table and adds an image and a RadioButtonList to each cell:

tcell.Controls.Add(r[i])

On clicking a submit button, I’m trying to access the value of SelectedIndex on all RadioButtonLists; however, it’s showing up as null.

var value = r[i].SelectedValue;

I found some answers on how to get the value of RadioButtons created dynamically using .FindControl, but since my table is also dynamic, when I give Table1.rows, it results in null.


问:
Splitting Column Header Into Row Elements In R
After performing data analysis on a larger data set using R, I get output as shown in following sample data:

```<code>   A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1
</code>```

Currently, I am trying to split the column header into such that they appear in two different column as element, and I get the sum of the column they represented. It will look something like this:

```<code>   P1  P2  Sum
1   A   B   4
2   C   D   2
3   E   F   3
4   G   H   5
</code>```

For sum of each column, I can directly make use of colSums(), however I am getting tangled on how splitting the column header and making them appear as cell element described above.

Please let me know any suggestions on how I can approach this, thanks.

答:
Try read.table(text = ...) like this.  Omit as.is = TRUE if you prefer factor columns.

In the Note below we have assumed a data frame but if the input were a matrix then the same code should work.

No packages are used.

```<code>DF2 <- read.table(text = colnames(DF), sep = "_", as.is = TRUE, col.names = c("P1", "P2"))
data.frame(DF2, Sum = colSums(DF), row.names = NULL)
</code>```

giving:

```<code>  P1 P2 Sum
1  A  B   4
2  C  D   2
3  E  F   3
4  G  H   5
</code>```

Note: The input data frame used above in reproducible form is:

```<code>Lines <- "A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1"

DF <- read.table(text = Lines, header = TRUE)
</code>```

Body:
After performing data analysis on a larger data set using R, I get output as shown in following sample data:

   A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1

Currently, I am trying to split the column header into such that they appear in two different column as element, and I get the sum of the column they represented. It will look something like this:

   P1  P2  Sum
1   A   B   4
2   C   D   2
3   E   F   3
4   G   H   5

For sum of each column, I can directly make use of colSums(), however I am getting tangled on how splitting the column header and making them appear as cell element described above.

Please let me know any suggestions on how I can approach this, thanks.

Body:
Try read.table(text = ...) like this.  Omit as.is = TRUE if you prefer factor columns.

In the Note below we have assumed a data frame but if the input were a matrix then the same code should work.

No packages are used.

DF2 <- read.table(text = colnames(DF), sep = "_", as.is = TRUE, col.names = c("P1", "P2"))
data.frame(DF2, Sum = colSums(DF), row.names = NULL)

giving:

  P1 P2 Sum
1  A  B   4
2  C  D   2
3  E  F   3
4  G  H   5

Note: The input data frame used above in reproducible form is:

Lines <- "A_B C_D E_F G_H
1   1   1   0   0
2   1   0   1   1
3   1   1   0   1
4   0   0   1   1
5   1   0   1   1
6   0   0   0   1"

DF <- read.table(text = Lines, header = TRUE)


答: Having a unique .git directory at the root of the project is a convenience. The .git directory can be anywhere in your project (or even outside) and it can be modified by setting GIT_DIR environment variable. But if you consider having it inside a subdirectory of your project, it is quite simple to delete it unwillingly which is much harder to do if it's at the root of the project.</p>

Title: Is the .git/ folder only supposed to be located in the project's root location?

Body:
Does git allow (i.e., is there a valid use case) a .git/ folder inside subfolders?

Or is the .git/ folder supposed to be only in one place and that is in the project's root location?


问:
MATLAB: Efficient way to find the feasible region of first-order polynomials x, y with unknown coefficents in [-1, 1]
As in the title, in MATLAB, I need the feasible region (bounds of all feasible solutions) of

```<code>x_0 + x_1 e_1 + ... + x_n e_n
</code>```

and

```<code>y_0 + y_1 e_1 + ... + y_n e_n
</code>```

where all unknown e_i are in the interval [-1, 1]. I would prefer the solution to not depend on non-standard 3rd party functions.

Below is my quick-and-dirty attempt, but the complexity grows O(2^n), where n is the number of e_i. Any thoughts?

```<code>x0 = 3;
x = [1; -3; 0];
y0 = -1;
y = [3; -2; 4];

% Get all permutations of noise symbol extremities
terms = size(x, 1);
xx = zeros(2^terms, 1);
yy = zeros(2^terms, 1);
for j = 1:2^terms
    e = double(bitget(j - 1, 1:terms))';
    e(e == 0) = -1;
    xx(j) = x0 + sum(x .* e);
    yy(j) = y0 + sum(y .* e);
end

k = convhull(xx, yy);
plot(xx(k), yy(k));
</code>```

答:
```<code>% First generate all possible permutations for [-1, 1] for n terms. This is similar to what you have done but uses a matlab function
all_e = de2bi(0:(2^terms-1), terms).';
all_e(all_e == 0) = -1;
% Multiply corresponding values of x and y with those of e
xx = x0 + arrayfun(@(z) sum(x .* all_e(:, z)), 1:(2^terms));
yy = x0 + arrayfun(@(z) sum(y .* all_e(:, z)), 1:(2^terms));
</code>```

You can read more about the function de2bi here

A method to find the absolute minimum and maximum bounds is as follows:

```<code>max_e = double(x >= 0);
min_e = double(~max_e);
max_e(max_e == 0) = -1;
min_e(min_e == 0) = -1;
absMax = x0 + sum(x .* max_e);
absMin = x0 + sum(x .* min_e);
</code>```

Similarly you could do for y

Body:
As in the title, in MATLAB, I need the feasible region (bounds of all feasible solutions) of

x_0 + x_1 e_1 + ... + x_n e_n

and

y_0 + y_1 e_1 + ... + y_n e_n

where all unknown e_i are in the interval [-1, 1]. I would prefer the solution to not depend on non-standard 3rd party functions.

Below is my quick-and-dirty attempt, but the complexity grows O(2^n), where n is the number of e_i. Any thoughts?

x0 = 3;
x = [1; -3; 0];
y0 = -1;
y = [3; -2; 4];

% Get all permutations of noise symbol extremities
terms = size(x, 1);
xx = zeros(2^terms, 1);
yy = zeros(2^terms, 1);
for j = 1:2^terms
    e = double(bitget(j - 1, 1:terms))';
    e(e == 0) = -1;
    xx(j) = x0 + sum(x .* e);
    yy(j) = y0 + sum(y .* e);
end

k = convhull(xx, yy);
plot(xx(k), yy(k));

Body:
% First generate all possible permutations for [-1, 1] for n terms. This is similar to what you have done but uses a matlab function
all_e = de2bi(0:(2^terms-1), terms).';
all_e(all_e == 0) = -1;
% Multiply corresponding values of x and y with those of e
xx = x0 + arrayfun(@(z) sum(x .* all_e(:, z)), 1:(2^terms));
yy = x0 + arrayfun(@(z) sum(y .* all_e(:, z)), 1:(2^terms));

You can read more about the function de2bi here

A method to find the absolute minimum and maximum bounds is as follows:

max_e = double(x >= 0);
min_e = double(~max_e);
max_e(max_e == 0) = -1;
min_e(min_e == 0) = -1;
absMax = x0 + sum(x .* max_e);
absMin = x0 + sum(x .* min_e);

Similarly you could do for y


问:
Image upload success but it doesn't show the right path on Laravel
I am uploading an image on my form then resizing it using a library. I can upload the pic with no problem here is my code:

```<code>public function store()
{
    $this->validate(request(),[

        'title'=>'required',
        'body'=>'required|min:5 ',
        'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    $image = request()->file('photo');

    $fileName = $image->getClientOriginalName();

    $publicPath = 'images/';
    $image_resize = Image::make($image->getRealPath());
    $image_resize->resize(1200, 800);

    $image_resize->save($publicPath.$fileName);

        auth()->user()->addPost(new Posts( [
        'title'=>request('title'),
        'body'=>request('body'),
        'photo'=> $fileName

    ]));

    return redirect('/');
}
</code>```

my issue is that the image doesn't show up on my front view. I have tried to remove the resizing its still the same

答:
Well the issue here is that when u are saving the post on database photo option u are saving only the filename, you should concatinate your public path with the image path like so: 'photo'=>  $publicPath.$fileName

```<code>$image = request()->file('photo');

$fileName = $image->getClientOriginalName();

$publicPath = 'images/';
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1200, 800);

$image_resize->save($publicPath.$fileName);

    auth()->user()->addPost(new Posts( [
    'title'=>request('title'),
    'body'=>request('body'),
    'photo'=>  $publicPath.$fileName

]));
</code>```

So try now it should work.

Body:
I am uploading an image on my form then resizing it using a library. I can upload the pic with no problem here is my code:

public function store()
{
    $this->validate(request(),[

        'title'=>'required',
        'body'=>'required|min:5 ',
        'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    $image = request()->file('photo');

    $fileName = $image->getClientOriginalName();

    $publicPath = 'images/';
    $image_resize = Image::make($image->getRealPath());
    $image_resize->resize(1200, 800);

    $image_resize->save($publicPath.$fileName);

        auth()->user()->addPost(new Posts( [
        'title'=>request('title'),
        'body'=>request('body'),
        'photo'=> $fileName

    ]));

    return redirect('/');
}

my issue is that the image doesn't show up on my front view. I have tried to remove the resizing its still the same

Body:
Well the issue here is that when u are saving the post on database photo option u are saving only the filename, you should concatinate your public path with the image path like so: 'photo'=>  $publicPath.$fileName

$image = request()->file('photo');

$fileName = $image->getClientOriginalName();

$publicPath = 'images/';
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1200, 800);

$image_resize->save($publicPath.$fileName);

    auth()->user()->addPost(new Posts( [
    'title'=>request('title'),
    'body'=>request('body'),
    'photo'=>  $publicPath.$fileName

]));

So try now it should work.


问:
Jquery Ajax post Spring MVC controller?
I am experimenting with Spring Boot and wanted to do an Ajax POST to a Spring Controller. I was testing it from POSTMAN but then I keep getting this error.

```<code>{
    "timestamp": 1499255141424,
    "status": 404,
    "error": "Not Found",
    "message": "/WEB-INF/view/jsondata.jsp",
    "path": "/jsondata"
}
</code>```

I want it to look for the jsondata method in my Index Controller. But it is looking for jsondata.jsp in my views.

```<code>@RequestMapping(value = "/jsondata", method = RequestMethod.POST)
    public void getfeeddata(@RequestBody String info)
    {
        System.out.println(info);
    }
</code>```

View -

```<code><!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<body>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#submit').click(function ()
            {
                var info =[];
                info.push("JsonPostdata");
                $.ajax({
                    type: "post",
                    url: "/jsondata",
                    data: JSON.stringify(info),
                    success: function(msg){
                        console.log("success");
                    }
                });
            });

        });
    </script>
</head>
    <div>
        <div>
            <h1>Spring Boot JSP Example</h1>
            <form >
              <input type="submit" id ="submit" value="Not clicked">

            </form>
            <h2>Hello ${message}</h2>

            Click on this <strong><a href="next">link</a></strong> to visit another page.
        </div>
    </div>

</body>
</html>
</code>```

答:
You need to define your view resolver to differentiate between web and rest calls:</p>

```<code>@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/view/");
    resolver.setSuffix(".jsp");
    return resolver;
}
</code>```

Title: Jquery Ajax post Spring MVC controller?

Body:
I am experimenting with Spring Boot and wanted to do an Ajax POST to a Spring Controller. I was testing it from POSTMAN but then I keep getting this error.

{
    "timestamp": 1499255141424,
    "status": 404,
    "error": "Not Found",
    "message": "/WEB-INF/view/jsondata.jsp",
    "path": "/jsondata"
}

I want it to look for the jsondata method in my Index Controller. But it is looking for jsondata.jsp in my views.

@RequestMapping(value = "/jsondata", method = RequestMethod.POST)
    public void getfeeddata(@RequestBody String info)
    {
        System.out.println(info);
    }

View -

<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

Spring Boot JSP Example

            <form >
              <input type="submit" id ="submit" value="Not clicked">

            </form>

Hello ${message}

            Click on this link to visit another page.

Body:
You need to define your view resolver to differentiate between web and rest calls:

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/view/");
    resolver.setSuffix(".jsp");
    return resolver;
}


问:
GoogleLoginService LoginFail
Has anyone experienced a GoogleLoginService fail when authenticating to use a google service (calendar in my case) through the AccountManager?  I obtained an authentication token using...

```<code>AccountManager mgr = AccountManager.get(this);
Account[] accts = mgr.getAccountsByType("com.google");
Account acct = accts[0];
AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(acct, "calendar",   null, this, null, null);

Bundle authTokenBundle = null;
try {authTokenBundle = accountManagerFuture.getResult();}
    catch (OperationCanceledException e) {e.printStackTrace();}
    catch (AuthenticatorException e) {e.printStackTrace();}
    catch (IOException e) {e.printStackTrace();}

authtoken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
</code>```

After obtaining my authentication token, I created a Calendar Service and tried to authenticate it...

```<code>CalendarService myService = new CalendarService("UserCalendar");
myService.setAuthSubToken(authtoken);
</code>```

When I use this on either a phone or emulator, it initially seems to work as expected... it brings up screen where google asks the user to 'allow' or 'deny' access by my app.  However, when I click allow, it says that the password of the google account is incorrect.

Now, I've tried it with multiple google accounts (both of which passwords work when I use them manually to login) and it still gives the same result.  Any ideas as per why I might be getting this?  The debug isn't extraordinarily useful... all that I get is two lines which just tell me it failed...

```<code>12-19 20:40:05.756: DEBUG/GoogleLoginService(245): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLoginService }
12-19 20:40:08.426: DEBUG/GoogleLoginService(245): LOGIN_FAIL
</code>```

Has anyone else had this issue before?  I'm assuming there is something simple I'm missing but just can't think of why it wouldn't authenticate... thanks!

答:
The google calendar service is called "cl" not "calendar". Use the following instead:</p>

```<code>mgr.getAuthToken(acct, "cl",   null, this, null, null);
</code>```

Title: GoogleLoginService LoginFail

Body:
Has anyone experienced a GoogleLoginService fail when authenticating to use a google service (calendar in my case) through the AccountManager?  I obtained an authentication token using...

AccountManager mgr = AccountManager.get(this);
Account[] accts = mgr.getAccountsByType("com.google");
Account acct = accts[0];
AccountManagerFuture<Bundle> accountManagerFuture = mgr.getAuthToken(acct, "calendar",   null, this, null, null);

Bundle authTokenBundle = null;
try {authTokenBundle = accountManagerFuture.getResult();}
    catch (OperationCanceledException e) {e.printStackTrace();}
    catch (AuthenticatorException e) {e.printStackTrace();}
    catch (IOException e) {e.printStackTrace();}

authtoken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();

After obtaining my authentication token, I created a Calendar Service and tried to authenticate it...

CalendarService myService = new CalendarService("UserCalendar");
myService.setAuthSubToken(authtoken);

When I use this on either a phone or emulator, it initially seems to work as expected... it brings up screen where google asks the user to 'allow' or 'deny' access by my app.  However, when I click allow, it says that the password of the google account is incorrect.

Now, I've tried it with multiple google accounts (both of which passwords work when I use them manually to login) and it still gives the same result.  Any ideas as per why I might be getting this?  The debug isn't extraordinarily useful... all that I get is two lines which just tell me it failed...

12-19 20:40:05.756: DEBUG/GoogleLoginService(245): onBind: Intent { act=android.accounts.AccountAuthenticator cmp=com.google.android.gsf/.loginservice.GoogleLoginService }
12-19 20:40:08.426: DEBUG/GoogleLoginService(245): LOGIN_FAIL

Has anyone else had this issue before?  I'm assuming there is something simple I'm missing but just can't think of why it wouldn't authenticate... thanks!

Body:
The google calendar service is called "cl" not "calendar". Use the following instead:

mgr.getAuthToken(acct, "cl",   null, this, null, null);


问:
AngularJS - Validate a part of a form
I'm using Angular 1.5.9

I have a big form, which I scattered through different Bootstrap Accordion.

When there is an error in the form, I want to be able to change the class of my accordions to show in which accordions the error is located.

To check for errors in a whole form, I can check

```<code>myFormName.$error
</code>```

And to check errors for an element, I can simply do

```<code>myFormName.myInputName.$error
</code>```

But I don't know if there is a way to do this for multiple element at once, without having to check each element individually.

My first thought was to change the name of my inputs like so:

```<code><input name="accordion1.fieldName">
</code>```

But this didn't give me the expected result: I don't have myFormName.accordion1.$error, actually, I don't even have myFormName.accordion1.fieldName, since my data is actually stored in myFormName['accordion1.fieldName'] which is pretty much useless.

Has anyone found an answer to this problem? I think I'll have to check each field, which is kinda ugly, and a mess to maintain whenever we add / remove fields...

Maybe there is a directive out there that could do that for me, but as a non-native English speaker, I can't find which key words to use for my search in this situation.

答:
You could name the fields with a prefix such as 'accordion1_' then add a controller function that will filter your fields.

```<code>ctrl.fieldGroup = function(form, fieldPrefix) {

    var fieldGroup = {};

    angular.forEach(form, function(value, key) {

        if (key.indexOf(prefix) === 0) {
            fieldGroup[key] = value;
        }

    });

    return fieldGroup;

}
</code>```

Then ctrl.fieldGroup('accordion1') will return an object with the appriopriate fields on it. You could extend the function further to add an aggregate $error property to the resulting fieldGroup object.

Title: AngularJS - Validate a part of a form

Body:
I'm using Angular 1.5.9

I have a big form, which I scattered through different Bootstrap Accordion.

When there is an error in the form, I want to be able to change the class of my accordions to show in which accordions the error is located.

To check for errors in a whole form, I can check

myFormName.$error

And to check errors for an element, I can simply do

myFormName.myInputName.$error

But I don't know if there is a way to do this for multiple element at once, without having to check each element individually.

My first thought was to change the name of my inputs like so:

<input name="accordion1.fieldName">

But this didn't give me the expected result: I don't have myFormName.accordion1.$error, actually, I don't even have myFormName.accordion1.fieldName, since my data is actually stored in myFormName['accordion1.fieldName'] which is pretty much useless.

Has anyone found an answer to this problem? I think I'll have to check each field, which is kinda ugly, and a mess to maintain whenever we add / remove fields...

Maybe there is a directive out there that could do that for me, but as a non-native English speaker, I can't find which key words to use for my search in this situation.

Body:
You could name the fields with a prefix such as 'accordion1_' then add a controller function that will filter your fields.

ctrl.fieldGroup = function(form, fieldPrefix) {

    var fieldGroup = {};

    angular.forEach(form, function(value, key) {

        if (key.indexOf(prefix) === 0) {
            fieldGroup[key] = value;
        }

    });

    return fieldGroup;

}

Then ctrl.fieldGroup('accordion1') will return an object with the appriopriate fields on it. You could extend the function further to add an aggregate $error property to the resulting fieldGroup object.


问:
Crash when using ignoringNonObjectArgs in OCMock in modern style
I am trying to mock a method mentioned bellow using the OCMock framework which takes an integer variable as the second argument. I also tried with old style OCMock stub call too with the same result. Using modern syntax the code I wrote is as bellow.

```<code>@interface Session : NSObject
- (Request *)RequestForURL:(NSURL *)url
                     flags:(unsigned int)flags
                     error:(NSError **)error;
@end
</code>```

This session class is mocked and I want to return the mocked Request from this mocked method.

```<code>id session = OCMClassMock(Session.class);
id Request = OCMClassMock(Request.class);

OCMStub([[session ignoringNonObjectArgs] RequestForURL:(NSURL *)OCMArg.anyObjectRef flags:0 error:OCMArg.anyObjectRef]).andReturn(Request);
</code>```

This gets compiled fine. But while running the test it crashes while calling
   RequestForURL
I am aware that I am using the modern OCMock syntax. I think the error occurs in flags that somehow is not ignored.

答:
Well, turned out one of my stupid mistakes. anyObjectRef is the reference and any is an id and here we need an id and I was using ref and casting it to NSURL * ... [facepalm on me]

correct way:

```<code>OCMStub([[session ignoringNonObjectArgs] RequestForURL:OCMArg.any flags:0 error:OCMArg.any]).andReturn(Request);
</code>```

Body:
I am trying to mock a method mentioned bellow using the OCMock framework which takes an integer variable as the second argument. I also tried with old style OCMock stub call too with the same result. Using modern syntax the code I wrote is as bellow.

@interface Session : NSObject
- (Request *)RequestForURL:(NSURL *)url
                     flags:(unsigned int)flags
                     error:(NSError **)error;
@end

This session class is mocked and I want to return the mocked Request from this mocked method.

id session = OCMClassMock(Session.class);
id Request = OCMClassMock(Request.class);

OCMStub([[session ignoringNonObjectArgs] RequestForURL:(NSURL *)OCMArg.anyObjectRef flags:0 error:OCMArg.anyObjectRef]).andReturn(Request);

This gets compiled fine. But while running the test it crashes while calling
   RequestForURL
I am aware that I am using the modern OCMock syntax. I think the error occurs in flags that somehow is not ignored.

Body:
Well, turned out one of my stupid mistakes. anyObjectRef is the reference and any is an id and here we need an id and I was using ref and casting it to NSURL * ... [facepalm on me]

correct way:

OCMStub([[session ignoringNonObjectArgs] RequestForURL:OCMArg.any flags:0 error:OCMArg.any]).andReturn(Request);


问:
How do I disable a radio input form control with the rest of the form?
When I call this.employeeForm.disable() inside of the ngOnInit function of my component, all of my form controls become disabled except for the reminder_email, radio button control.  If I place the disable call inside of a setTimeout of even 1 millisecond it works. (entire form is disabled)  I can even get it to work by placing a click handler somewhere on the page to toggle the control between enabled and disabled.  There are numerous hacks that I can apply to make it work but I would prefer to do this the right way.  If you need any more information, ask me in the comments.

component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CompanyService } from '../../../shared/services/company.service';
import { Employee } from '../../../shared/classes/employee';
import 'rxjs/add/operator/takeUntil';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-employee-detail',
  templateUrl: './employee-detail.component.html',
  styleUrls: ['./employee-detail.component.css']
})
export class EmployeeDetailComponent implements OnInit {

  packages: any = [];
  employee: Employee;
  validationMessages = this.companyService.validationMessages;
  formErrors = this.companyService.formErrors;
  roles = this.companyService.roles;
  employeeForm: FormGroup;
  submitted = false;
  active = false;

  constructor(private route: ActivatedRoute, public companyService: CompanyService, private fb: FormBuilder) { }

  ngOnInit() {

    const employeeId = this.route.snapshot.params.id;

    this.companyService.getEmployee(employeeId)
      .subscribe(data => {
        this.employee = data;
        this.buildForm();
        this.active = true;
        this.employeeForm.disable();
      });

  }

  buildForm(): void {
    this.employeeForm = this.fb.group({
      'firstname': [this.employee.firstname, [
        Validators.required,
        Validators.minLength(2),
        Validators.maxLength(24)
      ]
      ],
      'lastname': [this.employee.lastname, [
        Validators.required,
        Validators.minLength(2),
        Validators.maxLength(24)
      ]
      ],
      'email': [this.employee.email, [
        Validators.required,
        Validators.pattern(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
      ]
      ],
      'date_hired': [this.employee.date_hired, [
        Validators.required,
      ]
      ],
      'title': [this.employee.title, [
        Validators.required,
        Validators.minLength,
        Validators.maxLength
      ]
      ],
      'role': [this.employee.role, [
        Validators.required,
      ]
      ],
      'team': [this.employee.team, [

      ]
      ],
      'training_package': [this.employee.training_package, [
        Validators.required,
      ]
      ],
      'reminder_email': [this.employee.reminder_email, [
        Validators.required,
      ]
      ],
    });
};

  saveEmployee() {
    // save employee
  }
}
</code>```

html

```<code><form [formGroup]="employeeForm" *ngIf="active" (ngSubmit)="saveEmployee()">

            <div class="form-group">
              <label for="firstname">First Name:</label>
              <input type="text" class="form-control" formControlName="firstname" required>
              <div *ngIf="formErrors.firstname" class="alert alert-danger">{{ formErrors.firstname }}</div>
            </div>

            <div class="form-group">
              <label for="lastname">Last Name:</label>
              <input type="text" class="form-control" formControlName="lastname" required>
              <div *ngIf="formErrors.lastname" class="alert alert-danger">{{ formErrors.lastname }}</div>
            </div>

            <div class="form-group">
              <label for="email">Email:</label>
              <input type="email" class="form-control" formControlName="email" required>
              <div *ngIf="formErrors.email" class="alert alert-danger">{{ formErrors.email }}</div>
            </div>

            <div class="form-group">
              <label for="dateHired">Hire Date:</label>
              <input type="date" class="form-control" formControlName="date_hired" required>
              <div *ngIf="formErrors.date_hired" class="alert alert-danger">{{ formErrors.date_hired }}</div>
            </div>

            <div class="form-group">
              <label for="title">Title:</label>
              <input type="text" class="form-control" formControlName="title" required>
              <div *ngIf="formErrors.title" class="alert alert-danger">{{ formErrors.title }}</div>
            </div>

            <div class="form-group">
              <label for="role">Role:</label>
              <select class="form-control pointer" formControlName="role" required>
            <option *ngFor="let role of roles" [selected]="employee.role.name" [ngValue]="role.value">{{ role.title }}</option>
          </select>
              <div *ngIf="formErrors.title" class="alert alert-danger">{{ formErrors.title }}</div>
            </div>

            <div class="form-group">
              <label for="team">Team:</label>
              <input type="text" class="form-control" formControlName="team" [value]="employee.team.name">
              <div *ngIf="formErrors.team" class="alert alert-danger">{{ formErrors.team }}</div>
            </div>

            <div class="form-group">
              <label for="package">Training Package:</label>
              <select class="form-control pointer" formControlName="training_package" required>
            <option *ngFor="let package of packages" [selected]="employee.training_package.name" [ngValue]="package.id">{{ package.name }}</option>
          </select>
              <div *ngIf="formErrors.package" class="alert alert-danger">{{ formErrors.title }}</div>
            </div>

            <div class="form-group">
              <label>Send Reminder Emails?</label>
              <br>
              <label for="reminder_email">Yes</label>
              <input [checked]="employee.reminder_email === true" formControlName="reminder_email" type="radio" [value]=true [(ngModel)]="employee.reminder_email">
              <br>
              <label for="reminder_email">No</label>
              <input [checked]="employee.reminder_email === false" formControlName="reminder_email" type="radio" [value]=false [(ngModel)]="employee.reminder_email">
              <br>
            </div>

            <button type="submit" class="btn btn-primary">Save Changes</button>

          </form>
</code>```

答:
If I place the disable call inside of a setTimeout of even 1 millisecond it works. (entire form is disabled)

If you place the code inside a ngAfterViewInit it should call after the form has been established.

```<code>ngAfterViewInit(){
    const employeeId = this.route.snapshot.params.id;

    this.companyService.getEmployee(employeeId)
      .subscribe(data => {
        this.employee = data;
        this.buildForm();
        this.active = true;
        this.employeeForm.disable();
      });
}
</code>```

Body:
When I call this.employeeForm.disable() inside of the ngOnInit function of my component, all of my form controls become disabled except for the reminder_email, radio button control.  If I place the disable call inside of a setTimeout of even 1 millisecond it works. (entire form is disabled)  I can even get it to work by placing a click handler somewhere on the page to toggle the control between enabled and disabled.  There are numerous hacks that I can apply to make it work but I would prefer to do this the right way.  If you need any more information, ask me in the comments.

component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CompanyService } from '../../../shared/services/company.service';
import { Employee } from '../../../shared/classes/employee';
import 'rxjs/add/operator/takeUntil';
import { Subject } from 'rxjs/Subject';

@Component({
  selector: 'app-employee-detail',
  templateUrl: './employee-detail.component.html',
  styleUrls: ['./employee-detail.component.css']
})
export class EmployeeDetailComponent implements OnInit {

  packages: any = [];
  employee: Employee;
  validationMessages = this.companyService.validationMessages;
  formErrors = this.companyService.formErrors;
  roles = this.companyService.roles;
  employeeForm: FormGroup;
  submitted = false;
  active = false;

  constructor(private route: ActivatedRoute, public companyService: CompanyService, private fb: FormBuilder) { }

  ngOnInit() {

    const employeeId = this.route.snapshot.params.id;

    this.companyService.getEmployee(employeeId)
      .subscribe(data => {
        this.employee = data;
        this.buildForm();
        this.active = true;
        this.employeeForm.disable();
      });

  }

  buildForm(): void {
    this.employeeForm = this.fb.group({
      'firstname': [this.employee.firstname, [
        Validators.required,
        Validators.minLength(2),
        Validators.maxLength(24)
      ]
      ],
      'lastname': [this.employee.lastname, [
        Validators.required,
        Validators.minLength(2),
        Validators.maxLength(24)
      ]
      ],
      'email': [this.employee.email, [
        Validators.required,
        Validators.pattern(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)
      ]
      ],
      'date_hired': [this.employee.date_hired, [
        Validators.required,
      ]
      ],
      'title': [this.employee.title, [
        Validators.required,
        Validators.minLength,
        Validators.maxLength
      ]
      ],
      'role': [this.employee.role, [
        Validators.required,
      ]
      ],
      'team': [this.employee.team, [

      ]
      ],
      'training_package': [this.employee.training_package, [
        Validators.required,
      ]
      ],
      'reminder_email': [this.employee.reminder_email, [
        Validators.required,
      ]
      ],
    });
};

  saveEmployee() {
    // save employee
  }
}

html

<form [formGroup]="employeeForm" *ngIf="active" (ngSubmit)="saveEmployee()">

              First Name:
              <input type="text" class="form-control" formControlName="firstname" required>

{{ formErrors.firstname }}

              Last Name:
              <input type="text" class="form-control" formControlName="lastname" required>

{{ formErrors.lastname }}

              Email:
              <input type="email" class="form-control" formControlName="email" required>

{{ formErrors.email }}

              Hire Date:
              <input type="date" class="form-control" formControlName="date_hired" required>

{{ formErrors.date_hired }}

              Title:
              <input type="text" class="form-control" formControlName="title" required>

{{ formErrors.title }}

              Role:
              <select class="form-control pointer" formControlName="role" required>
            <option *ngFor="let role of roles" [selected]="employee.role.name" [ngValue]="role.value">{{ role.title }}</option>
          </select>

{{ formErrors.title }}

              Team:
              <input type="text" class="form-control" formControlName="team" [value]="employee.team.name">

{{ formErrors.team }}

              Training Package:
              <select class="form-control pointer" formControlName="training_package" required>
            <option *ngFor="let package of packages" [selected]="employee.training_package.name" [ngValue]="package.id">{{ package.name }}</option>
          </select>

{{ formErrors.title }}

              Send Reminder Emails?

              Yes
              <input [checked]="employee.reminder_email === true" formControlName="reminder_email" type="radio" [value]=true [(ngModel)]="employee.reminder_email">

              No
              <input [checked]="employee.reminder_email === false" formControlName="reminder_email" type="radio" [value]=false [(ngModel)]="employee.reminder_email">

            <button type="submit" class="btn btn-primary">Save Changes</button>

          </form>

Body:
If I place the disable call inside of a setTimeout of even 1 millisecond it works. (entire form is disabled)

If you place the code inside a ngAfterViewInit it should call after the form has been established.

ngAfterViewInit(){
    const employeeId = this.route.snapshot.params.id;

    this.companyService.getEmployee(employeeId)
      .subscribe(data => {
        this.employee = data;
        this.buildForm();
        this.active = true;
        this.employeeForm.disable();
      });
}


问:
Chef-vault with Users cookbook (users_manage resource)
I intend to encrypt "users" databag with chef-vault and use the same with chef provided "users" cookbook. "users_manage" resource provided by "users" cookbook accepts one of the attributes as "databag" (with username, group_id and search_group properties).
To my knowledge chef-vault allows you to decrypt one item at a time

```<code>vault = chef_vault_item(:mydatabbag, ‘item1’)
</code>```

ideally I would expect chef-vault to provide similar function to decrypt entire vault (encrypted databag) and I could pass the same to "uses_manage" resource:

```<code>decrypted_data_bag = chef_vault(:mydatabbag) #Something similar

users_manage "#{search_group}" do
  group_id search_group
  action [ :remove, :create ]
  data_bag "#{decrypted_data_bag}"
end
</code>```

Since chef-vault does not provide an ability to decrypt the entire databag, am I left with the only solution to call "users_manage" in a loop and pass each item (as hash)?

```<code>mydatabag.each do |myuser|
  decrypted_user = vault = chef_vault_item(:mydatabbag, "#{myuser}")
  users_manage "#{search_group}" do
    group_id search_group
    action [ :remove, :create ]
    data_bag "#{decrypted_user}"
  end
end
</code>```

Is there a better solution?

答:
The data_bag property is the name of a data bag, not the bag itself. You cannot use users_manage with chef-vault, you'll have to write something similar yourself.

That said, nothing in a user object should need to be private in the first place unless you're trying to set passwords or something (don't do that) so this is probably not needed.

Body:
I intend to encrypt "users" databag with chef-vault and use the same with chef provided "users" cookbook. "users_manage" resource provided by "users" cookbook accepts one of the attributes as "databag" (with username, group_id and search_group properties).
To my knowledge chef-vault allows you to decrypt one item at a time

vault = chef_vault_item(:mydatabbag, ‘item1’)

ideally I would expect chef-vault to provide similar function to decrypt entire vault (encrypted databag) and I could pass the same to "uses_manage" resource:

decrypted_data_bag = chef_vault(:mydatabbag) #Something similar

users_manage "#{search_group}" do
  group_id search_group
  action [ :remove, :create ]
  data_bag "#{decrypted_data_bag}"
end

Since chef-vault does not provide an ability to decrypt the entire databag, am I left with the only solution to call "users_manage" in a loop and pass each item (as hash)?

mydatabag.each do |myuser|
  decrypted_user = vault = chef_vault_item(:mydatabbag, "#{myuser}")
  users_manage "#{search_group}" do
    group_id search_group
    action [ :remove, :create ]
    data_bag "#{decrypted_user}"
  end
end

Is there a better solution?


问:
Get first record change timestamp when grouped by two columns SQL Server
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

```<code>id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')
</code>```

Expected output

```<code>id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')
</code>```

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

```<code>create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version
</code>```

Body:
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')

Expected output

id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version

Body:
Try

create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version values
(123, 1.5, '2015-03-28 08:21:04'),(123, 1.5, '2015-03-28 07:21:04'),(123, 1.5, '2015-03-27 07:21:04')
,(123, 1.0, '2015-03-21 12:58:24'),(123, 1.0, '2015-03-20 12:58:24'),(123, 1.2, '2015-03-22 12:58:24')
,(123, 1.2, '2015-03-21 12:58:24'),(234, 1.5, '2016-10-15 23:08:09'),(345, 1.5, '2016-10-10 15:18:09')
,(345, 1.5, '2016-09-02 21:30:00'),(345, 1.5, '2016-09-01 21:30:00'),(345, 1.5, '2016-08-02 21:30:00');

select top(1) with ties id, version, dt_create
from (
    select *, lag(version) over(partition by id order by dt_create) prev
    from #temp_version
    ) t
where version != prev or prev is null -- first change
--  recent version
order by row_number() over(partition by id order by dt_create desc);
-- or may be .. order by version .. depending on what is "recent"


问:
How to prevent boolean type juggling to int in PHP
Hey I'm learning PHP and I'm finding the type juggling to be a complete nightmare.
I was playing with iterables and noticed that instead TRUE or FALSE I got 1 and 0.

A small example:

```<code><?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }

        public function valid()
    {
        $key = key($this->var);
        $var = ($key !== NULL && $key !== FALSE);
        print_r("valid: ". $var ."\n<br />");
        return $var;
    }

}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a => $b) {
    print "$a: $b\n<br />";
}
</code>```

In bigger arrays or chunks of code this kind of output becomes really confusing is there a way to force PHP to dump TRUE or FALSE instead of 1 and 0?

答:
You can cast using (bool) or (boolean) operators, but you should rarely need to do this as PHP will cast automatically if it sees an operation that requires a boolean.

If you echo or print a boolean it will never output TRUE or FALSE  it will be converted to an int and display 1 or 0. You can however use var_dump((bool)$val) that will output bool(false) or bool(true) which can give you a better idea of how the boolean will be converted.

Body:
Hey I'm learning PHP and I'm finding the type juggling to be a complete nightmare.
I was playing with iterables and noticed that instead TRUE or FALSE I got 1 and 0.

A small example:

<?php
class MyIterator implements Iterator
{
    private $var = array();

    public function __construct($array)
    {
        if (is_array($array)) {
            $this->var = $array;
        }
    }

        public function valid()
    {
        $key = key($this->var);
        $var = ($key !== NULL && $key !== FALSE);
        print_r("valid: ". $var ."\n
");
        return $var;
    }

}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach ($it as $a => $b) {
    print "$a: $b\n
";
}

In bigger arrays or chunks of code this kind of output becomes really confusing is there a way to force PHP to dump TRUE or FALSE instead of 1 and 0?


问:
How to push data from one div to another div(table) using angular js?
I am trying to add the json data to a table on clicking the + icon. There are 2 section namely Pick Stocks from where the stocks and price (which inturn are coming from data.json) has to be added to the table present in Manage Portfolio section.

First Section

Second Section

So I want the stock name i.e. ADFI, ALAN etc and its respective price to be added to respective stock and price columns of table in second section when a respective + icon is clicked.
I have tried adding but I am not entirely sure about how to go forward.
Thank you.
Here is the plunker

```<code>             <table>
                <tr>
                    <th>STOCK</th>
                    <th>PRICE</th>
                    <th>SHARES</th>
                    <th>WEIGHT</th>
                </tr>
                <tr ng-repeat="portfolio in portfolios">
                    <td ng-model="portfolio.stockfromdata"></td>
                    <td ng-model="portfolio.pricefromdata"></td>
                    <td>num</td>
                    <td ng-model="portfolio.weightfromprice"></td>
                </tr>
            </table>
</code>```

Script

```<code> $scope.portfolios = [];

    $scope.addStock = function() {
        $scope.portfolios.push([{
            "key": $scope.portfolio.stockfromdata,
            "value": $scope.portfolio.pricefromdata
            // "weightfromprice": $scope.weightfromprice
        }]);
    };
</code>```

答:
If you follow similarly of having object & showing key values in table then you can write following on ng-click of plus sign

```<code>$scope.addToTable = function(key, value){
  var mystock={key: value};
    if (!(key in $scope.stocksObj)){
    $scope.stocksObj[key] = value;
    }
}

<tr ng-repeat="(key, value) in stocksObj"><td>{{key}}</td><td>{{value}}</td></tr>
</code>```

This's working plunk https://plnkr.co/edit/b3QECT1pvqnWwyQoEBTb?p=preview

But again this will not be useful if you need to have more fields in that stock. So better create object with properties as key, value, shares, weight, etc and push accordingly in array. The updated function will be

```<code>$scope.addToTable = function(key, value, index){
  var mystock={};
  mystock.key = key;
  mystock.value = value;
    console.log(index);
    if(indexes.indexOf(index) == -1){
        indexes.push(index);
        $scope.stocksArray.push(mystock);
    }
}
</code>```

Here's working plunk for that
https://plnkr.co/edit/r2WLGakBU9kGmWLWBN7K?p=preview

Body:
I am trying to add the json data to a table on clicking the + icon. There are 2 section namely Pick Stocks from where the stocks and price (which inturn are coming from data.json) has to be added to the table present in Manage Portfolio section.

First Section

Second Section

So I want the stock name i.e. ADFI, ALAN etc and its respective price to be added to respective stock and price columns of table in second section when a respective + icon is clicked.
I have tried adding but I am not entirely sure about how to go forward.
Thank you.
Here is the plunker

                    STOCK
                    PRICE
                    SHARES
                    WEIGHT

                    num

Script

 $scope.portfolios = [];

    $scope.addStock = function() {
        $scope.portfolios.push([{
            "key": $scope.portfolio.stockfromdata,
            "value": $scope.portfolio.pricefromdata
            // "weightfromprice": $scope.weightfromprice
        }]);
    };

Body:
If you follow similarly of having object & showing key values in table then you can write following on ng-click of plus sign

$scope.addToTable = function(key, value){
  var mystock={key: value};
    if (!(key in $scope.stocksObj)){
    $scope.stocksObj[key] = value;
    }
}

<tr ng-repeat="(key, value) in stocksObj"><td>{{key}}</td><td>{{value}}</td></tr>

This's working plunk https://plnkr.co/edit/b3QECT1pvqnWwyQoEBTb?p=preview

But again this will not be useful if you need to have more fields in that stock. So better create object with properties as key, value, shares, weight, etc and push accordingly in array. The updated function will be

$scope.addToTable = function(key, value, index){
  var mystock={};
  mystock.key = key;
  mystock.value = value;
    console.log(index);
    if(indexes.indexOf(index) == -1){
        indexes.push(index);
        $scope.stocksArray.push(mystock);
    }
}

Here's working plunk for that
https://plnkr.co/edit/r2WLGakBU9kGmWLWBN7K?p=preview


问:
big numbers from factorials
I'm working with factorials around 30! and I can't get a very good result for the value. I only want it accurate to 6 significant figures, or anything that gives a reasonable result. Currently my code is...

```<code>    static void Main(string[] args)
    {
        {
            int number = 30;
            long fact;
            factorial(number, out  fact);
        }
    }
    public static void factorial(int events, out  long  eventfact)
    {
        eventfact = 1;
        for (int tt = 1; tt <= events; tt++)
        {
            eventfact = eventfact * tt;
        }

    }
</code>```

This returns the result

```<code>-8764578968847253504
</code>```

this is far from

```<code>2.65252859812191E+32
</code>```

I've looked up about the different types of integers but nothing seems to be large enough for the numbers that I am working with.

Any help would be great!

答:
You can use the BigInteger struct for this task.</p>

```<code>static void Main(string[] args)
{
    int number = 30;
    BigInteger fact;
    factorial(number, out  fact);
}

public static void factorial(int events, out BigInteger eventfact)
{
    eventfact = new BigInteger(1);
    for (int tt = 2; tt <= events; tt++)
    {
        eventfact = eventfact * tt;
    }
}
</code>```

Title: big numbers from factorials

Body:
I'm working with factorials around 30! and I can't get a very good result for the value. I only want it accurate to 6 significant figures, or anything that gives a reasonable result. Currently my code is...

    static void Main(string[] args)
    {
        {
            int number = 30;
            long fact;
            factorial(number, out  fact);
        }
    }
    public static void factorial(int events, out  long  eventfact)
    {
        eventfact = 1;
        for (int tt = 1; tt <= events; tt++)
        {
            eventfact = eventfact * tt;
        }

    }

This returns the result

-8764578968847253504

this is far from

2.65252859812191E+32

I've looked up about the different types of integers but nothing seems to be large enough for the numbers that I am working with.

Any help would be great!

Body:
You can use the BigInteger struct for this task.

static void Main(string[] args)
{
    int number = 30;
    BigInteger fact;
    factorial(number, out  fact);
}

public static void factorial(int events, out BigInteger eventfact)
{
    eventfact = new BigInteger(1);
    for (int tt = 2; tt <= events; tt++)
    {
        eventfact = eventfact * tt;
    }
}


问:
How to iterate over single tuple item in array of tuples
I have an array of tuples of Int, CustomType, OtherCustomType. The array is sorted by the Int part of the tuples.

To add new elements at the correct position I wrote a binary search function to get the insertion point index.

The function returns a new tuple of Int, Bool, where Bool tells if the element is already present, and Int is either the index of the first occurrence of the new element, or the index of the first element which is larger than the new element.

The function is written genericly, and takes an array of a comparable type and a new element of the same type as arguments, so, obviously, I cannot simply pass my array of tuples.

A simple solution would be to re-organize my data so, instead of storing three values as tuples in one array, I could use three separate arrays, each of only one of the three values. I would then pass only the first array to the binary search function and then perform the desired action on all three arrays at the found index.

But is there a way to keep my data organized as tuples and pass only one element of each tuple to the function, like we are able to ignore parts of a tuple in comparisons like if tuple == (_ ,23, _) ?

Here is some sample code:

```<code>func findInsertPoint <T: Comparable> (forElement: T, inArray: [T]) -> (Int, Bool) {
    var low = 0
    var high = inArray.count

    if forElement > inArray[high-1] {
        return (high, false)
    }
    while low < high {
        let mid = (low+high)/2
        if inArray[mid] >= forElement {
            high = mid
        } else {
            low = mid+1
        }
    }
    return(low,(inArray[low] == forElement))
}
</code>```

An array of Ints works perfectly fine:

```<code>// index         0 1 2 3 4 5  6  7  8  9  10 11 12 13 14 15
var testArray = [1,2,5,7,8,11,12,12,12,15,19,22,22,26,52,56]

findInsertPoint(forElement: x, inArray: testArray)

// x = 17 returns (10,false)
// x = 19 returns (10,true)
</code>```

But my actual array looks something like this:

```<code>var testArray = [(4,"Bee",2.5),(5,"dog",1.0),(8,"dog",43.13)]
</code>```

How do I pass an array of only the first part of each tuple, but without the expensive creation of an actual new array each function call?

A possibility would be to call the function:

```<code>findInsertPoint(forElement: 7 in Array: testArray.0)
</code>```

which would be perfect, but I know this doesn't work.

Is there a Swift way to temporarily ignore members of a tuple or a struct for a function call that only accepts arrays of a single type?

If not, I know my two possibilities are:

stick to my taylored binary search, not the generic one from the code above.

divide the tuple into 3 separate arrays.

答:
You could create a structure and implement the Comparable protocol in it like so:

```<code>struct Foo: Comparable {
    let a: Int
    let b: TypeB
    let c: TypeC

    // compare according to the integers
    static func ==(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.a == rhs.a
    }

    static func <(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.a < rhs.a
    }
}
</code>```

With this structure, you could then call your custom generic sort function with the desired results as follows:

```<code>let foos = [Foo]()
let (position, exists) = customSort(foos)
</code>```

Since your custom sort function uses the comparable protocol, it should work just fine with the struct.

Body:
I have an array of tuples of Int, CustomType, OtherCustomType. The array is sorted by the Int part of the tuples.

To add new elements at the correct position I wrote a binary search function to get the insertion point index.

The function returns a new tuple of Int, Bool, where Bool tells if the element is already present, and Int is either the index of the first occurrence of the new element, or the index of the first element which is larger than the new element.

The function is written genericly, and takes an array of a comparable type and a new element of the same type as arguments, so, obviously, I cannot simply pass my array of tuples.

A simple solution would be to re-organize my data so, instead of storing three values as tuples in one array, I could use three separate arrays, each of only one of the three values. I would then pass only the first array to the binary search function and then perform the desired action on all three arrays at the found index.

But is there a way to keep my data organized as tuples and pass only one element of each tuple to the function, like we are able to ignore parts of a tuple in comparisons like if tuple == (_ ,23, _) ?

Here is some sample code:

func findInsertPoint <T: Comparable> (forElement: T, inArray: [T]) -> (Int, Bool) {
    var low = 0
    var high = inArray.count

    if forElement > inArray[high-1] {
        return (high, false)
    }
    while low < high {
        let mid = (low+high)/2
        if inArray[mid] >= forElement {
            high = mid
        } else {
            low = mid+1
        }
    }
    return(low,(inArray[low] == forElement))
}

An array of Ints works perfectly fine:

// index         0 1 2 3 4 5  6  7  8  9  10 11 12 13 14 15
var testArray = [1,2,5,7,8,11,12,12,12,15,19,22,22,26,52,56]

findInsertPoint(forElement: x, inArray: testArray)

// x = 17 returns (10,false)
// x = 19 returns (10,true)

But my actual array looks something like this:

var testArray = [(4,"Bee",2.5),(5,"dog",1.0),(8,"dog",43.13)]

How do I pass an array of only the first part of each tuple, but without the expensive creation of an actual new array each function call?

A possibility would be to call the function:

findInsertPoint(forElement: 7 in Array: testArray.0)

which would be perfect, but I know this doesn't work.

Is there a Swift way to temporarily ignore members of a tuple or a struct for a function call that only accepts arrays of a single type?

If not, I know my two possibilities are:

stick to my taylored binary search, not the generic one from the code above.

divide the tuple into 3 separate arrays.

Body:
You could create a structure and implement the Comparable protocol in it like so:

struct Foo: Comparable {
    let a: Int
    let b: TypeB
    let c: TypeC

    // compare according to the integers
    static func ==(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.a == rhs.a
    }

    static func <(lhs: Foo, rhs: Foo) -> Bool {
        return lhs.a < rhs.a
    }
}

With this structure, you could then call your custom generic sort function with the desired results as follows:

let foos = [Foo]()
let (position, exists) = customSort(foos)

Since your custom sort function uses the comparable protocol, it should work just fine with the struct.


问:
Perform Loess smoothing in R by ID?
I have time-series data on multiple individuals:

```<code>ID Day Weight
1 1 334
1 2 339
1 3 342
1 4 339
2 1 332
2 2 334
2 3 338
2 4 341
</code>```

How can I get the Loess smoothed results by ID? Running Loess smoothing on a single individual:

```<code>mod <- loess(Weight ~ Day, data=test, span=0.18)

smoothed <- predict(mod)
</code>```

答:
This will allow you to plot the loess curve since that is the default for geom_smooth.

Also facet_wrap allows you to create a separate plot for each ID.

```<code>ggplot(test, aes(x=Weight, y=Day))+geom_point()+geom_smooth()+facet_wrap(~ID)
</code>```

If you want it all in one plot:

```<code>ggplot(test, aes(x=Weight, y=Day,
                 col = as.factor(ID), group = as.factor(ID)))+geom_point()+geom_smooth()
</code>```

Which will give you this:

Title: Perform Loess smoothing in R by ID?

Body:
I have time-series data on multiple individuals:

ID Day Weight
1 1 334
1 2 339
1 3 342
1 4 339
2 1 332
2 2 334
2 3 338
2 4 341

How can I get the Loess smoothed results by ID? Running Loess smoothing on a single individual:

mod <- loess(Weight ~ Day, data=test, span=0.18)

smoothed <- predict(mod)

Body:
This will allow you to plot the loess curve since that is the default for geom_smooth.

Also facet_wrap allows you to create a separate plot for each ID.

ggplot(test, aes(x=Weight, y=Day))+geom_point()+geom_smooth()+facet_wrap(~ID)

If you want it all in one plot:

ggplot(test, aes(x=Weight, y=Day,
                 col = as.factor(ID), group = as.factor(ID)))+geom_point()+geom_smooth()

Which will give you this:


问:
Set DataTemplate control Style code behind
So ia have this ListView with Custom Column Progress-Bar:

```<code>            <ListView Name="lvFiles">
                <ListView.Resources>
                    <DataTemplate x:Key="MyDataTemplate">
                        <Grid Margin="0,0,0,0">
                            <ProgressBar
                                Name="progressBarColumn"
                                Maximum="100"
                                Value="{Binding Progress, UpdateSourceTrigger=PropertyChanged}"
                                Width="{Binding Path=Width, ElementName=ProgressCell}"
                                Margin="0,0,0,0"
                                Style="{StaticResource CustomProgressBar}" />
                            <TextBlock
                                Text="{Binding Path=Value, ElementName=progressBarColumn, StringFormat={}{0:N1}%}"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center"
                                FontSize="11.5"
                                Foreground="White"
                                Margin="0,-2,0,0"/>
                        </Grid>
                    </DataTemplate>
                    <ControlTemplate x:Key="ProgressBarTemplate">
                        <Label  HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </ControlTemplate>
                    <Style TargetType="{x:Type TextBlock}">
                        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=Text }"></Setter>
                    </Style>
                </ListView.Resources>
            </ListView>
</code>```

Style

```<code><Style x:Key="CustomProgressBar" TargetType="ProgressBar" >
    <Setter Property="Template" >
        <Setter.Value>
            <ControlTemplate TargetType="ProgressBar">
                <Border BorderBrush="#FF103766" BorderThickness="0" Background="#FF103766" CornerRadius="0" Padding="0">
                    <Grid x:Name="PART_Track">
                        <Rectangle x:Name="PART_Indicator" HorizontalAlignment="Left">
                            <Rectangle.Style>
                                <Style TargetType="Rectangle">
                                    <Setter Property="Fill" Value="Gray"/>
                                    <Style.Triggers>
                                        <DataTrigger Value="100" Binding="{Binding Path=Value, RelativeSource={RelativeSource AncestorType=ProgressBar}}">
                                            <Setter Property="Fill" Value="LightSeaGreen"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </Rectangle.Style>
                        </Rectangle>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

So in case i want to create several Styles and change this Style from code behain, is it possible ?

答:
One line of code can do that:

```<code>  progressBarColumn.Style = (Style)Application.Current.TryFindResource("CustomProgressBar");
</code>```

When you have multiple custom Progress Bar styles, you just replace "CustomProgressBar" in the code above with whatever the name of your desired progress bar style actually is.

Make sure that your Styles are in a dictionary (or location) that is visible at the application level.

Body:
So ia have this ListView with Custom Column Progress-Bar:

            <ListView Name="lvFiles">
                <ListView.Resources>
                    <DataTemplate x:Key="MyDataTemplate">
                        <Grid Margin="0,0,0,0">
                            <ProgressBar
                                Name="progressBarColumn"
                                Maximum="100"
                                Value="{Binding Progress, UpdateSourceTrigger=PropertyChanged}"
                                Width="{Binding Path=Width, ElementName=ProgressCell}"
                                Margin="0,0,0,0"
                                Style="{StaticResource CustomProgressBar}" />
                            <TextBlock
                                Text="{Binding Path=Value, ElementName=progressBarColumn, StringFormat={}{0:N1}%}"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center"
                                FontSize="11.5"
                                Foreground="White"
                                Margin="0,-2,0,0"/>
                        </Grid>
                    </DataTemplate>
                    <ControlTemplate x:Key="ProgressBarTemplate">

                    </ControlTemplate>

                </ListView.Resources>
            </ListView>

Style

                                </Style>
                            </Rectangle.Style>
                        </Rectangle>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

So in case i want to create several Styles and change this Style from code behain, is it possible ?

Body:
One line of code can do that:

  progressBarColumn.Style = (Style)Application.Current.TryFindResource("CustomProgressBar");

When you have multiple custom Progress Bar styles, you just replace "CustomProgressBar" in the code above with whatever the name of your desired progress bar style actually is.

Make sure that your Styles are in a dictionary (or location) that is visible at the application level.