问:
Office.JS “This add-in is no longer available” error when creating a Word Document with context.application.createDocument()
I'm developing an add-in for Microsoft Word 2016 using office js version 16.0.8626.1000. I use a web service to retrieve a document in base64 format and then I create a new Word instance with that.

The problem is that whenever I run the add-in from my server (not from visual studio debugger) it opens the document but the add-in frame displays an error

First Instance:

Second Instance:

This doesn't happen if I run the add-in from visual studio debugger, it opens the new instance without the frame.

This is my code

Office.initialize = function (reason) {
    // Checks for the DOM to load using the jQuery ready function.
    $(document).ready(function () {
        $('#get').click(function () {
            openWord();
        });
    });
}
```

<p>This how I retrieve the document (without real url):</p>

<pre class="lang-js prettyprint-override"><code>function openWord() {
    getDocumentAsBase64(function (data) {
        Word.run(function (context) {
            var myNewDoc = context.application.createDocument(data);
            context.load(myNewDoc);

            return context.sync()
                .then(function () {
                    myNewDoc.open();
                    context.sync();
                })
                .catch(function (myError) {
                    //otherwise we handle the exception here!
                    updateStatus(myError.message);
                })
        }).catch(function (myError) {
            updateStatus(myError.message);
        });
    });
}

function getDocumentAsBase64(callback) {
    $.ajax({
        url: 'http://myurltomydocument.com/getFile',
        data: "{}",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            callback(response.d);
        },
        error: function (response) {
            updateStatus(response.d);
        }
    });
}
</code>```

EDIT -- 8/12/2017

This is the manifest that I'm currently using if anyone wants to replicate the problem with Office 2016

答:
I don't read Spanish, but the error mentions Visual Studio. I think Office is still trying to run a version that was sideloaded with Visual Studio and it's telling you that it can't do that. The problem might be the manifest. I notice that it still has the string ~remoteAppUrl in many places. When you are debugging with VS, this string is automatically replaced with the localhost URL, but you need to manually change all these to your web service's domain and sideload the new manifest when you are going to run it from the web service.

EDIT 12/11/17:
If that doesn't fix it, try clearing the Office cache. Details are at: Clear the Office cache

Edit 12/19/17:
Try this:

Go on File->Info->Check for Issues -> Inspect Document -> Inspect.
Then on Task Pane Add-ins click Remove All

Body:
I'm developing an add-in for Microsoft Word 2016 using office js version 16.0.8626.1000. I use a web service to retrieve a document in base64 format and then I create a new Word instance with that.

The problem is that whenever I run the add-in from my server (not from visual studio debugger) it opens the document but the add-in frame displays an error

First Instance:

Second Instance:

This doesn't happen if I run the add-in from visual studio debugger, it opens the new instance without the frame.

This is my code

Office.initialize = function (reason) {
    // Checks for the DOM to load using the jQuery ready function.
    $(document).ready(function () {
        $('#get').click(function () {
            openWord();
        });
    });
}

This how I retrieve the document (without real url):

function openWord() {
    getDocumentAsBase64(function (data) {
        Word.run(function (context) {
            var myNewDoc = context.application.createDocument(data);
            context.load(myNewDoc);

            return context.sync()
                .then(function () {
                    myNewDoc.open();
                    context.sync();
                })
                .catch(function (myError) {
                    //otherwise we handle the exception here!
                    updateStatus(myError.message);
                })
        }).catch(function (myError) {
            updateStatus(myError.message);
        });
    });
}

function getDocumentAsBase64(callback) {
    $.ajax({
        url: 'http://myurltomydocument.com/getFile',
        data: "{}",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            callback(response.d);
        },
        error: function (response) {
            updateStatus(response.d);
        }
    });
}

EDIT -- 8/12/2017

This is the manifest that I'm currently using if anyone wants to replicate the problem with Office 2016


来源: stackexchange

问:
Save a List of custom object in savedInstanceState
I am currently building an app to retrieve information for a remote server. the data received are JSON and I am build a list of Data using the class below :

```<code>public class RedditData {

    private RedditTopic data;

    public RedditTopic getData() {
        return data;
    }
}
</code>```

and RedditTopic class is defined as below:

```<code>public final class RedditTopic {
    private static final String TAG = RedditTopic.class.getSimpleName();

    private String author;
    private String thumbnail;
    private String title;
    private String num_comments;
    private long created_utc;
    private String data;
    private String name;

    public RedditTopic(){};

    public String getData() {
        return data;
    }

    public String getAuthor() {
        return author;
    }

    public String getThumbnail(){
        return thumbnail;
    }

    public String getTitle(){
        return title;
    }

    public String getComments(){
        return num_comments + " comments";
    }

    public long getCreated_utc(){
        return created_utc;
    }

    public String getRedditName(){
        return name;
    }
}
</code>```

both of these classes are used to translate a JSON into an Object formatted data.

I do not want to really change them to make them Parceable to avoid impacting the extraction of JSON.

I have added :

```<code>@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> SAVE");
    savedInstanceState.putParcelableArrayList("RedditList", myListOfData );
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> RESTORE");
    List<RedditData> myListOfData = savedInstanceState.getParcelableArrayList("RedditList");
}
</code>```

Android complain because I need to implement Parceable in my class RedditData and I assume probably in the RedditTopic Class as well because RedditData returned a List of RedditTopic.

Is there a better way to do it? keep the List as I have it without requiring the Parceable option.

I do not have a List of String, it's a list of object.

Any idea?

Regards

答:
Make your model objects parcleable.

There is a great extension, https://plugins.jetbrains.com/plugin/7332-android-parcelable-code-generator that will generate the neccesary parcelable methods for your class.

I highly recommend it.

ContentLicense: CC BY-SA 3.0

Body:
I am currently building an app to retrieve information for a remote server. the data received are JSON and I am build a list of Data using the class below :

public class RedditData {

    private RedditTopic data;

    public RedditTopic getData() {
        return data;
    }
}

and RedditTopic class is defined as below:

public final class RedditTopic {
    private static final String TAG = RedditTopic.class.getSimpleName();

    private String author;
    private String thumbnail;
    private String title;
    private String num_comments;
    private long created_utc;
    private String data;
    private String name;

    public RedditTopic(){};

    public String getData() {
        return data;
    }

    public String getAuthor() {
        return author;
    }

    public String getThumbnail(){
        return thumbnail;
    }

    public String getTitle(){
        return title;
    }

    public String getComments(){
        return num_comments + " comments";
    }

    public long getCreated_utc(){
        return created_utc;
    }

    public String getRedditName(){
        return name;
    }
}

both of these classes are used to translate a JSON into an Object formatted data.

I do not want to really change them to make them Parceable to avoid impacting the extraction of JSON.

I have added :

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> SAVE");
    savedInstanceState.putParcelableArrayList("RedditList", myListOfData );
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>>> RESTORE");
    List<RedditData> myListOfData = savedInstanceState.getParcelableArrayList("RedditList");
}

Android complain because I need to implement Parceable in my class RedditData and I assume probably in the RedditTopic Class as well because RedditData returned a List of RedditTopic.

Is there a better way to do it? keep the List as I have it without requiring the Parceable option.

I do not have a List of String, it's a list of object.

Any idea?

Regards


问:
Get ID value from html string
I grabbed outlook's appointment description and got this string:

```<code><html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
  ID: 123456<br>
  Comments: blah blah
</body>
</html>
</code>```

I need to get ID value 123456 and Comments value out with c# code. I can only use standard .NET library, that is, I can't use html agility pack. I did something like this:

```<code>var index = html.IndexOf("ID");
var IDindex = index + "ID".Length + 2 ;
var IDvalue = html.Substring( IDIndex,6);
</code>```

But I like to do something more robust to handle for example ID length change.

答:
I would try something with a regular expression match and checking the 1st captured group of a regex like ID:\s*(\d+)

```<code>using System;
using System.Text.RegularExpressions;

namespace RegexExample
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Match match in Regex.Matches("ID: 12345<br />", @"ID:\s*(\d+)<br />"))
                Console.WriteLine(match.Groups[1]);
        }
    }
}
</code>```

Title: Get ID value from html string

Body:
I grabbed outlook's appointment description and got this string:

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  ID: 123456

  Comments: blah blah

I need to get ID value 123456 and Comments value out with c# code. I can only use standard .NET library, that is, I can't use html agility pack. I did something like this:

var index = html.IndexOf("ID");
var IDindex = index + "ID".Length + 2 ;
var IDvalue = html.Substring( IDIndex,6);

But I like to do something more robust to handle for example ID length change.

Body:
I would try something with a regular expression match and checking the 1st captured group of a regex like ID:\s*(\d+)<br />

using System;
using System.Text.RegularExpressions;

namespace RegexExample
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Match match in Regex.Matches("ID: 12345<br />", @"ID:\s*(\d+)<br />"))
                Console.WriteLine(match.Groups[1]);
        }
    }
}


问:
Fixing an element inside the scrollable div
The .parent div has overflow: scroll and the .child has position: fixed. I'd like to scroll the content of the .parent div while preserving the .child's position inside it.

.parent {
  border: 1px;
  height: 500px;
  width: 900px;
  overflow: scroll;
}

.child {
  background: black;
  color: white;
  position: fixed;
  height: 100px;
  width: 900px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  parent
  <div class="child">
    child
  </div>
</div></code>```

答:
.parent {
height:500px;
width:500px;
overflow:scroll;
position:absolute;
background:black;
}

.child {

position: sticky;
top:0;
height:80px;
width:500px;
background-color: #cae8ca;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "parent" >
<div class = "child"  >
chi
</div>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
</div></code>```

Body:
The .parent div has overflow: scroll and the .child has position: fixed. I'd like to scroll the content of the .parent div while preserving the .child's position inside it.

.parent {
  border: 1px;
  height: 500px;
  width: 900px;
  overflow: scroll;
}

.child {
  background: black;
  color: white;
  position: fixed;
  height: 100px;
  width: 900px;
}

  parent

    child

Body:
.parent {
height:500px;
width:500px;
overflow:scroll;
position:absolute;
background:black;
}

.child {

position: sticky;
top:0;
height:80px;
width:500px;
background-color: #cae8ca;
}

<div class = "parent" >
<div class = "child"  >
chi
</div>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
<hr>
<br>
</div>


问:
RecyclerView "cannot resolve symbol" errors - Android Studio
I am getting cannot resolve symbol errors on all my RecyclerView's.  What is going on?  Because I have an error with RecyclerView, I also have errors on LayoutManager.  My last four Override statements are in the wrong place and I don't know where they go.  I am a beginner and have a very basic knowledge of programming so I don't know how to fix this.  I am taking a class but the professor isn't helpful at all.</p>

```<code>package com.bignerdranch.android.criminalintent;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class CrimeListFragment extends Fragment {

    private RecyclerView mCrimeRecyclerView;
    private CrimeAdapter mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crime_list, container, false);

        mCrimeRecyclerView = (RecyclerView) view
                .findViewById(R.id.crime_recycler_view);
        mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void updateUI(){
        CrimeLab crimeLab = CrimeLab.get(getActivity());
        List<Crime> crimes = crimeLab.getCrimes();

        if (mAdapter == null) {
            mAdapter = new CrimeAdapter(crimes);
            mCrimeRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }
        private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
            private List<Crime> mCrimes;
            public CrimeAdapter(List<Crime> crimes) {
                mCrimes = crimes;
            }
        }
        private class CrimeHolder extends RecyclerView.ViewHolder
                implements View.OnClickListener {
            private TextView mTitleTextView;
            private TextView mDateTextView;
            private CheckBox mSolvedCheckBox;
            private Crime mCrime;

            public CrimeHolder(View itemView) {
                super(itemView);

                mTitleTextView = (TextView)
                        itemView.findViewById(R.id.list_item_crime_title_text_view);
                mDateTextView = (TextView)
                        itemView.findViewById(R.id.list_item_crime_date_text_view);
                mSolvedCheckBox = (CheckBox)
                        itemView.findViewById(R.id.list_item_crime_solved_check_box);
            }

            public void bindCrime(Crime crime) {
                mCrime = crime;
                mTitleTextView.setText(mCrime.getTitle());
                mDateTextView.setText(mCrime.getDate().toString());
                mSolvedCheckBox.setChecked(mCrime.isSolved());
            }

            @Override
            public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                View view = layoutInflater.inflate(R.layout.list_item_crime, parent, false);
                return new CrimeHolder(view);
            }

            @Override
            public void onBindViewHolder(CrimeHolder holder, int position) {
                Crime crime = mCrimes.get(position);
                holder.bindCrime(crime);
            }

            @Override
            public int getItemCount() {
                return mCrimes.size();
            }

            @Override
            public void onClick(View v) {
                Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
                startActivity(intent);
            }
        }
}
</code>```

答:
For the latest version of Android Studio 3:

Find your gradle file under Gradle Scripts, build.gradle (Module)

Add dependency:

```<code>dependencies {
...
    implementation 'com.android.support:cardview-v7:27.0.+'
    implementation 'com.android.support:recyclerview-v7:27.0.+'

}
</code>```

Sync your gradle file (File / Sync Project with gradle files).

Go back to your code and hit ALT+Enter on the missing reference.

That should be it.

Body:
I am getting cannot resolve symbol errors on all my RecyclerView's.  What is going on?  Because I have an error with RecyclerView, I also have errors on LayoutManager.  My last four Override statements are in the wrong place and I don't know where they go.  I am a beginner and have a very basic knowledge of programming so I don't know how to fix this.  I am taking a class but the professor isn't helpful at all.

package com.bignerdranch.android.criminalintent;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class CrimeListFragment extends Fragment {

    private RecyclerView mCrimeRecyclerView;
    private CrimeAdapter mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crime_list, container, false);

        mCrimeRecyclerView = (RecyclerView) view
                .findViewById(R.id.crime_recycler_view);
        mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void updateUI(){
        CrimeLab crimeLab = CrimeLab.get(getActivity());
        List<Crime> crimes = crimeLab.getCrimes();

        if (mAdapter == null) {
            mAdapter = new CrimeAdapter(crimes);
            mCrimeRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }
        private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
            private List<Crime> mCrimes;
            public CrimeAdapter(List<Crime> crimes) {
                mCrimes = crimes;
            }
        }
        private class CrimeHolder extends RecyclerView.ViewHolder
                implements View.OnClickListener {
            private TextView mTitleTextView;
            private TextView mDateTextView;
            private CheckBox mSolvedCheckBox;
            private Crime mCrime;

            public CrimeHolder(View itemView) {
                super(itemView);

                mTitleTextView = (TextView)
                        itemView.findViewById(R.id.list_item_crime_title_text_view);
                mDateTextView = (TextView)
                        itemView.findViewById(R.id.list_item_crime_date_text_view);
                mSolvedCheckBox = (CheckBox)
                        itemView.findViewById(R.id.list_item_crime_solved_check_box);
            }

            public void bindCrime(Crime crime) {
                mCrime = crime;
                mTitleTextView.setText(mCrime.getTitle());
                mDateTextView.setText(mCrime.getDate().toString());
                mSolvedCheckBox.setChecked(mCrime.isSolved());
            }

            @Override
            public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                View view = layoutInflater.inflate(R.layout.list_item_crime, parent, false);
                return new CrimeHolder(view);
            }

            @Override
            public void onBindViewHolder(CrimeHolder holder, int position) {
                Crime crime = mCrimes.get(position);
                holder.bindCrime(crime);
            }

            @Override
            public int getItemCount() {
                return mCrimes.size();
            }

            @Override
            public void onClick(View v) {
                Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
                startActivity(intent);
            }
        }
}

Body:
For the latest version of Android Studio 3:

Find your gradle file under Gradle Scripts, build.gradle (Module)

Add dependency:

dependencies {
...
    implementation 'com.android.support:cardview-v7:27.0.+'
    implementation 'com.android.support:recyclerview-v7:27.0.+'

}

Sync your gradle file (File / Sync Project with gradle files).

Go back to your code and hit ALT+Enter on the missing reference.

That should be it.


问:
How to remove log at start if it's declared as global?
I would like to use global log file. I declared it's as:

```<code>string logName = "ProcessingLog.txt";
FileLogger fLogger;
static this()
{
    fLogger = new FileLogger(logName);
}
void main()
{
 if (someCondition)
     remove(logName);
}
</code>```

But in main on some conditional I would like to recreate it (remove old and create new one), but the problem that I can't call function removeOldLog(); because current log is blocked by running app.

Removing log inside main is blocking by the same process. I tried to to move fLogger = new FileLogger(logName); in before every function that engender log, but than I got runtime error during it's writting. So it's seems that FileLogger should be init globally.

What is the right way to do it?

答:
You should open the file yourself and pass them as parameter:

```<code>auto file = File("logFile.log", "w");
auto log = new FileLogger(file);

if (some condition)
{
    file.close;
    remove(file.name);
}
</code>```

But remind that if the file gets closed, using the FileLogger for logging will result in undefined behaviour.

Body:
I would like to use global log file. I declared it's as:

string logName = "ProcessingLog.txt";
FileLogger fLogger;
static this()
{
    fLogger = new FileLogger(logName);
}
void main()
{
 if (someCondition)
     remove(logName);
}

But in main on some conditional I would like to recreate it (remove old and create new one), but the problem that I can't call function removeOldLog(); because current log is blocked by running app.

Removing log inside main is blocking by the same process. I tried to to move fLogger = new FileLogger(logName); in before every function that engender log, but than I got runtime error during it's writting. So it's seems that FileLogger should be init globally.

What is the right way to do it?

Body:
You should open the file yourself and pass them as parameter:

auto file = File("logFile.log", "w");
auto log = new FileLogger(file);

if (some condition)
{
    file.close;
    remove(file.name);
}

But remind that if the file gets closed, using the FileLogger for logging will result in undefined behaviour.


问:
Calculate hour difference between given date and current date in C#
I want to check to see how many hours difference there are between a given date and the current date. I'm looking for a date that's less then 24 hours away!

I thought this would work but it's giving me a true statement when the EventDateTime is Sunday which is greater then 24 hours out!

```<code>bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).Hours < 24 ? true : false;
</code>```

答:
Use .TotalHours

(spaceEvent.EventDateTime - DateTime.Now).TotalHours < 24

put that inside Math.Abs() if you want the proximity of 24 hour regardless which time is first

Use DateTimeOffset instead of DateTime so that time zones don't mess up your math.

Body:
I want to check to see how many hours difference there are between a given date and the current date. I'm looking for a date that's less then 24 hours away!

I thought this would work but it's giving me a true statement when the EventDateTime is Sunday which is greater then 24 hours out!

bool lessThen24Hours = (spaceEvent.EventDateTime - DateTime.Now).Hours < 24 ? true : false;


问:
groovy how create array with name?
IM trying to use this command in groovy but I cant print the array

appears and error

```<code>       Caught: java.lang.IllegalArgumentException: argument type mismatch
</code>```

java.lang.IllegalArgumentException: argument type mismatch
    at Test.main(Test.groovy:7)

how I could solve this

I use this same command without this line  and this works

```<code>          testArray["fff"] = "B"
</code>```

this is my code

I dont know because I cant create this 2d array

```<code> def testArray =  []
  testArray[0] = "A"
      testArray["fff"] = "B"
      testArray[2] = "C"

   println testArray
</code>```

please give me a help

答:
Arrays only take ints as indices.
"fff" is not a valid value for an index, therefore java crashes, telling you its a mismatch.

If you want to create a 2d array of Strings then you should try this.

String[][] testArray = new String[x][y];

where x and y are the dimensions for this array.

Title: groovy how create array with name?

Body:
IM trying to use this command in groovy but I cant print the array

appears and error

       Caught: java.lang.IllegalArgumentException: argument type mismatch

java.lang.IllegalArgumentException: argument type mismatch
    at Test.main(Test.groovy:7)

how I could solve this

I use this same command without this line  and this works

          testArray["fff"] = "B"

this is my code

I dont know because I cant create this 2d array

 def testArray =  []
  testArray[0] = "A"
      testArray["fff"] = "B"
      testArray[2] = "C"

   println testArray

please give me a help


问:
In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

```<code>extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}
</code>```

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

```<code>extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}
</code>```

I simply want to print the data type to the debug window, not do testing with is or as, etc.  It's strictly for logging/debugging reasons.

答:
In Swift 4 you can achieve that like this:</p>

```<code>static func map(value: Any) -> Any.Type {
    return type(of: value)
}
</code>```

Body:
What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}

I simply want to print the data type to the debug window, not do testing with is or as, etc.  It's strictly for logging/debugging reasons.

Body:
In Swift 4 you can achieve that like this:

static func map(value: Any) -> Any.Type {
    return type(of: value)
}


问:
How do I create a time series in R from Bureau of Economic Analysis Data?
BEA Data

I have a data frame (image above) with data from all 50 states plus DC that lists state economic output (in millions of current dollars) for three combined industry segments from 1997-2015.

How do I create a time series from data in this particular format?

答:
Suppose we have Lines as shown below.  Then we can read it into a data frame specifying that the row names are in column 1.   If it is in a file instead replace text = Lines with something like "myfile".  In R, multivariate time series are normally in columns, not rows, so we transpose it and create a zoo series from that.

At this point it can be used as is or converted using as.ts(z), fortify.zoo(z), fortify.zoo(z, melt = TRUE), coredata(z) or time(z) among other possibilities.

```<code>Lines <- "
Area 1997 1998 1999
A       1    2    3
B       4    5    6"

DF <- read.table(text = Lines, header = TRUE, check.names = FALSE, row.names = 1)

library(zoo)
z <- zoo(t(DF), as.numeric(colnames(DF)))
</code>```

Body:
Suppose we have Lines as shown below.  Then we can read it into a data frame specifying that the row names are in column 1.   If it is in a file instead replace text = Lines with something like "myfile".  In R, multivariate time series are normally in columns, not rows, so we transpose it and create a zoo series from that.

At this point it can be used as is or converted using as.ts(z), fortify.zoo(z), fortify.zoo(z, melt = TRUE), coredata(z) or time(z) among other possibilities.

Lines <- "
Area 1997 1998 1999
A       1    2    3
B       4    5    6"

DF <- read.table(text = Lines, header = TRUE, check.names = FALSE, row.names = 1)

library(zoo)
z <- zoo(t(DF), as.numeric(colnames(DF)))


问:
TypeError: db.collection is not a function, CANNOT GET
i'm trying to get some data from the apiRoutes.get('/resources/productinfo/:name') and i have this error, i dont know whats going wrong... also the apiRoutes.get('/book/:title') doesnt seems to work! i dont know what am i doing wrong

UPDATED:

```<code>>       TypeError: Cannot read property 'findOne' of undefined <br>    at Object.module.exports.findBookByTitle
> (/home/themis/firstapp/api/config/database.js:22:26) <br>
>  at /home/themis/firstapp/api/server.js:109:22 <br>
>  at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br>    at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br>    at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br>    at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br>    at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br>    at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:331:14)
> <br>    at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:347:14)
> <br>    at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:391:3)
> <br>    at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br>    at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br>    at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br>    at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br>    at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br>    at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
</code>```

here is the server.js

```<code>  var express     = require('express');
        MongoClient = require('mongodb').MongoClient,
        app = express(),
        mongoUrl = 'mongodb://localhost:27017/firstapp';
    var bodyParser  = require('body-parser');
    var morgan      = require('morgan');
    var mongoose    = require('mongoose');
    var passport    = require('passport');
    var redisClient = require('redis').createClient;
    var redis       = redisClient(6379, 'localhost');
    var config      = require('./config/database'); // get db config file
    var User        = require('./app/models/user'); // get the mongoose model
    var Products    = require('./app/models/products'); //get the mongoose model
    var Makeissue   = require('./app/models/makeissue'); //get the mongoose model
    var port        = process.env.PORT || 8080;
    var jwt         = require('jwt-simple');
    var access      = require('./config/database.js');
    MongoClient.connect(mongoUrl, function(err, db) {
        if (err) throw 'Error connecting to database - ' + err;
            // get our request parameters
            app.use(bodyParser.urlencoded({ extended: false }));
            app.use(bodyParser.json());

            // log to console
            app.use(morgan('dev'));

            // Use the passport package in our application
            app.use(passport.initialize());

            // demo Route (GET http://localhost:8080)
            app.get('/', function(req, res) {
                  res.send('The API is at http://localhost:' + port + '/api');
            });

            // connect to database
            mongoose.connect(config.database);

            // pass passport for configuration
            require('./config/passport')(passport);

            // bundle our routes
            var apiRoutes = express.Router();

            // create a new user account (POST http://localhost:8080/api/signup)
            apiRoutes.post('/signup', function(req, res) {
              if (!req.body.name || !req.body.password || !req.body.email) {
                res.json({success: false, msg: 'Please pass name and password and email.'});
              } else {
                var newUser = new User({
                  name: req.body.name,
                  password: req.body.password,
                  email: req.body.email
                });
                // save the user
                newUser.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Username already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new user.'});
                });
              }
            });

            // route to authenticate a user (POST http://localhost:8080/api/authenticate)
            apiRoutes.post('/authenticate', function(req, res) {
              User.findOne({
                name: req.body.name
              }, function(err, user) {
                if (err) throw err;

                if (!user) {
                  res.send({success: false, msg: 'Authentication failed. User not found.'});
                } else {
                  // check if password matches
                  user.comparePassword(req.body.password, function (err, isMatch) {
                    if (isMatch && !err) {
                      // if user is found and password is right create a token
                      var token = jwt.encode(user, config.secret);
                      // return the information including token as JSON
                      res.json({success: true, token: 'JWT ' + token});
                    } else {
                      res.send({success: false, msg: 'Authentication failed. Wrong password.'});
                    }
                  });
                }
              });
            });

            apiRoutes.post('/book', function (req, res) {
                    if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
                    else if (!req.body.text) res.status(400).send("Please send some text for the book");
                    else {
                        access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
                            if (err) res.status(500).send("Server error");
                            else res.status(201).send("Saved");
                        });
                    }
                });

             apiRoutes.get('/book/:title', function (req, res) {
                    if (!req.param('title')) res.status(400).send("Please send a proper title");
                    else {
                        access.findBookByTitle(db, req.param('title'), function (book) {
                            if (!req.body.text) res.status(500).send("Server error");
                            else res.status(200).send(book);
                        });
                    }
                });

            apiRoutes.get('/productinfo' , function(req, res, next) {
                Products.find( function (err, result) {
                if (err) return console.error(err);
                  res.json(result);
              });
            });

             apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
                if (!req.param('name')) res.status(400).send("Please send a proper name");
                else{
                  access.findProductsByName(Products, req.param('name'), function(Products) {
                      if (!products) res.status(500).send("server error");
                        });
                    }
                 });

            // create a new Product (POST http://localhost:8080/api/productsignup)
            apiRoutes.post('/resources/productsignup', function(req, res) {
              if (!req.body.name || !req.body.serialnumber) {
                res.json({success: false, msg: 'Please pass name and serial number.'});
                } else {
                var newProducts = new Products({
                  name: req.body.name,
                  serialnumber: req.body.serialnumber
                });
                // save the Product
                newProducts.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Product already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new Product.'});
                });
              }
            });

            apiRoutes.post('/resources/createpost', function(req, res) {
              if (!req.body.issue) {
                res.json({success: false, msg: 'Please pass a issue.'});
                } else {
                var newMakeissue = new Makeissue({
                  issue: req.body.issue
                });
                // save the Product
                newMakeissue.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Post already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new post.'});
                });
              }
            });

            // route to a restricted info (GET http://localhost:8080/api/memberinfo)
            apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
              var token = getToken(req.headers);
              if (token) {
                var decoded = jwt.decode(token, config.secret);
                User.findOne({
                  name: decoded.name
                }, function(err, user) {
                    if (err) throw err;

                    if (!user) {
                      return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
                    } else {
                      res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
                    }
                });
              } else {
                return res.status(403).send({success: false, msg: 'No token provided.'});
              }
            });

            getToken = function (headers) {
              if (headers && headers.authorization) {
                var parted = headers.authorization.split(' ');
                if (parted.length === 2) {
                  return parted[1];
                } else {
                  return null;
                }
              } else {
                return null;
              }
            };

            // connect the api routes under /api/*
            app.use('/api', apiRoutes);
            module.exports = apiRoutes;

            app.listen(8080, function() {
                console.log('listening on port 8080');
            });
    });
</code>```

and the database.js

```<code>module.exports = {
  'secret': 'di.ionio.gr',
  'database': 'mongodb://localhost/firstapp'
};

module.exports.saveBook = function (db, title, author, text, callback) {
    db.collection['text'].save({
        title: title,
        author: author,
        text: text
    }, callback);
};

module.exports.findBookByTitle = function (db, title, callback) {
    db.collection['text'].findOne({
        title: title
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.text);
    });
};

module.exports.findProductsByName = function (db, name, callback) {
    db.collection['products'].findOne({
        name: name
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.products);
    });
};
</code>```

and the package.json

```<code>{
  "name": "firstapp",
  "main": "server.js",
  "dependencies": {
    "bcrypt": "^0.8.5",
    "body-parser": "~1.9.2",
    "express": "~4.9.8",
    "jwt-simple": "^0.3.1",
    "mongoose": "~4.2.4",
    "mongodb" : "~1.2.5",
    "morgan": "~1.5.0",
    "passport": "^0.3.0",
    "passport-jwt": "^1.2.1",
    "redis": "~0.10.1"
  }
}
</code>```

答:
in package.json folder find mongodb inside dependencies and update with these value:

```<code>"mongodb": "^2.2.33",
</code>```

Then Run

```<code>npm install
</code>```

again. That will solve your probem.

Body:
i'm trying to get some data from the apiRoutes.get('/resources/productinfo/:name') and i have this error, i dont know whats going wrong... also the apiRoutes.get('/book/:title') doesnt seems to work! i dont know what am i doing wrong

UPDATED:

>       TypeError: Cannot read property 'findOne' of undefined
    at Object.module.exports.findBookByTitle
> (/home/themis/firstapp/api/config/database.js:22:26)

>  at /home/themis/firstapp/api/server.js:109:22

>  at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
>
    at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
>
    at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
>
    at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
>
    at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
>
    at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:331:14)
>
    at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:347:14)
>
    at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:391:3)
>
    at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
>
    at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
>
    at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
>
    at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
>
    at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
>
    at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)

here is the server.js

  var express     = require('express');
        MongoClient = require('mongodb').MongoClient,
        app = express(),
        mongoUrl = 'mongodb://localhost:27017/firstapp';
    var bodyParser  = require('body-parser');
    var morgan      = require('morgan');
    var mongoose    = require('mongoose');
    var passport    = require('passport');
    var redisClient = require('redis').createClient;
    var redis       = redisClient(6379, 'localhost');
    var config      = require('./config/database'); // get db config file
    var User        = require('./app/models/user'); // get the mongoose model
    var Products    = require('./app/models/products'); //get the mongoose model
    var Makeissue   = require('./app/models/makeissue'); //get the mongoose model
    var port        = process.env.PORT || 8080;
    var jwt         = require('jwt-simple');
    var access      = require('./config/database.js');
    MongoClient.connect(mongoUrl, function(err, db) {
        if (err) throw 'Error connecting to database - ' + err;
            // get our request parameters
            app.use(bodyParser.urlencoded({ extended: false }));
            app.use(bodyParser.json());

            // log to console
            app.use(morgan('dev'));

            // Use the passport package in our application
            app.use(passport.initialize());

            // demo Route (GET http://localhost:8080)
            app.get('/', function(req, res) {
                  res.send('The API is at http://localhost:' + port + '/api');
            });

            // connect to database
            mongoose.connect(config.database);

            // pass passport for configuration
            require('./config/passport')(passport);

            // bundle our routes
            var apiRoutes = express.Router();

            // create a new user account (POST http://localhost:8080/api/signup)
            apiRoutes.post('/signup', function(req, res) {
              if (!req.body.name || !req.body.password || !req.body.email) {
                res.json({success: false, msg: 'Please pass name and password and email.'});
              } else {
                var newUser = new User({
                  name: req.body.name,
                  password: req.body.password,
                  email: req.body.email
                });
                // save the user
                newUser.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Username already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new user.'});
                });
              }
            });

            // route to authenticate a user (POST http://localhost:8080/api/authenticate)
            apiRoutes.post('/authenticate', function(req, res) {
              User.findOne({
                name: req.body.name
              }, function(err, user) {
                if (err) throw err;

                if (!user) {
                  res.send({success: false, msg: 'Authentication failed. User not found.'});
                } else {
                  // check if password matches
                  user.comparePassword(req.body.password, function (err, isMatch) {
                    if (isMatch && !err) {
                      // if user is found and password is right create a token
                      var token = jwt.encode(user, config.secret);
                      // return the information including token as JSON
                      res.json({success: true, token: 'JWT ' + token});
                    } else {
                      res.send({success: false, msg: 'Authentication failed. Wrong password.'});
                    }
                  });
                }
              });
            });

            apiRoutes.post('/book', function (req, res) {
                    if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
                    else if (!req.body.text) res.status(400).send("Please send some text for the book");
                    else {
                        access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
                            if (err) res.status(500).send("Server error");
                            else res.status(201).send("Saved");
                        });
                    }
                });

             apiRoutes.get('/book/:title', function (req, res) {
                    if (!req.param('title')) res.status(400).send("Please send a proper title");
                    else {
                        access.findBookByTitle(db, req.param('title'), function (book) {
                            if (!req.body.text) res.status(500).send("Server error");
                            else res.status(200).send(book);
                        });
                    }
                });

            apiRoutes.get('/productinfo' , function(req, res, next) {
                Products.find( function (err, result) {
                if (err) return console.error(err);
                  res.json(result);
              });
            });

             apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
                if (!req.param('name')) res.status(400).send("Please send a proper name");
                else{
                  access.findProductsByName(Products, req.param('name'), function(Products) {
                      if (!products) res.status(500).send("server error");
                        });
                    }
                 });

            // create a new Product (POST http://localhost:8080/api/productsignup)
            apiRoutes.post('/resources/productsignup', function(req, res) {
              if (!req.body.name || !req.body.serialnumber) {
                res.json({success: false, msg: 'Please pass name and serial number.'});
                } else {
                var newProducts = new Products({
                  name: req.body.name,
                  serialnumber: req.body.serialnumber
                });
                // save the Product
                newProducts.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Product already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new Product.'});
                });
              }
            });

            apiRoutes.post('/resources/createpost', function(req, res) {
              if (!req.body.issue) {
                res.json({success: false, msg: 'Please pass a issue.'});
                } else {
                var newMakeissue = new Makeissue({
                  issue: req.body.issue
                });
                // save the Product
                newMakeissue.save(function(err) {
                  if (err) {
                    return res.json({success: false, msg: 'Post already exists.'});
                  }
                  res.json({success: true, msg: 'Successful created new post.'});
                });
              }
            });

            // route to a restricted info (GET http://localhost:8080/api/memberinfo)
            apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
              var token = getToken(req.headers);
              if (token) {
                var decoded = jwt.decode(token, config.secret);
                User.findOne({
                  name: decoded.name
                }, function(err, user) {
                    if (err) throw err;

                    if (!user) {
                      return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
                    } else {
                      res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
                    }
                });
              } else {
                return res.status(403).send({success: false, msg: 'No token provided.'});
              }
            });

            getToken = function (headers) {
              if (headers && headers.authorization) {
                var parted = headers.authorization.split(' ');
                if (parted.length === 2) {
                  return parted[1];
                } else {
                  return null;
                }
              } else {
                return null;
              }
            };

            // connect the api routes under /api/*
            app.use('/api', apiRoutes);
            module.exports = apiRoutes;

            app.listen(8080, function() {
                console.log('listening on port 8080');
            });
    });

and the database.js

module.exports = {
  'secret': 'di.ionio.gr',
  'database': 'mongodb://localhost/firstapp'
};

module.exports.saveBook = function (db, title, author, text, callback) {
    db.collection['text'].save({
        title: title,
        author: author,
        text: text
    }, callback);
};

module.exports.findBookByTitle = function (db, title, callback) {
    db.collection['text'].findOne({
        title: title
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.text);
    });
};

module.exports.findProductsByName = function (db, name, callback) {
    db.collection['products'].findOne({
        name: name
    }, function (err, doc) {
        if (err || !doc) callback(null);
        else callback(doc.products);
    });
};

and the package.json

{
  "name": "firstapp",
  "main": "server.js",
  "dependencies": {
    "bcrypt": "^0.8.5",
    "body-parser": "~1.9.2",
    "express": "~4.9.8",
    "jwt-simple": "^0.3.1",
    "mongoose": "~4.2.4",
    "mongodb" : "~1.2.5",
    "morgan": "~1.5.0",
    "passport": "^0.3.0",
    "passport-jwt": "^1.2.1",
    "redis": "~0.10.1"
  }
}

Body:
in package.json folder find mongodb inside dependencies and update with these value:

"mongodb": "^2.2.33",

Then Run

npm install

again. That will solve your probem.


问:
Google Maps are not showing up in a signed apk
I know this is a common question and usually the solution is to generate a separate key for release. I've done it several times and my API key in developers console contains two different SHA1-fingerprints: one for debug from AndroidStudio and on for release from my own keystore. I have signed the app with the same keystore and enabled Google Maps Android API v2 in the console. But still the maps activity shows just the white screen with 'Google' in the left bottom corner.

Are there any suggestions how to solve the problem?

答:
I did a lot of things to fix these but any solution not fix my problem
to fix these issue I did these things

Create signed apk with new keystore file make sure that the you will create that in release mode

After creating the signed apk you should note the keystore path where you save your keystore file.

You also need to use your google map API key with your release mode and debug mode both, you can use same API key with both but make sure that you should add two different sha keys for your single api key on google console.

You should  go to use the path of bin folder of java from c drive because keystore tool is inside bin folder so
suppose your file is like C:\Program Files\Java\jdk1.8.0_11\bin
so you should follow this path to your android studio terminal
change the path to C:\Program Files\Java\jdk1.8.0_11\bin
and then type this command:

```<code>keytool -list -v -keystore "/Users/NT/Desktop/generalkey.jks"(adress of your keystore file)
</code>```

Now by doing these you will get the sha key copy that key

Go to google console/credentials

Now go to your api you will see edit option go to edit and past your sha key into it and save it .

Run your code.

ContentLicense: CC BY-SA 4.0

Body:
I did a lot of things to fix these but any solution not fix my problem
to fix these issue I did these things

Create signed apk with new keystore file make sure that the you will create that in release mode

After creating the signed apk you should note the keystore path where you save your keystore file.

You also need to use your google map API key with your release mode and debug mode both, you can use same API key with both but make sure that you should add two different sha keys for your single api key on google console.

You should  go to use the path of bin folder of java from c drive because keystore tool is inside bin folder so
suppose your file is like C:\Program Files\Java\jdk1.8.0_11\bin
so you should follow this path to your android studio terminal
change the path to C:\Program Files\Java\jdk1.8.0_11\bin
and then type this command:

keytool -list -v -keystore "/Users/NT/Desktop/generalkey.jks"(adress of your keystore file)

Now by doing these you will get the sha key copy that key

Go to google console/credentials

Now go to your api you will see edit option go to edit and past your sha key into it and save it .

Run your code.


问:
multiple attachments in sendmail -UNIX
I'm sending a mail with HTML and attachment, by sendmail in UNIX.
But Im unable to add mutliple attachment in this way, my goal is to send mail with html content andattachment - but unable to add multiple attchment here.

```<code>mail_msg2()
{

DIR="/home/input"
SENDING_FILE_NAME="ExportData.xls"

v_mailpart="$(uuidgen)/$(hostname)"
echo "From: hello@world.com
To: hello@world.com
Cc: hello@world.com
Subject: $SubjectData
Content-Type: multipart/mixed; boundary=\"$v_mailpart\"

MIME-Version: 1.0

This is a multi-part message in MIME format.
--$v_mailpart
Content-Type: text/html

$Body

--$v_mailpart
Content-Transfer-Encoding: base64
Content-Type: application/xlsx; name=$SENDING_FILE_NAME
Content-Disposition: attachment; filename=$SENDING_FILE_NAME

`base64 $DIR/$SENDING_FILE_NAME`

--$v_mailpart--" | /usr/sbin/sendmail -t

}
</code>```

Body=cat $path/output/output.html

答:
This bit:

```<code>--$v_mailpart
Content-Transfer-Encoding: base64
Content-Type: application/xlsx; name=$SENDING_FILE_NAME
Content-Disposition: attachment; filename=$SENDING_FILE_NAME

`base64 $DIR/$SENDING_FILE_NAME`
</code>```

needs to be repeated for every attachment.

Title: multiple attachments in sendmail -UNIX

Body:
I'm sending a mail with HTML and attachment, by sendmail in UNIX.
But Im unable to add mutliple attachment in this way, my goal is to send mail with html content andattachment - but unable to add multiple attchment here.

mail_msg2()
{

DIR="/home/input"
SENDING_FILE_NAME="ExportData.xls"

v_mailpart="$(uuidgen)/$(hostname)"
echo "From: hello@world.com
To: hello@world.com
Cc: hello@world.com
Subject: $SubjectData
Content-Type: multipart/mixed; boundary=\"$v_mailpart\"

MIME-Version: 1.0

This is a multi-part message in MIME format.
--$v_mailpart
Content-Type: text/html

$Body

--$v_mailpart
Content-Transfer-Encoding: base64
Content-Type: application/xlsx; name=$SENDING_FILE_NAME
Content-Disposition: attachment; filename=$SENDING_FILE_NAME

`base64 $DIR/$SENDING_FILE_NAME`

--$v_mailpart--" | /usr/sbin/sendmail -t

}

Body=cat $path/output/output.html

Body:
This bit:

--$v_mailpart
Content-Transfer-Encoding: base64
Content-Type: application/xlsx; name=$SENDING_FILE_NAME
Content-Disposition: attachment; filename=$SENDING_FILE_NAME

`base64 $DIR/$SENDING_FILE_NAME`

needs to be repeated for every attachment.


问:
Constraint in array character elements in PostgreSQL
In PostgreSQL 10.1 I create the following table:

```<code>CREATE TABLE nationality_cumulative_criteria
(
    id             smallint NOT NULL,
    country_set    character varying(2)[] NOT NULL,
    number         smallint NOT NULL
);
</code>```

I wish to add a constraint (exclude) which will not allow, for example, "US" to appear in different tuples but only in one.

I have already checked and found only cases with ranges and functions but not with arrays of character elements.

Tia

答:
To do exactly what you said, do the following:

```<code> create unique index on nationality_cumulative_criteria
 (('US'=any(country_set)))
 where 'US'=any(country_set);
</code>```

This will allow 'US' (specifically) to only be used once in the entire table

Body:
In PostgreSQL 10.1 I create the following table:

CREATE TABLE nationality_cumulative_criteria
(
    id             smallint NOT NULL,
    country_set    character varying(2)[] NOT NULL,
    number         smallint NOT NULL
);

I wish to add a constraint (exclude) which will not allow, for example, "US" to appear in different tuples but only in one.

I have already checked and found only cases with ranges and functions but not with arrays of character elements.

Tia

Body:
To do exactly what you said, do the following:

 create unique index on nationality_cumulative_criteria
 (('US'=any(country_set)))
 where 'US'=any(country_set);

This will allow 'US' (specifically) to only be used once in the entire table


问:
Android - OpenCV Template Matching with threshold
I am new to OpenCV and I have been looking at tutorials plus the questions around here but I have not been able to understand and set a threshold to the template matching.

This is the code I am currently using.
Function that will be triggered when picture selected

```<code>BitmapDrawable drawable = (BitmapDrawable) imgView.getDrawable();
Bitmap viewBitmap = drawable.getBitmap();
Bitmap bitmapMatch = BitmapFactory.decodeResource(getResources(), R.drawable.template_1);

run(viewBitmap, bitmapMatch, "result.png", Imgproc.TM_CCOEFF_NORMED);
</code>```

Run function

```<code>public void run(Bitmap inFile, Bitmap templateFile, String outFile, int match_method) {
        System.out.println("\nRunning Template Matching");

        Mat img = new Mat();
        Utils.bitmapToMat(inFile, img);
        Mat templ = new Mat();
        Utils.bitmapToMat(templateFile, templ);

        // / Create the result matrix
        int result_cols = img.cols() - templ.cols() + 1;
        int result_rows = img.rows() - templ.rows() + 1;
        Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

        // / Do the Matching and Normalize
        Imgproc.matchTemplate(img, templ, result, match_method);
//        Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

        // / Localizing the best match with minMaxLoc
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);

        Point matchLoc;
        if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
            matchLoc = mmr.minLoc;
        } else {
            matchLoc = mmr.maxLoc;
        }

        Log.d(TAG, "point: " + mmr.maxVal);

        // / Show me what you got
//        Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
//                matchLoc.y + templ.rows()), new Scalar(255, 255, 255));

        // Save the visualized detection.
        System.out.println("Writing "+ outFile);

        if (match >= 0.8)
            SaveImage(img,outFile);
        else
            Log.d(TAG, "No Match Found");
    }
</code>```

I would like to add a threshold at the if statement if (match >= 0.8) in order to save the image if the match is equal or over the threshold (0.8). If not, the image will not be saved.

Please help and thank you.

答:
Core.MinMaxLocResult contains maxLoc, maxVal, minLoc, and minVal values.  Just assign match=mmr.maxVal or match=mmr.minVal depending on context.

Alternatively, you could index in the result Mat to get your value and then test if it's over 0.8 as so:

```<code>double[] resultVal = result.get(matchLoc.y, matchLoc.x);
if (resultVal[0] >= 0.8) ...
</code>```

Body:
I am new to OpenCV and I have been looking at tutorials plus the questions around here but I have not been able to understand and set a threshold to the template matching.

This is the code I am currently using.
Function that will be triggered when picture selected

BitmapDrawable drawable = (BitmapDrawable) imgView.getDrawable();
Bitmap viewBitmap = drawable.getBitmap();
Bitmap bitmapMatch = BitmapFactory.decodeResource(getResources(), R.drawable.template_1);

run(viewBitmap, bitmapMatch, "result.png", Imgproc.TM_CCOEFF_NORMED);

Run function

public void run(Bitmap inFile, Bitmap templateFile, String outFile, int match_method) {
        System.out.println("\nRunning Template Matching");

        Mat img = new Mat();
        Utils.bitmapToMat(inFile, img);
        Mat templ = new Mat();
        Utils.bitmapToMat(templateFile, templ);

        // / Create the result matrix
        int result_cols = img.cols() - templ.cols() + 1;
        int result_rows = img.rows() - templ.rows() + 1;
        Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

        // / Do the Matching and Normalize
        Imgproc.matchTemplate(img, templ, result, match_method);
//        Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

        // / Localizing the best match with minMaxLoc
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);

        Point matchLoc;
        if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
            matchLoc = mmr.minLoc;
        } else {
            matchLoc = mmr.maxLoc;
        }

        Log.d(TAG, "point: " + mmr.maxVal);

        // / Show me what you got
//        Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
//                matchLoc.y + templ.rows()), new Scalar(255, 255, 255));

        // Save the visualized detection.
        System.out.println("Writing "+ outFile);

        if (match >= 0.8)
            SaveImage(img,outFile);
        else
            Log.d(TAG, "No Match Found");
    }

I would like to add a threshold at the if statement if (match >= 0.8) in order to save the image if the match is equal or over the threshold (0.8). If not, the image will not be saved.

Please help and thank you.

Body:
Core.MinMaxLocResult contains maxLoc, maxVal, minLoc, and minVal values.  Just assign match=mmr.maxVal or match=mmr.minVal depending on context.

Alternatively, you could index in the result Mat to get your value and then test if it's over 0.8 as so:

double[] resultVal = result.get(matchLoc.y, matchLoc.x);
if (resultVal[0] >= 0.8) ...


问:
How do I list all files of a directory?
How can I list all files of a directory in Python and add them to a list?

答:
Here's my general-purpose function for this.  It returns a list of file paths rather than filenames since I found that to be more useful.  It has a few optional arguments that make it versatile.  For instance, I often use it with arguments like pattern='*.txt' or subfolders=True.

```<code>import os
import fnmatch

def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
    """Return a list of the file paths matching the pattern in the specified
    folder, optionally including files inside subfolders.
    """
    match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
    walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
    return [os.path.join(root, f)
            for root, dirnames, filenames in walked
            for f in filenames if match(f, pattern)]
</code>```

Title: How do I list all files of a directory?

Body:
Here's my general-purpose function for this.  It returns a list of file paths rather than filenames since I found that to be more useful.  It has a few optional arguments that make it versatile.  For instance, I often use it with arguments like pattern='*.txt' or subfolders=True.

import os
import fnmatch

def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
    """Return a list of the file paths matching the pattern in the specified
    folder, optionally including files inside subfolders.
    """
    match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
    walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
    return [os.path.join(root, f)
            for root, dirnames, filenames in walked
            for f in filenames if match(f, pattern)]


问:
Go cannot find file specified
I'm trying to make simple read settings from config file. Both files - config.json and Settings.go, are in the same folder. But I'm always getting "The system cannot find the file specified." What I'm doing wrong?

```<code>func GetDbConnectionString() string {
    file, err := os.Open("config.json")
    if err != nil {
        log.Fatal(err)
    }
    decoder := json.NewDecoder(file)
    settings := Settings{}
    err1 := decoder.Decode(&settings)
    if err1 != nil {
        fmt.Println("error:", err1)
    }
    log.Print(&settings)
    return fmt.Sprintf("%s:%s@/%s", settings.login, settings.password, settings.database)
}
</code>```

答:
Your settings.json is not in the same directory as your main.go. If you invoke either go run main.go, or go build . && ./app, the current path will be .../app/ which does not contain the settings.json file.

Try copying your settings.json file to the same directory as your app, local invocation will work (it will still fail if you run from a separate directory though).

Title: Go cannot find file specified

Body:
I'm trying to make simple read settings from config file. Both files - config.json and Settings.go, are in the same folder. But I'm always getting "The system cannot find the file specified." What I'm doing wrong?

func GetDbConnectionString() string {
    file, err := os.Open("config.json")
    if err != nil {
        log.Fatal(err)
    }
    decoder := json.NewDecoder(file)
    settings := Settings{}
    err1 := decoder.Decode(&settings)
    if err1 != nil {
        fmt.Println("error:", err1)
    }
    log.Print(&settings)
    return fmt.Sprintf("%s:%s@/%s", settings.login, settings.password, settings.database)
}


问:
F#'s DescriptiveStatistics unknown?
I am currently converting a project in F# to Python, I am a relative amateur in F#, please...what on earth does this line do...

```<code>       let stats = new DescriptiveStatistics(list)
</code>```

I cant find a good definition of DescriptiveStatistics anywhere! Please help!
Many thanks

答:
That is very likely from MathNet.

Check the beginning of your F# for the line:

```<code>using MathNet.Numerics.Statistics;
</code>```

Title: F#'s DescriptiveStatistics unknown?

Body:
I am currently converting a project in F# to Python, I am a relative amateur in F#, please...what on earth does this line do...

       let stats = new DescriptiveStatistics(list)

I cant find a good definition of DescriptiveStatistics anywhere! Please help!
Many thanks

Body:
That is very likely from MathNet.

Check the beginning of your F# for the line:

using MathNet.Numerics.Statistics;


问:
PEAR module (HTTP_Request2) installed, but not recognized in php file?
I have HTTP_Request2 installed on my server; pear list shows it in the list of installed packages. But the following php file:

```<code><?php

ini_set("include_path", '/path/to/php:' . ini_get("include_path"));

if (class_exists('HTTP_Request2')) {
    print("true");
} else {
    print("false");
}
</code>```

...returns false. I've also tried replacing the ini_set line with

```<code>include '/path/to/php/HTTP/Request2.php';
</code>```

...but I get the same result. Is there something I'm missing, or something else I can check?

答:
Simply setting the include path doesn't implicitly give you access to the code. You need to either set the include path and then use relative includes:

```<code>ini_set("include_path", ...);
require_once 'HTTP/Request2.php';
</code>```

Or just use fully qualified includes:

```<code>require_once '/path/to/HTTP/Request2.php';
</code>```

That said, HTTP_Request2 is kinda old and I'd instead recommend using something like Guzzle via composer.

Body:
I have HTTP_Request2 installed on my server; pear list shows it in the list of installed packages. But the following php file:

<?php

ini_set("include_path", '/path/to/php:' . ini_get("include_path"));

if (class_exists('HTTP_Request2')) {
    print("true");
} else {
    print("false");
}

...returns false. I've also tried replacing the ini_set line with

include '/path/to/php/HTTP/Request2.php';

...but I get the same result. Is there something I'm missing, or something else I can check?

Body:
Simply setting the include path doesn't implicitly give you access to the code. You need to either set the include path and then use relative includes:

ini_set("include_path", ...);
require_once 'HTTP/Request2.php';

Or just use fully qualified includes:

require_once '/path/to/HTTP/Request2.php';

That said, HTTP_Request2 is kinda old and I'd instead recommend using something like Guzzle via composer.


问:
Python OpenCV access webcam maximum resolution
I am trying to acquire images from my webcam using a python code that imports OpenCV. The code is the following:

```<code>import sys
sys.path.append("C:\\opencv\\build\\python\\2.7")
import cv2
import cv2.cv as cv
import time

# Set resolution
cap = cv2.VideoCapture(0)
print "Frame default resolution: (" + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)) + "; " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) + ")"
cap.set(cv.CV_CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 600)
print "Frame resolution set to: (" + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)) + "; " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) + ")"

# Acquire frame
capture = cv.CreateCameraCapture(0)
img = cv.QueryFrame(capture)
</code>```

The code works fine, except that the Camera default resolution is 640x480, and my code seems to be able to set only resolution values lower than that. For example, I can set the image size to 320x240, but I can't change it to 800x600. I have no error appearing: simply the resolution is set to the default one (640x480) as I try to set it to higher values.

The camera I am using (no other webcam is connected to the computer) is the QuickCam V-UBK45: with the software provided by Logitech, I am able to take pictures at full resolution (1280x960) and at all intermediate ones (e.g. 800x600).

Therefore, those frame sizes are supported from the hardware, but my code can't access them.

Does anyone know what I can do?

答:
For cv2 just change to this.</p>

```<code>    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)
</code>```

Body:
I am trying to acquire images from my webcam using a python code that imports OpenCV. The code is the following:

import sys
sys.path.append("C:\\opencv\\build\\python\\2.7")
import cv2
import cv2.cv as cv
import time

# Set resolution
cap = cv2.VideoCapture(0)
print "Frame default resolution: (" + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)) + "; " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) + ")"
cap.set(cv.CV_CAP_PROP_FRAME_WIDTH, 800)
cap.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 600)
print "Frame resolution set to: (" + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)) + "; " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)) + ")"

# Acquire frame
capture = cv.CreateCameraCapture(0)
img = cv.QueryFrame(capture)

The code works fine, except that the Camera default resolution is 640x480, and my code seems to be able to set only resolution values lower than that. For example, I can set the image size to 320x240, but I can't change it to 800x600. I have no error appearing: simply the resolution is set to the default one (640x480) as I try to set it to higher values.

The camera I am using (no other webcam is connected to the computer) is the QuickCam V-UBK45: with the software provided by Logitech, I am able to take pictures at full resolution (1280x960) and at all intermediate ones (e.g. 800x600).

Therefore, those frame sizes are supported from the hardware, but my code can't access them.

Does anyone know what I can do?

Body:
For cv2 just change to this.

    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 800)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)


问:
Guice: injector in provider
I know that generally injector should be used only once in all application (on startup). But i have following use case. I inject task implementation for Executor, and then inside that task i have dependency (lets say FileHandler) that has to be instantiated each time. I know the way is to inject provider (lets say FileHandlerProvider) that will return new instance each time requested. The problem is that FileHandler has a lot of dependencies of it own (lets say Parser, OutputPrinter...). Now those also need new instance each time (because implementations could have some state, for example counters, and on next thread run reusing same instance would be a problem). The thing is that after provider is injected the same instance of provider is reused, so new FileHandler is always created with same Parser and OuputPrinter. The solution could be again to inject ParserProvider  and OutputPrinterProvider instead of Parser and OuputPrinter in FileHandlerProvider, but thats just not right, it gets too complicated soon, because there are more dependencies. The only simple solution I see now could be to use Injector in FileHandlerProvider, that would return new instance FileHandler (and new instances of dependencies). Or maybe there is another more elegant solution in this situation?

答:
You should just bind FileHandler and its dependencies all with default scope (i.e. no scope). Then inject Provider<FileHandler> and use its get() every time you need a new FileHandler instance. Since FileHandler has no scope, each time get() is called a new instance of FileHandler needs to be created... and since its dependencies also have no scope, a new instance of each of them needs to be created each time as well. It should work just the way you want.

I think the thing that you're (maybe) missing here is that you don't need to write any of these providers yourself... just inject Provider<FileHandler> and Guice will do it all for you.

Edit: Here's a small class I wrote that demonstrates the dependencies of a class getting created new each time an instance of that class is created.

```<code>public class Test {
  public static void main(String[] args) {
    Injector injector = Guice.createInjector();
    injector.getInstance(Test.class);
  }

  @Inject public Test(Provider<FileHandler> fileHandlerProvider) {
    FileHandler fileHandler1 = fileHandlerProvider.get();
    FileHandler fileHandler2 = fileHandlerProvider.get();

    System.out.println("fileHandler1 == fileHandler2? " +
        (fileHandler1 == fileHandler2));
    System.out.println("fileHandler1.parser == fileHandler2.parser? " +
        (fileHandler1.parser == fileHandler2.parser));
    System.out.println("fileHandler1.print == fileHandler2.printer? " +
        (fileHandler1.printer == fileHandler2.printer));
  }

  private static class FileHandler {
    private final Parser parser;
    private final OutputPrinter printer;

    @Inject private FileHandler(Parser parser, OutputPrinter printer) {
      this.parser = parser;
      this.printer = printer;
    }
  }

  private static class Parser {
  }

  private static class OutputPrinter {
  }
}
</code>```

When run, this code prints:

```fileHandler1 == fileHandler2? false
fileHandler1.parser == fileHandler2.parser? false
fileHandler1.print == fileHandler2.printer? false```

This shows that not only was a new FileHandler instance created each time, new Parser and OutputPrinter instances were create and injected in to the FileHandler each time as well.

ContentLicense: CC BY-SA 2.5

Title: Guice: injector in provider

Body:
You should just bind FileHandler and its dependencies all with default scope (i.e. no scope). Then inject Provider<FileHandler> and use its get() every time you need a new FileHandler instance. Since FileHandler has no scope, each time get() is called a new instance of FileHandler needs to be created... and since its dependencies also have no scope, a new instance of each of them needs to be created each time as well. It should work just the way you want.

I think the thing that you're (maybe) missing here is that you don't need to write any of these providers yourself... just inject Provider<FileHandler> and Guice will do it all for you.

Edit: Here's a small class I wrote that demonstrates the dependencies of a class getting created new each time an instance of that class is created.

public class Test {
  public static void main(String[] args) {
    Injector injector = Guice.createInjector();
    injector.getInstance(Test.class);
  }

  @Inject public Test(Provider<FileHandler> fileHandlerProvider) {
    FileHandler fileHandler1 = fileHandlerProvider.get();
    FileHandler fileHandler2 = fileHandlerProvider.get();

    System.out.println("fileHandler1 == fileHandler2? " +
        (fileHandler1 == fileHandler2));
    System.out.println("fileHandler1.parser == fileHandler2.parser? " +
        (fileHandler1.parser == fileHandler2.parser));
    System.out.println("fileHandler1.print == fileHandler2.printer? " +
        (fileHandler1.printer == fileHandler2.printer));
  }

  private static class FileHandler {
    private final Parser parser;
    private final OutputPrinter printer;

    @Inject private FileHandler(Parser parser, OutputPrinter printer) {
      this.parser = parser;
      this.printer = printer;
    }
  }

  private static class Parser {
  }

  private static class OutputPrinter {
  }
}

When run, this code prints:

fileHandler1 == fileHandler2? false
fileHandler1.parser == fileHandler2.parser? false
fileHandler1.print == fileHandler2.printer? false

This shows that not only was a new FileHandler instance created each time, new Parser and OutputPrinter instances were create and injected in to the FileHandler each time as well.


问:
"Login failed for user..." when I log on to my online SQL Server using C#?
I have a database on a hosting server that I try to connect using C# SqlConnection class. I can log on to the server through SQL Server Management Studio using SQL Server authentication without problem.

My initiation code looks like this:

```<code>public static string ConnectionString { get; set; }

public Constructor() {
    ConnectionString = @"Data source=SQL6002.site4now.net;Initial Catalog=myDatabase;User Id=MyUserName;Password=MyPassword;";
}
</code>```

where database name, user name and passwords are replaced with the proper values. The connection code looks like:

```<code>using (SqlConnection con = new SqlConnection(ConnectionString))
{
    con.Open();
    ...
}
</code>```

This code works when I'm using a local db connection string. However, when I'm using the connection string above I get the error

An error has occurred. Login failed for user 'IFC\WINxxxx$'.

ExceptionType: System.Data.SqlClient.SqlException

  StackTrace

at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, etc. etc.

where x in the user name are numbers. Also, this isn't the user name I use in the connection string.

I have tried to add trusted_connection=true, and also integrated security=true without success.

When I log on to the server via SQL Server Management Studio and open properties in Security -> Logins -> MyUserName, I note that the password does not have the same length as the one I use to log on to SSMS with. I do not have permission to change it through SSMS, only through the host, smarterasp.net.

Any inputs are very welcome!

答:
Thanks for the comments. I moved the credentials to an instance of SqlCredentials, as

```<code>var credentials = new SqlCredentials(userName, password);
using (var con = new SqlConnection(ConnectionString, credentials){
    con.Open();
}
</code>```

where password is a readonly SecureString(). That did the trick!

Body:
I have a database on a hosting server that I try to connect using C# SqlConnection class. I can log on to the server through SQL Server Management Studio using SQL Server authentication without problem.

My initiation code looks like this:

public static string ConnectionString { get; set; }

public Constructor() {
    ConnectionString = @"Data source=SQL6002.site4now.net;Initial Catalog=myDatabase;User Id=MyUserName;Password=MyPassword;";
}

where database name, user name and passwords are replaced with the proper values. The connection code looks like:

using (SqlConnection con = new SqlConnection(ConnectionString))
{
    con.Open();
    ...
}

This code works when I'm using a local db connection string. However, when I'm using the connection string above I get the error

An error has occurred. Login failed for user 'IFC\WINxxxx$'.

ExceptionType: System.Data.SqlClient.SqlException

  StackTrace

at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, etc. etc.

where x in the user name are numbers. Also, this isn't the user name I use in the connection string.

I have tried to add trusted_connection=true, and also integrated security=true without success.

When I log on to the server via SQL Server Management Studio and open properties in Security -> Logins -> MyUserName, I note that the password does not have the same length as the one I use to log on to SSMS with. I do not have permission to change it through SSMS, only through the host, smarterasp.net.

Any inputs are very welcome!

Body:
Thanks for the comments. I moved the credentials to an instance of SqlCredentials, as

var credentials = new SqlCredentials(userName, password);
using (var con = new SqlConnection(ConnectionString, credentials){
    con.Open();
}

where password is a readonly SecureString(). That did the trick!