问:
SharePoint filtering list with multiple values of the same field

"Display the items in the list that either belongs to the category
  Health or Entertainment."

I have a sample list: http://www.example.com/Lists/MyList/AllItems.aspx

And if I am to filter the list items to look for Categories with the value "Entertainment", the URL will look like this:

http://www.example.com/Lists/MyList/AllItems.aspx?View={ViewId}&FilterField=Categories&FilterValue=Entertainment

Suppose I'd like to filter by the list items with the Categories "Entertainment" OR "Health". Unfortunately, this URL would not work as I can only filter with 1 value for the same field at a time:

http://www.example.com/Lists/MyList/AllItems.aspx?View={ViewId}&FilterField1=Categories&FilterValue1=Entertainment&FilterField2=Categories&FilterValue2=Health

What is the URL for filtering with multiple values of the same field ("OR" condition) in a SharePoint list?

答:
Solution for filtering multi value lookup column in SharePoint. Link for detailed instructions: Multi value Lookup Columns in SharePoint
Code for reference - Hope this helps some readers.

function multiValueLookup() {
    var items = "";
    var citiesListName = "Cities";
    $("select[title='City possible values'] option").remove();
    $("select[title='State selected values'] option").each(function (i) {
        var clientContext = new SP.ClientContext.get_current();
        var oList = clientContext.get_web().get_lists().getByTitle(citiesListName);
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Title' /></OrderBy><Where><Eq><FieldRef Name='State' LookupId='TRUE'/><Value Type='Lookup'>" + $(this).val() + "</Value></Eq></Where></Query></View>");
        var items = oList.getItems(camlQuery);
        clientContext.load(items);
        clientContext.executeQueryAsync(success, failure);
        function success() {
            var pn2 = "";
            var pn1 = "";
            var ListEnumerator = items.getEnumerator();
            while (ListEnumerator.moveNext()) {
                var currentItem = ListEnumerator.get_current();
                if (currentItem.get_item('Title') != null) {
                    var pn1 = currentItem.get_item('Title');
                    if (pn2 != pn1) {
                        items = "<option value='" + currentItem.get_item('ID') + "' title='" + pn1 + "'>" + pn1 + "</option>";
                        $("select[title='City possible values']").append(items);
                        pn2 = pn1;
                    }
                }
            }
        }
        function failure(sender, args) {
            // alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
        }
    });
}```


来源: stackexchange

问:
How to interface C++ and Excel (Output from C++ program to an Excel spreadsheet)
I am making a small program for my job (it has nothing to do with programming) to help them with the many measurements and efficiency of their job.

I have made most of the program in a Console App in C++ with Code::Blocks.

Would it be possible to yank the output of variables from my C++ and put them in certain cells in an Excel spreadsheet? I have looked around the internet for some forums but some do not work or have me use Visual Basics. Any clues or hints would help dramatically. Thanks.

Source Code:

```<code>#include <iostream>
#include <cstdlib>
#include <cmath>

//Function Prototypes -- *
void DisplayMenu();
void Bahama();
int Colonial();
int StormPanel();

 void DisplayMenu()
{

    int a;

    std::cout << "*---Display Menu---*\n";
    std::cout << "1) Bahama/Colonial\n";
    std::cout << "2) Strom Panel\n\n";

    std::cout << "Type the corresponding number for\n";
    std::cout << "the type of shutter you need calculated: ";

        std::cin >> a;

        switch(a)
        {
        case 1:
            Bahama();
            break;
        case 2:
            StormPanel();
            break;

        }

}

void Bahama()
{

    int Token = 200;

    do{

    int SN; //Shutter Number
    int QSL; // Quantity of Shutter Louvers

    double W; //Width
    double H; //Hight
    double Sl; // Shutter Louvers (trail)
    double SL; // Size of Shutter Louvers

    float Sd = 3.7812; // Single Deduction
    float Dd = 5.6562; // Double Deduction
    float Td = 7.5312; // Triple Deduction
    float Qd = 9.4062; // Quadruple Deduction
    float QTd = 11.2812; // Quintuple Deduction
    float STd = 13.1562; // Sextuple Deduction

    float HL; // Hight multiplied by Length

    system("cls");

    std::cout << "*----------------------------------------*\n\n";
    std::cout << "What is the Width of the Bahama/Colonial shutter?\n";
    std::cout << "(Whole Number or Decimal[Inches]): ";
        std::cin >> W;

    std::cout << "*----------------------------------------*\n\n";
    std::cout << "What is the Hight of the Bahama/Colonial shutter?\n";
    std::cout << "(Whole Number or Decimal[Inches]): ";
        std::cin >> H;

    HL = W*H;

    system("cls");

    std::cout << "*---------------------------------------------------------
----
---------------------------------------*\n\n";
    std::cout << "Is this Shutter a . . ." << "\n" << "Single (1), Double
(2),"
<< "\n" << "Triple (3), Quadruple (4)," << "\n" << "Quintuple (5), or
Sextuple
(6): ";
        std::cin >> SN;

    switch (SN)
    {
        case 1: Sl = W - Sd;
        break;

        case 2: Sl = W - Dd;
        break;

        case 3: Sl = W - Td;
        break;

        case 4: Sl = W - Qd;
        break;

        case 5: Sl = W - QTd;
        break;

        case 6: Sl = W - STd;
        break;

        default: Sl = W - Sd;
    }

    SL = Sl / SN;

    std::cout << "\n\nWith a Width of [" << W <<"] and a Hight of [" << H <<
"]";
    std::cout << " the Bahama/Colonial Shutters'. . .";

    std::cout << "\n\nSide Slide: ";
        std::cout << W - 3.3125;

    std::cout << "\n\nSide Rails: ";
        std::cout << H - 3.7187;

    std::cout << "\n\nLouver Size: ";
        std::cout << SL;

    // std::cout << "\n\nNumber of Louvers: ";
       // std::cout << NP;

    std::cout << "\n\n*-----------------------------------------------------
----
-------------------------------------------*\n\n\n";

    std::cout << "Would you like to measure out another Bahama/Colonial
shutter?";
    std::cout << "(1 = Yes)(2 = Main Menu)(0 = Quit): ";
        std::cin >> Token;

    switch (Token)
    {
    case 2: DisplayMenu();

    case 0: Token = 200;
    }

    } while (Token == 1);

}

int StormPanel()
{
    std::cout << "Storm Panel!";

    return 0;

}

int main()
{
    DisplayMenu();

    return 0;
}
</code>```

答:
You can control Excel via OLE Automation.

https://support.microsoft.com/en-us/help/216686/how-to-automate-excel-from-c-without-using-mfc-or-import

ContentLicense: CC BY-SA 3.0

Body:
I am making a small program for my job (it has nothing to do with programming) to help them with the many measurements and efficiency of their job.

I have made most of the program in a Console App in C++ with Code::Blocks.

Would it be possible to yank the output of variables from my C++ and put them in certain cells in an Excel spreadsheet? I have looked around the internet for some forums but some do not work or have me use Visual Basics. Any clues or hints would help dramatically. Thanks.

Source Code:

#include <iostream>
#include <cstdlib>
#include <cmath>

//Function Prototypes -- *
void DisplayMenu();
void Bahama();
int Colonial();
int StormPanel();

 void DisplayMenu()
{

    int a;

    std::cout << "*---Display Menu---*\n";
    std::cout << "1) Bahama/Colonial\n";
    std::cout << "2) Strom Panel\n\n";

    std::cout << "Type the corresponding number for\n";
    std::cout << "the type of shutter you need calculated: ";

        std::cin >> a;

        switch(a)
        {
        case 1:
            Bahama();
            break;
        case 2:
            StormPanel();
            break;

        }

}

void Bahama()
{

    int Token = 200;

    do{

    int SN; //Shutter Number
    int QSL; // Quantity of Shutter Louvers

    double W; //Width
    double H; //Hight
    double Sl; // Shutter Louvers (trail)
    double SL; // Size of Shutter Louvers

    float Sd = 3.7812; // Single Deduction
    float Dd = 5.6562; // Double Deduction
    float Td = 7.5312; // Triple Deduction
    float Qd = 9.4062; // Quadruple Deduction
    float QTd = 11.2812; // Quintuple Deduction
    float STd = 13.1562; // Sextuple Deduction

    float HL; // Hight multiplied by Length

    system("cls");

    std::cout << "*----------------------------------------*\n\n";
    std::cout << "What is the Width of the Bahama/Colonial shutter?\n";
    std::cout << "(Whole Number or Decimal[Inches]): ";
        std::cin >> W;

    std::cout << "*----------------------------------------*\n\n";
    std::cout << "What is the Hight of the Bahama/Colonial shutter?\n";
    std::cout << "(Whole Number or Decimal[Inches]): ";
        std::cin >> H;

    HL = W*H;

    system("cls");

    std::cout << "*---------------------------------------------------------
----
---------------------------------------*\n\n";
    std::cout << "Is this Shutter a . . ." << "\n" << "Single (1), Double
(2),"
<< "\n" << "Triple (3), Quadruple (4)," << "\n" << "Quintuple (5), or
Sextuple
(6): ";
        std::cin >> SN;

    switch (SN)
    {
        case 1: Sl = W - Sd;
        break;

        case 2: Sl = W - Dd;
        break;

        case 3: Sl = W - Td;
        break;

        case 4: Sl = W - Qd;
        break;

        case 5: Sl = W - QTd;
        break;

        case 6: Sl = W - STd;
        break;

        default: Sl = W - Sd;
    }

    SL = Sl / SN;

    std::cout << "\n\nWith a Width of [" << W <<"] and a Hight of [" << H <<
"]";
    std::cout << " the Bahama/Colonial Shutters'. . .";

    std::cout << "\n\nSide Slide: ";
        std::cout << W - 3.3125;

    std::cout << "\n\nSide Rails: ";
        std::cout << H - 3.7187;

    std::cout << "\n\nLouver Size: ";
        std::cout << SL;

    // std::cout << "\n\nNumber of Louvers: ";
       // std::cout << NP;

    std::cout << "\n\n*-----------------------------------------------------
----
-------------------------------------------*\n\n\n";

    std::cout << "Would you like to measure out another Bahama/Colonial
shutter?";
    std::cout << "(1 = Yes)(2 = Main Menu)(0 = Quit): ";
        std::cin >> Token;

    switch (Token)
    {
    case 2: DisplayMenu();

    case 0: Token = 200;
    }

    } while (Token == 1);

}

int StormPanel()
{
    std::cout << "Storm Panel!";

    return 0;

}

int main()
{
    DisplayMenu();

    return 0;
}


问:
use just the scope for fields_for with nested_attributes
I have 2 classes, A and B

```<code>class A
  has_many :bs
  accepts_nested_attributes_for :bs
end

class B
   belongs_to :a
end
</code>```

B has a field called :group and I want to group my b's by group in the form.

fields_for does 2 things, it 1) adds a scope around nested form elements, and 2) it iterates through the attributes. I only want the first part, the nested scope.  Is there a way to just scope the nesting so I can manually group my nested objects?

In pseudo code what I want is

```<code><%= form_for a do |f| %>
  <%= scope_for :gs do |g| %>
      <% f.object.bs.group_by{|x| x.group} do |k,v| %>
    <h3> Group <%= k %> </h3>
    <% v.each do |b| %>
       <%= g.text_field :field1
</code>```

...

Is there a Rails form helper that achieves this?

答:
There is no built-in helper that I know of that will let you do this, but it is possible to hack together a solution using just fields_for. The trick is to have a separate fields_for block for each group:

```<code> <% f.object.bs.group_by(&:group).each do |k, v| %>
   <%= f.fields_for "b_groups[]" do |g| %>
     <!-- ... -->
   <% end %>
 <% end %>
</code>```

Body:
I have 2 classes, A and B

class A
  has_many :bs
  accepts_nested_attributes_for :bs
end

class B
   belongs_to :a
end

B has a field called :group and I want to group my b's by group in the form.

fields_for does 2 things, it 1) adds a scope around nested form elements, and 2) it iterates through the attributes. I only want the first part, the nested scope.  Is there a way to just scope the nesting so I can manually group my nested objects?

In pseudo code what I want is

<%= form_for a do |f| %>
  <%= scope_for :gs do |g| %>
      <% f.object.bs.group_by{|x| x.group} do |k,v| %>

 Group <%= k %>

    <% v.each do |b| %>
       <%= g.text_field :field1

...

Is there a Rails form helper that achieves this?

Body:
There is no built-in helper that I know of that will let you do this, but it is possible to hack together a solution using just fields_for. The trick is to have a separate fields_for block for each group:

 <% f.object.bs.group_by(&:group).each do |k, v| %>
   <%= f.fields_for "b_groups[]" do |g| %>
     <!-- ... -->
   <% end %>
 <% end %>


问:
Make a delete function
I tried to implement a function that automatically does this:

```<code>del data['method_code']
del data['aqi']
del data['local_site_name']
del data['cbsa_name']
</code>```

I have this function:

```<code>def del_data_func(data,columns):
  data[columns] =  data[columns].apply(lambda x: del(x))
  return data
del_list = data.columns[['method_code','aqi','local_site_name','cbsa_name']]
del_data_func (data, del_list)
</code>```

How can i implement it in the right manner and avoid any errors like this one :

```<code>data[columns] =  data[columns].apply(lambda x: del(x))
SyntaxError: invalid syntax
</code>```

答:
Why not try this?

data.drop(['method_code', 'aqi', 'local_site_name', 'cbsa_name'], axis=1, inplace=True)

That list could be in fact any list as long as the elements in the list are valid column names from your dataframe.

Title: Make a delete function

Body:
I tried to implement a function that automatically does this:

del data['method_code']
del data['aqi']
del data['local_site_name']
del data['cbsa_name']

I have this function:

def del_data_func(data,columns):
  data[columns] =  data[columns].apply(lambda x: del(x))
  return data
del_list = data.columns[['method_code','aqi','local_site_name','cbsa_name']]
del_data_func (data, del_list)

How can i implement it in the right manner and avoid any errors like this one :

data[columns] =  data[columns].apply(lambda x: del(x))
SyntaxError: invalid syntax


问:
PostgreSQL - Function that returns labels of any ENUM
I am trying to write a "generic" function that will return labels of any enum (in any schema)...
But I am not having much luck because I am not sure what should argument type be...

The goal would be to be able to call function like this

```<code>SELECT common.get_enum_labels('public.rainbow_colors');
SELECT common.get_enum_labels('audit.user_actions');
</code>```

This is what I have so

```<code>CREATE OR REPLACE FUNCTION common.get_enum_labels(enum_name regtype)
RETURNS SETOF text AS
$$
BEGIN
  EXECUTE format('SELECT unnest(enum_range(NULL::%s))::text AS enum_labels ORDER BY 1', enum_name);
END;
$$
LANGUAGE plpgsql
STABLE
PARALLEL SAFE
;
</code>```

Any tips would be appreciated

答:
The argument type should be regtype, do not forget to return something from the function

```<code>CREATE OR REPLACE FUNCTION get_enum_labels(enum_name regtype)
RETURNS SETOF text AS
$$
BEGIN
    RETURN QUERY
        EXECUTE format('SELECT unnest(enum_range(NULL::%s))::text ORDER BY 1', enum_name);
END;
$$
LANGUAGE plpgsql
</code>```

Body:
I am trying to write a "generic" function that will return labels of any enum (in any schema)...
But I am not having much luck because I am not sure what should argument type be...

The goal would be to be able to call function like this

SELECT common.get_enum_labels('public.rainbow_colors');
SELECT common.get_enum_labels('audit.user_actions');

This is what I have so

CREATE OR REPLACE FUNCTION common.get_enum_labels(enum_name regtype)
RETURNS SETOF text AS
$$
BEGIN
  EXECUTE format('SELECT unnest(enum_range(NULL::%s))::text AS enum_labels ORDER BY 1', enum_name);
END;
$$
LANGUAGE plpgsql
STABLE
PARALLEL SAFE
;

Any tips would be appreciated

Body:
The argument type should be regtype, do not forget to return something from the function

CREATE OR REPLACE FUNCTION get_enum_labels(enum_name regtype)
RETURNS SETOF text AS
$$
BEGIN
    RETURN QUERY
        EXECUTE format('SELECT unnest(enum_range(NULL::%s))::text ORDER BY 1', enum_name);
END;
$$
LANGUAGE plpgsql


问:
ImageCoercion not enabled in PowerPoint 2016
I'm trying to insert image from addin to powerpoint slide using this function

```<code>Office.context.document.setSelectedDataAsync
</code>```

However, it does not work on PowerPoint 2016 whereas it works correctly on PowerPoint online. This is error message that I got

```<code>The enumeration isn't supported in the current host application.
</code>```

I updated office library to latest using

```<code><script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
</code>```

and also updated my manifest xml file

```<code><OfficeApp
          xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
          xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides"
          xsi:type="TaskPaneApp">
</code>```

My PowerPoint client version is 16.0.4266.1001 64-bit in Windows 7

Thanks for your help.

答:
that build number you have is quite old. if you want to try that API I strongly recommend you to update your office. PLease goto File->Account-> Office Update.

Once updated try again and it should work.
thx!

Body:
I'm trying to insert image from addin to powerpoint slide using this function

Office.context.document.setSelectedDataAsync

However, it does not work on PowerPoint 2016 whereas it works correctly on PowerPoint online. This is error message that I got

The enumeration isn't supported in the current host application.

I updated office library to latest using

and also updated my manifest xml file

<OfficeApp
          xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
          xmlns:ov="http://schemas.microsoft.com/office/taskpaneappversionoverrides"
          xsi:type="TaskPaneApp">

My PowerPoint client version is 16.0.4266.1001 64-bit in Windows 7

Thanks for your help.


问:
Calling a controller function from onchange event in html view
I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this:  "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

```<code>@Html.DropDownList("selectList", Model.ReverseMonthsLists())
</code>```

View Model Code

```<code>public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}
</code>```

Controller function

```<code>    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }
</code>```

答:
```<code>function SendDataToController (TheDropDownName){
       var DataToSend = $('#'+TheDropDownName).text();
       // Or Pass `this` From The Html When Assigning The Event Listener
       // and Do Something Like var DataToSend = this.text();
        $.ajax({
          url: "@(Url.Action("ActionName", "ControllerName"))",
          data: DataToSend,
          success: function(ResponseFromController){
            //Do Stuff With Response
          }
    });
}
</code>```

This Will Send The Data To Controller So You Should Receive It in A Parameter

```<code>public ActionResult MyAction (string DataToSend)
{
  //Do Stuff With Data and Get a Json Object To Return
   Return Json(JsonObject);
}
</code>```

MVC Ajax Is Essential So You Should Learn It Before Tryin To Work On Any MVC Project, Also You Should Handle Request Error Using fail attr in The Ajax Setting But I Will Leave That To You

Body:
I'm a new c# developer and I have a dropdownlist populated with string dates formatted like this:  "Jul 2017". There can be as many as 12 entries in the list.

When a user selects a date, I want to pass that selection to a controller method, convert it to a DateTime format and then use that date for further processing.

How do I pass the user selection to the controller so it can be converted and used? I've included commented out code below to show how I want to do the conversion. Getting the date to the controller is my challenge.

I've looked at similar questions on this site and they all seem overly complex (perhaps due to my naivete), but I was hoping for a more streamlined solution.

Html View Code

@Html.DropDownList("selectList", Model.ReverseMonthsLists())

View Model Code

public IEnumerable<SelectListItem> ReverseMonthsLists()
    {
        var selectListItems = GetDates()
            .Select(_ => _.ToString("MMM yyyy"))
            .Select((dateString, index) => new SelectListItem
                { Selected = index == 0, Text = dateString, Value = dateString })
            .ToList();
        return selectListItems;
    }

public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;
    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 +
        currentDate.Month - startDate.Month;
    var dates = new List<DateTime>(numberOfMonthsToShow);
    currentDate = currentDate.AddMonths(-1);

    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }

    return dates;
}

Controller function

    public ActionResult Report_Performance()
    {
        //var newDate = DateTime.Parse(strDate);  //<- Use newDate as parameter value into aVar to replace date at the end of the string
        var aVar = Models.Reporting.ListingStatsReportingViewModel.GetStats(userCurrentService.CompanyId.Value, Models.Reporting.DateTimePeriod.Monthly, DateTime.Now.Date.AddMonths(-1));
        return this.View(aVar);
    }

Body:
function SendDataToController (TheDropDownName){
       var DataToSend = $('#'+TheDropDownName).text();
       // Or Pass `this` From The Html When Assigning The Event Listener
       // and Do Something Like var DataToSend = this.text();
        $.ajax({
          url: "@(Url.Action("ActionName", "ControllerName"))",
          data: DataToSend,
          success: function(ResponseFromController){
            //Do Stuff With Response
          }
    });
}

This Will Send The Data To Controller So You Should Receive It in A Parameter

public ActionResult MyAction (string DataToSend)
{
  //Do Stuff With Data and Get a Json Object To Return
   Return Json(JsonObject);
}

MVC Ajax Is Essential So You Should Learn It Before Tryin To Work On Any MVC Project, Also You Should Handle Request Error Using fail attr in The Ajax Setting But I Will Leave That To You


问:
How can I imitate this view controller modal transition
So I'm trying to imitate the transition found in the Pocketcasts app. The idea is to have a view controller emerge from the bottom of the screen when an item is clicked on, and the view controller can either be swiped up to go full screen or swiped downwards to dismiss it. I honestly have no idea how I would achieve this, so I'm wondering if anyone has dealt with it before. Ideally this would be done in Swift, but Obj-C works. Thanks!</p>

答:
There is a really great video from WWDC 2017 that builds a similar component using UIViewPropertyAnimator. This allows for interruptible animations as shown in your gif.

The presentation is extremely well done, and provides sample code.

Advanced Animations with UIKit

UIViewPropertyAnimator Documentation


问:
RSA_public_decrypt fails when using RSA_set0_key(key, n,e,d)?
I have the n, e, d component from other devices not the OpenSSL. I want to encrypt and decrypt using the OpenSSL API. But decrypt always fails after encrypt.

I use RSA_set0_key for private key (n, e, d) setting, and RSA_private_encrypt is OK, but RSA_public_decrypt fails always. I wonder why it fails.

Why does RSA_public_decrypt fail?

答:
RSA_set0_key() with N, E, D is possible?

Yes. RSA_set0_key is documented in the OpenSSL man pages. Its signature is:

```<code>int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d);
</code>```

The description is:

The n, e and d parameter values can be set by calling RSA_set0_key() and passing the new values for n, e and d as parameters to the function. The values n and e must be non-NULL the first time this function is called on a given RSA object. The value d may be NULL. On subsequent calls any of these values may be NULL which means the corresponding RSA field is left untouched. Calling this function transfers the memory management of the values to the RSA object, and therefore the values that have been passed in should not be freed by the caller after this function has been called.

Further down, under RETURN VALUES:

RSA_set0_key(), RSA_set0_factors and RSA_set0_crt_params() return 1 on success or 0 on failure.

I use RSA_set0_key for key(N, E, D) setting, and RSA_private_encrypt is OK, but RSA_public_decrypt fails always

Its hard to say what is going on with your use of RSA_public_decrypt. Perhaps you can add some code, state what the return value is, and state the value of ERR_get_err when the function fails.

In the meantime, you may need your RSA object to have the extended private key parameters, like p, q, dp, dq, and qInv. Those are the Chinese Remainder Theorem (CRT) parameters, and they are set with RSA_set0_crt_params. Also see Unable to decrypt without Chinese Remainder Theorem factors? on the OpenSSL users mailing list.

Body:
RSA_set0_key() with N, E, D is possible?

Yes. RSA_set0_key is documented in the OpenSSL man pages. Its signature is:

int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d);

The description is:

The n, e and d parameter values can be set by calling RSA_set0_key() and passing the new values for n, e and d as parameters to the function. The values n and e must be non-NULL the first time this function is called on a given RSA object. The value d may be NULL. On subsequent calls any of these values may be NULL which means the corresponding RSA field is left untouched. Calling this function transfers the memory management of the values to the RSA object, and therefore the values that have been passed in should not be freed by the caller after this function has been called.

Further down, under RETURN VALUES:

RSA_set0_key(), RSA_set0_factors and RSA_set0_crt_params() return 1 on success or 0 on failure.

I use RSA_set0_key for key(N, E, D) setting, and RSA_private_encrypt is OK, but RSA_public_decrypt fails always

Its hard to say what is going on with your use of RSA_public_decrypt. Perhaps you can add some code, state what the return value is, and state the value of ERR_get_err when the function fails.

In the meantime, you may need your RSA object to have the extended private key parameters, like p, q, dp, dq, and qInv. Those are the Chinese Remainder Theorem (CRT) parameters, and they are set with RSA_set0_crt_params. Also see Unable to decrypt without Chinese Remainder Theorem factors? on the OpenSSL users mailing list.


问:
how do i reference an id with concatenated variable in jquery appendTo()?
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

```<code>$(... +
    '<div class="recommendations filter" id="recCards-'+ i +'">' +
    '<div><h5>Recommended Cards</h5></div>' +
        '<ul></ul>' +
    '</div>' +
  ...
 ).appendTo('.someDiv');
</code>```

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

```<code>var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

答:
Try this, use mask and replace by i,</p>

```<code>var strReccards = ".recCards-MYINDEX ul";
var recCardsList = $(div).attr('id', recCardIndex.replace("MYINDEX",i));
$('<div>'+recCardName+'</div>').appendTo(recCardsList);
</code>```

Body:
I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

$(... +
    '
' +
    '

Recommended Cards

' +
        '

' +
    '
' +
  ...
 ).appendTo('.someDiv');

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('
'+recCardName+'
').appendTo(recCardsList);

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

Body:
Try this, use mask and replace by i,

var strReccards = ".recCards-MYINDEX ul";
var recCardsList = $(div).attr('id', recCardIndex.replace("MYINDEX",i));
$('<div>'+recCardName+'</div>').appendTo(recCardsList);


问:
Is it possible to find out if some list is fixed size or not?
Is it possible to find out if some a list is fixed size or not?
I mean, for example this code:

```<code>String[] arr = {"a", "b"};
List<String> list = Arrays.asList(array);
</code>```

returns fixed size List backed by an array. But is it possible to understand programmatically if List is fixed-size or not without trying to add/remove elements and catching the exception? For example:

```<code>try {
    list.add("c");
}
catch(UnsupportedOperationException e) {
    // Fixed-size?
}
</code>```

答:
No.

The List API is identical regardless of whether a List is expandable or not, something that was deliberate.

There is also nothing in the List API that allows you to query it to determine this feature.

You can't completely reliably determine this information by reflection, because you will be depending on internal details of the implementation, and because there is an unbounded number of classes that are potentially fixed-size. For example, in addition to Arrays.asList, there is also Arrays.asList().subList, which happens to return a different class. There can also be wrappers around the base list like Collections.checkedList, Collections.synchronizedList and Collections.unmodifiableList. There are also other fixed-size lists: Collections.emptyList, Collections.singletonList, and Collections.nCopies. Outside the standard library, there are things like Guava's ImmutableList. It's also pretty trivial to hand-roll a list for something by extending AbstractList (for a fixed-size list you need only implement the size() and get(int) methods).

Even if you detect that your list is not fixed-size, the specification of List.add allows it to refuse elements for other reasons. For example, Collections.checkedList wrappers throw a ClassCastException for elements of unwanted type.

And even if you know your list is expandable, and allows arbitrary elements, that doesn't mean you want to use it. Perhaps it's synchronized, or not synchronized, or isn't serializable, or it's a slow linked list, or has some other quality that you don't want.

If you want control over the type, mutability, serializability, or thread-safety of the list, or you want to be sure that no other code has kept a reference to it, the practice is that you create a new one yourself. It's not expensive to do so when unnecessary (memcopies are blazing fast), and it lets you reason more definitely about your code will actually do at runtime. If you'd really like to avoid creating unnecessary copies, try whitelisting instead of blacklisting list classes. For example:

```<code>if (list.getClass() != ArrayList.class) {
    list = new ArrayList<>(list);
}
</code>```

(Note: That uses getClass instead of instanceof, because instanceof would also be true for any weird subclasses of ArrayList.)

Body:
Is it possible to find out if some a list is fixed size or not?
I mean, for example this code:

String[] arr = {"a", "b"};
List<String> list = Arrays.asList(array);

returns fixed size List backed by an array. But is it possible to understand programmatically if List is fixed-size or not without trying to add/remove elements and catching the exception? For example:

try {
    list.add("c");
}
catch(UnsupportedOperationException e) {
    // Fixed-size?
}

Body:
No.

The List API is identical regardless of whether a List is expandable or not, something that was deliberate.

There is also nothing in the List API that allows you to query it to determine this feature.

You can't completely reliably determine this information by reflection, because you will be depending on internal details of the implementation, and because there is an unbounded number of classes that are potentially fixed-size. For example, in addition to Arrays.asList, there is also Arrays.asList().subList, which happens to return a different class. There can also be wrappers around the base list like Collections.checkedList, Collections.synchronizedList and Collections.unmodifiableList. There are also other fixed-size lists: Collections.emptyList, Collections.singletonList, and Collections.nCopies. Outside the standard library, there are things like Guava's ImmutableList. It's also pretty trivial to hand-roll a list for something by extending AbstractList (for a fixed-size list you need only implement the size() and get(int) methods).

Even if you detect that your list is not fixed-size, the specification of List.add allows it to refuse elements for other reasons. For example, Collections.checkedList wrappers throw a ClassCastException for elements of unwanted type.

And even if you know your list is expandable, and allows arbitrary elements, that doesn't mean you want to use it. Perhaps it's synchronized, or not synchronized, or isn't serializable, or it's a slow linked list, or has some other quality that you don't want.

If you want control over the type, mutability, serializability, or thread-safety of the list, or you want to be sure that no other code has kept a reference to it, the practice is that you create a new one yourself. It's not expensive to do so when unnecessary (memcopies are blazing fast), and it lets you reason more definitely about your code will actually do at runtime. If you'd really like to avoid creating unnecessary copies, try whitelisting instead of blacklisting list classes. For example:

if (list.getClass() != ArrayList.class) {
    list = new ArrayList<>(list);
}

(Note: That uses getClass instead of instanceof, because instanceof would also be true for any weird subclasses of ArrayList.)


问:
How to remove github history for all team members
I am working on a project and using github as our source control server. The project is private and I want to make it public. But some credential is saved in the history of my git repo. I want to remove the history of commits and only keep the last commits for all branches. I know that I can do this by below commands.

```<code>Checkout

git checkout --orphan latest_branch
Add all the files

git add -A
Commit the changes

git commit -am "commit message"
Delete the branch

git branch -D master
Rename the current branch to master

git branch -m master
Finally, force update your repository

git push -f origin master
</code>```

but I am worried about other team members. If I follow above steps to clear the history but other team members don't, will they have trouble when they run git pull? Or will they bring the history back when they run git push?

答:
Clone repository in state you want your project to go public

Create new repository

Push to that fresh repository

Repo will be fresh with no history as a good working base.

Body:
I am working on a project and using github as our source control server. The project is private and I want to make it public. But some credential is saved in the history of my git repo. I want to remove the history of commits and only keep the last commits for all branches. I know that I can do this by below commands.

Checkout

git checkout --orphan latest_branch
Add all the files

git add -A
Commit the changes

git commit -am "commit message"
Delete the branch

git branch -D master
Rename the current branch to master

git branch -m master
Finally, force update your repository

git push -f origin master

but I am worried about other team members. If I follow above steps to clear the history but other team members don't, will they have trouble when they run git pull? Or will they bring the history back when they run git push?


问:
Facebook api swift current user is nil
I have a problem with Facebook api. After login and success unwrapping user token I have a problem with taking user profile: it's nil.

```<code>func updateLoginStatus() {
    if let _ = AccessToken.current {
        let currentUser = UserProfile.current
        userName.text = currentUser?.fullName
        userPictureView = UserProfile.PictureView(frame: blankUserImage.frame, profile: currentUser)
        userPictureView!.clipsToBounds = true
        userPictureView!.layer.cornerRadius = userPictureView!.bounds.width/2
        popUpView.addSubview(userPictureView!)
        isLogged = true
        updateLabels()
    } else {
        isLogged = false
        userPictureView?.removeFromSuperview()
        updateLabels()
    }
}
</code>```

Even if I try to get profile manual by using let userProfile = UserProfile(userId: (AccessToken.current?.userId)!) it also take nil at all parameters, but it have initialized user. Funny part is that with that UserProfile.current it have take user picture. What it can be? How I can get full user name by other methods?

答:
This problem happend in android too.
You should load profile (listen profile change in android) after you got access token.
I write a sample and just tested in swift 3, Facebook iOS SDK 4.21.0.
Then you can got updatedUser.</p>

```<code>if let _ = FBSDKAccessToken.current() {
    if let currentUser = FBSDKProfile.current() {
        print("current user got: \(currentUser)")
    } else {
        print("current user not got")
        FBSDKProfile.loadCurrentProfile(completion: {
            profile, error in
            if let updatedUser = profile {
                print("finally got user: \(updatedUser)")
            } else {
                print("current user still not got")
            }
        })
    }
}
</code>```

Title: Facebook api swift current user is nil

Body:
I have a problem with Facebook api. After login and success unwrapping user token I have a problem with taking user profile: it's nil.

func updateLoginStatus() {
    if let _ = AccessToken.current {
        let currentUser = UserProfile.current
        userName.text = currentUser?.fullName
        userPictureView = UserProfile.PictureView(frame: blankUserImage.frame, profile: currentUser)
        userPictureView!.clipsToBounds = true
        userPictureView!.layer.cornerRadius = userPictureView!.bounds.width/2
        popUpView.addSubview(userPictureView!)
        isLogged = true
        updateLabels()
    } else {
        isLogged = false
        userPictureView?.removeFromSuperview()
        updateLabels()
    }
}

Even if I try to get profile manual by using let userProfile = UserProfile(userId: (AccessToken.current?.userId)!) it also take nil at all parameters, but it have initialized user. Funny part is that with that UserProfile.current it have take user picture. What it can be? How I can get full user name by other methods?

Body:
This problem happend in android too.
You should load profile (listen profile change in android) after you got access token.
I write a sample and just tested in swift 3, Facebook iOS SDK 4.21.0.
Then you can got updatedUser.

if let _ = FBSDKAccessToken.current() {
    if let currentUser = FBSDKProfile.current() {
        print("current user got: \(currentUser)")
    } else {
        print("current user not got")
        FBSDKProfile.loadCurrentProfile(completion: {
            profile, error in
            if let updatedUser = profile {
                print("finally got user: \(updatedUser)")
            } else {
                print("current user still not got")
            }
        })
    }
}


问:
Finding just one or more comma in a string with ColdFusion
How can I detect if a string value only consists of one or more commas and nothing else. The correct value should be something like: ABC,BVC,BNM but sometimes I get value like: , or ,,, or ,, and this is not allowed. How can I detect that a string only have one or more commas and then I can create a warning to the user and stop the process.

Thank you

答:
If you are only concerned about detecting commas (or one or more of any character), just use ListLen().

It's a native ColdFusion function.

It ignores empty list items by default.

Its default delimiter is a comma.

So, if your_string consists only of one or more commas, then ListLen( your_string ) will always return 0.

Heads up, it also returns 0 for an empty string, so if you don't want your code to pop for empty strings, be sure to account for that.


问:
How to add column in table having default datetime value of timestamp
I want to add a column in my table police_publiclocation where column must have 5hr and 30min greater value than current TIMESTAMP value.

I am doing the following but it is not working..
Please provide me some solution.. Thanks in advance..

```<code>ALTER TABLE `police_publiclocation` ADD `datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+CONVERT(Datetime, '2011-09-28 05:30:00',120) AFTER `active`;
</code>```

ERROR:
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '+CONVERT(Datetime, '2011-09-28 05:30:00') AFTER active' at line 1

USING FOLLOWING

MYSQL

phpMyAdmin
Version information: 4.6.6 , latest stable version: 4.7.2

Database server

Server: Localhost via UNIX socket
Server type: MariaDB
Server version: 10.1.20-MariaDB - MariaDB Server
Protocol version: 10
Server charset: UTF-8 Unicode (utf8)

Web server
Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips
Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407 - $
PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation
PHP version: 7.0.8

答:
With MariaDB 10.2, you can have arbitrary expressions in DEFAULT.

Otherwise, consider using a TRIGGER to set it.

Body:
I want to add a column in my table police_publiclocation where column must have 5hr and 30min greater value than current TIMESTAMP value.

I am doing the following but it is not working..
Please provide me some solution.. Thanks in advance..

ALTER TABLE `police_publiclocation` ADD `datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+CONVERT(Datetime, '2011-09-28 05:30:00',120) AFTER `active`;

ERROR:
MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '+CONVERT(Datetime, '2011-09-28 05:30:00') AFTER active' at line 1

USING FOLLOWING

MYSQL

phpMyAdmin
Version information: 4.6.6 , latest stable version: 4.7.2

Database server

Server: Localhost via UNIX socket
Server type: MariaDB
Server version: 10.1.20-MariaDB - MariaDB Server
Protocol version: 10
Server charset: UTF-8 Unicode (utf8)

Web server
Apache/2.4.6 (CentOS) OpenSSL/1.0.1e-fips
Database client version: libmysql - mysqlnd 5.0.12-dev - 20150407 - $
PHP extension: mysqliDocumentation curlDocumentation mbstringDocumentation
PHP version: 7.0.8


问:
How to prevent users from visiting Deleted action method directly?
Scenario:

Clicking a delete hyperlink on one product of a product list will invoke /Product/Delete HttpGet action method. The user then clicks the confirmation button to invoke  /Product/Delete HttpPost action method which in turn redirect the user to /Product/Deleted HttpGet action method.

I want to prevent users from skipping /Product/Delete and  directly invoking /Product/Deleted.

答:
Before redirecting put something into TempData. Then in the Deleted action verify if this something is present in the TempData.

```<code>[HttpPost]
public ActionResult Delete()
{
    // TODO: Delete
    TempData["deleted"] = true;
    return RedirectToAction("deleted");
}

public ActionResult Deleted()
{
    if(TempData["deleted"] == null)
    {
        throw new HttpException(404, "not found");
    }
    return View();
}
</code>```

You should be aware that there is a price to pay with this. If the user presses F5 while browsing the /product/deleted action he will get 404. So basically what you are trying to do is bad design and I would recommend you avoiding it.

ContentLicense: CC BY-SA 2.5

Body:
Before redirecting put something into TempData. Then in the Deleted action verify if this something is present in the TempData.

[HttpPost]
public ActionResult Delete()
{
    // TODO: Delete
    TempData["deleted"] = true;
    return RedirectToAction("deleted");
}

public ActionResult Deleted()
{
    if(TempData["deleted"] == null)
    {
        throw new HttpException(404, "not found");
    }
    return View();
}

You should be aware that there is a price to pay with this. If the user presses F5 while browsing the /product/deleted action he will get 404. So basically what you are trying to do is bad design and I would recommend you avoiding it.


问:
How to return multiple values within a group of rows.
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

```<code>TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6
</code>```

I want to see the results:

```<code>ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6
</code>```

I have tried:

```<code>select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )
</code>```

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.

答:
```<code>SELECT *
 FROM Table D WHERE
  ConfigID = (SELECT MAX(ConfigID) FROM Table
   WHERE Location=D.Location )
        Union
Select * From Table
   Where ConfigID Is NULL
order by Location
</code>```

Body:
I have tried to use Max(), subqueries, and joins, but my knowledge is limited enough that I am not sure how to organize them. I was willing to just use several nested select statements, knowing it could be resource intensive, but I can't get it to work.

I need to return any nulls, as well as the highest ConfigID for each Location.

TABLE
ID     Location     ConfigID
1      AA           NULL
2      AA           2
3      AA           1
4      BB           5
5      BB           4
6      BB           3
7      CC           NULL
8      CC           6

I want to see the results:

ID     Location     ConfigID
1      AA           NULL
2      AA           2
4      BB           5
7      CC           NULL
8      CC           6

I have tried:

select ID, Location, ConfigID
from Table
where ConfigID is null
      or configID = (select ConfigID
                     from table
                     where Location in (select distinct Location
                                        from Table
                                        order by ConfigID desc
                                        )
                     )

SQL server didn't like that because I cannot have an order by in a subquery unless Top is used. Now that I am looking at it again, I don't think that the order by is even within the correct subquery. It was as close as I could get. I was hopeful when I saw Select Max from each subset, but that was a dead-end, I think. Also, I don't believe that a self-join will work because the data I would self-join on is all in one column.


问:
Delay in Rendering a Component?
I'm attempting to make my own personal website, and trying to use React to do so. In the process, I intend to make each section a different React Component. My plan is to have the navbar at the top be able to select which component is currently "active", and actually gets rendered and shown. In addition, when switching to a new section, I would like the old component to have a "leaving" animation, and the new component to have an "entering" animation (these are done with react-motion). However, currently both the entering and leaving are done at the same time, because I'm changing the active state for both components at the same time. Is there any way to delay one component becomes active after another one becoming inactive?

The parent component that houses each section looks like so:

```<code>class Website extends React.Component {

  constructor(props){
    super(props)
    this.state = {
    homeActive: true,
    aboutActive: false
  }

  homeActivator(){
    this.setState({
      homeActive: true,
      aboutActive: false
    })
  }

  aboutActivator(){
    this.setState({
      homeActive: false,
      aboutActive: true
    })
  }

  render(){
    return (
      <div>
        <NavBar handleHome={this.homeActivator.bind(this)} handleAbout=
          {this.aboutActivator.bind(this)}/>
        <Home active={this.state.homeActive} />
        <About active={this.state.aboutActive} />
      </div>
}
</code>```

And then one of the "sections" would look like so:

```<code>class Home extends React.Component{

  render() {
    let content = (
      <div>
        Home
      </div>
    )

    if (!this.props.active){
      return (
        //Some jsx that results in the content leaving the page
      )
    }

    return(
      //Some jsx that results in the content entering the page
    )
  }
}
</code>```

答:
I did not have a ton of time to answer this, but came up with the best example I could. It's not an exact replica of what you are looking to do, but is very similar, so if you understand it, you will be able to figure out your problem quite easily.

To make things a little easier to understand, I am mimicking components with methods placed inside the React Class. Obviously in the real world, you would be importing your components from other files. I'm sure you'll understand what's going on.

```<code>export default class Example extends Component {
  constructor(props) {
    super(props)

    this.state = {
      c1: true,
      c2: false
    }
  }

  // Component One
  renderc1() {
    return (
      <div>
        I am component one
      </div>
    )
  }

  // Component Two
  renderc2() {
    return (
      <div>
        I am component two
      </div>
    )
  }

  changeComponents = () => {
    this.setState({ c1: false })

    setTimeout(() => {
      this.setState({ c2: true })
    }, 1500)
  }

  render() {
    return (
      <div className="example">

        {this.state.c1 ? this.renderc1() : null}
        {this.state.c2 ? this.renderc2() : null}

        <button onClick={this.changeComponents}>Click me</button>

      </div>
    )
  }
}
</code>```

Clicking the button will fire off the changeComponents function, which will then immediately set the state of "c1" to false. A setTimeout after that ensures that component 2 will be delayed rendering to the screen.

Notice the arrow syntax, I used, which binds the this keyword to the class, so you don't have to worry about writing bind this everywhere.

Title: Delay in Rendering a Component?

Body:
I'm attempting to make my own personal website, and trying to use React to do so. In the process, I intend to make each section a different React Component. My plan is to have the navbar at the top be able to select which component is currently "active", and actually gets rendered and shown. In addition, when switching to a new section, I would like the old component to have a "leaving" animation, and the new component to have an "entering" animation (these are done with react-motion). However, currently both the entering and leaving are done at the same time, because I'm changing the active state for both components at the same time. Is there any way to delay one component becomes active after another one becoming inactive?

The parent component that houses each section looks like so:

class Website extends React.Component {

  constructor(props){
    super(props)
    this.state = {
    homeActive: true,
    aboutActive: false
  }

  homeActivator(){
    this.setState({
      homeActive: true,
      aboutActive: false
    })
  }

  aboutActivator(){
    this.setState({
      homeActive: false,
      aboutActive: true
    })
  }

  render(){
    return (

        <NavBar handleHome={this.homeActivator.bind(this)} handleAbout=
          {this.aboutActivator.bind(this)}/>
        <Home active={this.state.homeActive} />
        <About active={this.state.aboutActive} />

}

And then one of the "sections" would look like so:

class Home extends React.Component{

  render() {
    let content = (

        Home

    )

    if (!this.props.active){
      return (
        //Some jsx that results in the content leaving the page
      )
    }

    return(
      //Some jsx that results in the content entering the page
    )
  }
}

Body:
I did not have a ton of time to answer this, but came up with the best example I could. It's not an exact replica of what you are looking to do, but is very similar, so if you understand it, you will be able to figure out your problem quite easily.

To make things a little easier to understand, I am mimicking components with methods placed inside the React Class. Obviously in the real world, you would be importing your components from other files. I'm sure you'll understand what's going on.

export default class Example extends Component {
  constructor(props) {
    super(props)

    this.state = {
      c1: true,
      c2: false
    }
  }

  // Component One
  renderc1() {
    return (
      <div>
        I am component one
      </div>
    )
  }

  // Component Two
  renderc2() {
    return (
      <div>
        I am component two
      </div>
    )
  }

  changeComponents = () => {
    this.setState({ c1: false })

    setTimeout(() => {
      this.setState({ c2: true })
    }, 1500)
  }

  render() {
    return (
      <div className="example">

        {this.state.c1 ? this.renderc1() : null}
        {this.state.c2 ? this.renderc2() : null}

        <button onClick={this.changeComponents}>Click me</button>

      </div>
    )
  }
}

Clicking the button will fire off the changeComponents function, which will then immediately set the state of "c1" to false. A setTimeout after that ensures that component 2 will be delayed rendering to the screen.

Notice the arrow syntax, I used, which binds the this keyword to the class, so you don't have to worry about writing bind this everywhere.


问:
Can not get a styled anchor tag to display the proper height and width attributes for a simulated button in email on Outlook 2013 for Windows
My code does work properly in Outlook 15.33 for Mac. Buttons take the height and width of the linked text in the Windows version of Outlook. I have tried setting the buttons as  tags and  tags, but I have the same formatting issues on the Windows version of Outlook.</p>

```<code><table class="fullwidth260" border="0" width="215" cellspacing="0" cellpadding="5" align="left">
<tbody>
<tr>
<td valign="middle">
<a class="quickLinks" href="http://www.mba.org" style="display: flex; text-align: center; padding: 10px 20px 10px 20px; color: #496f8d; font-family: Arial, san-serif; size: 10pt; line-height: 1.2; border: 1px solid #c8d3dc; background-color: #e3e9ed; text-decoration: none; height: 60px; width: 160px; justify-content: center; flex-direction: column;">STATE RELATIONS ONLINE COMMUNITY</a>
</td>
</tr>
</tbody>
</table>
</code>```

答:
Give this method a try. I found it to work on all email clients that i know off. You will need to change the background color of the td, background color of the anchor tag, stroke color and the width of the button.

                      Get Started!

```

Let me know if this helps.

Body:
My code does work properly in Outlook 15.33 for Mac. Buttons take the height and width of the linked text in the Windows version of Outlook. I have tried setting the buttons as  tags and  tags, but I have the same formatting issues on the Windows version of Outlook.

STATE RELATIONS ONLINE COMMUNITY

Body:
Give this method a try. I found it to work on all email clients that i know off. You will need to change the background color of the td, background color of the anchor tag, stroke color and the width of the button.

<table border="0" cellpadding="0" cellspacing="0" style="margin:0 auto;">
                <tr>
                  <td align="center" bgcolor="#87be45" width="150" style="-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;">
                    <a href="http://www.example.com" style="padding: 10px;width:150px;display: block;text-decoration: none;border:0;text-align: center;font-weight: bold;font-size: 15px;font-family: sans-serif;color: #ffffff;background: #87be45;border: 1px solid #87be45;-moz-border-radius: 4px; -webkit-border-radius: 4px; border-radius: 4px;line-height:17px;" class="button_link">
                      Get Started!
                    </a>
                  </td>
                </tr>
              </table>

Let me know if this helps.


问:
I don't understand how to use document.getElementById(‘id’).onclick
I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.

I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.

If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.

Here is my code

```<code><nav>
      <button class="nav-button" id="nav">
        <div class="menu-button"></div>
        <div class="menu-button"></div>
        <div class="menu-button"></div>
      </button>
      <div class="dropdown-menu" id="dropdown">
        <a href="#">Hello</a>
        <a href="#">Hello</a>
        <a href="#">Hello</a>
      </div>
    </nav>

.nav-button {
  background: none;
  border: none;
  margin-left: 1em;
  padding-top: 12px;
  cursor: pointer;
}

.menu-button {
  background-color: #fff;
  width: 30px;
  height: 4px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.dropdown-menu {
  margin-top: 7px;
  width: 100px;
  background-color: #fff;
  display: none;
}

.showDropDown {
  display: block;
}

function showDropDown() {
  document.getElementById('dropdown').classList.toggle("showDropDown");
}

document.getElementById("nav").onclick = function showDropDown()
</code>```

Here is a codepen

Thanks for your help!

答:
Having it in a separate js file should work you just need to import the js file using the script tag. You should probably do this at the end of the HTML to guarantee that the js is ran after the DOM is loaded.

Update Your missing the brackets around the function call:

document.getElementById("nav").onclick = function() { showDropDown(); };

Body:
I'm learning javascript right now and I am just building a simple menu that will show when the nav button is clicked.

I don't understand how to use the document.getElementById(‘id’).onclick when in a separated js file that is linked to my html. Reading around I think I understand that my problem is that you cannot call onclick out the blue because the DOM element are not yet defined.. or something alone those line. I just don't understand then how to proceed.

If I add within my button html tag onclick="function()" it works, but it don't when I add it within my separate js file. I'm using the W3school tutorial found here.

Here is my code

      <button class="nav-button" id="nav">

      </button>

        Hello
        Hello
        Hello

.nav-button {
  background: none;
  border: none;
  margin-left: 1em;
  padding-top: 12px;
  cursor: pointer;
}

.menu-button {
  background-color: #fff;
  width: 30px;
  height: 4px;
  margin-bottom: 5px;
  border-radius: 5px;
}

.dropdown-menu {
  margin-top: 7px;
  width: 100px;
  background-color: #fff;
  display: none;
}

.showDropDown {
  display: block;
}

function showDropDown() {
  document.getElementById('dropdown').classList.toggle("showDropDown");
}

document.getElementById("nav").onclick = function showDropDown()

Here is a codepen

Thanks for your help!


问:
Split my file into 128 bytes using c++
I am new to C++, and I need to make a program to read a file and divide it into blocks of 214 bytes. In Java, I used readAllBytes() like this:

byte[] data= Files.readAllBytes(path);
for (int i = 0; i < data.length; i += 215) {
    byte[] data1 = Arrays.copyOfRange(data, i, i + 214);
}
```

<p>Now, in C++, I read the file into a buffer, but I dont have a clue how to divide the buffer into blocks of 214 bytes:</p>

<pre class="lang-cpp prettyprint-override"><code>#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{

    FILE *fileptr;
    char *buffer;
    long filelen;

    fileptr = fopen("test.txt", "rb");
    fseek(fileptr, 0, SEEK_END);
    filelen = ftell(fileptr);
    rewind(fileptr);
    buffer = (char *)malloc((filelen + 1) * sizeof(char));
    fread(buffer, filelen, 1, fileptr);
    cout << buffer;

    fclose(fileptr);
    return 0;
}
</code>```

Can anyone help me make this program, please?

答:
After closing file:</p>

```<code>char buff128[128];
long done = 0;
while (done < filelen)
{
    long available = min(128, filelen - done);
    memcpy(buffer + done, buff128, available);
    done += available;
    // Do whatever with buff128
}
</code>```

Title: Split my file into 128 bytes using c++

Body:
I am new to C++, and I need to make a program to read a file and divide it into blocks of 214 bytes. In Java, I used readAllBytes() like this:

byte[] data= Files.readAllBytes(path);
for (int i = 0; i < data.length; i += 215) {
    byte[] data1 = Arrays.copyOfRange(data, i, i + 214);
}

Now, in C++, I read the file into a buffer, but I dont have a clue how to divide the buffer into blocks of 214 bytes:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{

    FILE *fileptr;
    char *buffer;
    long filelen;

    fileptr = fopen("test.txt", "rb");
    fseek(fileptr, 0, SEEK_END);
    filelen = ftell(fileptr);
    rewind(fileptr);
    buffer = (char *)malloc((filelen + 1) * sizeof(char));
    fread(buffer, filelen, 1, fileptr);
    cout << buffer;

    fclose(fileptr);
    return 0;
}

Can anyone help me make this program, please?

Body:
After closing file:

char buff128[128];
long done = 0;
while (done < filelen)
{
    long available = min(128, filelen - done);
    memcpy(buffer + done, buff128, available);
    done += available;
    // Do whatever with buff128
}


问:
Golang - DTOs, Entities and Mapping
I am new to Go having come from a C# background, and I am just plain confused about structure a Go application.

Say I am building a REST API that will sit on top of a database. Also, say that, even after it is complete, this application could need to change somewhat frequently given the vicissitudes of the business, etc.

In C#, with tools like Entity Framework and DTOs, I somewhat alleviate this problem by abstracting the database from the results given by the controllers. If I change the name of a bunch of fields in the database, I might have to change my database access logic. Still, hopefully, the DTOs that I map to my entities using AutoMapper can remain the same, so I don't break frontend functionality that relies on a given DTO structure.

Should I replicate this structure with Go's structs? Something about such an approach seems wrong given that structs are just DTOs, and I will have quite a few DTO structs that are identical to the entity structs. I also have to setup logic to map entities to DTOs. This all just feels very unidiomatic somehow, and many of the examples I see on the web just serialize the database structs.

In short, how do people avoid excessive coupling between their API and the database in Go, and how would they broadly go about separating out the different parts of the application?

If it makes any difference, I am planning to use sqlx to marshal database results into structs which will mean more tags in addition to the JSON ones if I don't separate entities from DTOs.

答:
In the case of a REST API, you'll typically deal with at least three different implementation layers:

HTTP handler

some sort of business logic/use case

persistent storage/database interface

You can treat and build each of these separately which does not only decouple it but makes it just a lot more testable, too. These parts then are put together by injecting the necessary bits since they conform to interfaces you define. Usually this ends up leaving the main or a separate configuration mechanism the only place that's aware of what is combined and injected how.

The article Applying The Clean Architecture to Go applications illustrates very well how the various parts can be separated. How strictly you should follow this approach depends a little on the complexity of your project.

Below is a very basic breakdown, separating the handler from logic and database layer.

HTTP handler

The handler does nothing else than mapping the request values into local variables or possibly custom data structures if needed. In addition to that it just runs the use case logic and maps the result before writing it to the response. This is also a good place to map different errors to different response objects.

```<code>type Interactor interface {
    Bar(foo string) ([]usecases.Bar, error)
}

type MyHandler struct {
    Interactor Interactor
}

func (handler MyHandler) Bar(w http.ResponseWriter, r *http.Request) {
    foo := r.FormValue("foo")
    res, _ := handler.Interactor.Bar(foo)

    // you may want to map/cast res to a different type that is encoded
    // according to your spec
    json.NewEncoder(w).Encode(res)
}
</code>```

Unit tests are a great way to test that the HTTP response contains the correct data for different results and errors.

Use case / business logic

Since the repository is just specified as an interface it's very easy to create unit tests for the business logic with different results returned by a mock repository implementation that also conforms to DataRepository.

```<code>type DataRepository interface {
    Find(f string) (Bar, error)
}

type Bar struct {
    Identifier string
    FooBar     int
}

type Interactor struct {
    DataRepository DataRepository
}

func (interactor *Interactor) Bar(f string) (Bar, error) {
    b := interactor.DataRepository.Find(f)

    // ... custom logic

    return b
}
</code>```

Database interface

The part talking to the database implements the DataRepository interface but is otherwise totally independent on how it turns the data into the expected types.

```<code>type Repo {
    db sql.DB
}

func NewDatabaseRepo(db sql.DB) *Repo {
    // config if necessary...

    return &Repo{db: db}
}

func (r Repo)Find(f string) (usecases.Bar, error) {
    rows, err := db.Query("SELECT id, foo_bar FROM bar WHERE foo=?", f)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
        var id string, fooBar int
        if err := rows.Scan(&id, &fooBar); err != nil {
            log.Fatal(err)
        }
        // map row value to desired structure
        return usecases.Bar{Identifier: id, FooBar: fooBar}
    }

    return errors.New("not found")
}
</code>```

Again, this allows testing the database operations separately without the need of any mock SQL statements.

Note: The code above is very much pseudo code and incomplete.

ContentLicense: CC BY-SA 4.0

Title: Golang - DTOs, Entities and Mapping

Body:
In the case of a REST API, you'll typically deal with at least three different implementation layers:

HTTP handler

some sort of business logic/use case

persistent storage/database interface

You can treat and build each of these separately which does not only decouple it but makes it just a lot more testable, too. These parts then are put together by injecting the necessary bits since they conform to interfaces you define. Usually this ends up leaving the main or a separate configuration mechanism the only place that's aware of what is combined and injected how.

The article Applying The Clean Architecture to Go applications illustrates very well how the various parts can be separated. How strictly you should follow this approach depends a little on the complexity of your project.

Below is a very basic breakdown, separating the handler from logic and database layer.

HTTP handler

The handler does nothing else than mapping the request values into local variables or possibly custom data structures if needed. In addition to that it just runs the use case logic and maps the result before writing it to the response. This is also a good place to map different errors to different response objects.

type Interactor interface {
    Bar(foo string) ([]usecases.Bar, error)
}

type MyHandler struct {
    Interactor Interactor
}

func (handler MyHandler) Bar(w http.ResponseWriter, r *http.Request) {
    foo := r.FormValue("foo")
    res, _ := handler.Interactor.Bar(foo)

    // you may want to map/cast res to a different type that is encoded
    // according to your spec
    json.NewEncoder(w).Encode(res)
}

Unit tests are a great way to test that the HTTP response contains the correct data for different results and errors.

Use case / business logic

Since the repository is just specified as an interface it's very easy to create unit tests for the business logic with different results returned by a mock repository implementation that also conforms to DataRepository.

type DataRepository interface {
    Find(f string) (Bar, error)
}

type Bar struct {
    Identifier string
    FooBar     int
}

type Interactor struct {
    DataRepository DataRepository
}

func (interactor *Interactor) Bar(f string) (Bar, error) {
    b := interactor.DataRepository.Find(f)

    // ... custom logic

    return b
}

Database interface

The part talking to the database implements the DataRepository interface but is otherwise totally independent on how it turns the data into the expected types.

type Repo {
    db sql.DB
}

func NewDatabaseRepo(db sql.DB) *Repo {
    // config if necessary...

    return &Repo{db: db}
}

func (r Repo)Find(f string) (usecases.Bar, error) {
    rows, err := db.Query("SELECT id, foo_bar FROM bar WHERE foo=?", f)
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    for rows.Next() {
        var id string, fooBar int
        if err := rows.Scan(&id, &fooBar); err != nil {
            log.Fatal(err)
        }
        // map row value to desired structure
        return usecases.Bar{Identifier: id, FooBar: fooBar}
    }

    return errors.New("not found")
}

Again, this allows testing the database operations separately without the need of any mock SQL statements.

Note: The code above is very much pseudo code and incomplete.


答:
just instead of

```<code>document.getElementById("nav").onclick = function showDropDown()
</code>```

replace it with

```<code>document.getElementById("nav").onclick = showDropDown
</code>```

because the onclick accepts function and you'r already defined this function

Title: I don't understand how to use document.getElementById(‘id’).onclick

Body:
just instead of

document.getElementById("nav").onclick = function showDropDown()

replace it with

document.getElementById("nav").onclick = showDropDown

because the onclick accepts function and you'r already defined this function


问:
How to do a nightly build using Gradle?
I can build my android project in command line with ./gradlew assembleDebug but how do I automate this so Gradle builds itself once every day? Is there any way to do this without downloading something additional like Jenkins?</p>

答: If you're on Linux and can do it from the command line, you should look into CRON. That's built into every Linux install I've ever seen.</p>

Title: How to do a nightly build using Gradle?


问:
How to use onclick on html attributes inside JSX with Typescript
Typesript is giving the following error when attempting to use onclick on any HTML element I use.

```<code>ERROR in /Volumes/WorkSpace/Projects/wirecash-client/src/elements/dropdown/Dropdown.tsx
(25,45): error TS2339: Property 'onclick' does not exist on type 'HTMLProps<HTMLButtonElement>'.
</code>```

My component:

```<code>import React from 'react'
import { ClientTypes } from 'types'

interface Props {
  items: Array<ClientTypes.DropdownItem>
  onClick(item:ClientTypes.DropdownItem): () => void
}

const Dropdown = ({onClick, items}) => {
  let selectedItem = null;
  for(let i=0, j=items.length; i<j; i++) {
    if(items[i].selected) {
      selectedItem = items[i];
      break;
    }
  }
  return (
    <div className="dropdown show">
      <a className="btn btn-secondary dropdown-toggle" aria-haspopup="true" aria-expanded="false">
        {selectedItem.name}
      </a>

      <div className="dropdown-menu" aria-labelledby="dropdownMenuLink">
        {items.map((item) => (
          <button className="dropdown-item" onclick={onClick(item)}>
            Action
          </button>
        ))}
      </div>
    </div>
  )
}

export default Dropdown
</code>```

答:
The onclick attribute must be camel cased onClick

This works!

```<code><button className="dropdown-item" onClick={() => onClick(item)}>
  Action
</button>
</code>```

Body:
Typesript is giving the following error when attempting to use onclick on any HTML element I use.

ERROR in /Volumes/WorkSpace/Projects/wirecash-client/src/elements/dropdown/Dropdown.tsx
(25,45): error TS2339: Property 'onclick' does not exist on type 'HTMLProps<HTMLButtonElement>'.

My component:

import React from 'react'
import { ClientTypes } from 'types'

interface Props {
  items: Array<ClientTypes.DropdownItem>
  onClick(item:ClientTypes.DropdownItem): () => void
}

const Dropdown = ({onClick, items}) => {
  let selectedItem = null;
  for(let i=0, j=items.length; i<j; i++) {
    if(items[i].selected) {
      selectedItem = items[i];
      break;
    }
  }
  return (

        {selectedItem.name}

        {items.map((item) => (
          <button className="dropdown-item" onclick={onClick(item)}>
            Action
          </button>
        ))}

  )
}

export default Dropdown

Body:
The onclick attribute must be camel cased onClick

This works!

<button className="dropdown-item" onClick={() => onClick(item)}>
  Action
</button>


问:
MVC5 Azure Blobs and Models
Hello I have functionality to save text and image from forms to Azure SQL db  (text) and to Azure Blobs for my images. Also it's hosted in cloud in Azure and saving and uploading works fine. Running on the usual stack C# EF MVC5 Bootstrap Vanilla js and Azure Blobs Webrole etc.

I am stuck on an area I can't seem to figure out - display my view model (this is a viewmodel with two EF objects i.e. two database tables) together with the blob list (Azure blob object). Due to them not being same context types technically is the issue, but how can we combine the two and output like so:

Return View(jobsVModel + Blobs);

Here is my current working:
Model:

```<code>namespace client.Models
{
    public class JoinUsersandJobsModel : DbContext
    {

        public tradesusers tradesusers { get; set; }
        public jobs jobs { get; set; }
        public uploadedfiles uploadedfiles { get; set; }
        //add a blob service to our model
        //public BlobProfileImageServices _blobServices = new BlobProfileImageServices();

    }

}
</code>```

The I have my Controller:

```<code>private traderEntities db = new traderEntities();
BlobProfileImageServices _blobServices = new BlobProfileImageServices();
    public ActionResult Index(string usernameCookie)
        {

            var viewModel = from u in db.tradesusers
                            join j in db.jobs on u.id equals j.jobbyuserid
                            join pic in db.uploadedfiles on j.id equals pic.ImageId
                            where u.email.Equals(usernameCookie)
                            select new JoinUsersandJobsModel { tradesusers = u, jobs = j, uploadedfiles = pic };

            //blob container
            List<ImageVM> images;

            CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
            List<string> blobs = new List<string>();
            foreach (var blobItem in blobContainer.ListBlobs())
            {
                blobs.Add(blobItem.Uri.ToString());

            }

            images = blobs
               // convert an Azure blob record into an ImageVM:
               .Select(b => new ImageVM()
               {

               })
               .ToList();

            //return View(blobs);

            //return View(imageModel);

            //List<Object> allS = (from x in viewModel select (Object)x).ToList();
            //allS.AddRange((from x in blobs select (Object)x).ToList());

            return View(images);
            //return View(db.tradesusers.ToList());
        }
</code>```

As you can see above I want to return the two objects, one of which is called 'blobs' and the second called 'viewModel' together at the same time to my view but we can see they're are two different object types! 'Return View(viewModel.ToList());' alone works, so does 'Return View(blobs);'.

My View:

```<code>@model IEnumerable<traderclient.Models.JoinUsersandJobsModel>
<--!@model2 List<traderclient.Models.ImageVM>-->

@{
    ViewBag.Title = "Profile";
}

        <!DOCTYPE html>

        <html>
        <head>
            <meta name="viewport" content="width=device-width" />
            <title>system - Client's Profile</title>
        </head>
        <body>

            <br /><br /><br /><br /><br />
            <h1>Profile</h1>

                @foreach (var item in Model)
                {

                    <div>
                        <h5> Profile pic</h5>

                        <hr />

                        <dl class="dl-horizontal">
                            <dt>
                                Pic
                            </dt>

                            <dt>

                            </dt>

                            <dd>

                                <img src="@Url.Content(@item.uploadedfiles.ImagePath+@item.uploadedfiles.ImageName)" width="250" height="250" multiple />

                            </dd>

                        </dl>
                        <p>
                            @Html.ActionLink("Edit", "Edit", new { id = @item }) |
                            @Html.ActionLink("Back to List", "Index")
                        </p>
                    </div>          }

            <table>
                <tr>
                    <td>
                        <table class="table" style="width:200px;">
                            <tr>
                                <td style="width:50%"> Image </td>
                                <td style="width:25%"> Delete </td>
                            </tr>

                            <ul style="list-style-type:none; padding:0;">
                                @foreach (var item in model2)
                                {
                                    <tr>
                                        <td> <img src="@item." alt="image here is" width="100" height="100" /> </td>
                                        <td> <input type="button" id="@item." onclick="deleteImage('@item');" value="Delete" /></td>
                                    </tr>
                                }
                            </ul>
                        </table>
                    </td>
                    <td style="width:100px"></td>
                </tr>

            </table>
</code>```

Again above in the View using only ONE Model definition works so i.e. the IEnumerable for the jobs or tradesusers tables or if I ONLY use the List object for the Blob image object that works too. But like the controller I cannot combine the two. As I've previously mentioned the rest of data (all data apart from the blob) all resides in the Azure SQL database. Only the images live in the Azure Blobs.

Don't forget my definition for my Blobs which resides in this project's root too as a separate class:

答:
You shouldn't use your internal objects (be it Microsoft.WindowsAzure.Storage.* objects) or your own database entities) as ViewModels - you should create new ViewModel classes for each logical view component (view, partial, repeated element, etc) and populate them inside your Controller actions with data from your internal objects.

For example, if you have a View which shows a list of images, then it would be like this:

```<code>class ImagesController : Controller {

    public ActionResult Index() {

        List<ImageVM> images;
        if( useAzure ) {

            List<CloudStorageBlob> blobs = GetBlobs( ... );
            images = blobs
                // convert an Azure blob record into an ImageVM:
                .Select( b => new ImageVM()
                {
                    Url = b.BlobUrl
                } )
                .ToList();
        }
        else { // use local SQL

            List<MyImageEntity> dbImages = GetImagesFromDB( ... );
            images = dbImages
                // convert a database MyImageEntity into an ImageVM:
                .Select( i => new ImageVM()
                {
                    Url = i.ImageAddress
                } )
                .ToList();
        }

        return this.View( images );
    }
}
</code>```

ViewModels:

```<code>public class ImageVM {
    public String Url { get; set; }
    public String TitleText { get; set; }
    public String Etc { get; set; }
}
</code>```

View:

```<code>@model List<ImageVM>

<ul>
@foreach(ImageVM image in this.Model) {
    <li><img src="@image.Url" title="@image.TitleText" /></li>
}
</ul>
</code>```

Title: MVC5 Azure Blobs and Models

Body:
Hello I have functionality to save text and image from forms to Azure SQL db  (text) and to Azure Blobs for my images. Also it's hosted in cloud in Azure and saving and uploading works fine. Running on the usual stack C# EF MVC5 Bootstrap Vanilla js and Azure Blobs Webrole etc.

I am stuck on an area I can't seem to figure out - display my view model (this is a viewmodel with two EF objects i.e. two database tables) together with the blob list (Azure blob object). Due to them not being same context types technically is the issue, but how can we combine the two and output like so:

Return View(jobsVModel + Blobs);

Here is my current working:
Model:

namespace client.Models
{
    public class JoinUsersandJobsModel : DbContext
    {

        public tradesusers tradesusers { get; set; }
        public jobs jobs { get; set; }
        public uploadedfiles uploadedfiles { get; set; }
        //add a blob service to our model
        //public BlobProfileImageServices _blobServices = new BlobProfileImageServices();

    }

}

The I have my Controller:

private traderEntities db = new traderEntities();
BlobProfileImageServices _blobServices = new BlobProfileImageServices();
    public ActionResult Index(string usernameCookie)
        {

            var viewModel = from u in db.tradesusers
                            join j in db.jobs on u.id equals j.jobbyuserid
                            join pic in db.uploadedfiles on j.id equals pic.ImageId
                            where u.email.Equals(usernameCookie)
                            select new JoinUsersandJobsModel { tradesusers = u, jobs = j, uploadedfiles = pic };

            //blob container
            List<ImageVM> images;

            CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
            List<string> blobs = new List<string>();
            foreach (var blobItem in blobContainer.ListBlobs())
            {
                blobs.Add(blobItem.Uri.ToString());

            }

            images = blobs
               // convert an Azure blob record into an ImageVM:
               .Select(b => new ImageVM()
               {

               })
               .ToList();

            //return View(blobs);

            //return View(imageModel);

            //List<Object> allS = (from x in viewModel select (Object)x).ToList();
            //allS.AddRange((from x in blobs select (Object)x).ToList());

            return View(images);
            //return View(db.tradesusers.ToList());
        }

As you can see above I want to return the two objects, one of which is called 'blobs' and the second called 'viewModel' together at the same time to my view but we can see they're are two different object types! 'Return View(viewModel.ToList());' alone works, so does 'Return View(blobs);'.

My View:

@model IEnumerable<traderclient.Models.JoinUsersandJobsModel>
<--!@model2 List<traderclient.Models.ImageVM>-->

@{
    ViewBag.Title = "Profile";
}

        <!DOCTYPE html>

            <meta name="viewport" content="width=device-width" />
            <title>system - Client's Profile</title>

Profile

                @foreach (var item in Model)
                {

 Profile pic

                                Pic

                            @Html.ActionLink("Edit", "Edit", new { id = @item }) |
                            @Html.ActionLink("Back to List", "Index")

          }

                                 Image
                                 Delete

                                @foreach (var item in model2)
                                {

                                         <input type="button" id="@item." onclick="deleteImage('@item');" value="Delete" />

                                }

Again above in the View using only ONE Model definition works so i.e. the IEnumerable for the jobs or tradesusers tables or if I ONLY use the List object for the Blob image object that works too. But like the controller I cannot combine the two. As I've previously mentioned the rest of data (all data apart from the blob) all resides in the Azure SQL database. Only the images live in the Azure Blobs.

Don't forget my definition for my Blobs which resides in this project's root too as a separate class:

Body:
You shouldn't use your internal objects (be it Microsoft.WindowsAzure.Storage.* objects) or your own database entities) as ViewModels - you should create new ViewModel classes for each logical view component (view, partial, repeated element, etc) and populate them inside your Controller actions with data from your internal objects.

For example, if you have a View which shows a list of images, then it would be like this:

class ImagesController : Controller {

    public ActionResult Index() {

        List<ImageVM> images;
        if( useAzure ) {

            List<CloudStorageBlob> blobs = GetBlobs( ... );
            images = blobs
                // convert an Azure blob record into an ImageVM:
                .Select( b => new ImageVM()
                {
                    Url = b.BlobUrl
                } )
                .ToList();
        }
        else { // use local SQL

            List<MyImageEntity> dbImages = GetImagesFromDB( ... );
            images = dbImages
                // convert a database MyImageEntity into an ImageVM:
                .Select( i => new ImageVM()
                {
                    Url = i.ImageAddress
                } )
                .ToList();
        }

        return this.View( images );
    }
}

ViewModels:

public class ImageVM {
    public String Url { get; set; }
    public String TitleText { get; set; }
    public String Etc { get; set; }
}

View:

@model List<ImageVM>

<ul>
@foreach(ImageVM image in this.Model) {
    <li><img src="@image.Url" title="@image.TitleText" /></li>
}
</ul>


问:
R Split String By Delimiter in a column
I have a file with several lines. For example

```<code>A               B       C
awer.ttp.net    Code    554
abcd.ttp.net    Code    747
asdf.ttp.net    Part    554
xyz.ttp.net     Part    747
</code>```

I want to use R to split just column A of the table and I want a new column added to the table D, with values awe, abcd, asdf, and xyz.  Would prefer this to be done using dplyr.

答:
You can use mutate and gsub:

```<code>library(dplyr)
df = df %>% mutate(D=gsub("\\..*","",A))

              A    B   C    D
   awer.ttp.net Code 554 awer
   abcd.ttp.net Code 747 abcd
   asdf.ttp.net Part 554 asdf
    xyz.ttp.net Part 747  xyz
</code>```

Title: R Split String By Delimiter in a column

Body:
I have a file with several lines. For example

A               B       C
awer.ttp.net    Code    554
abcd.ttp.net    Code    747
asdf.ttp.net    Part    554
xyz.ttp.net     Part    747

I want to use R to split just column A of the table and I want a new column added to the table D, with values awe, abcd, asdf, and xyz.  Would prefer this to be done using dplyr.

Body:
You can use mutate and gsub:

library(dplyr)
df = df %>% mutate(D=gsub("\\..*","",A))

              A    B   C    D
   awer.ttp.net Code 554 awer
   abcd.ttp.net Code 747 abcd
   asdf.ttp.net Part 554 asdf
    xyz.ttp.net Part 747  xyz


答:
Here is a solution, using buffer reads of 214:

```<code>static const size_t BLOCK_SIZE = 214U;
char buffer[BLOCK_SIZE];
std::ifstream input("test.txt", std::ios::binary)
while (input.read(&buffer[0], BLOCK_SIZE))
{
  const size_t characters_read = input.gcount();
  Process_Buffer(buffer, characters_read);
}
</code>```

The above examples uses the block reading capability by using the read method.

The array is declared before the input so that there is only one allocation.

The array can be passed to a function for processing.

Title: Split my file into 128 bytes using c++

Body:
Here is a solution, using buffer reads of 214:

static const size_t BLOCK_SIZE = 214U;
char buffer[BLOCK_SIZE];
std::ifstream input("test.txt", std::ios::binary)
while (input.read(&buffer[0], BLOCK_SIZE))
{
  const size_t characters_read = input.gcount();
  Process_Buffer(buffer, characters_read);
}

The above examples uses the block reading capability by using the read method.

The array is declared before the input so that there is only one allocation.

The array can be passed to a function for processing.


问:
Import error for matplotlib.pyplot
I saw similar posts, but the error given when I tried to run import matplotlib.pyplot as plt was different:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 16, in <module>
    from .backend_qt5 import QtCore
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 26, in <module>
    import matplotlib.backends.qt_editor.figureoptions as figureoptions
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/qt_editor/figureoptions.py", line 20, in <module>
    import matplotlib.backends.qt_editor.formlayout as formlayout
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/qt_editor/formlayout.py", line 56, in <module>
    from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 128, in <module>
    from PyQt5 import QtCore, QtGui, QtWidgets
ImportError: libQt5Core.so.5: object file has no loadable segments
</code>```

I'm using miniconda2 and have already tried un-installing and re-installing matplotlib

答:
Thank you @SiHa. The post at Set Matplotlib Backend worked perfectly.

One of the answers on that post also gave useful info on how to set the default backend. Simply go to your matplotlibrc file (mine was at miniconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc) and change the backend variable.

Title: Import error for matplotlib.pyplot

Body:
I saw similar posts, but the error given when I tried to run import matplotlib.pyplot as plt was different:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py", line 16, in <module>
    from .backend_qt5 import QtCore
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 26, in <module>
    import matplotlib.backends.qt_editor.figureoptions as figureoptions
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/qt_editor/figureoptions.py", line 20, in <module>
    import matplotlib.backends.qt_editor.formlayout as formlayout
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/qt_editor/formlayout.py", line 56, in <module>
    from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore
  File "/home/jhn545/miniconda2/lib/python2.7/site-packages/matplotlib/backends/qt_compat.py", line 128, in <module>
    from PyQt5 import QtCore, QtGui, QtWidgets
ImportError: libQt5Core.so.5: object file has no loadable segments

I'm using miniconda2 and have already tried un-installing and re-installing matplotlib


问:
MVC5 how to find root path in code?
I have some helper methods to build Html output but it only comes out correct on my local dev and not my staging server. The ~ doesn't work since this is not Razor.

My local site path is http://localhost/testSite

My staging path is http://192.168.1.2/

On my local this produces
    src="/testSite/images.test.jpg"

On my staging instance it produces src="//images.test.jpg"

```<code>var baseUrl = HttpRuntime.AppDomainAppPath;
var tb = new TagBuilder("img");
tb.MergeAttribute("title", "Main Image");
tb.MergeAttribute("src", baseUrl +"\images\test.jpg");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
</code>```

I'm sure there is a method built in to do this on the code side

答:
var baseUrl = System.Web.Mvc.UrlHelper.GenerateContentUrl("~/images/",
  HttpContext.Current);

Using the GenerateContentUrl you can keep using ~/

Title: MVC5 how to find root path in code?

Body:
I have some helper methods to build Html output but it only comes out correct on my local dev and not my staging server. The ~ doesn't work since this is not Razor.

My local site path is http://localhost/testSite

My staging path is http://192.168.1.2/

On my local this produces
    src="/testSite/images.test.jpg"

On my staging instance it produces src="//images.test.jpg"

var baseUrl = HttpRuntime.AppDomainAppPath;
var tb = new TagBuilder("img");
tb.MergeAttribute("title", "Main Image");
tb.MergeAttribute("src", baseUrl +"\images\test.jpg");
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));

I'm sure there is a method built in to do this on the code side