问:
Visual Studio 2015 InvalidProgramException in Unit Test With Fakes
I am using Visual Studio 2015 Enterprise RTM to write unit tests for a project that uses Unity Container.

I have discovered that the simple act of adding a fakes assembly for Unity, not even actually using the fake, is sufficient to generate this exception:

System.InvalidProgramException: Common Language Runtime detected an invalid program.

Consider the following steps to reproduce:

Using Visual Studio 2015 Enterprise RTM create a Unit Test project targeting .NET 4.6

Add the NuGet package "Unity" version 3.5.1404.0

Add the NuGet package "CommonServiceLocator" version 1.2.0

Write a single unit test like so:

[TestClass]
public class UnitTest1 : IDisposable
{
    [TestMethod]
    public void TestMethod1()
    {
        new ResolvedArrayParameter<IDisposable>(new IDisposable[] {this});
    }

    void IDisposable.Dispose()
    {
    }
}
```

Verify the test passes

Right click on the Microsoft.Practices.Unity reference and choose "Add Fakes Assembly"

Re-run the test

Observe the following remarkable test failure:

Test Name: TestMethod1

Test FullName:  UnitTestProject11.UnitTest1.TestMethod1

Test Source:    c:\temp\UnitTestProject11\UnitTestProject11\UnitTest1.cs : line 12

Test Outcome:   Failed

Test Duration:  0:00:00.0572447

Result StackTrace:

at Microsoft.Practices.Unity.ResolvedArrayParameter..ctor(Type arrayParameterType, Type elementType, Object[] elementValues)

at Microsoft.Practices.Unity.ResolvedArrayParameter`1..ctor(Object[] elementValues)

at UnitTestProject11.UnitTest1.TestMethod1() in c:\temp\UnitTestProject11\UnitTestProject11\UnitTest1.cs:line 13

Result Message:

Test method UnitTestProject11.UnitTest1.TestMethod1 threw exception:

System.InvalidProgramException: Common Language Runtime detected an invalid program.

The most extraordinary feature of this problem is evidently fakes don't even need to appear directly in the code for the failure to manifest.

An extensive amount of fiddling reveals that retargeting the test project to .NET 4.5 "fixes" the problem, which is a non-starter for me because of another issue I posted some weeks back.

Even more fiddling with virtually all fakes settings (code contracts, etc.) yielded no solution.

Any advice on this issue would be very much appreciated.

答:
The only general solution is to make sure that all parts match the version of CLR you are using very closely and that VS has the latest updates.

There is no magic bullet for this problem. You need to know (dig out) the exact CLR version compatibility of all parts that are connected in your project when you inject fakes. Mind you that "compatibility" might be just the matter of manifest but more frequently they are the matter of nuances of how was/is the final code generated and for which version of the virtual machine.

These things normally don't matter for running and debugging since there are several layers that make sure that minor version differences either don't matter or you get a silent switch to whatever your code is declared to be compatible with.

But, when you use Fakes, the "system" injects raw code into your (which includes 3rd party libraries involved) and that means that it skips most checks - couldn't work otherwise. But, when the time comes to actually run the code, the engine (virtual machine) has to do some checks for it's own safety/integrity and it tends to get paranoid and bail out if it looks like declarations don't match closely enough.

This is the reason why someone asked whether assemblies involved are strongnamed or signed. That's the only level of guarantee that "system" will really trust. Without that it will do a degree of guessing and while it mostly doesn't matter for normal runs if matters a lot for code injection.

I'm still not talking possible real problems - this is all assuming that actual code is fine and just declarations are confused. You could try to play with that but it would take a lot of time and effort. Much easier to go checking if you can get versions of assemblies that are better matching.

The fact that errors vanished when you switched your flavor back to 4.5 tells you that either some of the assemblies involved are not "close enough" for 4.6 or there can be some glitches with code injection that were fixed by updates you haven't taken in yet.

Yes it involves a lot of pain but that's the price of wanting to be at the frontier.

Body:
I am using Visual Studio 2015 Enterprise RTM to write unit tests for a project that uses Unity Container.

I have discovered that the simple act of adding a fakes assembly for Unity, not even actually using the fake, is sufficient to generate this exception:

System.InvalidProgramException: Common Language Runtime detected an invalid program.

Consider the following steps to reproduce:

Using Visual Studio 2015 Enterprise RTM create a Unit Test project targeting .NET 4.6

Add the NuGet package "Unity" version 3.5.1404.0

Add the NuGet package "CommonServiceLocator" version 1.2.0

Write a single unit test like so:

[TestClass]
public class UnitTest1 : IDisposable
{
    [TestMethod]
    public void TestMethod1()
    {
        new ResolvedArrayParameter<IDisposable>(new IDisposable[] {this});
    }

    void IDisposable.Dispose()
    {
    }
}

Verify the test passes

Right click on the Microsoft.Practices.Unity reference and choose "Add Fakes Assembly"

Re-run the test

Observe the following remarkable test failure:

Test Name: TestMethod1

Test FullName:  UnitTestProject11.UnitTest1.TestMethod1

Test Source:    c:\temp\UnitTestProject11\UnitTestProject11\UnitTest1.cs : line 12

Test Outcome:   Failed

Test Duration:  0:00:00.0572447

Result StackTrace:

at Microsoft.Practices.Unity.ResolvedArrayParameter..ctor(Type arrayParameterType, Type elementType, Object[] elementValues)

at Microsoft.Practices.Unity.ResolvedArrayParameter`1..ctor(Object[] elementValues)

at UnitTestProject11.UnitTest1.TestMethod1() in c:\temp\UnitTestProject11\UnitTestProject11\UnitTest1.cs:line 13

Result Message:

Test method UnitTestProject11.UnitTest1.TestMethod1 threw exception:

System.InvalidProgramException: Common Language Runtime detected an invalid program.

The most extraordinary feature of this problem is evidently fakes don't even need to appear directly in the code for the failure to manifest.

An extensive amount of fiddling reveals that retargeting the test project to .NET 4.5 "fixes" the problem, which is a non-starter for me because of another issue I posted some weeks back.

Even more fiddling with virtually all fakes settings (code contracts, etc.) yielded no solution.

Any advice on this issue would be very much appreciated.


来源: stackexchange

问:
Python3 - retrieving Facebook html
```<code><a class="_2wma" href="https://www.facebook.com/SMRTCorpSG/?ref=page_internal">SMRT</a>
</code>```

I am trying to retrieve the text in the  however when i tired using the method below, the outcome is an empty list [] . Did i make a mistake here?

```<code>r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
name = soup.find_all("a",{"class": "_2wma"})
print(name)
name2 = soup.find_all("a", {"href": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})
print(name2)
</code>```

答:
the attribute should be href and not class for the second one

```<code>name2 = soup.find_all("a", {"class": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})
</code>```

should be

```<code>name2 = soup.find_all("a", {"href": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})
</code>```

also make sure you put the correct value when instantiating BeautifulSoup. Try to print r.content to check it.

```<code>print(r.content)
BeautifulSoup(r.content, "html.parser")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python3 - retrieving Facebook html

Body:
SMRT

I am trying to retrieve the text in the  however when i tired using the method below, the outcome is an empty list [] . Did i make a mistake here?

r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
name = soup.find_all("a",{"class": "_2wma"})
print(name)
name2 = soup.find_all("a", {"href": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})
print(name2)

Body:
the attribute should be href and not class for the second one

name2 = soup.find_all("a", {"class": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})

should be

name2 = soup.find_all("a", {"href": "https://www.facebook.com/SMRTCorpSG/?ref=page_internal"})

also make sure you put the correct value when instantiating BeautifulSoup. Try to print r.content to check it.

print(r.content)
BeautifulSoup(r.content, "html.parser")


问:
Scripting for file management with a very large amount of files
I have a three OSX machine setup that was using syncthing to keep shared drives synchronized remotely.  Someone made some mistakes and a lot of files ended up getting renamed.

So all throughout this drive I have situations where there's a file of size 0KB named,for example, file.jpg and another file with real size named
file.sync-confilct201705-4528.jpg.  I need to search the entire drive recursively and while I find a file with the sync-conflict string in it, check to see if there is the same file without the 'sync-conflict' string along with a size of 0KB.  If there is, I need to rename the sync-conflict file to overwrite the 0KB file.

I have considered tackling this with a bash script or a Perl script.  Using bash I think just using the 'find' command with -regex would get me started but I don't really know how to process the results and run the next find test.  I am studying and working on it.

Same problem with Perl. I can get through the first step using File::Find:find and select what I need using regex to filter out the files, but there again I am stuck getting to the next step, which would be finding the original file in the same directory and performing the necessary file move function.

In both of these cases I am willing to put in the time to figure it out, but I wonder what the caveats will be?  Can both of these scenarios handle recursing a large number of files without exception?  Is there perhaps a better approach anyone can recommend?

答:
find is great. But as you've noted, you need more.

What find gets you in this scenario is the ability to search recursively and match certain patterns. As it happens as of Bash version 4, you can do that right in the shell.

(Note that macOS ships with bash version 3, so for this solution, you'll need to install bash 4 from Macports, Homebrew or Fink.)

```<code>$ shopt -s globstar nullglob
$ for file in **/*sync-confilct2017*.*; do echo mv -v "$file" "${file%sync-conf*}${file##*.}"; done
mv -v file.sync-confilct201705-4528.jpg file.jpg
mv -v foo/bar.sync-confilct201705-4528.ext foo/bar.ext
</code>```

You can remove the echo to actually run the mv command.

The way this works is that the double asterisk, **, is treated by bash like a * that recurses. We're using parameter expansion to strip the parts of the filename we want in order to construct the "target" filename.

Body:
find is great. But as you've noted, you need more.

What find gets you in this scenario is the ability to search recursively and match certain patterns. As it happens as of Bash version 4, you can do that right in the shell.

(Note that macOS ships with bash version 3, so for this solution, you'll need to install bash 4 from Macports, Homebrew or Fink.)

$ shopt -s globstar nullglob
$ for file in **/*sync-confilct2017*.*; do echo mv -v "$file" "${file%sync-conf*}${file##*.}"; done
mv -v file.sync-confilct201705-4528.jpg file.jpg
mv -v foo/bar.sync-confilct201705-4528.ext foo/bar.ext

You can remove the echo to actually run the mv command.

The way this works is that the double asterisk, **, is treated by bash like a * that recurses. We're using parameter expansion to strip the parts of the filename we want in order to construct the "target" filename.


问:
Unity C# waiting
Currently, I have this code

```<code>void update()
{
    Debug.Log(1);
    StartCoroutine(wait());
    Debug.Log(4);
}
IEnumerator wait()
{
    Debug.Log(2)
    yield return new WaitForSeconds(3);
    Debug.Log(3)
}
</code>```

I want an output of 1, 2, 3, 4, but instead I'm getting 1, 2, 4, 3. I think I may be misunderstanding how coroutines function here. Why am I getting this behaviour and how would I go about fixing it? Thanks in advance

答:
To learn more about Coroutines, I recommend reading the excellent answer given here.

To give a high-level summary for your code, when you call StartCoroutine on wait(), all of the code until your yield statement will run. So now your output is 1, 2. When yield is called, Unity will return and execute the code in update(), logging the int 4. After 3 seconds it will return to wait() and continue execution, giving the final output 1,2,4,3.

If you want to output 1,2,3,4 you will need to use yield return to call the wait() method, so 4 is printed afterwards. In order to do this the code in update() will need to be in a method of return type IEnumerator itself.

```<code>void update()
{
    StartCoroutine(dosomething());
}

IEnumerator dosomething()
{
    Debug.Log(1);
    yield return wait();
    Debug.Log(4);
}

IEnumerator wait()
{
    Debug.Log(2);
    yield return new WaitForSeconds(3);
    Debug.Log(3);
}
</code>```

Title: Unity C# waiting

Body:
Currently, I have this code

void update()
{
    Debug.Log(1);
    StartCoroutine(wait());
    Debug.Log(4);
}
IEnumerator wait()
{
    Debug.Log(2)
    yield return new WaitForSeconds(3);
    Debug.Log(3)
}

I want an output of 1, 2, 3, 4, but instead I'm getting 1, 2, 4, 3. I think I may be misunderstanding how coroutines function here. Why am I getting this behaviour and how would I go about fixing it? Thanks in advance

Body:
To learn more about Coroutines, I recommend reading the excellent answer given here.

To give a high-level summary for your code, when you call StartCoroutine on wait(), all of the code until your yield statement will run. So now your output is 1, 2. When yield is called, Unity will return and execute the code in update(), logging the int 4. After 3 seconds it will return to wait() and continue execution, giving the final output 1,2,4,3.

If you want to output 1,2,3,4 you will need to use yield return to call the wait() method, so 4 is printed afterwards. In order to do this the code in update() will need to be in a method of return type IEnumerator itself.

void update()
{
    StartCoroutine(dosomething());
}

IEnumerator dosomething()
{
    Debug.Log(1);
    yield return wait();
    Debug.Log(4);
}

IEnumerator wait()
{
    Debug.Log(2);
    yield return new WaitForSeconds(3);
    Debug.Log(3);
}


问:
How do I send emails outside my domain with Exchange 2007 and c#
I am able to send emails using the typical C# SMTP code across Exchange 2007 as long as both the from and to addresses are within my domain.

As soon as I try to send emails outside the domain I get:

Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.1 Unable to relay

How can I get exchange to accept my email and send it out to the internet?

答:
You'll need to get your exchange admin to configure exchange to allow sending outside the domain.  In my experience they've been reluctant to do so because of spam concerns.

If its' for limited use, you can set up server-side rules in exchange to forward messages meeting certain criteria outside the domain.  You might be able to use VBA in these as well to pretty things up, but I am not sure.

OwnerDisplayName: jmcd

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: AlexCuse


问:
GC over limit exceeded when using Spring integration executor channel
```<code>   I have got the below exception , I suspect heap memory is full so GC exception was thrown . Kindly explain if any other perspective for the below application solution

  2017:06:07 21:18:36.275 [loginputtaskexecutor-7] ERROR o.s.i.handler.LoggingHandler - org.springframework.messaging.MessageHandlingException: nested exception is java.lang.IllegalStateException: Cannot process message
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:96)
    at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:89)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.access$000(UnicastingDispatcher.java:53)
    at org.springframework.integration.dispatcher.UnicastingDispatcher$3.run(UnicastingDispatcher.java:129)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Cannot process message
    at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:333)
    at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:155)
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:93)
    ... 11 more
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded

  **Application flow in detail :**
</code>```

Spring integration application build to listen message from ActiveMQ , after consuming message from ActiveMQ it will be handed over to input channel (Executor channel) which has subscriber as service activator . In Service Activator message is converted to json then stored to Cassandra . @ transaction was mentioned on the Service activator method .

With the above solution , I thought of breaking Message transaction flow by implementing executor channel , after message consumed it will be handed over to executor channel and the transaction ends . after then threads in executor channel would take care of performing parallel write to cassandra.

Is there any better way to write as fast as possible for large volume of data to casandra using java spring integration

答:
If the data sink can't keep up, add a limit to the queue size in the TaskExecutor and use a CallerRunsPolicy or CallerBlocksPolicy when the queue is full.

That will naturally throttle the workload at the rate the sink can deal with.

Body:
   I have got the below exception , I suspect heap memory is full so GC exception was thrown . Kindly explain if any other perspective for the below application solution

  2017:06:07 21:18:36.275 [loginputtaskexecutor-7] ERROR o.s.i.handler.LoggingHandler - org.springframework.messaging.MessageHandlingException: nested exception is java.lang.IllegalStateException: Cannot process message
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:96)
    at org.springframework.integration.handler.ServiceActivatingHandler.handleRequestMessage(ServiceActivatingHandler.java:89)
    at org.springframework.integration.handler.AbstractReplyProducingMessageHandler.handleMessageInternal(AbstractReplyProducingMessageHandler.java:109)
    at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)
    at org.springframework.integration.dispatcher.AbstractDispatcher.tryOptimizedDispatch(AbstractDispatcher.java:116)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.doDispatch(UnicastingDispatcher.java:148)
    at org.springframework.integration.dispatcher.UnicastingDispatcher.access$000(UnicastingDispatcher.java:53)
    at org.springframework.integration.dispatcher.UnicastingDispatcher$3.run(UnicastingDispatcher.java:129)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Cannot process message
    at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:333)
    at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:155)
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:93)
    ... 11 more
Caused by: java.lang.OutOfMemoryError: GC overhead limit exceeded

  **Application flow in detail :**

Spring integration application build to listen message from ActiveMQ , after consuming message from ActiveMQ it will be handed over to input channel (Executor channel) which has subscriber as service activator . In Service Activator message is converted to json then stored to Cassandra . @ transaction was mentioned on the Service activator method .

With the above solution , I thought of breaking Message transaction flow by implementing executor channel , after message consumed it will be handed over to executor channel and the transaction ends . after then threads in executor channel would take care of performing parallel write to cassandra.

Is there any better way to write as fast as possible for large volume of data to casandra using java spring integration


问:
How to call a function, but not receive a response until there is a value?
I have a function that queries the DOM and returns an array of data attributes.

```<code>var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}
</code>```

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?

答:
I believe that MutationObserver is exactly wat you need here.
Please read this: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Body:
I have a function that queries the DOM and returns an array of data attributes.

var getUIDs = function () {

    $list = $('.foo');

    if ( $list.length ) {

        // loop through all the .foos and build an array
        return fooArray;

    } else {

        setTimeout(function(){
            getUIDs()
        }, 500);

    }

}

This function can sometimes be called prior to .foo being present in the DOM. That's why if I check every half second or so, within a few seconds the array will exist and I could send it back.

My question is, is there an established pattern I should follow that allows a function to be called, but will not receive a return value until there is one?


问:
How to get the content of a
 tag with no id or class, based on the previous element using BeautifulSoup?
I am using BeautifulSoup to scrapping a web page.

I am trying to get the content of a p tag that have no id or class but it is preceded by a span with a distinct class:

```<code><p> uninteresting content here...</p>
<span class="description">DESCRIPTION:</span>
<p>Hi ! This is the content which I am interested in.</p>
<p> another uninteresting content to be discarded.</p>
</code>```

So, How do I get that p content, based on the span class="description" that comes before it ?

thanks in advance,

答:
```<code>soup.find("span", attrs={"class": "description"}).find_next('p')
</code>```

Title: How to get the content of a <p> tag with no id or class, based on the previous element using BeautifulSoup?

Body:
I am using BeautifulSoup to scrapping a web page.

I am trying to get the content of a p tag that have no id or class but it is preceded by a span with a distinct class:

 uninteresting content here...

DESCRIPTION:

Hi ! This is the content which I am interested in.

 another uninteresting content to be discarded.

So, How do I get that p content, based on the span class="description" that comes before it ?

thanks in advance,


问:
Examples - tag.first and tag.last
I can't seem to find any examples. </p>

```<code>text = Text(root)
text.tag_add("here", "tag.first", "tag.last")
text.tag_config("here", background="black", foreground="green")
</code>```

答:
tag.first and tag.last represent the first and last character of text with the given tag.

The following block of code adds the tag "here" to a range of text (line 13 character 25, to line 13 character 35), and then uses "here.first" to move the cursor to the first character that has the tag "here" (ie: line 13, character 25).

```<code>import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.pack(fill="both", expand=True)
text.tag_configure("here", background="black", foreground="green")

with open(__file__, "r") as f:
    text.insert("1.0", f.read())

text.tag_add("here", "13.25", "13.35")
text.mark_set("insert", "here.first")

root.mainloop()
</code>```

Title: Examples - tag.first and tag.last

Body:
I can't seem to find any examples.

text = Text(root)
text.tag_add("here", "tag.first", "tag.last")
text.tag_config("here", background="black", foreground="green")

Body:
tag.first and tag.last represent the first and last character of text with the given tag.

The following block of code adds the tag "here" to a range of text (line 13 character 25, to line 13 character 35), and then uses "here.first" to move the cursor to the first character that has the tag "here" (ie: line 13, character 25).

import tkinter as tk

root = tk.Tk()
text = tk.Text(root)
text.pack(fill="both", expand=True)
text.tag_configure("here", background="black", foreground="green")

with open(__file__, "r") as f:
    text.insert("1.0", f.read())

text.tag_add("here", "13.25", "13.35")
text.mark_set("insert", "here.first")

root.mainloop()


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答: Elegant way of showing what they(Customers) did bad.</p>


问:
Pyspark - create new column from operations of DataFrame columns gives error "Column is not iterable"
I have a PySpark DataFrame and I have tried many examples showing how to create a new column based on operations with existing columns, but none of them seem to work.

So I have t̶w̶o̶ one questions:

1- Why doesn't this code work?

```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
import pyspark.sql.functions as F

sc = SparkContext()
sqlContext = SQLContext(sc)

a = sqlContext.createDataFrame([(5, 5, 3)], ['A', 'B', 'C'])
a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show()
</code>```

I get the error:
TypeError: Column is not iterable

EDIT: Answer 1

I found out how to make this work. I have to use the native Python sum function. a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show(). It works, but I have no idea why.

2- If there is a way to make this sum work, how can I write a udf function to do this (and add the result to a new column of a DataFrame)?

```<code>import numpy as np
def my_dif(row):
    d = np.diff(row) # creates an array of differences element by element
    return d.mean() # returns the mean of the array
</code>```

I am using Python 3.6.1 and Spark 2.1.1.

Thank you!

Body:
I have a PySpark DataFrame and I have tried many examples showing how to create a new column based on operations with existing columns, but none of them seem to work.

So I have t̶w̶o̶ one questions:

1- Why doesn't this code work?

from pyspark import SparkContext, SparkConf
from pyspark.sql import SQLContext
import pyspark.sql.functions as F

sc = SparkContext()
sqlContext = SQLContext(sc)

a = sqlContext.createDataFrame([(5, 5, 3)], ['A', 'B', 'C'])
a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show()

I get the error:
TypeError: Column is not iterable

EDIT: Answer 1

I found out how to make this work. I have to use the native Python sum function. a.withColumn('my_sum', F.sum(a[col] for col in a.columns)).show(). It works, but I have no idea why.

2- If there is a way to make this sum work, how can I write a udf function to do this (and add the result to a new column of a DataFrame)?

import numpy as np
def my_dif(row):
    d = np.diff(row) # creates an array of differences element by element
    return d.mean() # returns the mean of the array

I am using Python 3.6.1 and Spark 2.1.1.

Thank you!

Body:
a = sqlContext.createDataFrame([(5, 5, 3)], ['A', 'B', 'C'])
a = a.withColumn('my_sum', F.UserDefinedFunction(lambda *args: sum(args), IntegerType())(*a.columns))
a.show()

+---+---+---+------+
|  A|  B|  C|my_sum|
+---+---+---+------+
|  5|  5|  3|    13|
+---+---+---+------+


问:
What is the difference between an .appxupload and an .appxbundle and which one should I upload to the store?
I have just build my application for UWP for the Windows store.

Visual Studio had produced a collection of files. Some of which are:

```<code>MyApp.appxupload
MyApp.appxBundle
</code>```

What is the difference between these two files? and which one should I upload to the store?

答:
What is the difference between these two files? and which one should I upload to the store?

Both of them can be uploaded to the Store, which is up to your need. See the Package section of submission in Dashboard:

.xap can be Windows Phone 8/8.1 Silverlight package format.

.appx can also be accepted by Dev Center, but for Windows universal app, it won't collect crash analytics experience from Dev Center if you do not include pdb symbol files. The .appxupload file is created as part of the Visual Studio packaging process and contains two other files: .appx and .appxsym. The .appxsym file is a compressed .pdb file containing public symbols of your app used for crash analytics in the Windows Dev Center. That's why we should upload .appxupload file for Store submission.

The .appxbundle file can reduce the size of the app that users download, which is very meaningful to the package containing language-specific assets, varying image-scale assets, or resources that apply to specific versions of Microsoft DirectX. Users just need to download the part of your package resource that works on their device.

Besides, with appxbundle, you can directly generate a package for x86, x64 and arm architecture so you don't need to create them one by one. Please note that once you upload .appxbundle as your Store package you're not able to go back to non-appxbundle in your future submission.

For more details, please read related article in Packaging apps.

Body:
I have just build my application for UWP for the Windows store.

Visual Studio had produced a collection of files. Some of which are:

MyApp.appxupload
MyApp.appxBundle

What is the difference between these two files? and which one should I upload to the store?


问:
golang sync.WaitGroup never completes
I have the below code that fetches a list of URL's and then conditionally downloads a file and saves it to the filesystem. The files are fetched concurrently and the main goroutine waits for all the files to be fetched. But, the program never exits (and there are no errors) after completing all the requests.

What I think is happening is that somehow the amount of go routines in the WaitGroup is either incremented by too many to begin with (via Add) or not decremented by enough (a Done call is not happening).

Is there something I am obviously doing wrong? How would I inspect how many go routines are presently in the WaitGroup so I can better debug what's happening?

```<code>package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
    "strings"
    "sync"
)

func main() {
    links := parseLinks()

    var wg sync.WaitGroup

    for _, url := range links {
        if isExcelDocument(url) {
            wg.Add(1)
            go downloadFromURL(url, wg)
        } else {
            fmt.Printf("Skipping: %v \n", url)
        }
    }
    wg.Wait()
}

func downloadFromURL(url string, wg sync.WaitGroup) error {
    tokens := strings.Split(url, "/")
    fileName := tokens[len(tokens)-1]
    fmt.Printf("Downloading %v to %v \n", url, fileName)

    content, err := os.Create("temp_docs/" + fileName)
    if err != nil {
        fmt.Printf("Error while creating %v because of %v", fileName, err)
        return err
    }

    resp, err := http.Get(url)
    if err != nil {
        fmt.Printf("Could not fetch %v because %v", url, err)
        return err
    }
    defer resp.Body.Close()

    _, err = io.Copy(content, resp.Body)
    if err != nil {
        fmt.Printf("Error while saving %v from %v", fileName, url)
        return err
    }

    fmt.Printf("Download complete for %v \n", fileName)

    defer wg.Done()
    return nil
}

func isExcelDocument(url string) bool {
    return strings.HasSuffix(url, ".xlsx") || strings.HasSuffix(url, ".xls")
}

func parseLinks() []string {
    linksData, err := ioutil.ReadFile("links.txt")
    if err != nil {
        fmt.Printf("Trouble reading file: %v", err)
    }

    links := strings.Split(string(linksData), ", ")

    return links
}
</code>```

答:
As @Bartosz mentioned, you will need to pass a reference to your WaitGroup object. He did a great job discussing the importance of defer ws.Done()

I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So your example could be solved this way:

```<code>func main() {
    links := parseLinks()

    functions := []func(){}
    for _, url := range links {
        if isExcelDocument(url) {
            function := func(url string){
                return func() { downloadFromURL(url) }
            }(url)

            functions = append(functions, function)
        } else {
            fmt.Printf("Skipping: %v \n", url)
        }
    }

    Parallelize(functions...)
}

func downloadFromURL(url string) {
    ...
}
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Title: golang sync.WaitGroup never completes

Body:
I have the below code that fetches a list of URL's and then conditionally downloads a file and saves it to the filesystem. The files are fetched concurrently and the main goroutine waits for all the files to be fetched. But, the program never exits (and there are no errors) after completing all the requests.

What I think is happening is that somehow the amount of go routines in the WaitGroup is either incremented by too many to begin with (via Add) or not decremented by enough (a Done call is not happening).

Is there something I am obviously doing wrong? How would I inspect how many go routines are presently in the WaitGroup so I can better debug what's happening?

package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "os"
    "strings"
    "sync"
)

func main() {
    links := parseLinks()

    var wg sync.WaitGroup

    for _, url := range links {
        if isExcelDocument(url) {
            wg.Add(1)
            go downloadFromURL(url, wg)
        } else {
            fmt.Printf("Skipping: %v \n", url)
        }
    }
    wg.Wait()
}

func downloadFromURL(url string, wg sync.WaitGroup) error {
    tokens := strings.Split(url, "/")
    fileName := tokens[len(tokens)-1]
    fmt.Printf("Downloading %v to %v \n", url, fileName)

    content, err := os.Create("temp_docs/" + fileName)
    if err != nil {
        fmt.Printf("Error while creating %v because of %v", fileName, err)
        return err
    }

    resp, err := http.Get(url)
    if err != nil {
        fmt.Printf("Could not fetch %v because %v", url, err)
        return err
    }
    defer resp.Body.Close()

    _, err = io.Copy(content, resp.Body)
    if err != nil {
        fmt.Printf("Error while saving %v from %v", fileName, url)
        return err
    }

    fmt.Printf("Download complete for %v \n", fileName)

    defer wg.Done()
    return nil
}

func isExcelDocument(url string) bool {
    return strings.HasSuffix(url, ".xlsx") || strings.HasSuffix(url, ".xls")
}

func parseLinks() []string {
    linksData, err := ioutil.ReadFile("links.txt")
    if err != nil {
        fmt.Printf("Trouble reading file: %v", err)
    }

    links := strings.Split(string(linksData), ", ")

    return links
}

Body:
As @Bartosz mentioned, you will need to pass a reference to your WaitGroup object. He did a great job discussing the importance of defer ws.Done()

I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So your example could be solved this way:

func main() {
    links := parseLinks()

    functions := []func(){}
    for _, url := range links {
        if isExcelDocument(url) {
            function := func(url string){
                return func() { downloadFromURL(url) }
            }(url)

            functions = append(functions, function)
        } else {
            fmt.Printf("Skipping: %v \n", url)
        }
    }

    Parallelize(functions...)
}

func downloadFromURL(url string) {
    ...
}

If you would like to use it, you can find it here https://github.com/shomali11/util


问:
Assignment 3 in Procedural Programming
I'm doing procedural programming and for my final assignment I have to create an application that will allow the user to do the following:

Allow the user to enter the customer’s details: name, postcode and loyalty card details

Check if the card has expired

Check the loyalty card number is valid by:

Allowing the user to enter the 8 digits shown on the front of the card

Removing the 8th digit and storing it as ‘check_digit’

Reversing the numbers

Multiplying the 1st, 3rd, 5th and 7th digits by 2

If the result of the multiplication is greater than 9 then subtract 9 from the result

Adding together the resulting 7 digits

Checking if the sum of the added digits plus the ‘check_digit’ is divisible by 10

Output whether the loyalty card is valid or not

Output customer and loyalty card details.

But, how do I go about removing the 'last digit' then storing it as a check_digit?  Sorry if this is vague, this is copied directly from my assignment brief.

答:
To get the last digit, you have to divide the number by 10 and get the remainder.

For example, to get the last digit of 123, you can do 123 % 10 which results to 3.

To remove the last digit, you have to divide the number by 10 and discard the remainder.

For example, to remove the last digit of 123, you can do 123 // 10 which results to 12.

Title: Assignment 3 in Procedural Programming


问:
TypeScript interface with XOR, {bar:string} xor {can:number}
How do I say that I want an interface to be one or the other, but not both or neither?</p>

```<code>interface IFoo {
    bar: string /*^XOR^*/ can: number;
}
</code>```

答:
try this:</p>

```<code>type Foo = {
    bar?: void;
    foo: string;
}

type Bar = {
    foo?: void;
    bar: number;
}

type FooBar = Foo | Bar;

// Error: Type 'string' is not assignable to type 'void'
let foobar: FooBar = {
    foo: "1",
    bar: 1
}

// no errors
let foo = {
    foo: "1"
}
</code>```

Body:
How do I say that I want an interface to be one or the other, but not both or neither?

interface IFoo {
    bar: string /*^XOR^*/ can: number;
}

Body:
try this:

type Foo = {
    bar?: void;
    foo: string;
}

type Bar = {
    foo?: void;
    bar: number;
}

type FooBar = Foo | Bar;

// Error: Type 'string' is not assignable to type 'void'
let foobar: FooBar = {
    foo: "1",
    bar: 1
}

// no errors
let foo = {
    foo: "1"
}


问:
How to use a proxy with google cloud libraries
My code is in an environment that has egress restrictions therefore I need to go through a proxy in order to connect to the outside world. Does google cloud libraries have the ability to pass in a proxy and connect via that?</p>

答:
Google Cloud Client libraries do not offer a built in proxy support. You will have to configure a system proxy or environment specific proxy.

For example, if you're running a JVM you can configure the proxy settings as described here.

Golang also supports something similar.


答:
You can get "one but not the other" with union and optional void type:

```<code>type IFoo = {bar: string; can?: void} | {bar?:void; can: number};
</code>```

However, you have to use --strictNullChecks to prevent having neither.

Title: TypeScript interface with XOR, {bar:string} xor {can:number}

Body:
You can get "one but not the other" with union and optional void type:

type IFoo = {bar: string; can?: void} | {bar?:void; can: number};

However, you have to use --strictNullChecks to prevent having neither.


问:
Why is the GitHub authorization button in the OAuth flow grayed out?
I am building an Android app that signs in users to GitHub using OAuth. I followed the instructions here to do so. As the first part of the process, I sent users to the URL

```<code>https://github.com/login/oauth/authorize?scope=repo&client_id=MY_CLIENT_ID
</code>```

However, when I sign in on my Android device, the Authorize xxxx button appears to be greyed out and I can't click it. Does anyone have a clue why this is? (Large screenshot below)

I think the button may not have been greyed out before, the first time I ran the app and signed in. However, I can't tell for sure because I was in a rush.

答:
So, I pasted the link into Chrome on my computer and the OAuth process worked fine. I noticed the button was greyed out at first, but then became bright green. This got me wondering: was JavaScript enabled by default in the Android WebView? Sure enough, it wasn't. I found this answer which details how to enable JS. This was the key line that got everything working:</p>

```<code>webView.getSettings().setJavaScriptEnabled(true);
</code>```

Body:
I am building an Android app that signs in users to GitHub using OAuth. I followed the instructions here to do so. As the first part of the process, I sent users to the URL

https://github.com/login/oauth/authorize?scope=repo&client_id=MY_CLIENT_ID

However, when I sign in on my Android device, the Authorize xxxx button appears to be greyed out and I can't click it. Does anyone have a clue why this is? (Large screenshot below)

I think the button may not have been greyed out before, the first time I ran the app and signed in. However, I can't tell for sure because I was in a rush.

Body:
So, I pasted the link into Chrome on my computer and the OAuth process worked fine. I noticed the button was greyed out at first, but then became bright green. This got me wondering: was JavaScript enabled by default in the Android WebView? Sure enough, it wasn't. I found this answer which details how to enable JS. This was the key line that got everything working:

webView.getSettings().setJavaScriptEnabled(true);


问:
Cancel file download from another thread at any time
I'm using HttpURLConnection to download a file. Can I cancel the download from another thread? If not, what method for file download should I use?</p>

答:
Did you try asynchronously closing connection's InputStream from another thread? Not sure if it's the right way, but it works with sockets so if Java uses similar design patter here it may work too. But even if it works, better look for a confirmation from some reliable source, though, as it may seem to work but fail sometimes as it often happens with multithreaded programming.

EDIT

Apparently, it doesn't work.


问:
Failing to open csv file
My current python script is like this:

```<code>import csv

with open ('2017_IL_sales.csv','r') as infile:
    reader=csv.reader(infile)
    with open('2017_IL_sales_report.csv') as outfile:
        writer=csv.writer(outfile)
        dict_report={rows[1]:rows[2] for rows in reader}

print dict_report
</code>```

In brief, I want to open a csv file called 2017_IL_sales then create a dictionary for two columns inside. But with whatever reason, everytime I run the code via IDLE it told me this IOError: [Errno 2] No such file or directory: '2017_IL_sales.csv'. Anyone knows the reason?

答:
Is IDLE's working directory that folder?

Run this in IDLE and see what you get:

```<code>import os
os.getcwd()
</code>```

Title: Failing to open csv file

Body:
My current python script is like this:

import csv

with open ('2017_IL_sales.csv','r') as infile:
    reader=csv.reader(infile)
    with open('2017_IL_sales_report.csv') as outfile:
        writer=csv.writer(outfile)
        dict_report={rows[1]:rows[2] for rows in reader}

print dict_report

In brief, I want to open a csv file called 2017_IL_sales then create a dictionary for two columns inside. But with whatever reason, everytime I run the code via IDLE it told me this IOError: [Errno 2] No such file or directory: '2017_IL_sales.csv'. Anyone knows the reason?

Body:
Is IDLE's working directory that folder?

Run this in IDLE and see what you get:

import os
os.getcwd()


问:
How to prevent text selection from obstructing onMouseMove event?
I'm implementing a "resize handle" to change the width of my left navigation panel. It is a div that receives an onMouseDown() event, calculates the necessary widths and applies them to the right elements in the subsequent calls to onMouseMove(). But I'm having some problems.

1) The article element, to the right of the navigation panel and handle, does not activate the onMouseUp() if I release the mouse there. Is this because the onMouseDown() was activated in other element?

2) If I move the mouse fast to the right, I can't prevent the text in the article from being selected, even calling methods like preventDefault() and stopPropagation().

3) Even if there's no text in the article, the resizing only works if I move the mouse very slowly. If the mouse moves fast over the article element, the resize stops, unless I release the mouse button - in this case the resize goes smoothly (suggesting it was the text-selecting that was stopping the resize, even with no text at all). But if I release the mouse button, the resize should stop (see point 1).

I've seen some solutions using CSS user-select: none, but this would prevent any text from being selected inside article, which is obviously an overkill.

So, how can I make the resizing smooth, without selecting any text, when I move the mouse over any element in my document? (After pressing the button in the right div, of course.)

That's my HTML:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>CSS Template</title>
</head>
<body>
<header>Header</header>
<main>
    <nav id='nav'>
        <div class='navcont' onmousemove='handMm(event)' onmouseup='handMu(event)'>
            <p>nav 1</p>
            <p>nav 2</p>
        </div>
        <div class='handle' onmousedown='handMd(event)' onmousemove='handMm(event)' onmouseup='handMu(event)'>
        </div>
    </nav>
    <article id='article' onmousemove='handMm(event)' onmouseup='handMu(event)'>
    </article>
</main>
<footer>Footer</footer>
</body>
</html>
</code>```

That's my CSS:

```<code>html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#CCC;
    width:auto;
    overflow:auto;
    padding:10px;
    flex-grow:1;
}
nav {
    width:300px;
    height:auto;
    overflow: hidden;
    display:flex;
}
.navcont {
    background:#8C8;
    width:auto;
    flex-grow:1;
}
.handle {
    background:#333;
    right:0px;
    width:30px;
    cursor:col-resize;
}
footer {
    text-align:center;
}
</code>```

That's my Javascript:

```<code>var mx,px,moving=false;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
}
function handMm(e) {
    if (moving) {
        e.preventDefault();
        e.stopPropagation();
        e.cancelBubble = true;
        e.returnValue = false;
        var diff = e.pageX - mx;
        document.getElementById('nav').style.width = (px + diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    moving = false;
}
</code>```

And here is a working example: https://jsfiddle.net/45h7vq7u/

Another example, including Ryan Tsui's answer: https://jsfiddle.net/v1cmk2f6/1/ (the text-selection is gone, but the div still won't move smoothly, but only when moving fast to the right).

答:
After analyzing how this was solved somewhere else, I came to the following changes.

HTML - only one event handler needed:

```<code>...
<main>
    <nav id='nav'>
        <div class='navcont'>
            <p>nav 1</p>
            <p>nav 2</p>
        </div>
        <div class='handle' onmousedown='handMd(event)'>
        </div>
    </nav>
    <article id='article'>
    </article>
</main>
...
</code>```

Javascript - attach and detach the onmousemove event handler is way better than calling onmousemove every time the mouse moves (to only then test if the mouse button has been pressed). Also, the event is now attached to the document, not to each div on screen:

```<code>var mx,px,minW = 200;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    document.addEventListener('mousemove',handMm);
    document.addEventListener('mouseup',handMu);
    document.getElementById('article').classList.toggle('moving',true);
    document.getElementById('nav').classList.toggle('moving',true);
}
function handMm(e) {
    var diff = e.pageX - mx;
    if (px+diff >= minW && window.innerWidth-px-diff >= minW) {
        document.getElementById('nav').style.width = (px+diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    document.removeEventListener('mousemove',handMm);
    document.removeEventListener('mouseup',handMu);
    document.getElementById('article').classList.toggle('moving',false);
    document.getElementById('nav').classList.toggle('moving',false);
}
</code>```

CSS - thanks to Ryan Tsui's answer, I eliminated the unwanted text selection while resizing:

```<code>.moving {
    user-select:none;
    -moz-user-select:none;
    -webkit-user-select:none;
    -ms-user-select:none;
}
</code>```

Body:
I'm implementing a "resize handle" to change the width of my left navigation panel. It is a div that receives an onMouseDown() event, calculates the necessary widths and applies them to the right elements in the subsequent calls to onMouseMove(). But I'm having some problems.

1) The article element, to the right of the navigation panel and handle, does not activate the onMouseUp() if I release the mouse there. Is this because the onMouseDown() was activated in other element?

2) If I move the mouse fast to the right, I can't prevent the text in the article from being selected, even calling methods like preventDefault() and stopPropagation().

3) Even if there's no text in the article, the resizing only works if I move the mouse very slowly. If the mouse moves fast over the article element, the resize stops, unless I release the mouse button - in this case the resize goes smoothly (suggesting it was the text-selecting that was stopping the resize, even with no text at all). But if I release the mouse button, the resize should stop (see point 1).

I've seen some solutions using CSS user-select: none, but this would prevent any text from being selected inside article, which is obviously an overkill.

So, how can I make the resizing smooth, without selecting any text, when I move the mouse over any element in my document? (After pressing the button in the right div, of course.)

That's my HTML:

<!DOCTYPE html>

<meta charset='UTF-8'>
<title>CSS Template</title>

Header

nav 1

nav 2

Footer

That's my CSS:

html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#CCC;
    width:auto;
    overflow:auto;
    padding:10px;
    flex-grow:1;
}
nav {
    width:300px;
    height:auto;
    overflow: hidden;
    display:flex;
}
.navcont {
    background:#8C8;
    width:auto;
    flex-grow:1;
}
.handle {
    background:#333;
    right:0px;
    width:30px;
    cursor:col-resize;
}
footer {
    text-align:center;
}

That's my Javascript:

var mx,px,moving=false;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
}
function handMm(e) {
    if (moving) {
        e.preventDefault();
        e.stopPropagation();
        e.cancelBubble = true;
        e.returnValue = false;
        var diff = e.pageX - mx;
        document.getElementById('nav').style.width = (px + diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    moving = false;
}

And here is a working example: https://jsfiddle.net/45h7vq7u/

Another example, including Ryan Tsui's answer: https://jsfiddle.net/v1cmk2f6/1/ (the text-selection is gone, but the div still won't move smoothly, but only when moving fast to the right).

Body:
After analyzing how this was solved somewhere else, I came to the following changes.

HTML - only one event handler needed:

...
<main>
    <nav id='nav'>
        <div class='navcont'>
            <p>nav 1</p>
            <p>nav 2</p>
        </div>
        <div class='handle' onmousedown='handMd(event)'>
        </div>
    </nav>
    <article id='article'>
    </article>
</main>
...

Javascript - attach and detach the onmousemove event handler is way better than calling onmousemove every time the mouse moves (to only then test if the mouse button has been pressed). Also, the event is now attached to the document, not to each div on screen:

var mx,px,minW = 200;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    document.addEventListener('mousemove',handMm);
    document.addEventListener('mouseup',handMu);
    document.getElementById('article').classList.toggle('moving',true);
    document.getElementById('nav').classList.toggle('moving',true);
}
function handMm(e) {
    var diff = e.pageX - mx;
    if (px+diff >= minW && window.innerWidth-px-diff >= minW) {
        document.getElementById('nav').style.width = (px+diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    document.removeEventListener('mousemove',handMm);
    document.removeEventListener('mouseup',handMu);
    document.getElementById('article').classList.toggle('moving',false);
    document.getElementById('nav').classList.toggle('moving',false);
}

CSS - thanks to Ryan Tsui's answer, I eliminated the unwanted text selection while resizing:

.moving {
    user-select:none;
    -moz-user-select:none;
    -webkit-user-select:none;
    -ms-user-select:none;
}


问:
Error when using array.sort
I have a variable that has a list of song titles:

```<code>var songTitles = ["Song Title 1", "Song Title 2", "Song Title 3"]
</code>```

I also have a variable for the author of the songs

```<code>var songAuthors = ["Song Author 1", "Song Author 2", "Song Author 3"]
</code>```

Whenever the view loads, I sort "songTitles" alphabetically like this

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    songTitles.sorted(by: { $0 < $1 })
    songTitles.sort()
}
</code>```

Last but not least, I have a table view with a subtitle cell. songTitle is equal to the title of the cell. songAuthor is equal to the subtitle.
Sorting the titles works out great, but the songAuthor does not match the songTitle. Like say that the song is Hello and the Author is AHAH and there is a song named Bye and the author Lala.

The tableview will display:

```<code>SONG TITLE - Bye  SONG AUTHOR - AHAH
SONG TITLE - Hello SONG AUTHOr - LALA
</code>```

Basically, the corresponding author does not match the correct song. How do I fix this?

答:
You fix this by not using parallel arrays:

Make a class Song that combines both a song title and its author

Make an array of Song objects

Sort the array on the field that you want

Now you can use Song objects in your table view, displaying its properties as needed.

```<code>class Song : CustomStringConvertible {
    let title:String
    let author:String
    init(title:String, author:String) {
        self.title = title
        self.author = author
    }
    var description : String {
        return "\(title) \(author)"
    }
}

var songs = [
    Song(title: "Song Title 3", author: "Song Author 3")
,   Song(title: "Song Title 2", author: "Song Author 2")
,   Song(title: "Song Title 1", author: "Song Author 1")
]

songs.sort() {$0.author < $1.author}

print(songs)
</code>```

Title: Error when using array.sort

Body:
I have a variable that has a list of song titles:

var songTitles = ["Song Title 1", "Song Title 2", "Song Title 3"]

I also have a variable for the author of the songs

var songAuthors = ["Song Author 1", "Song Author 2", "Song Author 3"]

Whenever the view loads, I sort "songTitles" alphabetically like this

override func viewDidLoad() {
    super.viewDidLoad()
    songTitles.sorted(by: { $0 < $1 })
    songTitles.sort()
}

Last but not least, I have a table view with a subtitle cell. songTitle is equal to the title of the cell. songAuthor is equal to the subtitle.
Sorting the titles works out great, but the songAuthor does not match the songTitle. Like say that the song is Hello and the Author is AHAH and there is a song named Bye and the author Lala.

The tableview will display:

SONG TITLE - Bye  SONG AUTHOR - AHAH
SONG TITLE - Hello SONG AUTHOr - LALA

Basically, the corresponding author does not match the correct song. How do I fix this?

Body:
You fix this by not using parallel arrays:

Make a class Song that combines both a song title and its author

Make an array of Song objects

Sort the array on the field that you want

Now you can use Song objects in your table view, displaying its properties as needed.

class Song : CustomStringConvertible {
    let title:String
    let author:String
    init(title:String, author:String) {
        self.title = title
        self.author = author
    }
    var description : String {
        return "\(title) \(author)"
    }
}

var songs = [
    Song(title: "Song Title 3", author: "Song Author 3")
,   Song(title: "Song Title 2", author: "Song Author 2")
,   Song(title: "Song Title 1", author: "Song Author 1")
]

songs.sort() {$0.author < $1.author}

print(songs)


问:
Outlook VBA find last Row in Excel Worksheet
I'm writing a function in Outlook VBA that involves reading content from an excel workbook.

The part I'm struggling with is finding the last row in a column (column A in this example). While the 1st line in the highlighted block correctly displays the content of A1 cell in given worksheet, the second line gives a Error "424" - object required.

Any suggestions into the problem would be greatly appreciated.

```<code>Public Function openExcel()

    Dim xlApp As Object
    Dim sourceWorkBook
    Dim sourceWorkSheet

    Dim cellVal As String
    Dim lastRow As Long

    Set xlApp = CreateObject("Excel.Application")

    With xlApp
        .Visible = True
        .EnableEvents = True
    End With

    Set sourceWorkBook = xlApp.Workbooks.Open("C:\SAMPLEPATH\Template.xlsx")
    Set sourceWorkSheet = sourceWorkBook.Worksheets("Sheet1")
    sourceWorkBook.Activate

    With Activesheet
</code>```

```<code>        cellVal = sourceWorkSheet.Cells(1, 1)
        lastRow = sourceWorkSheet.Cells(.Rows.Count, "A").End(xlUp).Row
</code>```

```<code>    End With

    sourceWorkBook.Save
    sourceWorkBook.Close
    xlApp.Quit

End Function
</code>```

答:
If you want to have the ability to use Excel constants within your code, you will need to either

a) Include a reference to a Microsoft Excel Object Library, or

b) Create your own constant, e.g.

```<code>End(-4162)
</code>```

or

```<code>Const xlUp As Long = -4162
...
... End(xlUp)
</code>```

Body:
I'm writing a function in Outlook VBA that involves reading content from an excel workbook.

The part I'm struggling with is finding the last row in a column (column A in this example). While the 1st line in the highlighted block correctly displays the content of A1 cell in given worksheet, the second line gives a Error "424" - object required.

Any suggestions into the problem would be greatly appreciated.

Public Function openExcel()

    Dim xlApp As Object
    Dim sourceWorkBook
    Dim sourceWorkSheet

    Dim cellVal As String
    Dim lastRow As Long

    Set xlApp = CreateObject("Excel.Application")

    With xlApp
        .Visible = True
        .EnableEvents = True
    End With

    Set sourceWorkBook = xlApp.Workbooks.Open("C:\SAMPLEPATH\Template.xlsx")
    Set sourceWorkSheet = sourceWorkBook.Worksheets("Sheet1")
    sourceWorkBook.Activate

    With Activesheet

        cellVal = sourceWorkSheet.Cells(1, 1)
        lastRow = sourceWorkSheet.Cells(.Rows.Count, "A").End(xlUp).Row

    End With

    sourceWorkBook.Save
    sourceWorkBook.Close
    xlApp.Quit

End Function

Body:
If you want to have the ability to use Excel constants within your code, you will need to either

a) Include a reference to a Microsoft Excel Object Library, or

b) Create your own constant, e.g.

End(-4162)

or

Const xlUp As Long = -4162
...
... End(xlUp)


问:
JavaScript file inclusion. Should I not link in ?
I'm watching Douglas Crockfords "Theory of the DOM" and he mentioned that the location of my script tags can greatly affect the load time of my applications.  Furthermore, he asserts that a script tag should be included as far towards the bottom of the document body as possible.

Is this accurate?

OR

Is this video out of date? (which he actually sites as a reason he didn't lecture on the DOM sooner).

答: I too have heard that JavaScript should be included at the end of the page to "hopefully" ensure the DOM has loaded. I believe I read this in the Yahoo documentation a while back.</p>

Title: JavaScript file inclusion. Should I not link in <head>?


问:
Create apex rollup triggers
I am looking to replace the rollups in my Salesforce rollup helper with apex versions, and run those instead.  I am trying to transform the following into Apex code.  Please let me know if you have any ideas.

答:
This is a very straight forward use case for Apex.  You need to create a Trigger on the child object that will do the math and update the parent object.
Best Practices dictate that the Trigger should actually call a method in a class, but here is an abbreviated version of the solution:</p>

```<code>trigger myTrigger on Collateral__c (after insert, after update){
Map<Id, Deal__c> dealMap = new Map<Id, Deal__c>();
for ( Collateral__c c : Trigger.new ){
    dealMap.put( c.Deal__c, new Deal__c( Id=c.Deal__c, Total_Lendable_Collateral__c=0) );
}
for ( AggregateResult ar : [
   SELECT Deal__c parentId, SUM(Lendable_Value__c) s
   FROM Collateral__c
   WHERE Deal__c IN :dealMap.keySet()
]){
    Id i = (Id)ar.get('parentId');
    dealMap.put( i, new Deal__c(Id=i,Total_Lendable_Collateral__c=(Decimal)ar.get('s')));
}
update dealMap.values();
}
</code>```

Title: Create apex rollup triggers

Body:
This is a very straight forward use case for Apex.  You need to create a Trigger on the child object that will do the math and update the parent object.
Best Practices dictate that the Trigger should actually call a method in a class, but here is an abbreviated version of the solution:

trigger myTrigger on Collateral__c (after insert, after update){
Map<Id, Deal__c> dealMap = new Map<Id, Deal__c>();
for ( Collateral__c c : Trigger.new ){
    dealMap.put( c.Deal__c, new Deal__c( Id=c.Deal__c, Total_Lendable_Collateral__c=0) );
}
for ( AggregateResult ar : [
   SELECT Deal__c parentId, SUM(Lendable_Value__c) s
   FROM Collateral__c
   WHERE Deal__c IN :dealMap.keySet()
]){
    Id i = (Id)ar.get('parentId');
    dealMap.put( i, new Deal__c(Id=i,Total_Lendable_Collateral__c=(Decimal)ar.get('s')));
}
update dealMap.values();
}


问:
VBA to copy sheets from all files in folder and copy it to master
I have a folder full of multiple excel files and all of the files have a specific sheet that i need to copy into my master.

I need macro to open all files in that folder one by one and copy the specific sheet to the master file using the source file name as sheet name in the master workbook. Excel 2013.

I tried searching online and have the following code:

```<code>Option Explicit

Sub test()

Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xls")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    'Your copy/paste code here (((((need help here please))))))))
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation

End Sub
</code>```

EDIT:

So i manage to get to the below however its still not working properly. It doesn't rename the sheet to the source filename. Can someone please help?

Option Explicit

Sub test()

```<code>Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xlsx")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation
</code>```

End Sub

答:
You could simply copy your sheet in the new workbook, following this code:

Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)

And then, rename the sheet to fit your means.

Body:
I have a folder full of multiple excel files and all of the files have a specific sheet that i need to copy into my master.

I need macro to open all files in that folder one by one and copy the specific sheet to the master file using the source file name as sheet name in the master workbook. Excel 2013.

I tried searching online and have the following code:

Option Explicit

Sub test()

Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xls")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    'Your copy/paste code here (((((need help here please))))))))
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation

End Sub

EDIT:

So i manage to get to the below however its still not working properly. It doesn't rename the sheet to the source filename. Can someone please help?

Option Explicit

Sub test()

Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xlsx")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation

End Sub


问:
SignalR js client wrong Server port
I'm starting with signalr but got some trouble, my test server run at http://localhost:22660/ and my web run at
http://localhost:61963/.I got this error when connect from client to server:

GET http://localhost:61963/signalr/negotiate?clientProtocol=1.4&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1496809403215 404 (Not Found)

I already config:  $.connection.hub.url = 'http://localhost:22660/signalr'; but not work, this my js code:

```<code>var connection = $.hubConnection();
$.connection.hub.url = 'http://localhost:22660/signalr';
var chatHub = connection.createHubProxy('ChatHub');
connection.start()
    .done(function () { console.log('Now connected, connection ID=' + connection.id); })
    .fail(function () { console.log('Could not connect'); });
</code>```

Server:

```<code>namespace test
{
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {
                EnableJSONP = true
            };
            map.RunSignalR(hubConfiguration);
        });
    }
}
}
namespace SignalRChat
{
public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);
    }
}
}
</code>```

答: I dont sure, but i think because i using different version of signalr (2.1.2 and 2.2.0). Using same version solved my problem.</p>

Title: SignalR js client wrong Server port

Body:
I'm starting with signalr but got some trouble, my test server run at http://localhost:22660/ and my web run at
http://localhost:61963/.I got this error when connect from client to server:

GET http://localhost:61963/signalr/negotiate?clientProtocol=1.4&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1496809403215 404 (Not Found)

I already config:  $.connection.hub.url = 'http://localhost:22660/signalr'; but not work, this my js code:

var connection = $.hubConnection();
$.connection.hub.url = 'http://localhost:22660/signalr';
var chatHub = connection.createHubProxy('ChatHub');
connection.start()
    .done(function () { console.log('Now connected, connection ID=' + connection.id); })
    .fail(function () { console.log('Could not connect'); });

Server:

namespace test
{
public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Map("/signalr", map =>
        {
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration
            {
                EnableJSONP = true
            };
            map.RunSignalR(hubConfiguration);
        });
    }
}
}
namespace SignalRChat
{
public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the addNewMessageToPage method to update clients.
        Clients.All.addNewMessageToPage(name, message);
    }
}
}


问:
php-cs-fixer not working on mac after update
I ran php-cs-fixer self-update on a Mac machine and php-cs-fixer stopped working. No output returned (even with --verbose). Files stay unchanged. I tried reinstalling it (used all possible install options). Tried running with sudo. Still nothing happens. Before update it worked, and now it just does not. Version is 2.3.2 now. Unfortunately, I do not know what version was prior to update. How do I fix my php-cs-fixer?

答: turns out it was a corrupt .php_cs file in the root of the project. I renamed the file and php-cs-fixer started working

ContentLicense: CC BY-SA 4.0


问:
The name "getView" does not exist in the current context
I am building an Android application that uses fragments to display different views. The first tab contains the code below. Unfortunately, I get this error:

The name 'getView' does not exist in the current context

I also tried placing the getView() in onActivityCreated, rather than onViewCreated, but I received the same error. Why is getView not being recognized?

```<code>namespace BottomToolbar
{
    public class FirstFragment : Fragment
    {
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public static FirstFragment NewInstance()
        {
            var fragment = new FirstFragment { Arguments = new Bundle() };
            return fragment;
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.FirstFragment, container, false);
            return view;
        }

        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            Button button = (Button)getView().findViewById(Resource.Id.getWeatherButton);
        }
    }
}
</code>```

答:
Try this:</p>

```<code>Public override void OnViewCreated(View view, Bundle savedInstanceState) {
    Button button = (Button)view.getView().findViewById(Resource.Id.getWeatherButton); }
</code>```

Body:
I am building an Android application that uses fragments to display different views. The first tab contains the code below. Unfortunately, I get this error:

The name 'getView' does not exist in the current context

I also tried placing the getView() in onActivityCreated, rather than onViewCreated, but I received the same error. Why is getView not being recognized?

namespace BottomToolbar
{
    public class FirstFragment : Fragment
    {
        public override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
        }

        public static FirstFragment NewInstance()
        {
            var fragment = new FirstFragment { Arguments = new Bundle() };
            return fragment;
        }

        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View view = inflater.Inflate(Resource.Layout.FirstFragment, container, false);
            return view;
        }

        public override void OnViewCreated(View view, Bundle savedInstanceState)
        {
            Button button = (Button)getView().findViewById(Resource.Id.getWeatherButton);
        }
    }
}

Body:
Try this:

Public override void OnViewCreated(View view, Bundle savedInstanceState) {
    Button button = (Button)view.getView().findViewById(Resource.Id.getWeatherButton); }


答:
Change

```<code>Button button = (Button)getView().findViewById(Resource.Id.getWeatherButton);
</code>```

to

```<code>Button button = View.FindViewById<Button>(Resource.Id.getWeatherButton);
</code>```

Title: The name "getView" does not exist in the current context

Body:
Change

Button button = (Button)getView().findViewById(Resource.Id.getWeatherButton);

to

Button button = View.FindViewById<Button>(Resource.Id.getWeatherButton);


问:
syntax error in python while checking for greater than symbol
I am getting syntax error in the below piece of code in python. Can someone please help me to know where I did the mistake. I am new to python.

```<code>X = lambda cus['id'],cus['maxamt']: \
       df1_test.TXNID[(df1_test['CUSTOMERID'] == cus['id'])\
      &(df1_test['CREDITAMT'] > cus['maxamt'])]
</code>```

Thanks for your responses. Here I have a small array with all distinct values of of CUSTOMERID (1st column) and crresponding maximum CREDITAMT (2nd column). df1_test is a bigger dataframe with many columns in it.

I am trying to find the all the records of the df1_test dataset where the CREDITAMT of the customer is greater that the maximum value of the particular customer (The maximum credit amount and distinct customer id I can get from the smaller array)

Here is what I have tried. But it gives me error that " too many indices for array".

I did not want to use a for loop for the problem as the data is huge.

Can someone please help me.

My actual piece of code is:

```<code>X = sorted(cus_np,key=lambda x: \
         df1_test.TXNID[(df1_test['CUSTOMERID']==x[:,0])\
       &(df1_test['CREDITAMT'] > x[:,1])])
</code>```

Thanks for the respose. Please see the example of my data:

```<code>import pandas as pd

small_distinct_array=pd.DataFrame({'id':[1,2,3,4],'max':[200,500,800,400]})

bigger_all_array=pd.DataFrame({'custid':[1,3,4,3,1,1,2,2,3,4],'amt':[300,400,800,300,900,700,500,700,400,500]})
</code>```

I am trying to get the 'custid' values of the bigger_all_array where the corresponding 'amt' value is greater than the max field of small_distinct_array of the same customerid.

答: & is a bitwise operator. Use and in place of &.

Body:
I am getting syntax error in the below piece of code in python. Can someone please help me to know where I did the mistake. I am new to python.

X = lambda cus['id'],cus['maxamt']: \
       df1_test.TXNID[(df1_test['CUSTOMERID'] == cus['id'])\
      &(df1_test['CREDITAMT'] > cus['maxamt'])]

Thanks for your responses. Here I have a small array with all distinct values of of CUSTOMERID (1st column) and crresponding maximum CREDITAMT (2nd column). df1_test is a bigger dataframe with many columns in it.

I am trying to find the all the records of the df1_test dataset where the CREDITAMT of the customer is greater that the maximum value of the particular customer (The maximum credit amount and distinct customer id I can get from the smaller array)

Here is what I have tried. But it gives me error that " too many indices for array".

I did not want to use a for loop for the problem as the data is huge.

Can someone please help me.

My actual piece of code is:

X = sorted(cus_np,key=lambda x: \
         df1_test.TXNID[(df1_test['CUSTOMERID']==x[:,0])\
       &(df1_test['CREDITAMT'] > x[:,1])])

Thanks for the respose. Please see the example of my data:

import pandas as pd

small_distinct_array=pd.DataFrame({'id':[1,2,3,4],'max':[200,500,800,400]})

bigger_all_array=pd.DataFrame({'custid':[1,3,4,3,1,1,2,2,3,4],'amt':[300,400,800,300,900,700,500,700,400,500]})

I am trying to get the 'custid' values of the bigger_all_array where the corresponding 'amt' value is greater than the max field of small_distinct_array of the same customerid.


答:
Forget fpdf and turn to tfpdf to get the solution.
From latest fpdf document about font. It supports charators as below

cp1250 (Central Europe)

cp1251 (Cyrillic)

cp1252 (Western Europe)

cp1253 (Greek)

cp1254 (Turkish)

cp1255 (Hebrew)

cp1257 (Baltic)

cp1258 (Vietnamese)

cp874 (Thai)

ISO-8859-1 (Western Europe)

ISO-8859-2 (Central Europe)

ISO-8859-4 (Baltic)

ISO-8859-5 (Cyrillic)

ISO-8859-7 (Greek)

ISO-8859-9 (Turkish)

ISO-8859-11 (Thai)

ISO-8859-15 (Western Europe)

ISO-8859-16 (Central Europe)

KOI8-R (Russian)

KOI8-U (Ukrainian).

Title: fpdf greek character shows like chinese

Body:
I am using FPDF with PHP Barcode for creating a PDF-attached mail from form with the below code:

  // -------------------------------------------------- //
  //                      USEFUL
  // -------------------------------------------------- //
    class eFPDF extends FPDF{
    function TextWithRotation($x, $y, $txt, $txt_angle, $font_angle=0)
    {
        $font_angle+=90+$txt_angle;
        $txt_angle*=M_PI/180;
        $font_angle*=M_PI/180;

        $txt_dx=cos($txt_angle);
        $txt_dy=sin($txt_angle);
        $font_dx=cos($font_angle);
        $font_dy=sin($font_angle);

        $s=sprintf('BT %.2F %.2F %.2F %.2F %.2F %.2F Tm (%s) Tj ET',$txt_dx,$txt_dy,$font_dx,$font_dy,$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt));
        if ($this->ColorFlag)
            $s='q '.$this->TextColor.' '.$s.' Q';
        $this->_out($s);
    }
  }

  // -------------------------------------------------- //
  //                  PROPERTIES
  // -------------------------------------------------- //

  $fontSize = 10;
  $marge    = 10;   // between barcode and hri in pixel
  $x        = 430;  // barcode center
  $y        = 660;  // barcode center
  $height   = 25;   // barcode height in 1D ; module size in 2D
  $width    = 1;    // barcode height in 1D ; not use in 2D
  $angle    = 0;   // rotation in degrees

  $code     = ''.$_POST['barcode'].''; // barcode, of course ;)
  $type     = 'code128';
  $black    = '000000'; // color in hexa

  // -------------------------------------------------- //
  //            ALLOCATE FPDF RESSOURCE
  // -------------------------------------------------- //

  $pdf = new eFPDF('P', 'pt');
  $pdf->AddPage();
  $pdf->Image('e-invitation-gr.jpg',0,0,600);

  // -------------------------------------------------- //
  //                      BARCODE
  // -------------------------------------------------- //

  $data = Barcode::fpdf($pdf, $black, $x, $y, $angle, $type, array('code'=>$code), $width, $height);

  // -------------------------------------------------- //
  //                      HRI
  // -------------------------------------------------- //

  $pdf->SetFont('Arial','B',$fontSize);
  $pdf->SetTextColor(0, 0, 0);
  $len = $pdf->GetStringWidth($data['hri']);
  Barcode::rotate(-$len / 2, ($data['height'] / 2) + $fontSize + $marge, $angle, $xt, $yt);
  $pdf->TextWithRotation($x + $xt, $y + $yt, $data['hri'], $angle);
  $pdf->SetY(610);
$pdf->SetX(370);
$txt=''.$_POST['surname'].'  '.$_POST['name'].'';
$field = iconv('UTF-8', 'cp1252', $txt);
  $pdf->Cell(0,0,$field);
 $pdf->SetY(630);
$pdf->SetX(390);
  $pdf->Cell(0,0,''.$_POST['company_name'].'');

// email stuff (change data below)
$company_name =$_REQUEST['company_name'];
$surname =$_REQUEST['surname'];
$mail =$_REQUEST['mail'];
$email =$_REQUEST['mail'];
$name= $_REQUEST['name'];

I have tested all the possible solutions but iconv doesn't work at all and UTF8 decode shows ???? characters.

Is there anyway to make it with FPDF or should I change plugin?


问:
How to set a property as a foreign key in One to one Relationship using code-first Fluent API ?
I have two class of Student and StudentAddress. Where a Student have one Address. Now How can I set the Primary key StudentId of the Student class as the Foreign key of the StudentAddress class using Fluent API. I want a different property such as StudentId will be the Foreign key in StudentAddress. How can i do this? (I am using Entity Framework 6). Here is my classes.</p>

```<code>public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

    //Navigation property
    public virtual StudentAddress StudentAddress { get; set; }
}
public class StudentAddress
{

    public int StudentAddressId { get; set; }
    public int StudentId { get; set; }  //Set this property as a forign key
    public string Address { get; set; }
    //Navigation property
    public virtual Student Student { get; set; }

}
</code>```

答:
you can easily do that , with the following code:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);

    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<Student>()
                .HasOptional(s => s.Address)
                .WithRequired(ad => ad.StudentId);

}
</code>```

Just FYI without Fluent API:

```<code>public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}

public class StudentAddress
{
    [Key, ForeignKey("Student")]
    public int StudentId { get; set; }

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}
</code>```

For additional  info: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

Hope above information was helpful.

Thanks

Karthik

Body:
I have two class of Student and StudentAddress. Where a Student have one Address. Now How can I set the Primary key StudentId of the Student class as the Foreign key of the StudentAddress class using Fluent API. I want a different property such as StudentId will be the Foreign key in StudentAddress. How can i do this? (I am using Entity Framework 6). Here is my classes.

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

    //Navigation property
    public virtual StudentAddress StudentAddress { get; set; }
}
public class StudentAddress
{

    public int StudentAddressId { get; set; }
    public int StudentId { get; set; }  //Set this property as a forign key
    public string Address { get; set; }
    //Navigation property
    public virtual Student Student { get; set; }

}

Body:
you can easily do that , with the following code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);

    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<Student>()
                .HasOptional(s => s.Address)
                .WithRequired(ad => ad.StudentId);

}

Just FYI without Fluent API:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}

public class StudentAddress
{
    [Key, ForeignKey("Student")]
    public int StudentId { get; set; }

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

For additional  info: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

Hope above information was helpful.

Thanks

Karthik


问:
Getting error MsRestAzure::AzureOperationError: AuthorizationFailed while trying to create vm instance using Ruby api
I am new to Azure platform. I have followed this link to generate service principle : https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

When I reach to step : Assign application to role > point 6 (Search for your application, and select it.) I can't see my application in result of search.

After that I have tried to create VM using ruby api :

https://github.com/Azure/azure-sdk-for-ruby/tree/master/management/azure_mgmt_compute

When I implement code to create VM, I get following error :

```<code>"message": "MsRestAzure::AzureOperationError: AuthorizationFailed: The client 'xxxx' with object id 'xxxx' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/write' over scope '/subscriptions/xxxx/resourceGroups/my_group/providers/Microsoft.Compute/virtualMachines/test-ubuntu3'.",
</code>```

In above error message both client and object id is same. I don't know why and what is the meaning of object id.

How I can resolve this issue ? Where I should look at in portal ? Any help will be appreciated.

Thank you

答:
Root cause is the service principal you are using doesn't have rights within that tenant.

Tenants have subscriptions and service principals belong to tenants. Azure resource manager also exposes role based authorization for a given principal, which would give it rights on Azure resources. It appears the service principal doesn't have rights to read from that subscription.

Please use Azure CLI 2.0 to create service principal:

```<code>az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName"
</code>```

Here is the information about CLI 2.0 to create service principal:

```<code>C:\Users>az ad sp create-for-rbac -h

Command
    az ad sp create-for-rbac: Create a service principal and configure its access to Azure
    resources.

Arguments
    --cert           : PEM or DER formatted public certificate using string or `@<file path>` to
                       load from a file. Do not include private key info.
    --create-cert    : Create and upload self-signed certificate which you can use to login.
    --expanded-view  : Once created, display more information like subscription and cloud
                       environments.
    --name -n        : A display name or an app id uri. Command will generate one if missing.
    --password -p    : The password used to login. If missing, command will generate one.
    --role           : Role the service principal has on the resources.  Default: Contributor.
    --scopes         : Space separated scopes the service principal's role assignment applies to.
                       Defaults to the root of the current subscription.
    --skip-assignment: Do not create default assignment.
    --years          : Years the password will be valid. Default: 1 year.

Global Arguments
    --debug          : Increase logging verbosity to show all debug logs.
    --help -h        : Show this help message and exit.
    --output -o      : Output format.  Allowed values: json, jsonc, table, tsv.  Default: json.
    --query          : JMESPath query string. See http://jmespath.org/ for more information and
                       examples.
    --verbose        : Increase logging verbosity. Use --debug for full debug logs.

Examples
    Create with a default role assignment.
        az ad sp create-for-rbac

    Create using a custom name, and with a default assiggment.
        az ad sp create-for-rbac -n "http://MyApp"

    Create without a default assignment.
        az ad sp create-for-rbac --skip-assignment

    Create with customized assignments
        az ad sp create-for-rbac -n "http://MyApp" --role contributor --scopes
        /subscriptions/11111111-2222-3333-4444-555555555555/resourceGroups/MyResourceGroup
        /subscriptions/11111111-2222-3333-4444-666666666666/resourceGroups/MyAnotherResourceGroup

    Create using self-signed certificte
        az ad sp create-for-rbac --create-cert

    Login with a service principal.
        az login --service-principal -u <name> -p <password> --tenant <tenant>

    Login with self-signed certificate
        az login --service-principal -u <name> -p <certificate file path> --tenant <tenant>

    Reset credentials on expiration.
        az ad sp reset-credentials --name <name>

    Create extra role assignments in future.
        az role assignment create --assignee <name> --role Contributor

    Revoke the service principal when done with it.
        az ad app delete --id <name>

    Create using certificate from Key Vault
        az keyvault certificate download --vault-name vault -n cert-name -f cert.pem
        az ad sp create-for-rbac --cert @cert.pem
</code>```

Body:
I am new to Azure platform. I have followed this link to generate service principle : https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal

When I reach to step : Assign application to role > point 6 (Search for your application, and select it.) I can't see my application in result of search.

After that I have tried to create VM using ruby api :

https://github.com/Azure/azure-sdk-for-ruby/tree/master/management/azure_mgmt_compute

When I implement code to create VM, I get following error :

"message": "MsRestAzure::AzureOperationError: AuthorizationFailed: The client 'xxxx' with object id 'xxxx' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/write' over scope '/subscriptions/xxxx/resourceGroups/my_group/providers/Microsoft.Compute/virtualMachines/test-ubuntu3'.",

In above error message both client and object id is same. I don't know why and what is the meaning of object id.

How I can resolve this issue ? Where I should look at in portal ? Any help will be appreciated.

Thank you

Body:
Root cause is the service principal you are using doesn't have rights within that tenant.

Tenants have subscriptions and service principals belong to tenants. Azure resource manager also exposes role based authorization for a given principal, which would give it rights on Azure resources. It appears the service principal doesn't have rights to read from that subscription.

Please use Azure CLI 2.0 to create service principal:

az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/mySubscriptionID/resourceGroups/myResourceGroupName"

Here is the information about CLI 2.0 to create service principal:

C:\Users>az ad sp create-for-rbac -h

Command
    az ad sp create-for-rbac: Create a service principal and configure its access to Azure
    resources.

Arguments
    --cert           : PEM or DER formatted public certificate using string or `@<file path>` to
                       load from a file. Do not include private key info.
    --create-cert    : Create and upload self-signed certificate which you can use to login.
    --expanded-view  : Once created, display more information like subscription and cloud
                       environments.
    --name -n        : A display name or an app id uri. Command will generate one if missing.
    --password -p    : The password used to login. If missing, command will generate one.
    --role           : Role the service principal has on the resources.  Default: Contributor.
    --scopes         : Space separated scopes the service principal's role assignment applies to.
                       Defaults to the root of the current subscription.
    --skip-assignment: Do not create default assignment.
    --years          : Years the password will be valid. Default: 1 year.

Global Arguments
    --debug          : Increase logging verbosity to show all debug logs.
    --help -h        : Show this help message and exit.
    --output -o      : Output format.  Allowed values: json, jsonc, table, tsv.  Default: json.
    --query          : JMESPath query string. See http://jmespath.org/ for more information and
                       examples.
    --verbose        : Increase logging verbosity. Use --debug for full debug logs.

Examples
    Create with a default role assignment.
        az ad sp create-for-rbac

    Create using a custom name, and with a default assiggment.
        az ad sp create-for-rbac -n "http://MyApp"

    Create without a default assignment.
        az ad sp create-for-rbac --skip-assignment

    Create with customized assignments
        az ad sp create-for-rbac -n "http://MyApp" --role contributor --scopes
        /subscriptions/11111111-2222-3333-4444-555555555555/resourceGroups/MyResourceGroup
        /subscriptions/11111111-2222-3333-4444-666666666666/resourceGroups/MyAnotherResourceGroup

    Create using self-signed certificte
        az ad sp create-for-rbac --create-cert

    Login with a service principal.
        az login --service-principal -u <name> -p <password> --tenant <tenant>

    Login with self-signed certificate
        az login --service-principal -u <name> -p <certificate file path> --tenant <tenant>

    Reset credentials on expiration.
        az ad sp reset-credentials --name <name>

    Create extra role assignments in future.
        az role assignment create --assignee <name> --role Contributor

    Revoke the service principal when done with it.
        az ad app delete --id <name>

    Create using certificate from Key Vault
        az keyvault certificate download --vault-name vault -n cert-name -f cert.pem
        az ad sp create-for-rbac --cert @cert.pem