问:
SQL Linked Server Named pipes provider - error 5
I have SQL server 2012 installed on a machine. I connected it successfully using Linked Server from the another machine. however when i tried to connected the same machine from another labtop  which is on the same network i got the following error: please note that i have checked i can assess the sql server from SQL Server Management studio but it does not connected if i try to do it using linked server. I have checked tcp, named pipes are enable. Any suggestion

Error:

```<code>Named Pipes Provider: Could not open a connection to SQL Server [5].
OLE DB provider "SQLNCLI11" for linked server "MAL_SQL" returned message "Login timeout expired".
OLE DB provider "SQLNCLI11" for linked server "MAL_SQL" returned message "A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.". (.Net SqlClient Data Provider)
</code>```

答:
I had exactly this problem and I got it solved by doing these steps:

1) Go to Network Connections

2) Click on Alt key and select Advanced and then Advanced Settings

3) On Adapters and Bindings tab and in the Connections section, make Ethernet the first connection

Voila!

Body:
I have SQL server 2012 installed on a machine. I connected it successfully using Linked Server from the another machine. however when i tried to connected the same machine from another labtop  which is on the same network i got the following error: please note that i have checked i can assess the sql server from SQL Server Management studio but it does not connected if i try to do it using linked server. I have checked tcp, named pipes are enable. Any suggestion

Error:

Named Pipes Provider: Could not open a connection to SQL Server [5].
OLE DB provider "SQLNCLI11" for linked server "MAL_SQL" returned message "Login timeout expired".
OLE DB provider "SQLNCLI11" for linked server "MAL_SQL" returned message "A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.". (.Net SqlClient Data Provider)


来源: stackexchange

问:
How to use global variable in onCreate method of Android
I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.

Here's my code:

```<code>public class MyActivity extends AppCompatActivity
{
    public static int num_i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
        TextView tv = findViewById(R.id.textView);
        tv.setText(num_i);
        num_i++;
    }
}
</code>```

Please help me in this.

答:
Don't use tv.setText() with a number as parameter. Try using String.valueOf(num_i).

So in your case:
 tv.setText(String.valueOf(num_i)) or tv.setText(num_i + "");

ContentLicense: CC BY-SA 3.0

Body:
I am very much new to Android world. I was just trying to check how a global variable can be used in onCreate() method in Android, whenever i tried doing so, it closed abruptly. When I displayed some random text in the code, it was displayed successfully.

Here's my code:

public class MyActivity extends AppCompatActivity
{
    public static int num_i=0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_beer);
        TextView tv = findViewById(R.id.textView);
        tv.setText(num_i);
        num_i++;
    }
}

Please help me in this.


问:
How to make link, phone number clickable (Same behaviour as in textview) in a custom view where i draw text?
I made a view and draw text on it and i want that if any text contains link(Hyperlink) or Phone Number It would be clickable (Same Behaviour As in Text View) So how to Achieve it   ?

Code For View In which i am Drawing Text :-

```<code>class DrawRectCellView: UIView {

    var text: NSAttributedString?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Only override drawRect: if you perform custom drawing.

    override func draw(_ rect: CGRect)
    {
        UIColor.white.setFill()
        UIGraphicsGetCurrentContext()?.fill(rect)

        // Drawing code

        if let attributedText = text {
            attributedText.draw(in: rect)
        }
    }

}
</code>```

Code For TableCell :-

```<code>class DrawRectCell: UITableViewCell {

    var cellView: DrawRectCellView?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
        cellView = DrawRectCellView(frame: self.frame)

        if let cell = cellView {
            cell.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
            cell.contentMode = UIViewContentMode.redraw
        }

        self.contentView.addSubview(cellView!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTextString(_ text: NSAttributedString) {
        if let view = cellView {
            view.text = text
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}
</code>```

i am Setting Text like = www.google.com or any phone number its showing as normal text only (Not Showing Like In textview (it makes it clickable))

答:
First you need to detect your text contain url or numbers like this way.

```<code>let input = "This is a test with the URL https://www.hackingwithswift.com to be detected."
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))

for match in matches {
    guard let range = Range(match.range, in: input) else { continue }
    let url = input[range]
    print(url)
}
</code>```

if you detect url after setting to the textview you need to add UITapGestureRecognizer on UITextView like this way.

```<code>let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap")

textview.addGestureRecognizer(tapGesture)

func handleTap(sender: UITapGestureRecognizer) {

    if sender.state == .began {
      //write your code here for url tap
    }
}
</code>```

Body:
I made a view and draw text on it and i want that if any text contains link(Hyperlink) or Phone Number It would be clickable (Same Behaviour As in Text View) So how to Achieve it   ?

Code For View In which i am Drawing Text :-

class DrawRectCellView: UIView {

    var text: NSAttributedString?

    override init(frame: CGRect) {
        super.init(frame: frame)

    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Only override drawRect: if you perform custom drawing.

    override func draw(_ rect: CGRect)
    {
        UIColor.white.setFill()
        UIGraphicsGetCurrentContext()?.fill(rect)

        // Drawing code

        if let attributedText = text {
            attributedText.draw(in: rect)
        }
    }

}

Code For TableCell :-

class DrawRectCell: UITableViewCell {

    var cellView: DrawRectCellView?

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // Initialization code
        cellView = DrawRectCellView(frame: self.frame)

        if let cell = cellView {
            cell.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleWidth.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue)))
            cell.contentMode = UIViewContentMode.redraw
        }

        self.contentView.addSubview(cellView!)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setTextString(_ text: NSAttributedString) {
        if let view = cellView {
            view.text = text
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

i am Setting Text like = www.google.com or any phone number its showing as normal text only (Not Showing Like In textview (it makes it clickable))

Body:
First you need to detect your text contain url or numbers like this way.

let input = "This is a test with the URL https://www.hackingwithswift.com to be detected."
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let matches = detector.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))

for match in matches {
    guard let range = Range(match.range, in: input) else { continue }
    let url = input[range]
    print(url)
}

if you detect url after setting to the textview you need to add UITapGestureRecognizer on UITextView like this way.

let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap")

textview.addGestureRecognizer(tapGesture)

func handleTap(sender: UITapGestureRecognizer) {

    if sender.state == .began {
      //write your code here for url tap
    }
}


问:
Javascript adding zeros to the beginning of a string (max length 4 chars)
```<code>var number = 1310;
</code>```

should be left alone.

```<code>var number = 120;
</code>```

should be changed to "0120";

```<code>var number = 10;
</code>```

should be changed to "0010";

```<code>var number = 7;
</code>```

should be changed to "0007";

答:
```<code>function pad_with_zeroes(number, length) {

    var my_string = '' + number;
    while (my_string.length < length) {
        my_string = '0' + my_string;
    }

    return my_string;

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
var number = 1310;

should be left alone.

var number = 120;

should be changed to "0120";

var number = 10;

should be changed to "0010";

var number = 7;

should be changed to "0007";


问:
Python private method for public usage
I have a class A that need to implement a method meth().
Now, I don't want this method to be called by the end-user of my package. Thus, I have to make this method private (i.e. _meth(). I know that it's not really, private, but conventions matter.)

The problem though is that I have yet another class B in my package that has to call that method _meth(). Problem is that I now get the warning method that say that B tries to access a protected method of a class. Thus, I have to make the method public, i.e. without the leading underscore. This contradicts my intentions.

What is the most pythonic way to solve this dilemma?

I know I can re-implement that method outside of A, but it will lead to code duplication and, as meth() uses private attributes of A, will lead to the same problem.

Inheriting from a single metaclass is not an option as those classes have entirely different purposes and that will be contributing towards a ghastly mess.

答:
The fact that pylint/your editor/whatever external tool gives you a warning doesn't prevent code execution. I don't know about your editor but pylint warnings can be disabled on a case-by-case basis using special comments (nb: "case by case" meaning: "do not warn me for this line or block", not "totally disable this warning").

And it's perfectly ok for your own code to access protected attributes and methods in the same package - the "_protected" naming convention does not mean "None shall pass", just "are you sure you understand what you're doing and willing to take responsability if you break something ?". Since you're the author/maintainer of the package and those are intra-package access you are obviously entitled to take this responsability ;)

Title: Python private method for public usage


问:
How to implement form validations for Dynamically generated Form fields
I have a page in my Angular application where all form fields are created dynamically based on data coming from backend.

```<code>                <div class="col-md-12">
                    <form class="form-inline" name="reportsForm">
                        <div class="form-group form-group-grid" ng-repeat="fields in selectedTabData.requiredField" ng-switch="fields.paramType">
                            <label>{{fields.paramName}}<span class="asterisk" ng-if="fields.mandatory==true">*</span></label>
                            <input type="number" class="form-control" ng-switch-when="Number" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            <input type="date" data-date-format="mm/DD/YYYY" class="form-control" ng-switch-when="DatePicker" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            <input type="text" class="form-control" ng-switch-when="Text" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            <select type="date" class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            </select>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary form-inline-grid-button" ng-click="getReport()">Run Report</button>
                        </div>
                    </form>
                    <span  style="color:red">Please enter all the required fields marked with (*)</span>
                </div>
</code>```

I need the validation error message to be shown if anyone of the required field in the form is left empty.

The form fields data coming from backend is assigned in $scope.selectedTabData.requiredField

```<code>$scope.selectedTabData.requiredField.forEach(function(item)
        {
            if(item.paramType == "DatePicker")
            {
                var date = new Date(item.fieldValue);
                var formattedDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear();
                paramValue.push(formattedDate);
                paramName.push(item.paramName);
            }
            else
            {
                if(item.mandatory == true && item.fieldValue == undefined){
                    //need to set validation as failed
                }else{
                    //need to set validation as passed
                }
                paramValue.push(item.fieldValue);
                paramName.push(item.paramName);
            }
        })
</code>```

This is the condition I need to check to validate the form :

```<code>if(item.mandatory == true && item.fieldValue == undefined){
                    //need to set validation as failed
                }else{
                    //need to set validation as passed
                }
</code>```

This is the first time I am working with dynamic fields, can anyone help me with implementation of validation in this case?

Thanks.

答:
So to fix this, I had to deal with this the basic way.

I created a scope variable and set it as a flag.

in HTML :

```<code><div>
<span ng-if="formInvalid" style="color:red">Please fill in all the required fields(*)</span>
</div>
</code>```

In Controller :

```<code>$scope.formInvalid = false;

if(item.mandatory == true && item.fieldValue==null)
            {
                $scope.formInvalid = true;
            }
</code>```

This worked out for me. Please add more answers if you have an alternate solution to handle validations in dynamic elements.

Body:
I have a page in my Angular application where all form fields are created dynamically based on data coming from backend.

                    <form class="form-inline" name="reportsForm">

                            {{fields.paramName}}*
                            <input type="number" class="form-control" ng-switch-when="Number" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            <input type="date" data-date-format="mm/DD/YYYY" class="form-control" ng-switch-when="DatePicker" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            <input type="text" class="form-control" ng-switch-when="Text" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            <select type="date" class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-required="fields.mandatory">
                            </select>

                            <button type="submit" class="btn btn-primary form-inline-grid-button" ng-click="getReport()">Run Report</button>

                    </form>
                    Please enter all the required fields marked with (*)

I need the validation error message to be shown if anyone of the required field in the form is left empty.

The form fields data coming from backend is assigned in $scope.selectedTabData.requiredField

$scope.selectedTabData.requiredField.forEach(function(item)
        {
            if(item.paramType == "DatePicker")
            {
                var date = new Date(item.fieldValue);
                var formattedDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear();
                paramValue.push(formattedDate);
                paramName.push(item.paramName);
            }
            else
            {
                if(item.mandatory == true && item.fieldValue == undefined){
                    //need to set validation as failed
                }else{
                    //need to set validation as passed
                }
                paramValue.push(item.fieldValue);
                paramName.push(item.paramName);
            }
        })

This is the condition I need to check to validate the form :

if(item.mandatory == true && item.fieldValue == undefined){
                    //need to set validation as failed
                }else{
                    //need to set validation as passed
                }

This is the first time I am working with dynamic fields, can anyone help me with implementation of validation in this case?

Thanks.

Body:
So to fix this, I had to deal with this the basic way.

I created a scope variable and set it as a flag.

in HTML :

<div>
<span ng-if="formInvalid" style="color:red">Please fill in all the required fields(*)</span>
</div>

In Controller :

$scope.formInvalid = false;

if(item.mandatory == true && item.fieldValue==null)
            {
                $scope.formInvalid = true;
            }

This worked out for me. Please add more answers if you have an alternate solution to handle validations in dynamic elements.


问:
Access to a pointer whose address is in a string in C
I want to make a memdump function that with fgets() gets the address from the keyboard to dump and then, using this function prints the contents of that address in memory
I have this code:

```<code>#include <stdio.h>
void print_bytes(void *object, size_t size)
{
  char * bytes = object;
  size_t i;

  for(i = 0; i < size; i++)
  {
    printf("%c", bytes[i]);
  }
}

void CMD_Memdump(char* string){
    print_bytes(string, 200);
}

int main(){
    char* str;
    fgets(str, sizeof(str), stdin);
    CMD_Memdump(str);
}
</code>```

I want to print the content of 0x7f3900e03000 that I have already ensured that is a valid address; the program prints on screen this:

```<code>0x7f3900e03000(garbage)
</code>```

Why?

答:
Maybe you could try to you *bytes[i] instead of just bytes[i] :)

```<code>void print_bytes(void *object, size_t size)
{
  char * bytes = object;
  size_t i;

for(i = 0; i < size; i++)
  {
    printf("%c", *bytes[i]);  //<-Have you tried using *bytes[i] instead of
                              //bytes[i]?
  }
}

void CMD_Memdump(char* string){
    print_bytes(string, 200);
}

int main(){
    char* str;
    fgets(str, sizeof(str), stdin);
    CMD_Memdump(str);
}
</code>```

i hope i could help.

Body:
I want to make a memdump function that with fgets() gets the address from the keyboard to dump and then, using this function prints the contents of that address in memory
I have this code:

#include <stdio.h>
void print_bytes(void *object, size_t size)
{
  char * bytes = object;
  size_t i;

  for(i = 0; i < size; i++)
  {
    printf("%c", bytes[i]);
  }
}

void CMD_Memdump(char* string){
    print_bytes(string, 200);
}

int main(){
    char* str;
    fgets(str, sizeof(str), stdin);
    CMD_Memdump(str);
}

I want to print the content of 0x7f3900e03000 that I have already ensured that is a valid address; the program prints on screen this:

0x7f3900e03000(garbage)

Why?

Body:
Maybe you could try to you *bytes[i] instead of just bytes[i] :)

void print_bytes(void *object, size_t size)
{
  char * bytes = object;
  size_t i;

for(i = 0; i < size; i++)
  {
    printf("%c", *bytes[i]);  //<-Have you tried using *bytes[i] instead of
                              //bytes[i]?
  }
}

void CMD_Memdump(char* string){
    print_bytes(string, 200);
}

int main(){
    char* str;
    fgets(str, sizeof(str), stdin);
    CMD_Memdump(str);
}

i hope i could help.


问:
Html button call a function in code behind and it fires only once
I have html button which calls a function in code behind and it fires only once.

I want it to fire event every time I click the button.

It is possibly duplicated but I have tried to add "!IsPostBack" but it doesn't work.

My ascx class:

```<code><button runat="server" type="button" class="btn btn-report" onserverclick="OnReportBtnClick" id="reportBtn">
<i class="glyphicon glyphicon-floppy-disk"></i>
</button>
</code>```

I have to use html button, not <asp:Button> because <asp:Button> doesn't let me to insert  tag inside.

Here is my code behind:

```<code>protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            try
            {
                reportBtn.ServerClick += OnReportBtnClick;
            }
            catch (Exception ex)
            {
            }
        }
    }

//this method is called only once even I click the button many times afterwards.
    protected void OnReportBtnClick(object sender, EventArgs e)
    {
        try
        {
            // Set file name
            string pdfName = SPContext.Current.Web.Title + fileType;
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime startDate = DateTime.MinValue;
            if (!string.IsNullOrEmpty(report_startDate_datePicker.Value))
                startDate = DateTime.ParseExact(report_startDate_datePicker.Value, format, provider);

            DateTime endDate = DateTime.MaxValue;
            if (!string.IsNullOrEmpty(report_endDate_datePicker.Value))
                endDate = DateTime.ParseExact(report_endDate_datePicker.Value, format, provider);
            // Provisioning data for report
            var report = GetReport(startDate, endDate);
            // Merger data to template html
            byte[] data = GetPdfData(htmlTemplate, report);
            //Respond report to client
            RenderResponse(pdfName, data);
        }
        catch (Exception ex)
        {
            LoggingService.LogError(LoggingService.NTT_ERROR,
                string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
        }
    }

//I think the problem could be this method.
//I return a pdf file to client
private void RenderResponse(string pdfName, byte[] data)
        {
            try
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + pdfName);
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.BinaryWrite(data);
                HttpContext.Current.Response.End();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                LoggingService.LogError(LoggingService.NTT_ERROR,
                    string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
            }
</code>```

答:
You can use a LinkButton

```<code><asp:LinkButton runat="server" ID="ReportBtn" Text="<i class='glyphicon glyphicon-floppy-disk'></i>" OnClick="ReportBtn_Click" CssClass="btn btn-report" />
</code>```

in .cs page

```<code>protected void ReportBtn_Click(object sender, EventArgs e)
{
//your code
}
</code>```

They do support html in the text field.

Body:
I have html button which calls a function in code behind and it fires only once.

I want it to fire event every time I click the button.

It is possibly duplicated but I have tried to add "!IsPostBack" but it doesn't work.

My ascx class:

<button runat="server" type="button" class="btn btn-report" onserverclick="OnReportBtnClick" id="reportBtn">

</button>

I have to use html button, not <asp:Button> because <asp:Button> doesn't let me to insert  tag inside.

Here is my code behind:

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            try
            {
                reportBtn.ServerClick += OnReportBtnClick;
            }
            catch (Exception ex)
            {
            }
        }
    }

//this method is called only once even I click the button many times afterwards.
    protected void OnReportBtnClick(object sender, EventArgs e)
    {
        try
        {
            // Set file name
            string pdfName = SPContext.Current.Web.Title + fileType;
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime startDate = DateTime.MinValue;
            if (!string.IsNullOrEmpty(report_startDate_datePicker.Value))
                startDate = DateTime.ParseExact(report_startDate_datePicker.Value, format, provider);

            DateTime endDate = DateTime.MaxValue;
            if (!string.IsNullOrEmpty(report_endDate_datePicker.Value))
                endDate = DateTime.ParseExact(report_endDate_datePicker.Value, format, provider);
            // Provisioning data for report
            var report = GetReport(startDate, endDate);
            // Merger data to template html
            byte[] data = GetPdfData(htmlTemplate, report);
            //Respond report to client
            RenderResponse(pdfName, data);
        }
        catch (Exception ex)
        {
            LoggingService.LogError(LoggingService.NTT_ERROR,
                string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
        }
    }

//I think the problem could be this method.
//I return a pdf file to client
private void RenderResponse(string pdfName, byte[] data)
        {
            try
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ContentType = "application/pdf";
                HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + pdfName);
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.BinaryWrite(data);
                HttpContext.Current.Response.End();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                LoggingService.LogError(LoggingService.NTT_ERROR,
                    string.Format("ERROR: {0} - SOURCE: {1} | {2}", ex.Message, ex.Source, System.Reflection.MethodBase.GetCurrentMethod().Name));
            }

Body:
You can use a LinkButton

<asp:LinkButton runat="server" ID="ReportBtn" Text="<i class='glyphicon glyphicon-floppy-disk'></i>" OnClick="ReportBtn_Click" CssClass="btn btn-report" />

in .cs page

protected void ReportBtn_Click(object sender, EventArgs e)
{
//your code
}

They do support html in the text field.


问:
AutoMapper instantiate complex types with StructureMap
Assuming that I have a complex type, for example:

```<code>interface IFoo
{
  IBar {get;set;}
}
</code>```

and it is mapped to some DTO using AutoMapper, i.e. Mapper.CreateMap<IFoo, FooDto>()

How should I configure AutoMapper so that it will use StructureMap to get an instance of IFoo as well as IBar when mapping from FooDto to IFoo?

答:
Try

```<code>Mapper.CreateMap<FooDto, IFoo>()
    .ConstructUsing(fooDto => ObjectFactory.GetInstance<IFoo>())
    .AfterMap((fooDto, iFoo) => iFoo.IBar = ObjectFactory.GetInstance<IBar>());
</code>```

Is IBar a dependency in the constructor of IFoo?  Then you could skip the AfterMap() step.

Body:
Assuming that I have a complex type, for example:

interface IFoo
{
  IBar {get;set;}
}

and it is mapped to some DTO using AutoMapper, i.e. Mapper.CreateMap<IFoo, FooDto>()

How should I configure AutoMapper so that it will use StructureMap to get an instance of IFoo as well as IBar when mapping from FooDto to IFoo?

Body:
Try

Mapper.CreateMap<FooDto, IFoo>()
    .ConstructUsing(fooDto => ObjectFactory.GetInstance<IFoo>())
    .AfterMap((fooDto, iFoo) => iFoo.IBar = ObjectFactory.GetInstance<IBar>());

Is IBar a dependency in the constructor of IFoo?  Then you could skip the AfterMap() step.


问:
Aptana 3 (3.6.1) Will Not Load on my Windows 10 Laptop
I know you all heard similar complaints, yet no response has worked for me through browsing these questions and answers. Please forgive me if you believe this to overly repetitive.

Loaded Node.js (4.2.2) first tried 32bit, and later tried 64bit installer.

Attempted to load Aptana studio 3 (3.6.1) but got an error.

"Failed to acquire installer_nodejs_windows.msi file: CRC error."

I have tried updating environmental variables, and loading the 64bit instead. I have uninstalled, reinstalled, rebooted, etc. I like this application on my school computer, and really want to give it a try at home. Can someone please help me?

答:
Same error. Install Node js

Install Node JS:
https://nodejs.org/en/download/


问:
Linking video to an HTML anchor tag
I am trying to make a website that has an anchor link to "watch the video", what I want to do is to link a video to the anchor tag and when someone clicks on the link, the video appears on the same webpage but upon webpage and behind the video, page should be lightened. Help me to figure this out.

  Watch Video
  Explore More

```

答:
var $iframe = $('iframe'),
    $videoLink = $('.video-link'),
    playerTemplate = '

<button class="video-close">×</button>

';

$videoLink.on('click', function(e) {
    var localTemplate = '',
        videoWidth = parseInt($(this).data('width')),
        videoHeight = parseInt($(this).data('height')),
        videoAspect = ( videoHeight / videoWidth ) * 100,
        // elements
        $player = null,
        $video = null,
        $close = null,
        $iframe = null;

    e.preventDefault();

    localTemplate = playerTemplate.replace('{{iframevideo}}', $(this).prop('href'));

    $player = $(localTemplate);

    $player
        .find('.video-filler')
        .css('padding-top', videoAspect + '%');

    $close = $player
        .find('.video-close')
        .on('click', function() {
            $(this).off().closest('.player').hide().remove();
        });

    $player.appendTo('body').addClass('js--show-video');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.video-link {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 4px;
    text-decoration: none;
    color: white;
    background-color: #f03;
    box-shadow: 0 5px 10px -3px rgba(0,0,0,.5);
}

/* --- */
.player {
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,1);
    background: -webkit-radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%, rgba(0,0,0,1) 100%);
    background: -moz-radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%, rgba(0,0,0,1) 100%);
    background: -ms-radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%, rgba(0,0,0,1) 100%);
    background: radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%,rgba(0,0,0,1) 100%);

    opacity: 0;
    -webkit-transition: opacity 0.3s ease-in-out;
    transition: opacity 0.3s ease-in-out;
}

.player__video {
    position: relative;
    top: 50%;
    left: 50%;
    width: auto;
    max-width: 75%;
    background-color: #fff;
    box-shadow: 0 0 50px rgba(0,0,0,.95);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

.js--show-video { opacity: 1; }

.video-filler {
    display: block;
    width: 100%;
}

.video-close {
    position: absolute;
    z-index: 0;
    top: 0;
    right: -30px;
    padding: 5px 10px;
    border: none;
    outline: none;
    border-radius: 0 50% 50% 0;
    cursor: pointer;
    font-size: 24px;
    color: #000;
    background-color: #fff;
    box-shadow: 0 0 20px rgba(0,0,0,.75);
}

.video-iframe {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 10px solid #fff;
}</code>```

Open video```

Title: Linking video to an HTML anchor tag

Body:
var $iframe = $('iframe'),
    $videoLink = $('.video-link'),
    playerTemplate = '<div class="player"><div class="player__video"><div class="video-filler"></div><button class="video-close">&times;</button><iframe class="video-iframe" src="{{iframevideo}}" frameborder="0" allowfullscreen></iframe></div><div/>';

$videoLink.on('click', function(e) {
    var localTemplate = '',
        videoWidth = parseInt($(this).data('width')),
        videoHeight = parseInt($(this).data('height')),
        videoAspect = ( videoHeight / videoWidth ) * 100,
        // elements
        $player = null,
        $video = null,
        $close = null,
        $iframe = null;

    e.preventDefault();

    localTemplate = playerTemplate.replace('{{iframevideo}}', $(this).prop('href'));

    $player = $(localTemplate);

    $player
        .find('.video-filler')
        .css('padding-top', videoAspect + '%');

    $close = $player
        .find('.video-close')
        .on('click', function() {
            $(this).off().closest('.player').hide().remove();
        });

    $player.appendTo('body').addClass('js--show-video');
});

.video-link {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 4px;
    text-decoration: none;
    color: white;
    background-color: #f03;
    box-shadow: 0 5px 10px -3px rgba(0,0,0,.5);
}

/* --- */
.player {
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,1);
    background: -webkit-radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%, rgba(0,0,0,1) 100%);
    background: -moz-radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%, rgba(0,0,0,1) 100%);
    background: -ms-radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%, rgba(0,0,0,1) 100%);
    background: radial-gradient(center, ellipse cover, rgba(0,0,0,.65) 0%,rgba(0,0,0,1) 100%);

    opacity: 0;
    -webkit-transition: opacity 0.3s ease-in-out;
    transition: opacity 0.3s ease-in-out;
}

.player__video {
    position: relative;
    top: 50%;
    left: 50%;
    width: auto;
    max-width: 75%;
    background-color: #fff;
    box-shadow: 0 0 50px rgba(0,0,0,.95);
    -webkit-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}

.js--show-video { opacity: 1; }

.video-filler {
    display: block;
    width: 100%;
}

.video-close {
    position: absolute;
    z-index: 0;
    top: 0;
    right: -30px;
    padding: 5px 10px;
    border: none;
    outline: none;
    border-radius: 0 50% 50% 0;
    cursor: pointer;
    font-size: 24px;
    color: #000;
    background-color: #fff;
    box-shadow: 0 0 20px rgba(0,0,0,.75);
}

.video-iframe {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 10px solid #fff;
}

<a class="video-link" href="https://www.youtube.com/embed/ONaPq2L-MRg?html5=1" data-width="1920" data-height="1080">Open video</a>


问:
Android YouTube app Play Video Intent
I have created a app where you can download YouTube videos for android. Now, I want it so that if you play a video in the YouTube native app you can download it too. To do this, I need to know the Intent that the YouTube native app puts out in order to play the YouTube app.

I could do this easially if I had the YouTube program on my emulator, so my 1st question is:

1. Can I download the YouTube app for my emulator, or...

2. What is the intent used when the user selects a video for playback.

答:
This function work fine for me...just pass url string in function:</p>
```<code>void watch_video(String url)
{
    Intent yt_play = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
    Intent chooser = Intent.createChooser(yt_play , "Open With");

    if (yt_play.resolveActivity(getPackageManager()) != null) {
                    startActivity(chooser);
                }
}
</code>```

OwnerDisplayName: Isaac Waller

Title: Android YouTube app Play Video Intent

Body:
This function work fine for me...just pass url string in function:

void watch_video(String url)
{
    Intent yt_play = new Intent(Intent.ACTION_VIEW, Uri.parse(url))
    Intent chooser = Intent.createChooser(yt_play , "Open With");

    if (yt_play.resolveActivity(getPackageManager()) != null) {
                    startActivity(chooser);
                }
}

ContentLicense: CC BY-SA 4.0


问:
How can I tell webdriver-io to use firefox developer edition?
How can I tell webdriver-io to use firefox developer edition instead of normal firefox? I need to use CSS4 selectors which normal firefox does not support. I read the documentation but I can not find the option.</p>

答:
Florent, thanks for answer, I used it to test my application with Firefox Quantum.
I used Firefox Developer Version, which already contains Firefox Quantum Beta 14, and added in my BrowserFactory Class:

```<code>            else if (browserName.equals ("quantum") {
        FirefoxOptions options = new FirefoxOptions();
        System.setProperty ("webdriver.gecko.driver", "src/test/resources/drivers/geckodriver.exe");
        System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
        System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,javaIoTmpDir+"\\geckodriverlogs.txt");
        System.setProperty("webdriver.firefox.bin", "C:\\Portable\\FirefoxPortableDeveloper\\App\\Firefox64\\firefox.exe");
        driver = new FirefoxDriver(options);
</code>```

Body:
Florent, thanks for answer, I used it to test my application with Firefox Quantum.
I used Firefox Developer Version, which already contains Firefox Quantum Beta 14, and added in my BrowserFactory Class:

            else if (browserName.equals ("quantum") {
        FirefoxOptions options = new FirefoxOptions();
        System.setProperty ("webdriver.gecko.driver", "src/test/resources/drivers/geckodriver.exe");
        System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
        System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,javaIoTmpDir+"\\geckodriverlogs.txt");
        System.setProperty("webdriver.firefox.bin", "C:\\Portable\\FirefoxPortableDeveloper\\App\\Firefox64\\firefox.exe");
        driver = new FirefoxDriver(options);


问:
Google Drive API download NODE.JS sample doesn't work
Here is my code based on Google: "Here are examples of performing a file download with our Drive API client libraries." NODE.JS

```<code>const fs = require('fs')
const google = require('googleapis')
const googleAuth = require('google-auth-library')

const SCOPES = ['https://www.googleapis.com/auth/drive'] // Full, permissive scope to access all of a user's files, excluding the Application Data folder. Request this scope only when it is strictly necessary.
const TOKEN_DIR = './credentials/'
const TOKEN_PATH = TOKEN_DIR + 'token4joeDlEs6.json'
const CLIENT_SECRET_FILEPATH = 'client_secret.json'

var clientSecretStr = fs.readFileSync(CLIENT_SECRET_FILEPATH).toString('utf-8')
var tokenStr = fs.readFileSync(TOKEN_PATH).toString('utf-8')

var credentials = JSON.parse(clientSecretStr)

var clientSecret = credentials.installed.client_secret
var clientId = credentials.installed.client_id
var redirectUrl = credentials.installed.redirect_uris[0]
var auth = new googleAuth()
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl)

oauth2Client.credentials = JSON.parse(tokenStr)

var drive = google.drive('v3');

// ["Examples"-NODE.JS tab](https://developers.google.com/drive/v3/web/manage-downloads)
var fileId = 'OBFUSCATED' // Safeway (OBFUSCATED)
var dest = fs.createWriteStream('out/safeway.txt')
drive.files.get({
  auth: oauth2Client,
  fileId: fileId,
  //alt: 'media'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);
</code>```

RUNS WITHOUT ERRORS:

```<code>$ node joeDlSample.js
Done
$
</code>```

EXPECTED RESULT

out/safeway.txt to contain my shopping list. :)

ACTUAL RESULT

out/safeway.txt contains

```<code>{
  "access_token" : "OBFUSCATED.OBFUSCATED",
  "expires_in" : 3600,
  "token_type" : "Bearer"
}
</code>```

2nd RUN CLOSER TO EXAMPLE

I also uploaded a .jpg picture, & uncommented the alt: media line in the code

EXPECTED RESULT

out/elb.jpg to contain elb picture

ACTUAL RESULT

out/elb.jpg contains

```<code>{
  "access_token" : "OBFUSCATED.OBFUSCATED",
  "expires_in" : 3600,
  "token_type" : "Bearer"
}
</code>```

答:
I managed to get Downloading Files in Drive API working by combining the Drive NodeJS Quickstart and the Download Files sample for NodeJS.

From the NodeJS Quickstart there's this line:

```<code>authorize(JSON.parse(content), listFiles);
</code>```

I created my own downloadFile function to download files instead of listing files and modified the above mentioned line to

```<code>  authorize(JSON.parse(content), downloadFile);
</code>```

And here's the downloadFile function part from the NodeJS sample:

```<code>function downloadFile(auth){
  var service = google.drive('v3');
  var fileId = 'FILE_ID_OF_SHOPPINGLIST_TEXT_FILE';
  var dest = fs.createWriteStream('/usr/local/google/home/username/Downloads/shoppinglist.txt');

  service.files.get({
      auth: auth,
      fileId: fileId,
      alt: 'media'
  })
      .on('end', function () {
        console.log('Done');
      })
      .on('error', function (err) {
        console.log('Error during download', err);
      })
      .pipe(dest);
}
</code>```

The downloaded file in my Downloads folder:

Works for me :)

Body:
Here is my code based on Google: "Here are examples of performing a file download with our Drive API client libraries." NODE.JS

const fs = require('fs')
const google = require('googleapis')
const googleAuth = require('google-auth-library')

const SCOPES = ['https://www.googleapis.com/auth/drive'] // Full, permissive scope to access all of a user's files, excluding the Application Data folder. Request this scope only when it is strictly necessary.
const TOKEN_DIR = './credentials/'
const TOKEN_PATH = TOKEN_DIR + 'token4joeDlEs6.json'
const CLIENT_SECRET_FILEPATH = 'client_secret.json'

var clientSecretStr = fs.readFileSync(CLIENT_SECRET_FILEPATH).toString('utf-8')
var tokenStr = fs.readFileSync(TOKEN_PATH).toString('utf-8')

var credentials = JSON.parse(clientSecretStr)

var clientSecret = credentials.installed.client_secret
var clientId = credentials.installed.client_id
var redirectUrl = credentials.installed.redirect_uris[0]
var auth = new googleAuth()
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl)

oauth2Client.credentials = JSON.parse(tokenStr)

var drive = google.drive('v3');

// ["Examples"-NODE.JS tab](https://developers.google.com/drive/v3/web/manage-downloads)
var fileId = 'OBFUSCATED' // Safeway (OBFUSCATED)
var dest = fs.createWriteStream('out/safeway.txt')
drive.files.get({
  auth: oauth2Client,
  fileId: fileId,
  //alt: 'media'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);

RUNS WITHOUT ERRORS:

$ node joeDlSample.js
Done
$

EXPECTED RESULT

out/safeway.txt to contain my shopping list. :)

ACTUAL RESULT

out/safeway.txt contains

{
  "access_token" : "OBFUSCATED.OBFUSCATED",
  "expires_in" : 3600,
  "token_type" : "Bearer"
}

2nd RUN CLOSER TO EXAMPLE

I also uploaded a .jpg picture, & uncommented the alt: media line in the code

EXPECTED RESULT

out/elb.jpg to contain elb picture

ACTUAL RESULT

out/elb.jpg contains

{
  "access_token" : "OBFUSCATED.OBFUSCATED",
  "expires_in" : 3600,
  "token_type" : "Bearer"
}

Body:
I managed to get Downloading Files in Drive API working by combining the Drive NodeJS Quickstart and the Download Files sample for NodeJS.

From the NodeJS Quickstart there's this line:

authorize(JSON.parse(content), listFiles);

I created my own downloadFile function to download files instead of listing files and modified the above mentioned line to

  authorize(JSON.parse(content), downloadFile);

And here's the downloadFile function part from the NodeJS sample:

function downloadFile(auth){
  var service = google.drive('v3');
  var fileId = 'FILE_ID_OF_SHOPPINGLIST_TEXT_FILE';
  var dest = fs.createWriteStream('/usr/local/google/home/username/Downloads/shoppinglist.txt');

  service.files.get({
      auth: auth,
      fileId: fileId,
      alt: 'media'
  })
      .on('end', function () {
        console.log('Done');
      })
      .on('error', function (err) {
        console.log('Error during download', err);
      })
      .pipe(dest);
}

The downloaded file in my Downloads folder:

Works for me :)


问:
Data not inserted in table with entity framework 6
I just created a local database in my c# console project, and also an ADO.NET connection with EntityFramework 6.2.0 to that database.

Now I try to insert my new data from object type Kunde into to the table [dbo].[Kunde] like this:

```<code>public void gastSpeichern(Kunde kunde)
{
    using (var context = new HotelzimmerverwaltungDBEntities())
    {
        context.Kunde.Add(kunde);
        context.SaveChanges();
    }
}
</code>```

I create the object which i give to my method gastSpeichern like this:

```<code>Kunde k = new Kunde{Kunden_Nr = 1337, Name = "Dennis"};

dt.gastSpeichern(k);
</code>```

But as you can see the table is always empty and the code runs trough without any errors:

this is my table definition:

答: Your entity does not have a primary key. Add either a property "Id" or add an attribute [Key] to your "Kunden_Nr"</p>

Body:
I just created a local database in my c# console project, and also an ADO.NET connection with EntityFramework 6.2.0 to that database.

Now I try to insert my new data from object type Kunde into to the table [dbo].[Kunde] like this:

public void gastSpeichern(Kunde kunde)
{
    using (var context = new HotelzimmerverwaltungDBEntities())
    {
        context.Kunde.Add(kunde);
        context.SaveChanges();
    }
}

I create the object which i give to my method gastSpeichern like this:

Kunde k = new Kunde{Kunden_Nr = 1337, Name = "Dennis"};

dt.gastSpeichern(k);

But as you can see the table is always empty and the code runs trough without any errors:

this is my table definition:


问:
3 tier application with JHipster
How can I have 3 tier application running using JHipster. With CUBA RAD can do that, why not with JHipster? The problem of CUBA is that it is not attached to a totally free front-end (Vaadin), they have extensible front-end (Angular 1, Angular 2, and React is under development). So my question is if I can deploy JHipster in 3 tier environment.</p>

答: My doubt was how could I separate it when building. I caught the solution already. Thank you. The answer has been found here: http://www.jhipster.tech/separating-front-end-and-api/. </p>

Title: 3 tier application with JHipster


问:
Sed how to add variable with vertical bar to the end of first line
i want to append variable with string to the first line of my_file

sed -i "1 s/$/   $my_variable/" ~/my_file

Now i have this:

42 192.168.1.1   string_from_my_variable

It works. But the task become harder, now i need to add delimiter before string_from_my_variable

I tried to sed -i "1 s#$#   \|\$my_variable#" ~/my_file, of course it does not help. I need to have this:

42 192.168.1.1   | string_from_my_variable

How can i do this ? Thanks for your attention.

答:
Since you want to deal with literal strings that come from a shell variable, I would go with awk:

```<code>awk -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file
</code>```

Add the extra string to the first line and 1 at the end is the shortest way to write 1 { print $0 }, so every line gets printed.

To overwrite your original file:

```<code># GNU Awk
awk -i inplace -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file
# any Awk
awk -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file > tmp && mv tmp file
</code>```

Body:
Since you want to deal with literal strings that come from a shell variable, I would go with awk:

awk -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file

Add the extra string to the first line and 1 at the end is the shortest way to write 1 { print $0 }, so every line gets printed.

To overwrite your original file:

# GNU Awk
awk -i inplace -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file
# any Awk
awk -v extra="$my_variable" 'NR == 1 { $0 = $0 "   |" extra } 1' file > tmp && mv tmp file


问:
split one column from import into 2 column in database
i have a file i need to import that has a column with the settings A, S and B in them,

i would like to split this column and and all the A's go into a column but be reset to a 1 and the rest to go into another column and changed to a 1.

is this possible in derived columns?

答:
I'm not 100% sure what you're asking for but how about something like this:

```<code>SELECT
  CASE ImportColumn WHEN 'A' THEN 1 ELSE NULL END AS [A Column]
, CASE ImportColumn WHEN 'A' THEN NULL ELSE 1 END AS [Other Column]
FROM
  Import
</code>```

When the value is 'A' then a row will be added with the first col 1 and 2nd col null.
When the value is not 'A' then a row will be added with null in first col and 1 in the second.  Is that what you meant?

Body:
I'm not 100% sure what you're asking for but how about something like this:

SELECT
  CASE ImportColumn WHEN 'A' THEN 1 ELSE NULL END AS [A Column]
, CASE ImportColumn WHEN 'A' THEN NULL ELSE 1 END AS [Other Column]
FROM
  Import

When the value is 'A' then a row will be added with the first col 1 and 2nd col null.
When the value is not 'A' then a row will be added with null in first col and 1 in the second.  Is that what you meant?


问:
How to start service and redirect to another activity in a same time?
What I want is when I click on the button,start a service immediately.Once started the service,intent to another activity immediately.

Here is my code to achieve it:

```<code>button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        //here I start the service
        Intent intent = new Intent(MyActivity.this, UploadService.class);
                intent.putExtra(UploadService.ID,id);
        startService(intent);

        //after start the service,I want to redirect to Activity2.class
        Intent intent1 = new Intent(MyActivity.this,Activity2.class);
        startActivity(intent1);

        }
}
</code>```

But when I do this,the service is not start,and not redirect to Activity2.class,instead it redirect to the previous activity.

I tried intent inside the onHandleIntent(Intent intent) of Service.class the problem still the same

Here is what I tried in UploadService.class:

```<code>@Override
protected void onHandleIntent(Intent intent) {
  //other code here

  Intent intent1 = new Intent(MyActivity.this,Activity2.class);
  startActivity(intent1);
}
</code>```

But still the service not start,intent to the previous activity(the activity which MyActivity.class intent from).

So how can I redirect to another activity immediately just after start a Service?

Edit:
I already declare the UploadService in manifest like so:

```<code><service
    android:name=".services.UploadService"
    android:enabled="true">
</service>
</code>```

So what I still missing here??

答:
Make sure you have registered your Service class in manifest.xml.
Try changing your Service class name from 'Service' to some other name. As Service.java class is System class.

Try starting service like below

```<code>startService(new Intent(context, MyService.class));
</code>```

EDit

More Clarification Firstly check your app is running or not. If your Application is not running then call this code.

```<code>Intent i = new Intent(context,SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
</code>```

If running then use this code

```<code>Intent i = new Intent(context,SecondActivity.class);
context.startActivity(i);
</code>```

Body:
What I want is when I click on the button,start a service immediately.Once started the service,intent to another activity immediately.

Here is my code to achieve it:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        //here I start the service
        Intent intent = new Intent(MyActivity.this, UploadService.class);
                intent.putExtra(UploadService.ID,id);
        startService(intent);

        //after start the service,I want to redirect to Activity2.class
        Intent intent1 = new Intent(MyActivity.this,Activity2.class);
        startActivity(intent1);

        }
}

But when I do this,the service is not start,and not redirect to Activity2.class,instead it redirect to the previous activity.

I tried intent inside the onHandleIntent(Intent intent) of Service.class the problem still the same

Here is what I tried in UploadService.class:

@Override
protected void onHandleIntent(Intent intent) {
  //other code here

  Intent intent1 = new Intent(MyActivity.this,Activity2.class);
  startActivity(intent1);
}

But still the service not start,intent to the previous activity(the activity which MyActivity.class intent from).

So how can I redirect to another activity immediately just after start a Service?

Edit:
I already declare the UploadService in manifest like so:

<service
    android:name=".services.UploadService"
    android:enabled="true">
</service>

So what I still missing here??

Body:
Make sure you have registered your Service class in manifest.xml.
Try changing your Service class name from 'Service' to some other name. As Service.java class is System class.

Try starting service like below

startService(new Intent(context, MyService.class));

EDit

More Clarification Firstly check your app is running or not. If your Application is not running then call this code.

Intent i = new Intent(context,SecondActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

If running then use this code

Intent i = new Intent(context,SecondActivity.class);
context.startActivity(i);


问:
Django - Model property 'getter'?
If I had a model like this:

```<code>  class Entry(models.Model):
 STATUS_LIVE = 1
 STATUS_DRAFT = 2
 STATUS_HIDDEN = 3
 STATUS_CHOICES = (
  (STATUS_LIVE, ('Live')),
  (STATUS_DRAFT, ('Draft')),
  (STATUS_HIDDEN, ('Hidden')),
 )

 id = models.AutoField(primary_key=True)
 status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES,
</code>```

And I wanted to show the property 'status' in a view as either 'Live', 'Draft' or 'Hidden' (as opposed to 1, 2 or 3), how would I do this?

It seems Django doesn't have any kind of getter / setter functionality inside of models, I'd like to be able to use entry.status and not something like entry.full_status because it becomes awfully confusing having lots of differently named properties.

Any suggestions would be appreciated

答: You would call Entry.get_status_display().

Title: Django - Model property 'getter'?

Body:
If I had a model like this:

  class Entry(models.Model):
 STATUS_LIVE = 1
 STATUS_DRAFT = 2
 STATUS_HIDDEN = 3
 STATUS_CHOICES = (
  (STATUS_LIVE, ('Live')),
  (STATUS_DRAFT, ('Draft')),
  (STATUS_HIDDEN, ('Hidden')),
 )

 id = models.AutoField(primary_key=True)
 status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES,

And I wanted to show the property 'status' in a view as either 'Live', 'Draft' or 'Hidden' (as opposed to 1, 2 or 3), how would I do this?

It seems Django doesn't have any kind of getter / setter functionality inside of models, I'd like to be able to use entry.status and not something like entry.full_status because it becomes awfully confusing having lots of differently named properties.

Any suggestions would be appreciated


问:
Insert statement conflict with foreign key constraint
I am writing the script for practice and Following is the emp and department table :

```<code>Create table Employee
(
EmpId       int,
Name        varchar(30),
Designation varchar(50),
DateOfBirth date,
Salary      int,
Department  int,
Gender      char(2),
Primary key(empId),
    foreign key(empId) references Department(DeptId)
)
Create table Department
(
DeptId      int,
Department  varchar(30),
Primary key(DeptId)
)
</code>```

When I am inserting rows into Employee table then I am getting the following error :

Msg 547, Level 16, State 0, Line 2
  The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Employee_EmpId". The conflict occurred in database "Ramandeep", table "dbo.Department", column 'DeptId'.
  The statement has been terminated.

Below is the row which I am trying to insert :

```<code> Insert into Employee(EmpId,Name,Designation,DateOfBirth,Salary,Department,Gender) values (4,'Sam','Accountant','1973-05-13',6500,4,'M')
</code>```

And values are available in Department table

```<code>Insert into Department(DeptId,Department) values (1,'HR')
Insert into Department(DeptId,Department) values (2,'Operation')
Insert into Department(DeptId,Department) values (3,'IT')
Insert into Department(DeptId,Department) values (4,'Admin')
</code>```

I don't know why I am getting this error. Please help to fix it.

答:
This error seems as trying to insert a record with a value in the foreign key column that doesn't exist in the foreign table.

if your Department Table has values are available, please check the transaction has been committed in Database.

Body:
I am writing the script for practice and Following is the emp and department table :

Create table Employee
(
EmpId       int,
Name        varchar(30),
Designation varchar(50),
DateOfBirth date,
Salary      int,
Department  int,
Gender      char(2),
Primary key(empId),
    foreign key(empId) references Department(DeptId)
)
Create table Department
(
DeptId      int,
Department  varchar(30),
Primary key(DeptId)
)

When I am inserting rows into Employee table then I am getting the following error :

Msg 547, Level 16, State 0, Line 2
  The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Employee_EmpId". The conflict occurred in database "Ramandeep", table "dbo.Department", column 'DeptId'.
  The statement has been terminated.

Below is the row which I am trying to insert :

 Insert into Employee(EmpId,Name,Designation,DateOfBirth,Salary,Department,Gender) values (4,'Sam','Accountant','1973-05-13',6500,4,'M')

And values are available in Department table

Insert into Department(DeptId,Department) values (1,'HR')
Insert into Department(DeptId,Department) values (2,'Operation')
Insert into Department(DeptId,Department) values (3,'IT')
Insert into Department(DeptId,Department) values (4,'Admin')

I don't know why I am getting this error. Please help to fix it.


问:
Why is it impossible to drop user despite it exists in dba_users view
I try to drop/alter user like this

```<code>drop user AVASILIEV_AXIOM_10X
</code>```

And I get the following error

```<code>SQL> drop user AVASILIEV_AXIOM_10X;
drop user AVASILIEV_AXIOM_10X
          *
ERROR at line 1:
ORA-01918: user 'AVASILIEV_AXIOM_10X' does not exist
</code>```

But this user exists in the dba_users view:

```<code>SQL> select username from dba_users where username='AVASILIEV_AXIOM_10X';

USERNAME
------------------------------
AVASILIEV_AXIOM_10X

SQL>
</code>```

Also, I can't create user with the same name because it already exists in the DB. What's the problem?

My Oracle version:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
PL/SQL Release 11.2.0.4.0 - Production
"CORE   11.2.0.4.0  Production"
TNS for Linux: Version 11.2.0.4.0 - Production
NLSRTL Version 11.2.0.4.0 - Production

答:
This is old thread but for reference Oracle Doc ID 1297361.1 suggests as follows:

```<code>SQL> drop user ahong3;
</code>```

drop user ahong3
   *
ERROR at line 1:

```<code>ORA-01918: user 'AHONG3' does not exist

SQL> select username from dba_users where username='ahong3';

USERNAME
------------------------------
ahong3

SQL> execute hcheck.full
HCheck Version 8i-11/1.95

Found 0 potential problems and 0 warnings
</code>```

PL/SQL procedure successfully completed.

CAUSE
User was created forcibly in lower case.  Drop user considers the user to be in upper case, and hence can't find it.

Ex: below statement will force the creation of the user in lower case.

```<code>SQL> Create user "ahong3";
</code>```

SOLUTION
Force the drop user statement to drop the user created in lower case by specifying the user name in double quotes:

```<code>SQL> Drop user "ahong3";
</code>```

This solution worked for me

Body:
I try to drop/alter user like this

drop user AVASILIEV_AXIOM_10X

And I get the following error

SQL> drop user AVASILIEV_AXIOM_10X;
drop user AVASILIEV_AXIOM_10X
          *
ERROR at line 1:
ORA-01918: user 'AVASILIEV_AXIOM_10X' does not exist

But this user exists in the dba_users view:

SQL> select username from dba_users where username='AVASILIEV_AXIOM_10X';

USERNAME
------------------------------
AVASILIEV_AXIOM_10X

SQL>

Also, I can't create user with the same name because it already exists in the DB. What's the problem?

My Oracle version:
Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production
PL/SQL Release 11.2.0.4.0 - Production
"CORE   11.2.0.4.0  Production"
TNS for Linux: Version 11.2.0.4.0 - Production
NLSRTL Version 11.2.0.4.0 - Production

Body:
This is old thread but for reference Oracle Doc ID 1297361.1 suggests as follows:

SQL> drop user ahong3;

drop user ahong3
   *
ERROR at line 1:

ORA-01918: user 'AHONG3' does not exist

SQL> select username from dba_users where username='ahong3';

USERNAME
------------------------------
ahong3

SQL> execute hcheck.full
HCheck Version 8i-11/1.95

Found 0 potential problems and 0 warnings

PL/SQL procedure successfully completed.

CAUSE
User was created forcibly in lower case.  Drop user considers the user to be in upper case, and hence can't find it.

Ex: below statement will force the creation of the user in lower case.

SQL> Create user "ahong3";

SOLUTION
Force the drop user statement to drop the user created in lower case by specifying the user name in double quotes:

SQL> Drop user "ahong3";

This solution worked for me


问:
How to deploy application to minikube use registry in Kubernetes?
Intalled registry in Kubernetes kubectl create -f kube-registry.yaml.

There has docker image in it:

```<code>curl http://192.168.99.100:5000/v2/_catalog
{"repositories":["app1"]}
</code>```

Also did port-forward:

```<code>kubectl port-forward --namespace kube-system \
$(kubectl get po -n kube-system | grep kube-registry-v0 | \
awk '{print $1;}') 5000:5000
</code>```

Set image: 192.168.99.100:5000/app1 in Kubernetes deployment file(deployment.yaml).

After deploy it to cluster:

```<code>kubectl create -f deployment.yaml
</code>```

Check status from Kubernetes dashboard on Deployments menu, got error:

```<code>Failed to pull image "192.168.99.100:5000/app1": rpc error: code = 2 desc = Error response from daemon: {"message":"Get https://192.168.99.100:5000/v1/_ping: http: server gave HTTP response to HTTPS client"}
Error syncing pod
</code>```

The reason is can't get registry content from http protocol. How to resolve it?

Added insecure-registries by (The real content is 192.168.99.100:5000. Here is a different IP/port picture.)

答:
Useful resource

```<code>minikube start --insecure-registry "10.0.0.0/24"
</code>```

https://github.com/kubernetes/minikube/blob/master/docs/insecure_registry.md

Body:
Intalled registry in Kubernetes kubectl create -f kube-registry.yaml.

There has docker image in it:

curl http://192.168.99.100:5000/v2/_catalog
{"repositories":["app1"]}

Also did port-forward:

kubectl port-forward --namespace kube-system \
$(kubectl get po -n kube-system | grep kube-registry-v0 | \
awk '{print $1;}') 5000:5000

Set image: 192.168.99.100:5000/app1 in Kubernetes deployment file(deployment.yaml).

After deploy it to cluster:

kubectl create -f deployment.yaml

Check status from Kubernetes dashboard on Deployments menu, got error:

Failed to pull image "192.168.99.100:5000/app1": rpc error: code = 2 desc = Error response from daemon: {"message":"Get https://192.168.99.100:5000/v1/_ping: http: server gave HTTP response to HTTPS client"}
Error syncing pod

The reason is can't get registry content from http protocol. How to resolve it?

Added insecure-registries by (The real content is 192.168.99.100:5000. Here is a different IP/port picture.)

Body:
Useful resource

minikube start --insecure-registry "10.0.0.0/24"

https://github.com/kubernetes/minikube/blob/master/docs/insecure_registry.md


问:
How to read a too long repo diff
I'm trying to read the output of the repo diff command but it is too long to be shown on the terminal, so I can't read the whole thing. Is there any solution like exporting the output in a file so I can read all the lines?

答:
You can pipe output to less:</p>

```<code>git diff HEAD^ HEAD | less
</code>```

Title: How to read a too long repo diff

Body:
You can pipe output to less:

git diff HEAD^ HEAD | less


问:
JSON Array request cannot be applied error listener
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

```<code>private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }
</code>```

答:
It seems like you're passing wrong arguments to JsonArrayRequest().
According to the documentation found here, the method signature is public JsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) and you're passing (int, String, null, Response.Listener<JSONArray>, Response.ErrorListener).

Remove the Request.Method.POST and the null and you should be good to go.

Body:
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }


问:
Apache Flink: How to count the total number of events in a DataStream
I have two raw streams and I am joining those streams and then I want to count what is the total number of events that have been joined and how much events have not. I am doing this by using map on joinedEventDataStream as shown below

```<code>joinedEventDataStream.map(new RichMapFunction<JoinedEvent, Object>() {

            @Override
            public Object map(JoinedEvent joinedEvent) throws Exception {

                number_of_joined_events += 1;

                return null;
            }
        });
</code>```

Question # 1: Is this the appropriate way to count the number of events in the stream?

Question # 2: I have noticed a wired behavior, which some of you might not believe. The issue is that when I run my Flink program in IntelliJ IDE, it shows me correct value for number_of_joined_events but 0 in the case when I submit this program as jar. So I am getting the initial value of number_of_joined_events when I run the program as a jar file instead of the actual count. Why is this happening only in case of jar file submission and not in IDE?

答:
Your approach is not working. The behavior you  noticed when executing the program via a JAR file is expected.

I don't know how number_of_joined_events is defined, but I assume its a static variable in your program. When you run the program in your IDE, it runs in a single JVM. Hence, all operators have access to the static variable. When you submit a JAR file to a remote process, the program is executed in a different JVM (possibly multiple JVMs) and the static variable in your client process is never updated.

You can use Flink's metrics or a ReduceFunction that sums 1s to count the number of processed records.

Body:
I have two raw streams and I am joining those streams and then I want to count what is the total number of events that have been joined and how much events have not. I am doing this by using map on joinedEventDataStream as shown below

joinedEventDataStream.map(new RichMapFunction<JoinedEvent, Object>() {

            @Override
            public Object map(JoinedEvent joinedEvent) throws Exception {

                number_of_joined_events += 1;

                return null;
            }
        });

Question # 1: Is this the appropriate way to count the number of events in the stream?

Question # 2: I have noticed a wired behavior, which some of you might not believe. The issue is that when I run my Flink program in IntelliJ IDE, it shows me correct value for number_of_joined_events but 0 in the case when I submit this program as jar. So I am getting the initial value of number_of_joined_events when I run the program as a jar file instead of the actual count. Why is this happening only in case of jar file submission and not in IDE?


问:
TabLayout Not Binding to Viewpager
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.

For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.

Here is my code...I'm wondering what I am doing wrong.

PopularHolderFragment.java

```<code>import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Andrew Quebe on 10/20/2017.
 */

@SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularHolderFragment newInstance() {
        return new PopularHolderFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));

        tabLayout.addTab(tabLayout.newTab().setText("Posts"));
        tabLayout.addTab(tabLayout.newTab().setText("Users"));
        tabLayout.setupWithViewPager(viewPager);
    }
}
</code>```

PopularFragmentsAdapter.java

```<code>import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;

/**
 * Created by Andrew Quebe on 8/7/2017.
 */

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

    public PopularFragmentsAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

    @Override
    public int getCount() {
        return 2;
    }
}
</code>```

fragment_popular_holder.xml

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="2dp"
            tools:targetApi="lollipop" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/util_popular_main_content" />

</android.support.design.widget.CoordinatorLayout>
</code>```

util_popular_main_content.xml

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_popular_holder">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>
</code>```

Screenshots

Also wondering why the text isn't its normal size.

Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.

答:
May be my answer is not correct answer for your question. I faced same issue while dealing with Fragments... Below is the mistake I did.

```<code>return super.onCreateView(inflater, container, savedInstanceState);
</code>```

This was creating this kind of issue. I removed this sentence and just inflated some view from the layout files, then it was working fine.

Just check your onCreateView function it will probably solve your problem.

My point is clear here. You should return your inflated view in onCreateView function instead of super.onCreateView(inflater, container, savedInstanceState);

Title: TabLayout Not Binding to Viewpager

Body:
I have a fragment which hosts a TabLayout and a ViewPager. The host fragment is part of a container that switches based on the item selection of a bottom navigation bar.

For some reason, the ViewPager isn't inflating the fragments, and the TabLayout is unresponsive. When sliding left or right, the indicator stops as soon as you stop sliding, and doesn't snap like it should. And, of course, the fragments don't show.

Here is my code...I'm wondering what I am doing wrong.

PopularHolderFragment.java

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ai.gab.android.R;
import ai.gab.android.ui.adapters.fragment.PopularFragmentsAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Andrew Quebe on 10/20/2017.
 */

@SuppressWarnings("ConstantConditions")
public class PopularHolderFragment extends Fragment {

    @BindView(R.id.tabLayout)
    TabLayout tabLayout;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    public static PopularHolderFragment newInstance() {
        return new PopularHolderFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_popular_holder, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewPager.setAdapter(new PopularFragmentsAdapter(getActivity().getSupportFragmentManager()));

        tabLayout.addTab(tabLayout.newTab().setText("Posts"));
        tabLayout.addTab(tabLayout.newTab().setText("Users"));
        tabLayout.setupWithViewPager(viewPager);
    }
}

PopularFragmentsAdapter.java

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import ai.gab.android.ui.fragments.popular.PopularPostsFragment;
import ai.gab.android.ui.fragments.popular.PopularUsersFragment;

/**
 * Created by Andrew Quebe on 8/7/2017.
 */

public class PopularFragmentsAdapter extends FragmentStatePagerAdapter {

    public PopularFragmentsAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return PopularPostsFragment.newInstance();
            case 1:
                return PopularUsersFragment.newInstance();
        }
        return null;
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Posts";
            case 1:
                return "Users";
        }
        return super.getPageTitle(position);
    }

    @Override
    public int getCount() {
        return 2;
    }
}

fragment_popular_holder.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.activities.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Light">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="2dp"
            tools:targetApi="lollipop" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/util_popular_main_content" />

</android.support.design.widget.CoordinatorLayout>

util_popular_main_content.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_popular_holder">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.constraint.ConstraintLayout>

Screenshots

Also wondering why the text isn't its normal size.

Note that I do not want a toolbar in this layout, and perhaps that is my issue, but I don't see why it would be as the widgets should be able to work independently of each other.

Body:
May be my answer is not correct answer for your question. I faced same issue while dealing with Fragments... Below is the mistake I did.

return super.onCreateView(inflater, container, savedInstanceState);

This was creating this kind of issue. I removed this sentence and just inflated some view from the layout files, then it was working fine.

Just check your onCreateView function it will probably solve your problem.

My point is clear here. You should return your inflated view in onCreateView function instead of super.onCreateView(inflater, container, savedInstanceState);


问:
Configure the Smidge library for asp.net core
Scott Hanselman today blogged about Smidge. I think the library is pretty nice and I'm evaluating the library.

I like the option to define logic for Debug and Production like in the sample:

```<code>bundles.CreateJs("test-bundle-3", "~/Js/Bundle3")
   .WithEnvironmentOptions(BundleEnvironmentOptions.Create()
      .ForDebug(builder => builder
         .EnableCompositeProcessing()
         .EnableFileWatcher()
         .SetCacheBusterType<AppDomainLifetimeCacheBuster>()
         .CacheControlOptions(enableEtag: false, cacheControlMaxAge: 0))
      .Build()
</code>```

However I couldn't find out what defines Debug/Production. Is there a way to tell the system when he's in debug and when he is in production mode?

Also seems that the Version can only be defined in the config.

```<code>"smidge": {
  "dataFolder" : "App_Data/Smidge",
  "version" : "1"
}
</code>```

Is there an option do define the version in the code?

答:
There's a section in the Rendering docs on debugging, included here for completeness:

By default Smidge will combine/compress/minify but while you are developing you probably don't want this to happen. Each of the above rendering methods has an optional boolean 'debug' parameter. If you set this to true then the combine/compress/minify is disabled.

It goes on to include an example of how to manage this using ASP.NET Core MVC's environment Tag Helper:

```<code><environment names="Development">
    <script src="my-awesome-js-bundle" type="text/javascript" debug="true"></script>
</environment>
<environment names="Staging,Production">
    <script src="my-awesome-js-bundle" type="text/javascript"></script>
</environment>
</code>```

SmidgeConfig obtains the version from IConfiguration directly, as can be seen in the source:

```<code>public string Version => _config["version"] ?? "1";
</code>```

This means you can't change it within the code itself, but you might be able to add something to the ASP.NET Core configuration system in order to provide a different value for this.

EDIT: I looked into the configuration thing a bit more and concluded that you could achieve what you want with AddInMemoryCollection. The docs give a good example of how to use this, so I've included a context-specific example for you below, adapted from the example code:

```<code>var dict = new Dictionary<string, string>
{
    {"smidge:version", "1"}
};

var builder = new ConfigurationBuilder();

// ...
// Whatever code you're using to set up the builder.
// If you're in ASP.NET Core 2, this will be setup differently, but the docs cover it well.
// ...

builder.AddInMemoryCollection(dict);
</code>```

Body:
Scott Hanselman today blogged about Smidge. I think the library is pretty nice and I'm evaluating the library.

I like the option to define logic for Debug and Production like in the sample:

bundles.CreateJs("test-bundle-3", "~/Js/Bundle3")
   .WithEnvironmentOptions(BundleEnvironmentOptions.Create()
      .ForDebug(builder => builder
         .EnableCompositeProcessing()
         .EnableFileWatcher()
         .SetCacheBusterType<AppDomainLifetimeCacheBuster>()
         .CacheControlOptions(enableEtag: false, cacheControlMaxAge: 0))
      .Build()

However I couldn't find out what defines Debug/Production. Is there a way to tell the system when he's in debug and when he is in production mode?

Also seems that the Version can only be defined in the config.

"smidge": {
  "dataFolder" : "App_Data/Smidge",
  "version" : "1"
}

Is there an option do define the version in the code?

Body:
There's a section in the Rendering docs on debugging, included here for completeness:

By default Smidge will combine/compress/minify but while you are developing you probably don't want this to happen. Each of the above rendering methods has an optional boolean 'debug' parameter. If you set this to true then the combine/compress/minify is disabled.

It goes on to include an example of how to manage this using ASP.NET Core MVC's environment Tag Helper:

<environment names="Development">
    <script src="my-awesome-js-bundle" type="text/javascript" debug="true"></script>
</environment>
<environment names="Staging,Production">
    <script src="my-awesome-js-bundle" type="text/javascript"></script>
</environment>

SmidgeConfig obtains the version from IConfiguration directly, as can be seen in the source:

public string Version => _config["version"] ?? "1";

This means you can't change it within the code itself, but you might be able to add something to the ASP.NET Core configuration system in order to provide a different value for this.

EDIT: I looked into the configuration thing a bit more and concluded that you could achieve what you want with AddInMemoryCollection. The docs give a good example of how to use this, so I've included a context-specific example for you below, adapted from the example code:

var dict = new Dictionary<string, string>
{
    {"smidge:version", "1"}
};

var builder = new ConfigurationBuilder();

// ...
// Whatever code you're using to set up the builder.
// If you're in ASP.NET Core 2, this will be setup differently, but the docs cover it well.
// ...

builder.AddInMemoryCollection(dict);


问:
Call accept_invitation_url in a different view
I need to call accept_invitation_url(@resource, :invitation_token => @token) in a different view outside of the devise mailer and when doing that i got an err

```<code>ActionView::Template::Error: Could not find a valid mapping for nil
from /var/lib/gems/2.3.0/gems/devise-4.3.0/lib/devise/mapping.rb:44:in `find_scope!'
</code>```

Is it not the right way to do it? I just want to be able to invite users from a different view

答:
i found a way to do this.</p>

```<code>@token, encrypted_token = Devise.token_generator.generate(User, :invitation_token) @user.update_attribute(invitation_token: encrypted_token)
</code>```

Body:
I need to call accept_invitation_url(@resource, :invitation_token => @token) in a different view outside of the devise mailer and when doing that i got an err

ActionView::Template::Error: Could not find a valid mapping for nil
from /var/lib/gems/2.3.0/gems/devise-4.3.0/lib/devise/mapping.rb:44:in `find_scope!'

Is it not the right way to do it? I just want to be able to invite users from a different view

Body:
i found a way to do this.

@token, encrypted_token = Devise.token_generator.generate(User, :invitation_token) @user.update_attribute(invitation_token: encrypted_token)


问:
adsisearcher error: "The (mail=john.doe)) search filter is invalid"
I have a question, regarding mail address-generation logic. It'll start by assuming FirstName.Lastname, and check if that's already in AD.

If it already exists, it will add numbers of the end last-name until it finds an unused mail address:

john.doe@contoso.com, john.doe2@contoso.com, john.doe3@contoso.com, etc.

Note: we have the first name as $FirstName and the last name as $LastName

```<code>$count = $null
do {
    $query = "(mail=$username$count))"
    $result = ([adsisearcher]$query).FindOne()
    if ($result) {if ($count -eq $null) {$count = 2} else {$count++}}
} while ($result)

Write-Host "The account name you should use is: $username$count"
</code>```

Here my error message is:

Exception calling "FindOne" with "0" argument(s): "The (mail=john.doe)) search filter is invalid."

  At line:5 char:45

答:
If i'm understand you well, you want to find the next available email address and add 1 to the end of it in case it it exist?

if so, you can use this simple function:

add your input as email format, and it will add 1 until it not found it, and return the available mail

```<code>Function Get-AvailableMail()
{
Param(
$Email
)

$i = 1

    while (([adsisearcher]"(&(mail= $($Email)))").FindOne())
    {
    $Email = ($Email -split '@')[0] + "$i@" + ($Email -split '@')[1]
    $i++
    }

    return $Email

}
</code>```

Body:
I have a question, regarding mail address-generation logic. It'll start by assuming FirstName.Lastname, and check if that's already in AD.

If it already exists, it will add numbers of the end last-name until it finds an unused mail address:

john.doe@contoso.com, john.doe2@contoso.com, john.doe3@contoso.com, etc.

Note: we have the first name as $FirstName and the last name as $LastName

$count = $null
do {
    $query = "(mail=$username$count))"
    $result = ([adsisearcher]$query).FindOne()
    if ($result) {if ($count -eq $null) {$count = 2} else {$count++}}
} while ($result)

Write-Host "The account name you should use is: $username$count"

Here my error message is:

Exception calling "FindOne" with "0" argument(s): "The (mail=john.doe)) search filter is invalid."

  At line:5 char:45

Body:
If i'm understand you well, you want to find the next available email address and add 1 to the end of it in case it it exist?

if so, you can use this simple function:

add your input as email format, and it will add 1 until it not found it, and return the available mail

Function Get-AvailableMail()
{
Param(
$Email
)

$i = 1

    while (([adsisearcher]"(&(mail= $($Email)))").FindOne())
    {
    $Email = ($Email -split '@')[0] + "$i@" + ($Email -split '@')[1]
    $i++
    }

    return $Email

}