问:
adding multiplied numbers using javascript

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
       document.getElementById("total").value = +num3 ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
<p>Total :<br>
<input type="text" name="total" id="total" value=""/>
</p></code>```

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p></code>```

I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.

答:
You need to add event handlers if you want to calculate on change of textbox input like following.

function multiplyBy()
{
     var result = document.getElementById("result");
      var  num1 = document.getElementById("firstNumber").value;
       var num2 = document.getElementById("secondNumber").value;

     var num3= parseFloat(num1) * parseFloat(num2);// to convert entered values to float and || 0 to  use 0 if no value is there

       if(!isNaN(num3)){
          document.getElementById("resultPrev").value =   document.getElementById("result").value;
           document.getElementById("resultCurrent").value =   num3;
             result.value =  parseFloat(result.value || 0) + num3;
       }

}

document.getElementById("firstNumber").addEventListener("change",multiplyBy);

document.getElementById("secondNumber").addEventListener("change",multiplyBy);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<p>The Previous Result is : <br>
<input type="text" name="resultPrev" id = "resultPrev" value="0"/>
</p>
<p>The Current Result is : <br>
<input type="text" name="resultCurrent" id = "resultCurrent" value=""/>
</p>
<p>The Final Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p></code>```

Consider handling non number values.

Body:
function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
       document.getElementById("total").value = +num3 ;
}

1st Number : <input type="text" id="firstNumber" value="" />

2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" />

The Result is :

<input type="text" name="result" id = "result" value=""/>

Total :

<input type="text" name="total" id="total" value=""/>

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
}

1st Number : <input type="text" id="firstNumber" value="" />

2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" />

The Result is :

<input type="text" name="result" id = "result" value=""/>

I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.

Body:
You need to add event handlers if you want to calculate on change of textbox input like following.

function multiplyBy()
{
     var result = document.getElementById("result");
      var  num1 = document.getElementById("firstNumber").value;
       var num2 = document.getElementById("secondNumber").value;

     var num3= parseFloat(num1) * parseFloat(num2);// to convert entered values to float and || 0 to  use 0 if no value is there

       if(!isNaN(num3)){
          document.getElementById("resultPrev").value =   document.getElementById("result").value;
           document.getElementById("resultCurrent").value =   num3;
             result.value =  parseFloat(result.value || 0) + num3;
       }

}

document.getElementById("firstNumber").addEventListener("change",multiplyBy);

document.getElementById("secondNumber").addEventListener("change",multiplyBy);

1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<p>The Previous Result is : <br>
<input type="text" name="resultPrev" id = "resultPrev" value="0"/>
</p>
<p>The Current Result is : <br>
<input type="text" name="resultCurrent" id = "resultCurrent" value=""/>
</p>
<p>The Final Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>

Consider handling non number values.


来源: stackexchange

问:
iOS 10 Callkit : How to notify OS that my VOIP application supports Callkit on fresh installation of my app
I want to show my VOIP app in suggestion from native contacts when user long press the call button.

Currently i am informing to OS about callkit while placing/receiving the calls.

But i want to inform OS about callkit in my app as the app installed first time like whatsapp is doing.

Can anyone suggest me how can i do that ?.

答:
When you configure the provider delegate, you must configure supported handle types with CXHandleTypePhoneNumber.

But for notify to system, you need start app once at least (and you must be sure that provider delegate is init to notify system), it isn't enough with install.

ContentLicense: CC BY-SA 3.0


问:
How to split Pandas dictionary?
I have a Pandas series like this

```<code>pd.DataFrame({"name": ['John','Mary','Tommy'],
              "time": ['"data": [{"t": "16:50"},{"t": "17:05"}]',
                       '"data": [{"t": "16:10"}, {"t": "17:11"}, {"t": "17:12"}]',
                       np.nan]})
</code>```

Now when it comes to data it would look like this

```<code>    name                                               time
0   John            "data": [{"t": "16:50"},{"t": "17:05"}]
1   Mary  "data": [{"t": "16:10"}, {"t": "17:11"}, {"t":...
2  Tommy                                                NaN
</code>```

In column time is a dictionary (in string format) and it contains a list (max 3 items, sometimes it is NaN). As the max list size is known so I would like to flatten my data into the following.

```<code>    name  time1  time2  time3
0   John  16:50  17:05    NaN
1   Mary  16:10  17:11  17:12
2  Tommy    NaN    NaN    NaN
</code>```

Except using for loop, I am not sure how to do that in Panda's way. Thanks in advance.

答:
You can evaluate the string to a dict and then convert the list to columns. Finally merge the new columns with name.</p>

```<code>pd.concat([data['name'],
           data.time.apply(lambda x: eval('{'+x+'}')['data'] if pd.notnull(x) else np.nan)\
           .apply(pd.Series).applymap(lambda x: x['t'] if pd.notnull(x) else x)],axis=1)\
           .rename(columns={0:'time1',1:'time2',2:'time3'})
Out[567]:
    name  time1  time2  time3
0   John  16:50  17:05    NaN
1   Mary  16:10  17:11  17:12
2  Tommy    NaN    NaN    NaN
</code>```

Title: How to split Pandas dictionary?

Body:
I have a Pandas series like this

pd.DataFrame({"name": ['John','Mary','Tommy'],
              "time": ['"data": [{"t": "16:50"},{"t": "17:05"}]',
                       '"data": [{"t": "16:10"}, {"t": "17:11"}, {"t": "17:12"}]',
                       np.nan]})

Now when it comes to data it would look like this

    name                                               time
0   John            "data": [{"t": "16:50"},{"t": "17:05"}]
1   Mary  "data": [{"t": "16:10"}, {"t": "17:11"}, {"t":...
2  Tommy                                                NaN

In column time is a dictionary (in string format) and it contains a list (max 3 items, sometimes it is NaN). As the max list size is known so I would like to flatten my data into the following.

    name  time1  time2  time3
0   John  16:50  17:05    NaN
1   Mary  16:10  17:11  17:12
2  Tommy    NaN    NaN    NaN

Except using for loop, I am not sure how to do that in Panda's way. Thanks in advance.

Body:
You can evaluate the string to a dict and then convert the list to columns. Finally merge the new columns with name.

pd.concat([data['name'],
           data.time.apply(lambda x: eval('{'+x+'}')['data'] if pd.notnull(x) else np.nan)\
           .apply(pd.Series).applymap(lambda x: x['t'] if pd.notnull(x) else x)],axis=1)\
           .rename(columns={0:'time1',1:'time2',2:'time3'})
Out[567]:
    name  time1  time2  time3
0   John  16:50  17:05    NaN
1   Mary  16:10  17:11  17:12
2  Tommy    NaN    NaN    NaN


问:
Selecting DbContext based on Entity with AutoFac
I'm trying to specify which dbcontext to use based on entity with autofac. Below are my codes:

Global.asax

```<code>foreach (var database in DatabaseManager.Databases)
            {
                builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString, database.Alias)) //database.Alias is database name
                    .As<IDbContext>()
                    .Named<IDbContext>(database.Alias)
                    .InstancePerLifetimeScope();
            }
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
</code>```

Is there anyway i can specify which dbcontext to pass to EfRepository?

```<code>public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly IDbContext _context;
        private IDbSet<T> _entities;

        public EfRepository(IDbContext context)
        {
            this._context = context;
        }
}
</code>```

and in my entity i would have something like this

```<code>[DatabaseName("Database1")]
public partial class SampleEntity : BaseEntity
{
}
</code>```

UPDATED
Here is my objectcontext class

```<code>public class CodesObjectContext : DbContext, IDbContext
    {
        public virtual string DatabaseName { get; private set; }
        public CodesObjectContext(string nameOrConnectionString, string databaseName)
            : base(nameOrConnectionString)
        {
            DatabaseName = databaseName;
        }
}
</code>```

So is there a way to match entity database attribute and context database name, then only pass this context to the repository constructor

答:
Assuming you already have defined your attribute DatabaseName, I will answer </p>

```<code>//first in your base context, define contructor that takes string as database name.
//It should be something like this
public MyContext(string mydbName = "DefaultDBName") : base(mydbName)
        {
        }

// In your getter, do something like this, get database Name from your attributes
string dbName =
            (DatabaseName) Attribute.GetCustomAttribute(typeof(T), typeof (DatabaseName));
if(dbName==null) throw new Exception ("Missing Attribute");
else
{
// .Name might change depending on your attribute
string DatabaseName = db.Name;
// then init your context
    using (var db = new MyContext(DatabaseName))
    {//do something }
}
</code>```

<p>I hope that will help. </p>

Body:
I'm trying to specify which dbcontext to use based on entity with autofac. Below are my codes:

Global.asax

foreach (var database in DatabaseManager.Databases)
            {
                builder.Register<IDbContext>(c => new CodesObjectContext(database.ConnectionString, database.Alias)) //database.Alias is database name
                    .As<IDbContext>()
                    .Named<IDbContext>(database.Alias)
                    .InstancePerLifetimeScope();
            }
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

Is there anyway i can specify which dbcontext to pass to EfRepository?

public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly IDbContext _context;
        private IDbSet<T> _entities;

        public EfRepository(IDbContext context)
        {
            this._context = context;
        }
}

and in my entity i would have something like this

[DatabaseName("Database1")]
public partial class SampleEntity : BaseEntity
{
}

UPDATED
Here is my objectcontext class

public class CodesObjectContext : DbContext, IDbContext
    {
        public virtual string DatabaseName { get; private set; }
        public CodesObjectContext(string nameOrConnectionString, string databaseName)
            : base(nameOrConnectionString)
        {
            DatabaseName = databaseName;
        }
}

So is there a way to match entity database attribute and context database name, then only pass this context to the repository constructor

Body:
Assuming you already have defined your attribute DatabaseName, I will answer

//first in your base context, define contructor that takes string as database name.
//It should be something like this
public MyContext(string mydbName = "DefaultDBName") : base(mydbName)
        {
        }

// In your getter, do something like this, get database Name from your attributes
string dbName =
            (DatabaseName) Attribute.GetCustomAttribute(typeof(T), typeof (DatabaseName));
if(dbName==null) throw new Exception ("Missing Attribute");
else
{
// .Name might change depending on your attribute
string DatabaseName = db.Name;
// then init your context
    using (var db = new MyContext(DatabaseName))
    {//do something }
}

I hope that will help.


问:
Issue with Docusign authentication registration flow
Our application offers Docusign integration.
Therefore, we allow our users to Login to Docusign.

Everything is fine when the user is already a Docusign user and logs in:

User taps on Login to Docusign

A browser is opened and redirected to Docusign login dialog where he enters his email address

He enters the email address

He enters his password

He is redirected to callback_url

However, when the user needs to register to Docusign, the process becomes like this:

User taps on Login to Docusign

A browser is opened and redirected to Docusign login dialog where he enters his email address

Since he doesnt have an email registered with docusign, he taps on "Register" link

An activation email is sent to his email address.

user clicks on the activation link in the email

User is redirected to his Docusign dashboard

The problem with this registration flow is that on step 6, the user is not being redirected to callback_url.
Therefore, the loop with our application is now broken and user is confused.

Shouldn't Docusign redirect users back to callback_url when activation is completed?

答:
If your application's User Experience (UX) explicitly enables the user to either create an account on DocuSign or to sign in, then you can remove the "Create an account" option from the OAuth window:

In your initial GET to the DocuSign authentication server, include query parameter of

```<code>ui_flavors=no_sign_up
</code>```

This should prevent the "Sign Up" links / options from being shown.

This is not the optimal answer for the question, but it is available now.

Body:
If your application's User Experience (UX) explicitly enables the user to either create an account on DocuSign or to sign in, then you can remove the "Create an account" option from the OAuth window:

In your initial GET to the DocuSign authentication server, include query parameter of

ui_flavors=no_sign_up

This should prevent the "Sign Up" links / options from being shown.

This is not the optimal answer for the question, but it is available now.


问:
SAT4J Implication use case
I'm new to sat4j library. How I can define implication e.g. (A1 v A2 v A3) => (A1 ∧ A4) using sat4j and find boolean values for all variables?

I had found unit test for sat4j than I have tried something like in listing below. Problem is that hasASolution() returns true but solution variable is empty.

```<code>DependencyHelper<String, String> dependencyHelper = new DependencyHelper<>(SolverFactory.newEclipseP2());
dependencyHelper.implication("A1", "A2", "A3").implies("A1").and("A4");
// Before get a solution it must be checked
assertTrue(dependencyHelper.hasASolution());
IVec<String> solution = dependencyHelper.getSolution();
System.out.println(solution.toString());
</code>```

答:
solution provides you a list of "satisfied" variables. Here, falsifying the variables satisfy your implication.

thus the empty solution set means that all the variables are falsified.

Title: SAT4J Implication use case

Body:
I'm new to sat4j library. How I can define implication e.g. (A1 v A2 v A3) => (A1 ∧ A4) using sat4j and find boolean values for all variables?

I had found unit test for sat4j than I have tried something like in listing below. Problem is that hasASolution() returns true but solution variable is empty.

DependencyHelper<String, String> dependencyHelper = new DependencyHelper<>(SolverFactory.newEclipseP2());
dependencyHelper.implication("A1", "A2", "A3").implies("A1").and("A4");
// Before get a solution it must be checked
assertTrue(dependencyHelper.hasASolution());
IVec<String> solution = dependencyHelper.getSolution();
System.out.println(solution.toString());


问:
Regular expression for duplicate words
I'm a regular expression newbie and I can't quite figure out how to write a single regular expression that would "match" any duplicate consecutive words such as:

Paris in the the spring.

Not that that is related.

Why are you laughing?  Are my my regular expressions THAT bad??

Is there a single regular expression that will match ALL of the bold strings above?

答:
Try this with below RE

\b     start of word word boundary

\W+    any word character

\1     same word matched already

\b     end of word

()*     Repeating again

```<code>public static void main(String[] args) {

    String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
    Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);

    Scanner in = new Scanner(System.in);

    int numSentences = Integer.parseInt(in.nextLine());

    while (numSentences-- > 0) {
        String input = in.nextLine();

        Matcher m = p.matcher(input);

        // Check for subsequences of input that match the compiled pattern
        while (m.find()) {
            input = input.replaceAll(m.group(0),m.group(1));
        }

        // Prints the modified sentence.
        System.out.println(input);
    }

    in.close();
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Regular expression for duplicate words

Body:
Try this with below RE

\b     start of word word boundary

\W+    any word character

\1     same word matched already

\b     end of word

()*     Repeating again

public static void main(String[] args) {

    String regex = "\\b(\\w+)(\\b\\W+\\b\\1\\b)*";//  "/* Write a RegEx matching repeated words here. */";
    Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE/* Insert the correct Pattern flag here.*/);

    Scanner in = new Scanner(System.in);

    int numSentences = Integer.parseInt(in.nextLine());

    while (numSentences-- > 0) {
        String input = in.nextLine();

        Matcher m = p.matcher(input);

        // Check for subsequences of input that match the compiled pattern
        while (m.find()) {
            input = input.replaceAll(m.group(0),m.group(1));
        }

        // Prints the modified sentence.
        System.out.println(input);
    }

    in.close();
}


问:
Java return type generic
I'm newbie in using generic in java, i have simple method that i would like to return any type from that, this method return other class getters methods, for example i have channels class and that have getChannelId() method, i want to return that from this method:

```<code>@SuppressWarnings("unchecked")
public <T extends Channels> T getChannelColumn(ChannelContentModel.channelColumns column) {
    switch (column) {
        case id:
            return (T) channel.getId();
        break;
        case title:
            return (T) channel.getChannelTitle();
            break;
    }
    return null;
}
</code>```

getId is int and getChannelTitle is string, how can i fix this method to return any type?

in my code channel is instance of Channels class, Thanks in advance

答:
As commented by @Geckstar;

Java is statically typed

But it is possible to clear your code sample from compile errors.

Remove breaks, because there is no need to break after return statement.

extend return type from object. T extends Object instead T extends Channel

id must be Integer, not int or change to (T)(Integer) channel.getId()

This is not a good solution, it only fixes compile errors.But this method's usage may cause runtime failures.

```<code>@SuppressWarnings("unchecked")
public <T extends Object> T getChannelColumn(ChannelContentModel.channelColumns column) {
    switch (column) {
        case id:
            return (T) channel.getId(); //int must be Integer
        case title:
            return (T) channel.getChannelTitle();
    }
    return null;
}
</code>```

Title: Java return type generic

Body:
I'm newbie in using generic in java, i have simple method that i would like to return any type from that, this method return other class getters methods, for example i have channels class and that have getChannelId() method, i want to return that from this method:

@SuppressWarnings("unchecked")
public <T extends Channels> T getChannelColumn(ChannelContentModel.channelColumns column) {
    switch (column) {
        case id:
            return (T) channel.getId();
        break;
        case title:
            return (T) channel.getChannelTitle();
            break;
    }
    return null;
}

getId is int and getChannelTitle is string, how can i fix this method to return any type?

in my code channel is instance of Channels class, Thanks in advance

Body:
As commented by @Geckstar;

Java is statically typed

But it is possible to clear your code sample from compile errors.

Remove breaks, because there is no need to break after return statement.

extend return type from object. T extends Object instead T extends Channel

id must be Integer, not int or change to (T)(Integer) channel.getId()

This is not a good solution, it only fixes compile errors.But this method's usage may cause runtime failures.

@SuppressWarnings("unchecked")
public <T extends Object> T getChannelColumn(ChannelContentModel.channelColumns column) {
    switch (column) {
        case id:
            return (T) channel.getId(); //int must be Integer
        case title:
            return (T) channel.getChannelTitle();
    }
    return null;
}


问:
C++ mix new/delete between libs?
If I use the new keyword in my library (which is built differently than my main app), when I delete it in my main app with delete, is there a chance that I may get a crash/error?

答:
You're quite right that there's a problem there, but for most cases there's an even simpler solution than the other answers (so far) have proposed.  You can continue using new and delete freely -- all you need to do is overload new and delete for each class in your library that might be used across DLL boundaries.

Personally, I just defined a simple class to provide the needed functionality:

```<code>class NewDelete
{
    public:
        void *operator new (size_t size);
        void operator delete (void *memory);
        void *operator new (size_t size, void *ptr);
        void operator delete (void *memory, void *ptr);
};
</code>```

As long as those four member functions are all defined in the same DLL, then any class which derives from this class is automatically "DLL-safe" -- new and delete can be used normally on them without worrying about DLL boundaries.

Title: C++ mix new/delete between libs?

Body:
You're quite right that there's a problem there, but for most cases there's an even simpler solution than the other answers (so far) have proposed.  You can continue using new and delete freely -- all you need to do is overload new and delete for each class in your library that might be used across DLL boundaries.

Personally, I just defined a simple class to provide the needed functionality:

class NewDelete
{
    public:
        void *operator new (size_t size);
        void operator delete (void *memory);
        void *operator new (size_t size, void *ptr);
        void operator delete (void *memory, void *ptr);
};

As long as those four member functions are all defined in the same DLL, then any class which derives from this class is automatically "DLL-safe" -- new and delete can be used normally on them without worrying about DLL boundaries.

OwnerDisplayName: Sol

ContentLicense: CC BY-SA 2.5


问:
Find All Capital Letter in a String - Regular Expression C#
I need to find all capital letters in a string. For example

Input : Electronics and Communication Engineering

Output: ECE

答:
Using LINQ:    </p>

```<code>string text = "Electronics and Communication Engineering";
var capitalLetters = text.Where(c => char.IsUpper(c)).ToArray();
</code>```

Body:
Using LINQ:

string text = "Electronics and Communication Engineering";
var capitalLetters = text.Where(c => char.IsUpper(c)).ToArray();


答:
If you insist on regular expressions:

```<code> string source = @"Electronics and Communication Engineering";

 string result = string.Concat(Regex
   .Matches(source, "[A-Z]")
   .OfType<Match>()
   .Select(match => match.Value));
</code>```

Linq is a (shorter) alternative:

```<code> string result = string.Concat(source.Where(c => c >= 'A' && c <= 'Z'));
</code>```

Edit: If "capital letters" include all Unicode capital letters, not only English, but, say, Russian ones, regular expression will use a different pattern

```<code> string result = string.Concat(Regex
   .Matches(source, @"\p{Lu}")
   .OfType<Match>()
   .Select(match => match.Value));
</code>```

and Linq solution will use a different condition:

```<code> string result = string.Concat(source.Where(c => char.IsUpper(c)));
</code>```

Title: Find All Capital Letter in a String - Regular Expression C#

Body:
I need to find all capital letters in a string. For example

Input : Electronics and Communication Engineering

Output: ECE

Body:
If you insist on regular expressions:

 string source = @"Electronics and Communication Engineering";

 string result = string.Concat(Regex
   .Matches(source, "[A-Z]")
   .OfType<Match>()
   .Select(match => match.Value));

Linq is a (shorter) alternative:

 string result = string.Concat(source.Where(c => c >= 'A' && c <= 'Z'));

Edit: If "capital letters" include all Unicode capital letters, not only English, but, say, Russian ones, regular expression will use a different pattern

 string result = string.Concat(Regex
   .Matches(source, @"\p{Lu}")
   .OfType<Match>()
   .Select(match => match.Value));

and Linq solution will use a different condition:

 string result = string.Concat(source.Where(c => char.IsUpper(c)));


问:
SCTP implementation with java?
How to implement SCTP protocol between a gateway and a server with java ?</p>

答:
No need, just use sctp:

https://github.com/RestComm/sctp

Handles most needs, works great.

Title: SCTP implementation with java?


问:
bootstrap 3 close Modal when pushing browser back button
I just want to create a modal page which behaves the same either pushing the browser back button or the close button inside the modal, using bootstrap 3. I found a script which does that, but there is a problem. let's say I start off with a google.com, go to this modal page, then push the "Modal!" button, then push the browser back button, it will close the modal, if I push the back button again, it will take me back to google.com (all is good). But this time, if I open the modal page and close the modal using the "close" button instead. But now, I would have to push the back button twice to go back to google.com. If I open and close the modal with the close button inside of modal for like 10x. I found that I have to push the browser back button 10 more times to get back to google.com page. How to fix this problem? TIA

```<code><!--html, bootstrap 3.2.0-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-body">
    <p>If you press the web browser's back button not the modal's "close" button, the modal will close and the hash "#myModal" will be removed for the URL</p>
  </div>
  <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div>
</div>
</div>
</div>

<!--jquery-->
$('#myModal').on('show.bs.modal', function (e) {
    window.history.pushState('forward', null, '#modal');
});

$('#myModal').on('hide.bs.modal', function (e) {
    //pop the forward state to go back to original state before pushing the "Modal!" button
});

$(window).on('popstate', function () {
    $('#myModal').modal('hide');
});
</code>```

jsfiddle source

答:
On button click popup will come up.

```<code>$(document).ready(function(){
      $(".popup-btn").click(function () {
          location.hash = "popup";
          $(".popup-panel").show();
      });
});
</code>```

On location change it would get hidden:

```<code>$(window).bind('hashchange', function () {
      if (location.hash == null || location.hash == "") {
          $(".popup-panel").hide();
      }
});
</code>```

Body:
I just want to create a modal page which behaves the same either pushing the browser back button or the close button inside the modal, using bootstrap 3. I found a script which does that, but there is a problem. let's say I start off with a google.com, go to this modal page, then push the "Modal!" button, then push the browser back button, it will close the modal, if I push the back button again, it will take me back to google.com (all is good). But this time, if I open the modal page and close the modal using the "close" button instead. But now, I would have to push the back button twice to go back to google.com. If I open and close the modal with the close button inside of modal for like 10x. I found that I have to push the browser back button 10 more times to get back to google.com page. How to fix this problem? TIA

If you press the web browser's back button not the modal's "close" button, the modal will close and the hash "#myModal" will be removed for the URL

<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

$('#myModal').on('show.bs.modal', function (e) {
    window.history.pushState('forward', null, '#modal');
});

$('#myModal').on('hide.bs.modal', function (e) {
    //pop the forward state to go back to original state before pushing the "Modal!" button
});

$(window).on('popstate', function () {
    $('#myModal').modal('hide');
});

jsfiddle source

Body:
On button click popup will come up.

$(document).ready(function(){
      $(".popup-btn").click(function () {
          location.hash = "popup";
          $(".popup-panel").show();
      });
});

On location change it would get hidden:

$(window).bind('hashchange', function () {
      if (location.hash == null || location.hash == "") {
          $(".popup-panel").hide();
      }
});


问:
How to install Visual Studio 2017 64bit version explicitly?
I have 64bit windows 10 machine .When downloading and installing visual studio, I didn't see any step to select the version which is 32bit or 64bit. Implicitly installer takes the installation path as :

C:\Program Files (x86)\Microsoft Visual Studio

And after installation it is showing as a 32bit version in task manager.

答:
Visual Studio 2017 is still a 32Bit application, Microsoft tried to defend their decision to not provide VS as 64bit in various blog posts.

So by default 32Bit applications install to C:\Program Files (x86)\ and everything is ok what you see.

// Update

The next Visual Studio Version 2022, will be 64Bit to fix the out of memory issues:

The next major release of Visual Studio will be faster, more
approachable, and more lightweight, designed for both learners and
those building industrial scale solutions. For the first time ever,
Visual Studio will be 64-bit.
Visual Studio 2022 will be a 64-bit application, no longer limited to ~4gb of memory in the main devenv.exe process. With a 64-bit Visual Studio on Windows, you can open, edit, run, and debug even the biggest and most complex solutions without running out of memory.


问:
Qt: passing objects to every window
Im a beginner at C++ since I'm a Java-Dev. I'm learning Qt right now.
Now I want in my widget application on central object for holding special functionality (for example a bunch of methods for sending different network-command or something like that). In my mainwindow.cpp I've got this

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //...
    BusinessLogic* bl = new BusinessLogic;
    bl->setMyValue(44);
    this->setBusinessLogic(bl);
    this->getBusinessLogic();

    //...
}

BusinessLogic* MainWindow::getBusinessLogic()
{
    return this->bl;
}

void MainWindow::setBusinessLogic(BusinessLogic* newbl)
{
    this->bl = newbl;
}
</code>```

Where BusinessLogic.cpp is the class which I want to access from all windows in my application. So in my Dialog which get opend when the pushButton is clicked, I try to use the businesslogic instance like this in the constructor

```<code>Dialog::Dialog(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    //...
    ((MainWindow*)parent)->getBusinessLogic();
}
</code>```

Unfortunately the program crashes everytime the dialog get instanciated (the line with ((MainWindow*)parent)->getBusinessLogic(); get called.

What can I do?

答:
There are several methods for achieving your goal(all depends on your requirements) but one approach is you can create Singleton class of your BusinessLogic and then access it anywhere. have a look here. OR you can also pass object of class one class to another. OR you can use signal slot mechanism.

For you best Solution can be

```<code>Class BLogic{
public:
    static BLogic* instance(){
       static BLogic ins;
       return &ins;
    }
    void setVal(int v){
        val = v;
    }
private:
    BLogic(){}
    int val;
};
</code>```

Now you can call functions of BLogic from any class like

```<code>BLogic::instance()->setVal(10);
</code>```

OR Example of passing objects can be

```<code>class ClassA
{
public:
   void setClassB(ClassB *ob){
      m_classB = ob;
   }
   ClassB* getClassB(){
      return m_classB;
   }
private:
   ClassB* m_classB;
};

class ClassB
{
public:
   void setClassA(ClassA *ob){
      m_classA = ob;
   }
   ClassA* getClassA(){
      return m_classA;
   }
private:
   ClassA* m_classA;
};
</code>```

Now from main.cpp

```<code>ClassA* obA = new ClassA;
ClassB* obB = new ClassB;
obA->setClassB(obB);
obB->setClassA(obA);
</code>```

Title: Qt: passing objects to every window

Body:
Im a beginner at C++ since I'm a Java-Dev. I'm learning Qt right now.
Now I want in my widget application on central object for holding special functionality (for example a bunch of methods for sending different network-command or something like that). In my mainwindow.cpp I've got this

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    //...
    BusinessLogic* bl = new BusinessLogic;
    bl->setMyValue(44);
    this->setBusinessLogic(bl);
    this->getBusinessLogic();

    //...
}

BusinessLogic* MainWindow::getBusinessLogic()
{
    return this->bl;
}

void MainWindow::setBusinessLogic(BusinessLogic* newbl)
{
    this->bl = newbl;
}

Where BusinessLogic.cpp is the class which I want to access from all windows in my application. So in my Dialog which get opend when the pushButton is clicked, I try to use the businesslogic instance like this in the constructor

Dialog::Dialog(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    //...
    ((MainWindow*)parent)->getBusinessLogic();
}

Unfortunately the program crashes everytime the dialog get instanciated (the line with ((MainWindow*)parent)->getBusinessLogic(); get called.

What can I do?

Body:
There are several methods for achieving your goal(all depends on your requirements) but one approach is you can create Singleton class of your BusinessLogic and then access it anywhere. have a look here. OR you can also pass object of class one class to another. OR you can use signal slot mechanism.

For you best Solution can be

Class BLogic{
public:
    static BLogic* instance(){
       static BLogic ins;
       return &ins;
    }
    void setVal(int v){
        val = v;
    }
private:
    BLogic(){}
    int val;
};

Now you can call functions of BLogic from any class like

BLogic::instance()->setVal(10);

OR Example of passing objects can be

class ClassA
{
public:
   void setClassB(ClassB *ob){
      m_classB = ob;
   }
   ClassB* getClassB(){
      return m_classB;
   }
private:
   ClassB* m_classB;
};

class ClassB
{
public:
   void setClassA(ClassA *ob){
      m_classA = ob;
   }
   ClassA* getClassA(){
      return m_classA;
   }
private:
   ClassA* m_classA;
};

Now from main.cpp

ClassA* obA = new ClassA;
ClassB* obB = new ClassB;
obA->setClassB(obB);
obB->setClassA(obA);


问:
How to use c# tuple value types in a switch statement
I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

```<code>using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}
</code>```

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

答:
Thanks for the replies.

I decided to drop the use of a switch statement and go for the old if/else statement.

```<code>using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            if (_test.letterA == 'A' && _test.letterB == 'B')
            {
                Console.WriteLine("Case A ok.");
            }
            else if (_test.letterA == 'D' && _test.letterB == '\0')
            {
                Console.WriteLine("Case D ok.");
            }

        }
    }
}
</code>```

This way I can decide if I want to test for all values in the tuple and in the order that I need. It shouldn't be much different in performance I think.

If there are another way of using tuples with a switch statement please feel free to give an example.

Body:
I'm using the new tuple value types in .net 4.7. In this example I am trying to make a switch statement for one or more cases of a tuple:

using System;
namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            switch (_test)
            {
                case ('A', 'B'):
                    Console.WriteLine("Case ok.");
                    break;
            }

        }
    }
}

This does not compile unfortunately.

How do I take a tuple and make cases in a switch statement correctly?

Body:
Thanks for the replies.

I decided to drop the use of a switch statement and go for the old if/else statement.

using System;

namespace ValueTupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            (char letterA, char letterB) _test = ('A','B');
            Console.WriteLine($"Letter A: '{_test.letterA}', Letter B: '{_test.letterB}'");

            if (_test.letterA == 'A' && _test.letterB == 'B')
            {
                Console.WriteLine("Case A ok.");
            }
            else if (_test.letterA == 'D' && _test.letterB == '\0')
            {
                Console.WriteLine("Case D ok.");
            }

        }
    }
}

This way I can decide if I want to test for all values in the tuple and in the order that I need. It shouldn't be much different in performance I think.

If there are another way of using tuples with a switch statement please feel free to give an example.


问:
ssh clone failed in gitolite at a GCP compute engine
After install gitolite in a GCP compute engine and added a new ssh public key in gitolite-admin/keydir/charley_rsa.pub and add a new repo for charley:

conf/gitolite.conf:

```<code>repo test
    RW+     =   charley
</code>```

Then: git clone gitolite-admin in GCP local console is ok.

When we do git clone in remote local pc, it shows 'DENIED by fallthru' error

```<code>git clone ssh://git@serverip/test
Cloning into 'test'...
FATAL: R any test charley_rsa DENIED by fallthru
(or you mis-spelled the reponame)
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

( clone testing (@all) in remote local pc is ok )

答:
The way you add new keys is by first cloning gitolite_admin repo, modifying it and pushing back: that triggers the recompilation of the ~/.gitolite/ configuration files.

If you do anything directly on the server, then follow "administering gitolite directly on the server"

You would need at least

```<code>gitolite compile; gitolite trigger POST_COMPILE
</code>```

Body:
After install gitolite in a GCP compute engine and added a new ssh public key in gitolite-admin/keydir/charley_rsa.pub and add a new repo for charley:

conf/gitolite.conf:

repo test
    RW+     =   charley

Then: git clone gitolite-admin in GCP local console is ok.

When we do git clone in remote local pc, it shows 'DENIED by fallthru' error

git clone ssh://git@serverip/test
Cloning into 'test'...
FATAL: R any test charley_rsa DENIED by fallthru
(or you mis-spelled the reponame)
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

( clone testing (@all) in remote local pc is ok )

Body:
The way you add new keys is by first cloning gitolite_admin repo, modifying it and pushing back: that triggers the recompilation of the ~/.gitolite/ configuration files.

If you do anything directly on the server, then follow "administering gitolite directly on the server"

You would need at least

gitolite compile; gitolite trigger POST_COMPILE


问:
Spring and MongoDB: Saving Value Objects in a more flat way
For a new Spring application I'm designing and developing, we're using MongoDB as the persistence layer for a number of technical reasons. This is the first project where I'm trying to implement some DDD principles, including Value Objects. I'm trying to find the best way to save a ValueObject which is in fact simply a String. Using Lombok's @Value, my Spring REST Controller happily parses a value into a ValueObject on the RestController side. But then when saving the value, it gets saved in a structured way on the MongoDB side.

For example

My VO:

```<code>@Value
public class PersonKey {
    private String value;
}
</code>```

The document I'll be storing in MongoDB:

```<code>@Document
public class PersonDocument {
    private PersonKey personKey;
    private Name name;
    ...
}
</code>```

What gets saved in MongoDB:

```<code>{.. "personKey": {"value": "faeeaf2"} ...}
</code>```

What I actually want:

```<code>{.. "personKey": "faeeaf2" ..}
</code>```

Of course with minimal extra boilerplate code.. :-)

答:
Coincidentally I am working on exactly the same problem. And you can actually do this with CustomConverters. Maybe not exactly like you want but in a very similar way. The only problem I have been unable to overcome is that you can't dynamically choose Converters at runtime. This is due to implementation of CustomConversions#registerConversion on line number 182.

This example shows what I am currently working on. I am using a GenericConverter but you can also fallback to regular Converters. This example doesn't check on Field annotations. Rather it uses an interface called SingleValue. All of my Value Objects that represent a single value implement this interface. So no need for an annotation on the Field.

```<code>@Configuration
@Slf4j
public class MongoDbConfiguration {

    @Bean
    @Primary
    public CustomConversions mongoCustomConversions() throws Exception {
        final List converterList = new ArrayList<>();
        converterList.add(new SingleValueConverter());
        return new CustomConversions(converterList);
    }

    private static class SingleValueConverter implements GenericConverter {

        @Override
        public Set<ConvertiblePair> getConvertibleTypes() {
            return new HashSet<>(Arrays.asList(new ConvertiblePair[]{
                    new ConvertiblePair(UUIDEntityReference.class, String.class),
                    new ConvertiblePair(String.class, FundingProcessId.class)
                    // put here all of your type conversions (two way!)
            }));
        }

        @Override
        public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            try {
                // first check if the instance of this type is an instance of our 'SingleValue' interface
                if (source instanceof SingleValue) {
                    return ((SingleValue) source).getValue();
                }

                final Class<?> objectType = targetType.getType();
                final Constructor<?> constructor = objectType.getConstructor(sourceType.getType());
                return constructor.newInstance(source);
            } catch (ReflectiveOperationException e) {
                throw new RuntimeException("Could not convert unexpected type " +
                        sourceType.getObjectType().getName() + " to " + targetType.getObjectType().getName(), e);
            }
        }
    }
}
</code>```

This is the most elegant way I could find. Still looking for way to automate the registration of all types. This may be possible with annotations and classpath scanning.

Note that this implementation assumes a couple of things

You have an interface SingleValue with a method getValue

Each of your 'single-valued' Value classes have a constructor with a single argument of the internal type representation (e.g. String for a UUID)

EDIT: I posted the wrong example code. Updated it

Body:
For a new Spring application I'm designing and developing, we're using MongoDB as the persistence layer for a number of technical reasons. This is the first project where I'm trying to implement some DDD principles, including Value Objects. I'm trying to find the best way to save a ValueObject which is in fact simply a String. Using Lombok's @Value, my Spring REST Controller happily parses a value into a ValueObject on the RestController side. But then when saving the value, it gets saved in a structured way on the MongoDB side.

For example

My VO:

@Value
public class PersonKey {
    private String value;
}

The document I'll be storing in MongoDB:

@Document
public class PersonDocument {
    private PersonKey personKey;
    private Name name;
    ...
}

What gets saved in MongoDB:

{.. "personKey": {"value": "faeeaf2"} ...}

What I actually want:

{.. "personKey": "faeeaf2" ..}

Of course with minimal extra boilerplate code.. :-)

Body:
Coincidentally I am working on exactly the same problem. And you can actually do this with CustomConverters. Maybe not exactly like you want but in a very similar way. The only problem I have been unable to overcome is that you can't dynamically choose Converters at runtime. This is due to implementation of CustomConversions#registerConversion on line number 182.

This example shows what I am currently working on. I am using a GenericConverter but you can also fallback to regular Converters. This example doesn't check on Field annotations. Rather it uses an interface called SingleValue. All of my Value Objects that represent a single value implement this interface. So no need for an annotation on the Field.

@Configuration
@Slf4j
public class MongoDbConfiguration {

    @Bean
    @Primary
    public CustomConversions mongoCustomConversions() throws Exception {
        final List converterList = new ArrayList<>();
        converterList.add(new SingleValueConverter());
        return new CustomConversions(converterList);
    }

    private static class SingleValueConverter implements GenericConverter {

        @Override
        public Set<ConvertiblePair> getConvertibleTypes() {
            return new HashSet<>(Arrays.asList(new ConvertiblePair[]{
                    new ConvertiblePair(UUIDEntityReference.class, String.class),
                    new ConvertiblePair(String.class, FundingProcessId.class)
                    // put here all of your type conversions (two way!)
            }));
        }

        @Override
        public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
            try {
                // first check if the instance of this type is an instance of our 'SingleValue' interface
                if (source instanceof SingleValue) {
                    return ((SingleValue) source).getValue();
                }

                final Class<?> objectType = targetType.getType();
                final Constructor<?> constructor = objectType.getConstructor(sourceType.getType());
                return constructor.newInstance(source);
            } catch (ReflectiveOperationException e) {
                throw new RuntimeException("Could not convert unexpected type " +
                        sourceType.getObjectType().getName() + " to " + targetType.getObjectType().getName(), e);
            }
        }
    }
}

This is the most elegant way I could find. Still looking for way to automate the registration of all types. This may be possible with annotations and classpath scanning.

Note that this implementation assumes a couple of things

You have an interface SingleValue with a method getValue

Each of your 'single-valued' Value classes have a constructor with a single argument of the internal type representation (e.g. String for a UUID)

EDIT: I posted the wrong example code. Updated it


问:
How to test multiple variables for equality against a single value?
I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:

```<code>x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0:
    mylist.append("c")
if x or y or z == 1:
    mylist.append("d")
if x or y or z == 2:
    mylist.append("e")
if x or y or z == 3:
    mylist.append("f")
</code>```

which would return a list of:

```<code>["c", "d", "f"]
</code>```

答:
One line solution:

```<code>mylist = [{0: 'c', 1: 'd', 2: 'e', 3: 'f'}[i] for i in [0, 1, 2, 3] if i in (x, y, z)]
</code>```

Or:

```<code>mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]
</code>```

Body:
I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:

x = 0
y = 1
z = 3
mylist = []

if x or y or z == 0:
    mylist.append("c")
if x or y or z == 1:
    mylist.append("d")
if x or y or z == 2:
    mylist.append("e")
if x or y or z == 3:
    mylist.append("f")

which would return a list of:

["c", "d", "f"]

Body:
One line solution:

mylist = [{0: 'c', 1: 'd', 2: 'e', 3: 'f'}[i] for i in [0, 1, 2, 3] if i in (x, y, z)]

Or:

mylist = ['cdef'[i] for i in range(4) if i in (x, y, z)]


问:
angular2 ionic 2 keeping keyboard popped up
I'm building a chat app where the ion-footer is used as a text box + send button. when I tap on the input box the keyboard popups up nicely as I need. however, when I tap on send button, the keyboard goes down and it becomes a frustrating experience for end user.

I understand it happens as the keyboard looses the focus and ionic pushes it down. however, this is not what I want.  How, do I keep keyboard as is until I really hit the send button.

```<code>my current ionic 2 looks like
<ion-footer padding>
    <form [formGroup]="chatForm" (ngSubmit)="sendChatMessage()">
        <ion-input type="text" formControlName="messageInput" placeholder="start typing..."></ion-input>
        <ion-buttons end>
            <button item-right ion-button clear type="submit" [disabled]="chatForm.controls['messageInput'].value === ''"><ion-icon name="ios-send" style="zoom:2.0;"></ion-icon></button>
        </ion-buttons>
    </form>
</ion-footer>
</code>```

答:
Setting focus will open the keyboard back up.

Setting the reference:

```<code><ion-input #sendInput type="text" formControlName="messageInput" placeholder="start typing...">
</ion-input>
</code>```

Connection reference to class:

```<code>@ViewChild("sendInput") public sendInput: TextInput;
</code>```

Setting the focus:

```<code>this.sendInput.setFocus();
</code>```

Body:
I'm building a chat app where the ion-footer is used as a text box + send button. when I tap on the input box the keyboard popups up nicely as I need. however, when I tap on send button, the keyboard goes down and it becomes a frustrating experience for end user.

I understand it happens as the keyboard looses the focus and ionic pushes it down. however, this is not what I want.  How, do I keep keyboard as is until I really hit the send button.

my current ionic 2 looks like
<ion-footer padding>
    <form [formGroup]="chatForm" (ngSubmit)="sendChatMessage()">
        <ion-input type="text" formControlName="messageInput" placeholder="start typing..."></ion-input>
        <ion-buttons end>
            <button item-right ion-button clear type="submit" [disabled]="chatForm.controls['messageInput'].value === ''"><ion-icon name="ios-send" style="zoom:2.0;"></ion-icon></button>
        </ion-buttons>
    </form>
</ion-footer>

Body:
Setting focus will open the keyboard back up.

Setting the reference:

<ion-input #sendInput type="text" formControlName="messageInput" placeholder="start typing...">
</ion-input>

Connection reference to class:

@ViewChild("sendInput") public sendInput: TextInput;

Setting the focus:

this.sendInput.setFocus();


问:
How to read the excel file from cloud or server?
I have following code:

```<code>     Wbnwsheet = pd.read_excel(r"C:/Users/SHI/ingrendient.xlsm",
                   sheetname="Step1", sep='\t')
</code>```

this code is direct read from my desktop, how about if I want read the excel file from cloud or server that the path are start with" \ingredient\....\  ?

Any idea about this?

答:
If you read the documentation of Pandas.read_excel here, you will notice that io parameter also accepts the follow parameters

http urls

ftp url

Parameters:

io : string, path object (pathlib.Path or py._path.local.LocalPath),

file-like object, pandas ExcelFile, or xlrd workbook. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For
  file URLs, a host is expected. For instance, a local file could be
  file://localhost/path/to/workbook.xlsx

hence, you could use pd.read_excel() in the following way to achieve your purpose.

```<code>pd.read_excel('http://yourwebsite.com/path_to_excel_doc/excel_doc.xlsm')
</code>```

Cheers!

Body:
I have following code:

     Wbnwsheet = pd.read_excel(r"C:/Users/SHI/ingrendient.xlsm",
                   sheetname="Step1", sep='\t')

this code is direct read from my desktop, how about if I want read the excel file from cloud or server that the path are start with" \ingredient\....\  ?

Any idea about this?

Body:
If you read the documentation of Pandas.read_excel here, you will notice that io parameter also accepts the follow parameters

http urls

ftp url

Parameters:

io : string, path object (pathlib.Path or py._path.local.LocalPath),

file-like object, pandas ExcelFile, or xlrd workbook. The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For
  file URLs, a host is expected. For instance, a local file could be
  file://localhost/path/to/workbook.xlsx

hence, you could use pd.read_excel() in the following way to achieve your purpose.

pd.read_excel('http://yourwebsite.com/path_to_excel_doc/excel_doc.xlsm')

Cheers!


问:
Stop text from wrapping underneath image
I want to stop the text from wrapping underneath an image, without making any changes to the HTML. Can this be done solely by CSS? I know the text can be wrapped in a div but I'm not able to do that on Wordpress.

JSFiddle: https://jsfiddle.net/s01x1ere/

HTML

```<code><div>
  <p>
    <a href="amazon.com"><img src="https://www.easycalculation.com/area/images/big-square.gif"></a>
    Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
  </p>

</div>
</code>```

CSS

```<code>div {
  width:500px;
}

img {
  float:left;
  height:100px;
  width:100px;
}
</code>```

答:
Please attache this code

div { width:500px; }
img { float:left; height:100px; width:100px; margin-right: 15px;}
p { display: flex; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
            <p>
              <img src="https://www.easycalculation.com/area/images/big-square.gif">
              Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
            </p>
        </div></code>```

Body:
I want to stop the text from wrapping underneath an image, without making any changes to the HTML. Can this be done solely by CSS? I know the text can be wrapped in a div but I'm not able to do that on Wordpress.

JSFiddle: https://jsfiddle.net/s01x1ere/

HTML

    Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text

CSS

div {
  width:500px;
}

img {
  float:left;
  height:100px;
  width:100px;
}

Body:
Please attache this code

div { width:500px; }
img { float:left; height:100px; width:100px; margin-right: 15px;}
p { display: flex; }

<div>
            <p>
              <a href="amazon.com"><img src="https://www.easycalculation.com/area/images/big-square.gif"></a>
              Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text Text
            </p>
        </div>


答:
Linq Solution Example is here:

The extension method Where will helps you to get the capital letters from the given string. You can use either String.Join or String.Concat(nicer as suggested by DmitryBychenko) for getting the final output as a string. Go through the following snippet

```<code>string inputStr = "Electronics and Communication Engineering";
string outputStr=String.Concat(inputStr.Where(x=>Char.IsUpper(x)));
Console.WriteLine(outputStr);
</code>```

Body:
I need to find all capital letters in a string. For example

Input : Electronics and Communication Engineering

Output: ECE

Body:
Linq Solution Example is here:

The extension method Where will helps you to get the capital letters from the given string. You can use either String.Join or String.Concat(nicer as suggested by DmitryBychenko) for getting the final output as a string. Go through the following snippet

string inputStr = "Electronics and Communication Engineering";
string outputStr=String.Concat(inputStr.Where(x=>Char.IsUpper(x)));
Console.WriteLine(outputStr);


问:
How to detect if URL() constructor is supported by browsers?
I want to detect if a browser support the URL() constructor.

I want to use it like this:

```<code>const url = new URL(urlString, [baseURLstring])
</code>```

I can't find a proper method to check if it's supported by browser?

答:
Assuming the check needs to be done in JavaScript -

Use if(typeof URL === "function")

If true URL is supported

Sample Code

if (typeof URL === "function") {
  const baseURLstring = "http://www.aaa.bbb/";
  let urlString = "/hello";
  const url = new URL(urlString, [baseURLstring]);
  console.log(url)
}
else if (navigator.userAgent.indexOf('MSIE') != -1 && typeof URL === 'object') {
  const baseURLstring = "http://www.aaa.bbb/";
  let urlString = "/hello";
  const url = new URL(urlString, [baseURLstring]);
  console.log(url)
}```

Body:
I want to detect if a browser support the URL() constructor.

I want to use it like this:

const url = new URL(urlString, [baseURLstring])

I can't find a proper method to check if it's supported by browser?


问:
how can i track users without cookies
ok... im looking to have a good round of brainstorming here...

say i was google... the adword/adsense/analytics division. i would be getting a little worried about the future, when users start to disable cookies (or at least delete them on a regular basis), use private browsing, roam on multiple devices. how could google alternatively track users without the benefits of cookies?

some ideas to get started (please elaborate on these and any others):

-track users using some other persistent local/client side storage

-use user-agent string fingerprinting

-test cache response - if user 304's an image, they were here

-track mac address

-any random/out of the box ideas?

答:
Information about browser/system/display through js and IP of cause;

Java Applet provide a lot of info about user;

Flash also (e.g. installed fonts);

Modern browsers also provide a lot of information about users (e.g. installed extensions) and provide new ways to save information on client-side (e.g. html5 storage).
altogether: http://panopticlick.eff.org/

Title: how can i track users without cookies


问:
Back button on Action Bar crashing app android
Synposis: I have 3 activity (LoginActivity, MainActivity and EditProfileActivity). After Facebook login in my LoginActivity I srart the MainActivity. (Till this point the app is working perfectly correct with no error). I have a NavigationDrawer for my navigations, When I click on Edit Profile link from the NavigationDrawer it starts the EditProfileActivity.

Problem: When I click on the LeftArrow in the Top blue bar, the app crashes.

Please see the images:

MainActivity

Navigation Drawer

EditProfileActivity

App Crash on clicking the top left arrow

Here is my Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider"
            android:exported="true" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".EditProfileActivity"
            android:parentActivityName=".MainActivity" >
            <!-- The meta-data tag is required if you support API level 15 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>

</manifest>
</code>```

Here is my MainActivity.java

package com.example.example;

```<code>import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        Bundle inBundle = getIntent().getExtras();
        String first_name = inBundle.get("first_name").toString();
        String last_name = inBundle.get("last_name").toString();
        String imageUrl = inBundle.get("imageUrl").toString();

        TextView nameView = (TextView)findViewById(R.id.nameView);
        nameView.setText("" + first_name + " " + last_name);
        new DownloadImage((ImageView)findViewById(R.id.imageView)).execute(imageUrl);
        return true;
    }
    public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if(id == R.id.nav_user_edit){
            Intent intent = new Intent(this, EditProfileActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
</code>```

答:
You have to define your activities parent in the manifest file like this

```<code><meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="fully qualified activity name" />
</code>```

Make sure that you keep this meta data of your activity containing back button. Other wise its just like you are not telling you back button where to go !!

You have to add these two lines in your MainActivity.java file:

```<code>getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
</code>```

Add this in your onOptionsItemSelected(MenuItem item) method:

```<code>if (id==android.R.id.home)
        {
            NavUtils.navigateUpFromSameTask(this);
        }
</code>```

Body:
Synposis: I have 3 activity (LoginActivity, MainActivity and EditProfileActivity). After Facebook login in my LoginActivity I srart the MainActivity. (Till this point the app is working perfectly correct with no error). I have a NavigationDrawer for my navigations, When I click on Edit Profile link from the NavigationDrawer it starts the EditProfileActivity.

Problem: When I click on the LeftArrow in the Top blue bar, the app crashes.

Please see the images:

MainActivity

Navigation Drawer

EditProfileActivity

App Crash on clicking the top left arrow

Here is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider"
            android:exported="true" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".EditProfileActivity"
            android:parentActivityName=".MainActivity" >

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>

</manifest>

Here is my MainActivity.java

package com.example.example;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        Bundle inBundle = getIntent().getExtras();
        String first_name = inBundle.get("first_name").toString();
        String last_name = inBundle.get("last_name").toString();
        String imageUrl = inBundle.get("imageUrl").toString();

        TextView nameView = (TextView)findViewById(R.id.nameView);
        nameView.setText("" + first_name + " " + last_name);
        new DownloadImage((ImageView)findViewById(R.id.imageView)).execute(imageUrl);
        return true;
    }
    public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if(id == R.id.nav_user_edit){
            Intent intent = new Intent(this, EditProfileActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Body:
You have to define your activities parent in the manifest file like this

<meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="fully qualified activity name" />

Make sure that you keep this meta data of your activity containing back button. Other wise its just like you are not telling you back button where to go !!

You have to add these two lines in your MainActivity.java file:

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Add this in your onOptionsItemSelected(MenuItem item) method:

if (id==android.R.id.home)
        {
            NavUtils.navigateUpFromSameTask(this);
        }


问:
How can I use case_when inside dplyr mutate() function?
As far as I understand, case_when() is a generalised version of ifelse().

However, I don't understand how to use this function inside dplyr::mutate() function. It used to work using github's last version of dplyr but since I'm back to the CRAN version (0.5), it doesn't work anymore. Does anyone has a clue ?

Here is my reproducible example :

library(devtools)
library(tibble)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

tibble(
  group = c("A", "A", "A", "B", "B", "B"),
  x = 1:6
  ) %>%
  mutate(
    y = ifelse(group == "A", -x, x)
    )
#> # A tibble: 6 × 3
#>   group     x     y
#>   <chr> <int> <int>
#> 1     A     1    -1
#> 2     A     2    -2
#> 3     A     3    -3
#> 4     B     4     4
#> 5     B     5     5
#> 6     B     6     6

tibble(
  group = c("A", "A", "A", "B", "B", "B"),
  x = 1:6
  ) %>%
  mutate(
    y = case_when(
      group == "A" ~ -x,
      TRUE ~ x
      )
  )
#> Error in mutate_impl(.data, dots): object 'group' not found

tibble(
  group = c("A", "A", "A", "B", "B", "B"),
  x = 1:6
  ) %>%
  mutate_(
    .dots = list(
      "y" = lazyeval::interp(
        ~ case_when(var1 == "A" ~ -var2, TRUE, var2),
        var1 = as.name(group),
        var2 = as.name(x)
        )
    )
  )
#> Error in as.name(group): object 'group' not found

devtools::session_info()
#> Session info -------------------------------------------------------------
#>  setting  value
#>  version  R version 3.3.2 (2016-10-31)
#>  system   x86_64, linux-gnu
#>  ui       X11
#>  language (EN)
#>  collate  C
#>  tz       <NA>
#>  date     2017-03-10
#> Packages -----------------------------------------------------------------
#>  package    * version     date       source
#>  assertthat   0.1         2013-12-06 CRAN (R 3.2.2)
#>  backports    1.0.5       2017-01-18 cran (@1.0.5)
#>  DBI          0.6         2017-03-09 cran (@0.6)
#>  devtools   * 1.12.0.9000 2017-03-07 Github (hadley/devtools@d8ab190)
#>  digest       0.6.12      2017-01-27 cran (@0.6.12)
#>  dplyr      * 0.5.0       2016-06-24 CRAN (R 3.3.2)
#>  evaluate     0.10        2016-10-11 cran (@0.10)
#>  htmltools    0.3.5       2016-03-21 CRAN (R 3.2.3)
#>  knitr        1.15.1      2016-11-22 cran (@1.15.1)
#>  lazyeval     0.2.0.9000  2016-10-14 Github (hadley/lazyeval@c155c3d)
#>  magrittr     1.5         2014-11-22 CRAN (R 3.2.3)
#>  memoise      1.0.0.9001  2017-02-13 Github (hadley/memoise@884d565)
#>  pkgbuild     0.0.0.9000  2017-03-07 Github (r-pkgs/pkgbuild@65eace0)
#>  pkgload      0.0.0.9000  2017-03-07 Github (r-pkgs/pkgload@fc907a1)
#>  R6           2.2.0       2016-10-05 cran (@2.2.0)
#>  Rcpp         0.12.9      2017-01-14 cran (@0.12.9)
#>  rmarkdown    1.3.9004    2017-03-09 Github (rstudio/rmarkdown@01dc037)
#>  rprojroot    1.2         2017-01-16 cran (@1.2)
#>  stringi      1.1.2       2016-10-01 CRAN (R 3.3.1)
#>  stringr      1.2.0       2017-02-18 cran (@1.2.0)
#>  tibble     * 1.2         2016-08-26 CRAN (R 3.2.3)
#>  withr        1.0.2       2016-06-20 CRAN (R 3.2.3)
#>  yaml         2.1.14      2016-11-12 cran (@2.1.14)
```

答: dplyr has been updated and so the code should work now without using .$ or transforming to data.table - see https://github.com/tidyverse/dplyr/issues/1965</p>


问:
How to create a download file and not save it in server with javascript
i have problem about how to create button which will downloading PDF file for one div.

i tried window.print() like this :

```<code>$(document).ready(function(){

        $('#printBtn').on('click',function(){
            window.print();
        });

    });
</code>```

and save it as PDF file. i don't know other ways than that and i don't want to save it on server first.

答:
You try direct download link with using a elements attribute download

```<code><a href="/images/myw3schoolsimage.jpg" download>
</code>```

---- OR ----

```<code><button id="print" onclick="print('uname');" >Print</button>
<div id="uname">
<label>Name</label>
<label>Spider</label>
</div>

<button id="print" onclick="printContent('uname');" >Print</button>

    function print(e){var divToPrint=document.getElementById('e');

    var newWin=window.open('','Print-Window');

    newWin.document.open();

    newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

    newWin.document.close();

    setTimeout(function(){
        newWin.close();
    },10);
}
</code>```

Demo Here

Body:
i have problem about how to create button which will downloading PDF file for one div.

i tried window.print() like this :

$(document).ready(function(){

        $('#printBtn').on('click',function(){
            window.print();
        });

    });

and save it as PDF file. i don't know other ways than that and i don't want to save it on server first.

Body:
You try direct download link with using a elements attribute download

<a href="/images/myw3schoolsimage.jpg" download>

---- OR ----

<button id="print" onclick="print('uname');" >Print</button>
<div id="uname">
<label>Name</label>
<label>Spider</label>
</div>

<button id="print" onclick="printContent('uname');" >Print</button>

    function print(e){var divToPrint=document.getElementById('e');

    var newWin=window.open('','Print-Window');

    newWin.document.open();

    newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

    newWin.document.close();

    setTimeout(function(){
        newWin.close();
    },10);
}

Demo Here


问:
Single controller with multiple GET methods in ASP.NET Web API
In Web API I had a class of similar structure:

public class SomeController : ApiController
{
    [WebGet(UriTemplate = "{itemSource}/Items")]
    public SomeValue GetItems(CustomParam parameter) { ... }

    [WebGet(UriTemplate = "{itemSource}/Items/{parent}")]
    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}
```

<p>Since we could map individual methods, it was very simple to get the right request at the right place. For similar class which had only a single <code>GET</code> method but also had an <code>Object</code> parameter, I successfully used <code>IActionValueBinder</code>. However, in the case described above I get the following error:</p>

```Multiple actions were found that match the request:

SomeValue GetItems(CustomParam parameter) on type SomeType

SomeValue GetChildItems(CustomParam parameter, SomeObject parent) on type SomeType
```

I am trying to approach this problem by overriding the ExecuteAsync method of ApiController but with no luck so far. Any advice on this issue?

Edit: I forgot to mention that now I am trying to move this code on ASP.NET Web API which has a different approach to routing. The question is, how do I make the code work on ASP.NET Web API?

答:
I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):

```<code>[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {
</code>```

...without also also placing a [RoutePrefix] at the top of the Controller:

```<code>[RoutePrefix("api/values")]
public class ValuesController : ApiController
</code>```

I was getting errors stating that no Route was found matching the submitted URI.  Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.

Body:
In Web API I had a class of similar structure:

public class SomeController : ApiController
{
    [WebGet(UriTemplate = "{itemSource}/Items")]
    public SomeValue GetItems(CustomParam parameter) { ... }

    [WebGet(UriTemplate = "{itemSource}/Items/{parent}")]
    public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}

Since we could map individual methods, it was very simple to get the right request at the right place. For similar class which had only a single GET method but also had an Object parameter, I successfully used IActionValueBinder. However, in the case described above I get the following error:

Multiple actions were found that match the request:

SomeValue GetItems(CustomParam parameter) on type SomeType

SomeValue GetChildItems(CustomParam parameter, SomeObject parent) on type SomeType

I am trying to approach this problem by overriding the ExecuteAsync method of ApiController but with no luck so far. Any advice on this issue?

Edit: I forgot to mention that now I am trying to move this code on ASP.NET Web API which has a different approach to routing. The question is, how do I make the code work on ASP.NET Web API?

Body:
I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):

[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {

...without also also placing a [RoutePrefix] at the top of the Controller:

[RoutePrefix("api/values")]
public class ValuesController : ApiController

I was getting errors stating that no Route was found matching the submitted URI.  Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.


问:
VBscript & cmd full command what is missing?
```<code>Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /k tzutil /l "
</code>```

when running the first script it worked fine but when running the second script full command it does not so what is missing?

```<code>Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /k tzutil /s "Israel Standard Time""
</code>```

答:
Remove the extra double quotes and try again:

```<code>objShell.Run "cmd /k tzutil /s Israel Standard Time"
</code>```

Or, if you want to pass the time zone inside double quotes, you can try this:

```<code>objShell.Run "cmd /k tzutil /s ""Israel Standard Time"""
</code>```

Or, you can just write,

```<code>objShell.Run "tzutil /s Israel Standard Time"
</code>```

All these will let you change the current time zone to Israel's Time Zone.

Body:
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /k tzutil /l "

when running the first script it worked fine but when running the second script full command it does not so what is missing?

Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /k tzutil /s "Israel Standard Time""

Body:
Remove the extra double quotes and try again:

objShell.Run "cmd /k tzutil /s Israel Standard Time"

Or, if you want to pass the time zone inside double quotes, you can try this:

objShell.Run "cmd /k tzutil /s ""Israel Standard Time"""

Or, you can just write,

objShell.Run "tzutil /s Israel Standard Time"

All these will let you change the current time zone to Israel's Time Zone.


问:
Making a prime generator
This is supposed to be a prime generator. I try running this but it doesn't print out the integers. The program will also end right away. I don't know if its running  </p>

```<code>def prime_gen():

    start = 1

    while start:

        if start % start == 0:
            print(start)

            start += 1
</code>```

答:
You have 2 main issues here:

Your algorithm doesn't calculate primes - it runs infinitely (while start), and prints a number when number % number == 0 (aka number modulo number) which is always true. So this is an infinite loop printing the numbers from 1 up.

you never call prime_gen() which is why the program doesn't do anything.
You have created a function but did not call it.

for a nice way of calculating primes, take a look at Sieve of Eratosthenes (Wikipedia).

Title: Making a prime generator

Body:
This is supposed to be a prime generator. I try running this but it doesn't print out the integers. The program will also end right away. I don't know if its running

def prime_gen():

    start = 1

    while start:

        if start % start == 0:
            print(start)

            start += 1


问:
Creating a CI Build for in premise TFS 2015
I create a new build definition using the Visual Studio template. In the part where I have to Save and Queue the build, I see this window below but I cannot see anything in Queue drop-down to select. How should I set this up? Looks like I am missing a step.

答:
There should be some agent pools for you selecting under the queue drop.

First you could manually check if there are some agent pools under Agent Queues--All Queues

If there are, this may related to permissions. Double check if your account have enough related permission  such as queue builds. Make sure there is not any deny setting for your account and any group your account joined. In TFS, deny trumps allow.


问:
how to translate a dynamically added SVG animation on jointjs when a paper is scaled
I am not able to figure out how to re position an svg animation that i add dynamically on my paper during a zoom in or zoom out.

I add the animation when the link is active according to business logic in the following way.

```<code>  c = joint.V('circle', { r: 8, fill: 'green' });
      c.animateAlongPath({ dur: '4s', repeatCount: 'indefinite' }, canvasPaper.findViewByModel(link).$('.connection')[0]);
      joint.V(canvasPaper.svg).append(c)
</code>```

Now i go to the canvas and zoom in or zoom out the elements in the canvas scale appropriately . i use the paper.scale command. But the animation that i added does not move. I was able to get it scaled down to size but not its position. How do i achieve this?.

My zoom in and zoom out code is as below. I also know that i have to use the translate command on the svg object but i do not know how to calculate the translate values based on the zoomLevel

```<code>  $('#zoom-in').on('click', function(e) {
          e.preventDefault();
          zoomLevel = Number((Math.min(1, zoomLevel + 0.2)).toFixed(1));
          canvasPaper.scale(zoomLevel, zoomLevel,0,0);

_.each(canvasGraph.getLinks(), function(link) {
  if(link.attr('linkActiveAnimationSvgId/text')) {document.getElementById(link.attr('linkActiveAnimationSvgId/text')).setAttribute("transform", "scale(" + zoomLevel + "," + zoomLevel + ")")
  }
})

  })
</code>```

My zoom out code is as below

```<code>  $('#zoom-out').on('click', function(e) {
          e.preventDefault();
      zoomLevel =Number((Math.max(0.2, zoomLevel - 0.2)).toFixed(1));
    canvasPaper.scale(zoomLevel, zoomLevel,0,0);

_.each(canvasGraph.getLinks(), function(link) {
  if(link.attr('linkActiveAnimationSvgId/text')) {document.getElementById(link.attr('linkActiveAnimationSvgId/text')).setAttribute("transform", "scale(" + zoomLevel + "," + zoomLevel + ")")
  }
})

  })
</code>```

答:
ok all i had to do was to find the view of the paper and then
paperView.vel.append(c)
instead of
joint.V(canvasPaper.svg).append(c)
and now i scale the paper and the animation scales/translates appropriately</p>

Body:
I am not able to figure out how to re position an svg animation that i add dynamically on my paper during a zoom in or zoom out.

I add the animation when the link is active according to business logic in the following way.

  c = joint.V('circle', { r: 8, fill: 'green' });
      c.animateAlongPath({ dur: '4s', repeatCount: 'indefinite' }, canvasPaper.findViewByModel(link).$('.connection')[0]);
      joint.V(canvasPaper.svg).append(c)

Now i go to the canvas and zoom in or zoom out the elements in the canvas scale appropriately . i use the paper.scale command. But the animation that i added does not move. I was able to get it scaled down to size but not its position. How do i achieve this?.

My zoom in and zoom out code is as below. I also know that i have to use the translate command on the svg object but i do not know how to calculate the translate values based on the zoomLevel

  $('#zoom-in').on('click', function(e) {
          e.preventDefault();
          zoomLevel = Number((Math.min(1, zoomLevel + 0.2)).toFixed(1));
          canvasPaper.scale(zoomLevel, zoomLevel,0,0);

_.each(canvasGraph.getLinks(), function(link) {
  if(link.attr('linkActiveAnimationSvgId/text')) {document.getElementById(link.attr('linkActiveAnimationSvgId/text')).setAttribute("transform", "scale(" + zoomLevel + "," + zoomLevel + ")")
  }
})

  })

My zoom out code is as below

  $('#zoom-out').on('click', function(e) {
          e.preventDefault();
      zoomLevel =Number((Math.max(0.2, zoomLevel - 0.2)).toFixed(1));
    canvasPaper.scale(zoomLevel, zoomLevel,0,0);

_.each(canvasGraph.getLinks(), function(link) {
  if(link.attr('linkActiveAnimationSvgId/text')) {document.getElementById(link.attr('linkActiveAnimationSvgId/text')).setAttribute("transform", "scale(" + zoomLevel + "," + zoomLevel + ")")
  }
})

  })


问:
how to create a service in python in windows?
I want to run a service in windows which will keep running in background and will run a cron with specific time.

how i can do that in windows using python?

答: Use pywin32. A tutorial was written (in 2005 mind you) here about how one might do that.</p>