问:
User ASP.NET Impersonation
I'm working on a ASP.Net application where i'm planing to implement feature where the admin of the app can impersonate user and use the application as that user. If someone have an idea or experience with this will be very helpful. BTW can i use cookies to store the impersonate user data and retrieve it to the application.

Thanks a lot.

Update
I found this solution http://tech.trailmax.info/2014/06/user-impersonation-with-asp-net-identity-2/ for my project but now i'm facing some other issues. Here is also a sample from the code where I'm getting error.

```<code> public async Task ImpersonateUserAsync(string userName)
    {
        var context = HttpContext.Current;

        var originalUsername = context.User.Identity.Name;

        var impersonatedUser = await userManager.FindByNameAsync(userName);

        var impersonatedIdentity = await userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
        impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));
        impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));

        var authenticationManager = context.GetOwinContext().Authentication;
        authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);
    }
</code>```

The error is by this line var authenticationManager = context.GetOwinContext().Authentication;. Also here is the error msg.

CS1061  C# 'HttpContext' does not contain a definition for
  'GetOwinContext' and no extension method 'GetOwinContext' accepting a
  first argument of type 'HttpContext' could be found (are you missing a
  using directive or an assembly reference?)

Any ideas what i'm missing.

答:
The GetOwinContext extension method is located in the System.Web.Http.Owin dll which needs to be downloaded as a nuget package (The nuget package name is Microsoft.AspNet.WebApi.Owin)

```<code>Install-Package Microsoft.AspNet.WebApi.Owin
</code>```

https://learn.microsoft.com/en-us/nuget/guides/install-nuget

Title: User ASP.NET Impersonation

Body:
I'm working on a ASP.Net application where i'm planing to implement feature where the admin of the app can impersonate user and use the application as that user. If someone have an idea or experience with this will be very helpful. BTW can i use cookies to store the impersonate user data and retrieve it to the application.

Thanks a lot.

Update
I found this solution http://tech.trailmax.info/2014/06/user-impersonation-with-asp-net-identity-2/ for my project but now i'm facing some other issues. Here is also a sample from the code where I'm getting error.

 public async Task ImpersonateUserAsync(string userName)
    {
        var context = HttpContext.Current;

        var originalUsername = context.User.Identity.Name;

        var impersonatedUser = await userManager.FindByNameAsync(userName);

        var impersonatedIdentity = await userManager.CreateIdentityAsync(impersonatedUser, DefaultAuthenticationTypes.ApplicationCookie);
        impersonatedIdentity.AddClaim(new Claim("UserImpersonation", "true"));
        impersonatedIdentity.AddClaim(new Claim("OriginalUsername", originalUsername));

        var authenticationManager = context.GetOwinContext().Authentication;
        authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, impersonatedIdentity);
    }

The error is by this line var authenticationManager = context.GetOwinContext().Authentication;. Also here is the error msg.

CS1061  C# 'HttpContext' does not contain a definition for
  'GetOwinContext' and no extension method 'GetOwinContext' accepting a
  first argument of type 'HttpContext' could be found (are you missing a
  using directive or an assembly reference?)

Any ideas what i'm missing.

Body:
The GetOwinContext extension method is located in the System.Web.Http.Owin dll which needs to be downloaded as a nuget package (The nuget package name is Microsoft.AspNet.WebApi.Owin)

Install-Package Microsoft.AspNet.WebApi.Owin

https://learn.microsoft.com/en-us/nuget/guides/install-nuget


来源: stackexchange

问:
React Native: Unable To Sign Into my App- Error in fetching sourceURL
I am unable to sign into my app on my iOS simulator on my computer or iPhone 7 (I am able to load expo and get to my sign in/register screen). It was working fine a couple days ago and today it stopped.. I have not touched any code that relates to the error I am getting. On the simulator I went to localhost:19001 and it says that React Native packager is running.

Here is the error I get in terminal:

error in fetching

{"line":22374,"column":29,"sourceURL":"http://localhost:19001/node_modules/react-native-scripts/build/bin/crna-entry.bundle?platform=ios&dev=true&strict=false&minify=false&hot=false&assetPlugin=expo/tools/hashAssetFiles"}

Any advice or help would be great appreciated, I am eager to work on my project again.

答: I think it is because you are running your APP on localhost, try to change the server host from to localhost to the IP which you are using.

ContentLicense: CC BY-SA 3.0


问:
Radix Sort for Negative Integers
I am trying to implement radix sort for integers, including negative integers. For non-negative ints, I was planning to create a queue of 10 queues correspondingly for the digits 0-9 and implement the LSD algorithm. But I was kind of confused with negative integers. What I am thinking now, is to go ahead and create another queue of 10 queues for them and separately sort them and then at the end, I will gave 2 lists, one containing negative ints sorted and the other containing non-negative ints. And finally I would merge them.

What do you think about this? Is there more efficient way to handle with negative integers?

答:
Your radix sort wont be faster than the famous comparison sorts if you dont use "bitshift" and "bitwise AND" for radix calculation.

Computers use 2's complement to represent signed numbers, here the sign-bit lies at the leftmost end of a binary digit, in memory representation

eg

 436163157 (as 32 bit number) = 00011001 11111111 01010010 01010101
 -436163157 (as 32 bit number) = 11100110 00000000 10101101 10101011

1 (as 32 bit number) = 00000000 00000000 00000000 00000001

-1 (as 32 bit number) = 11111111 1111111 1111111 11111111

0 is represented as = 00000000 00000000 00000000 00000000

Highest negative value as = 10000000 00000000 00000000 00000000

So you see, the more negative a number becomes, it looses that many 1's, a small negative number has many 1's, if you set only the sign-bit to 0, it becomes a very large positive number. Vice versa a small positive number becomes a large negative number.

In radix sort the key to sorting negative numbers is how you handle the last 8 bits, for negative numbers at least the last bit has to be 1, in 32-bit scheme it has to be from
 10000000 00000000 00000000 00000000 which is the most negative value farthest from zero to 11111111 11111111 11111111 11111111 which is -1. If you look at the leftmost 8 bits, the magnitude ranges from 10000000 to 11111111, i.e. from 128 to 255.

These values can be obtained by this code piece

```<code>V = ( A[i] >> 24 ) & 255
</code>```

For negative numbers V will always lie from 128 upto 255. For positive numbers it will be from 0 to 127. As said earlier, the value of M will be 255 for -1 and 128 for highest negative number in 32-bit scheme. Build up your histogram as usual. Then from index 128 to 255 do the cumulative sum, then add frequency of 255 to 0, and proceed the cumulative sum from 0 till index 127. Perform the Sort as usual. This technique is both optimal, fast, elegant and neat both in theory and in practice. No need of any kind of separate lists nor order reversal after sorting nor converting all inputs to positive which make the sort slow and messy.

For the code see Radix Sort Optimization
 A 64-bit version can be built using same concepts

Further read:

http://codercorner.com/RadixSortRevisited.htm

http://stereopsis.com/radix.html

ContentLicense: CC BY-SA 4.0

Title: Radix Sort for Negative Integers

Body:
Your radix sort wont be faster than the famous comparison sorts if you dont use "bitshift" and "bitwise AND" for radix calculation.

Computers use 2's complement to represent signed numbers, here the sign-bit lies at the leftmost end of a binary digit, in memory representation

eg

 436163157 (as 32 bit number) = 00011001 11111111 01010010 01010101
 -436163157 (as 32 bit number) = 11100110 00000000 10101101 10101011

1 (as 32 bit number) = 00000000 00000000 00000000 00000001

-1 (as 32 bit number) = 11111111 1111111 1111111 11111111

0 is represented as = 00000000 00000000 00000000 00000000

Highest negative value as = 10000000 00000000 00000000 00000000

So you see, the more negative a number becomes, it looses that many 1's, a small negative number has many 1's, if you set only the sign-bit to 0, it becomes a very large positive number. Vice versa a small positive number becomes a large negative number.

In radix sort the key to sorting negative numbers is how you handle the last 8 bits, for negative numbers at least the last bit has to be 1, in 32-bit scheme it has to be from
 10000000 00000000 00000000 00000000 which is the most negative value farthest from zero to 11111111 11111111 11111111 11111111 which is -1. If you look at the leftmost 8 bits, the magnitude ranges from 10000000 to 11111111, i.e. from 128 to 255.

These values can be obtained by this code piece

V = ( A[i] >> 24 ) & 255

For negative numbers V will always lie from 128 upto 255. For positive numbers it will be from 0 to 127. As said earlier, the value of M will be 255 for -1 and 128 for highest negative number in 32-bit scheme. Build up your histogram as usual. Then from index 128 to 255 do the cumulative sum, then add frequency of 255 to 0, and proceed the cumulative sum from 0 till index 127. Perform the Sort as usual. This technique is both optimal, fast, elegant and neat both in theory and in practice. No need of any kind of separate lists nor order reversal after sorting nor converting all inputs to positive which make the sort slow and messy.

For the code see Radix Sort Optimization
 A 64-bit version can be built using same concepts

Further read:

http://codercorner.com/RadixSortRevisited.htm

http://stereopsis.com/radix.html


问:
Is it possible to use your own laravel package before registering it on Packagist?
I created a Laravel package (it is located in a private BitBucket repository) and I would like to test it in a new Laravel project if it works the way I want before registering it on Packagist. Is there any way to do that?</p>

答:
Yes, it is possible.

You have to add information where to look for your source code to composer.json. For example you could add your own private repository.

How to add private repository

There are other possibilites, too. I suggest reading through the corresponding composer documentation


问:
Cancel search in vscode
If i try search something in vs code it works fine but even after it has found the result i am looking for it continues to search, which is not ideal because i think it is searching everything in the node-modules folder, which depending on my search term, with freeze vs code completely.

I know i could probably just regex the node-modules folder out of the search, but its so simple as it is , it always finds the results quickly but then just hangs. Don't know if i have maybe overlooked something in the editor but is there a simple stop on searching?

答:
Just press esc to stop the search

Here's the default keybinding for that:

```<code>{
     "key": "escape",
     "command": "search.action.cancel",
     "when": "listFocus && searchViewletVisible"
}
</code>```

Title: Cancel search in vscode

Body:
Just press esc to stop the search

Here's the default keybinding for that:

{
     "key": "escape",
     "command": "search.action.cancel",
     "when": "listFocus && searchViewletVisible"
}


问:
How to combine async and non-async services in MVVM?

Scenario

In an MVVMLight based app I use a couple of views and services to do some work time calculation. Among others there are the following services...

DataService: As the name suggests, used to get the data from the database. Because it's I/O operations per nature the methods are using async/await.

Contract: This is a CPU bound service that actually calculates the work times (e.g. for a given day, week, month, ...)

Now, let's have a look at the following method (which is located in the Contract service):

```<code>public TimeSpan GetWorkTimeForDay(Date date)
{
    // Check if that result was already calculated before and is still
    // valid. In this case, load it and return it
    if (ContractCalculationCacheResults.Contains(date))
        return ContractCalculationCacheResults.Get(date);

    var finalWorkTime = TimeSpan.Zero;

    // Get the work day from the database in a synchronous fashion
    var workDay = DataService.GetWorkDay(date);

    // if there is a work day in the database then finally calculate the work time
    if (workDay != null)
        finalWorkTime = GetWorkTimeForDay(workDay);

    // cache the result
    ContractCalculationCacheResults.Put(date, finalWorkTime);

    // return the final result
    return finalWorkTime;
}
</code>```

This method is located in the Contract service. It has the dependency to the DataService to get the required data for the calculations.

As you can see, DataService.GetWorkDay() is synchronous at the moment. This is how the database got accessed for quite some time. Now, while porting the app from WP8 Silverlight to UWP I wanted to clean up the code and changed the data service so that it only provides async methods instead of synchronous methods. But now I'm struggling with combining two actually separate services where ones nature is synchronous while the others is asynchronous.

Problem

I need to update the method GetWorkTimeForDay() (and many others that look similar) to use the new DataService.GetWorkDayAsync() method which, as the name applies, is defined as follows:

```<code>public async Task<WorkDay> GetWorkDayAsync(Date dateKey)
</code>```

However, this leads to many open questions as suddenly GetWorkTimeForDay should become an async method as well, even though its nature is CPU bound. So this won't make sense.

Possible Solutions

1. Make GetWorkTimeForDay an async method

The result would be something like this:

```<code>public async Task<TimeSpan> GetWorkTimeForDay(Date date)
{
    ...

    // Get the work day from the database in a synchronous fashion
    var workDay = await DataService.GetWorkDayAsync(date);

    ...
}
</code>```

While this looks easy, it has a lot of implications on the rest of the code. Simply because that everywhere where GetWorkTimeForDay is called I would have to change the code because this method is now async. I would have to await for it and therefore might need to change the calling method as well... and so on. But sometimes it is not required to call GetWorkTimeForDay() asynchronously simply because it is already running in a separate thread or a background task. Let alone all the Unit-Test that exist so far. So there are cases where it won't block the UI.

Furthermore, suddenly the CPU bound calculations become asynchronous which is not how it should work (at least if I understood this post (and others) by Stephen Cleary correctly.

2. Separate the services

So the next solution that came to my mind is to separate the services. In other words, do not have one service depend on another. This would change the signature for GetWorkTimeForDay() like so:

```<code>public TimeSpan GetWorkTimeForDay(WorkDay workDay, Date date)
{
    var finalWorkTime = TimeSpan.Zero;

    if (workDay != null)
        finalWorkTime = GetWorkTimeForDay(workDay);

    return finalWorkTime;
}
</code>```

The calling method would then look similar to this:

```<code>public async void Caller(Date date)
{
    ...

    if (ContractCalculationCacheResults.Contains(date))
        return ContractCalculationCacheResults.Get(date);

    var workDay = await DataService.GetWorkDay(date);
    var workTime = Contract.GetWorkTimeForDay(workDay, date);

    ContractCalculationCacheResults.Put(date, workTime);

    ...
}
</code>```

The downside, just like for for the other solution, is that all the caller methods would have to be updated (and its callers, ...) even though sometimes this is not necessary. Also a lot of redundant code for the caching and database access will be added.

One more downside, from an MVVM point of view, is probably that suddenly the data is provided to the contract service. So I won't use DI anymore which is more or less against the rules for good reasons. (Here to me the question pops up on how to correctly inject a service into a service)

Last but not least, I would have to remove the caching from the GetWorkTimeForDay method as well. Only when the result was not cached before, I'm gonna ask the database to get the work day and do the calculations afterwards.

3. ?

...

Actual Question

What is a good design to combine an async service together with a non-async service in an MVVM based project?

I want to keep the actual calculations synchronous because they are CPU bound. I want to keep the data access asynchronous because they are not CPU bound but might take some time.

So this post is not about a technical solution on how to wait for the result of await/Task/... . It is more an architectural question about MVVM, services injected into other services, combination of services that are synchronous and asynchronous.

答:
Furthermore, suddenly the CPU bound calculations become asynchronous which is not how it should work...

There is a simple reason behind this: When people see an async method, they usually think, that this method will execute asynchronously and therefor not block the current thread.

Your method would act like this:

```<code>//Start...             (On current thread)
//Access the database  (On IO Thread, freeing up the current thread)
//Return to current thread
//Do the calculations  (On the current thread)
</code>```

What people might not expect is the workload on the calling thread.

I'd go with @kevin-gosse here: Just change it to an async method, because it still has an IO Bound part int it. If you expect other people to call that method, make sure to document that is has an CPU intensive part too.

Stephen Cleary has some great examples on his blog.

Your second solution approach is completly valid too. If you think of your ´Contract´ purely as a calculation engine, that should absolutely not care where it's data comes from. You'd still have a decoupled, testable class.

Body:
Scenario

In an MVVMLight based app I use a couple of views and services to do some work time calculation. Among others there are the following services...

DataService: As the name suggests, used to get the data from the database. Because it's I/O operations per nature the methods are using async/await.

Contract: This is a CPU bound service that actually calculates the work times (e.g. for a given day, week, month, ...)

Now, let's have a look at the following method (which is located in the Contract service):

public TimeSpan GetWorkTimeForDay(Date date)
{
    // Check if that result was already calculated before and is still
    // valid. In this case, load it and return it
    if (ContractCalculationCacheResults.Contains(date))
        return ContractCalculationCacheResults.Get(date);

    var finalWorkTime = TimeSpan.Zero;

    // Get the work day from the database in a synchronous fashion
    var workDay = DataService.GetWorkDay(date);

    // if there is a work day in the database then finally calculate the work time
    if (workDay != null)
        finalWorkTime = GetWorkTimeForDay(workDay);

    // cache the result
    ContractCalculationCacheResults.Put(date, finalWorkTime);

    // return the final result
    return finalWorkTime;
}

This method is located in the Contract service. It has the dependency to the DataService to get the required data for the calculations.

As you can see, DataService.GetWorkDay() is synchronous at the moment. This is how the database got accessed for quite some time. Now, while porting the app from WP8 Silverlight to UWP I wanted to clean up the code and changed the data service so that it only provides async methods instead of synchronous methods. But now I'm struggling with combining two actually separate services where ones nature is synchronous while the others is asynchronous.

Problem

I need to update the method GetWorkTimeForDay() (and many others that look similar) to use the new DataService.GetWorkDayAsync() method which, as the name applies, is defined as follows:

public async Task<WorkDay> GetWorkDayAsync(Date dateKey)

However, this leads to many open questions as suddenly GetWorkTimeForDay should become an async method as well, even though its nature is CPU bound. So this won't make sense.

Possible Solutions

1. Make GetWorkTimeForDay an async method

The result would be something like this:

public async Task<TimeSpan> GetWorkTimeForDay(Date date)
{
    ...

    // Get the work day from the database in a synchronous fashion
    var workDay = await DataService.GetWorkDayAsync(date);

    ...
}

While this looks easy, it has a lot of implications on the rest of the code. Simply because that everywhere where GetWorkTimeForDay is called I would have to change the code because this method is now async. I would have to await for it and therefore might need to change the calling method as well... and so on. But sometimes it is not required to call GetWorkTimeForDay() asynchronously simply because it is already running in a separate thread or a background task. Let alone all the Unit-Test that exist so far. So there are cases where it won't block the UI.

Furthermore, suddenly the CPU bound calculations become asynchronous which is not how it should work (at least if I understood this post (and others) by Stephen Cleary correctly.

2. Separate the services

So the next solution that came to my mind is to separate the services. In other words, do not have one service depend on another. This would change the signature for GetWorkTimeForDay() like so:

public TimeSpan GetWorkTimeForDay(WorkDay workDay, Date date)
{
    var finalWorkTime = TimeSpan.Zero;

    if (workDay != null)
        finalWorkTime = GetWorkTimeForDay(workDay);

    return finalWorkTime;
}

The calling method would then look similar to this:

public async void Caller(Date date)
{
    ...

    if (ContractCalculationCacheResults.Contains(date))
        return ContractCalculationCacheResults.Get(date);

    var workDay = await DataService.GetWorkDay(date);
    var workTime = Contract.GetWorkTimeForDay(workDay, date);

    ContractCalculationCacheResults.Put(date, workTime);

    ...
}

The downside, just like for for the other solution, is that all the caller methods would have to be updated (and its callers, ...) even though sometimes this is not necessary. Also a lot of redundant code for the caching and database access will be added.

One more downside, from an MVVM point of view, is probably that suddenly the data is provided to the contract service. So I won't use DI anymore which is more or less against the rules for good reasons. (Here to me the question pops up on how to correctly inject a service into a service)

Last but not least, I would have to remove the caching from the GetWorkTimeForDay method as well. Only when the result was not cached before, I'm gonna ask the database to get the work day and do the calculations afterwards.

3. ?

...

Actual Question

What is a good design to combine an async service together with a non-async service in an MVVM based project?

I want to keep the actual calculations synchronous because they are CPU bound. I want to keep the data access asynchronous because they are not CPU bound but might take some time.

So this post is not about a technical solution on how to wait for the result of await/Task/... . It is more an architectural question about MVVM, services injected into other services, combination of services that are synchronous and asynchronous.

Body:
Furthermore, suddenly the CPU bound calculations become asynchronous which is not how it should work...

There is a simple reason behind this: When people see an async method, they usually think, that this method will execute asynchronously and therefor not block the current thread.

Your method would act like this:

//Start...             (On current thread)
//Access the database  (On IO Thread, freeing up the current thread)
//Return to current thread
//Do the calculations  (On the current thread)

What people might not expect is the workload on the calling thread.

I'd go with @kevin-gosse here: Just change it to an async method, because it still has an IO Bound part int it. If you expect other people to call that method, make sure to document that is has an CPU intensive part too.

Stephen Cleary has some great examples on his blog.

Your second solution approach is completly valid too. If you think of your ´Contract´ purely as a calculation engine, that should absolutely not care where it's data comes from. You'd still have a decoupled, testable class.


问:
How to set default value for form field in Symfony2?
Is there an easy way to set a default value for text form field?</p>

答:
If you set 'data' in your creation form, this value will be not modified when edit your entity.

My solution is :

```<code>public function buildForm(FormBuilderInterface $builder, array $options) {
    // In my example, data is an associated array
    $data = $builder->getData();

    $builder->add('myfield', 'text', array(
     'label' => 'Field',
     'data' => array_key_exits('myfield', $data) ? $data['myfield'] : 'Default value',
    ));
}
</code>```

Bye.

Body:
If you set 'data' in your creation form, this value will be not modified when edit your entity.

My solution is :

public function buildForm(FormBuilderInterface $builder, array $options) {
    // In my example, data is an associated array
    $data = $builder->getData();

    $builder->add('myfield', 'text', array(
     'label' => 'Field',
     'data' => array_key_exits('myfield', $data) ? $data['myfield'] : 'Default value',
    ));
}

Bye.


问:
VHDL can't matching context of call for to_unsigned in user defined function
I'm using Quartus Prime Pro.

I'm dealing with a function as such:

```<code>library ieee ;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

function round_resize (a : unsigned; b : integer) return unsigned is
  variable c : signed (a'length - 1 downto 0); --problem child
  variable d : signed (b - 1 downto 0);
begin
  c := a + to_signed(2**(b-2), a'length);
  d := to_unsigned(c(c'length-2 downto (c'length-b-1)));
  return d;
end function;
</code>```

But I get the error:

Error(13643): VHDL error at file.vhd(109): can't determine definition of operator ""+"" -- found 0 possible definitions

So I changed the problem child to this:

```<code>c := to_unsigned( a + to_signed(2**(b-2), a'length), a'length);
</code>```

But I get the following error:

Error(13815): VHDL Qualified Expression error at cpmmod.vhd(110): to_unsigned type specified in Qualified Expression must match signed type that is implied for expression by context

What else can I try to make this work?

答:
Nathanael is correct.

To understand what is happening, you need to understand two concepts:

i) operators in VHDL are functions

When you use an operator, you are really calling a function. In the numeric_std package, there are many definitions of various operators. For example, one definition of the + operator is

```<code>  function "+" (L, R: UNSIGNED) return UNSIGNED;
</code>```

ii) VHDL uses overloading

If you look in the numeric_std package, you will see many definitions of + operators:

```<code>  function "+" (L, R: UNSIGNED) return UNSIGNED;
  function "+" (L, R: SIGNED) return SIGNED;
  function "+" (L: UNSIGNED; R: NATURAL) return UNSIGNED;
  function "+" (L: NATURAL; R: UNSIGNED) return UNSIGNED;
  function "+" (L: INTEGER; R: SIGNED) return SIGNED;
  function "+" (L: SIGNED; R: INTEGER) return SIGNED;
</code>```

Each has a different combination of argument types and return types. The compiler can determine which one to call by this combination (called the signature). This idea is called overloading. It only works if there is exactly one possible function to call. If there is more than one, the compiler doesn't know which one to call; if there is less than one, the compiler doesn't have a function to call...

...and that is your problem. If you look at the signatures of the + operator functions in numeric_std listed above, you will see that there are no + operators defined which combine SIGNED and UNSIGNED types. Therefore, in your case, the compiler has no function to call and overloading fails.

You need to think carefully about the arithmetic you wish to implement and then convert everything to either SIGNED or UNSIGNED as you see fit. You do do that easily using type conversions, because SIGNED and UNSIGNED are closely related types (they are both arrays of std_logic indexed by an integer).

Body:
I'm using Quartus Prime Pro.

I'm dealing with a function as such:

library ieee ;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

function round_resize (a : unsigned; b : integer) return unsigned is
  variable c : signed (a'length - 1 downto 0); --problem child
  variable d : signed (b - 1 downto 0);
begin
  c := a + to_signed(2**(b-2), a'length);
  d := to_unsigned(c(c'length-2 downto (c'length-b-1)));
  return d;
end function;

But I get the error:

Error(13643): VHDL error at file.vhd(109): can't determine definition of operator ""+"" -- found 0 possible definitions

So I changed the problem child to this:

c := to_unsigned( a + to_signed(2**(b-2), a'length), a'length);

But I get the following error:

Error(13815): VHDL Qualified Expression error at cpmmod.vhd(110): to_unsigned type specified in Qualified Expression must match signed type that is implied for expression by context

What else can I try to make this work?

Body:
Nathanael is correct.

To understand what is happening, you need to understand two concepts:

i) operators in VHDL are functions

When you use an operator, you are really calling a function. In the numeric_std package, there are many definitions of various operators. For example, one definition of the + operator is

  function "+" (L, R: UNSIGNED) return UNSIGNED;

ii) VHDL uses overloading

If you look in the numeric_std package, you will see many definitions of + operators:

  function "+" (L, R: UNSIGNED) return UNSIGNED;
  function "+" (L, R: SIGNED) return SIGNED;
  function "+" (L: UNSIGNED; R: NATURAL) return UNSIGNED;
  function "+" (L: NATURAL; R: UNSIGNED) return UNSIGNED;
  function "+" (L: INTEGER; R: SIGNED) return SIGNED;
  function "+" (L: SIGNED; R: INTEGER) return SIGNED;

Each has a different combination of argument types and return types. The compiler can determine which one to call by this combination (called the signature). This idea is called overloading. It only works if there is exactly one possible function to call. If there is more than one, the compiler doesn't know which one to call; if there is less than one, the compiler doesn't have a function to call...

...and that is your problem. If you look at the signatures of the + operator functions in numeric_std listed above, you will see that there are no + operators defined which combine SIGNED and UNSIGNED types. Therefore, in your case, the compiler has no function to call and overloading fails.

You need to think carefully about the arithmetic you wish to implement and then convert everything to either SIGNED or UNSIGNED as you see fit. You do do that easily using type conversions, because SIGNED and UNSIGNED are closely related types (they are both arrays of std_logic indexed by an integer).


问:
How to use _.SortBy() with an array of Objects?
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);```
</div>
</div>
</p>

<h3>EDIT :</h3>

<p>It seems there is a problem with my array, i tried this two function, but i couldn't see any <code>console.log()</code>... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);</code>```

答:
Problem solved ! So the "sort()" method was not the cause. The problem was with the asynchronous communication between firebase and my Array, when I put the sort() method inside my firebase request (the one I used to populate the Array) the sort was successful.

Thank you all for your support ! ;)

Body:
I tried a lot of algorithm to convert my Array with objects inside into an array of arrays. But each time either it doesn't work or my new create array is empty. For exemple, I can't run into it with angular.foreach()or myArray.forEach(function(element)). I really don't know why, because it is declared and initialized as an array "var myArray = [];".

Then I'm using pushto populate it, and what I obtained in the console.log is :

What I would like to have is something usable into _.SortBy(myArray, 'date'); (Underscore.js) to do it I need myArray to be like that :

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];

Following this post : Converting a JS object to an array I tried barely everything listed, but nothing worked...Can you give me a hand ?

$scope.myArray = [];

// This is into an angular.foreach

 $scope.myArray.push({'Name' : snapshot.val().name, 'Link' : snapshot.val().link, 'second' : snapshot.val().second, 'var' : snapshot.val().var, 'selfID' : 'MyID', 'date' : snapshot.val().date, 'hour' : snapshot.val().hour });

 console.log("MyArray :", $scope.myArray);

EDIT :

It seems there is a problem with my array, i tried this two function, but i couldn't see any console.log()... Is it possible that my array is locked ? Maybe no function (sort, _.sortBy...) can run into it ?

// One try to run into and sort
$scope.myArray.sort(function(x, y)
{
            var date1 = new Date(x.date);
            var date2 = new Date(y.date);

            console.log("My dates :", date1);
            console.log("My dates :", date2);

            return date1 - date2 ;
});

// An other try to run into my array
for(var i = 0; i < $scope.myArray.length; i++)
{
            console.log("I'm in "+i+" with : "+$scope.newCal[i]);
}

// Even is showing the complete Array in console.log is working, this below shows me "undefined"

 console.log("One element : "+$scope.newCal[1]);


问:
How to remap array only on changes?
I have component Page which contains components Editor and Preview.

Page contains array items.

```<code>[
    {
        value: 0,
        text: 'Item 1'
    },
    ...
]
</code>```

Array items is passed to Editor & Preview like this:

```<code><editor  [items]="items"></editor>
<preview [items]="items"></preview>
</code>```

Editor can add/delete/edit/reorder items.

Issue is preview needs this array in another format.

```<code>[
    {
        index: 0,
        label: 'Item 1'
    },
    ...
]
</code>```

If I do like this

```<code>getRadioItems(): any[] {
    const items = [];
    for (let i = 0; i < this.items.length; i++) {
        items.push({ index: this.items[i].value,
                     label: this.items[i].text });
    }
    return items;
}
</code>```

and then

```<code><radio-list [radioItems]="getRadioItems()"></radio-list>
</code>```

It refreshes radio list hundreds times per second. You can't even change value because it will be reset on every refresh.

If it were without remapping - it would work fine.

What is correct way to remap items to radioItems in such case?

答: Have you tried setting the ChangeDetectionStrategy of the preview component to OnPush? Then change detection should only be run when the @Input() items is updated.

Title: How to remap array only on changes?

Body:
I have component Page which contains components Editor and Preview.

Page contains array items.

[
    {
        value: 0,
        text: 'Item 1'
    },
    ...
]

Array items is passed to Editor & Preview like this:

<editor  [items]="items"></editor>
<preview [items]="items"></preview>

Editor can add/delete/edit/reorder items.

Issue is preview needs this array in another format.

[
    {
        index: 0,
        label: 'Item 1'
    },
    ...
]

If I do like this

getRadioItems(): any[] {
    const items = [];
    for (let i = 0; i < this.items.length; i++) {
        items.push({ index: this.items[i].value,
                     label: this.items[i].text });
    }
    return items;
}

and then

<radio-list [radioItems]="getRadioItems()"></radio-list>

It refreshes radio list hundreds times per second. You can't even change value because it will be reset on every refresh.

If it were without remapping - it would work fine.

What is correct way to remap items to radioItems in such case?


问:
Use microsoft-graph-client in project with SystemJS
Currently I'm trying to get ng2-adal to work within my project, but I ran into some trouble.

Fortunately I got an answer from Fei Xue, but it still hangs. By trying to reproduce the problem I published a sample project on GitHub, but Fei had problems in the first run to get it to work and he provided a working sample from his side. I cloned the repo and tried it out and after removing the e2e test and updating rx.js to version 5.4.2 it worked.

Then I tried to add the microsoft-graph-client to the project. Fei already added it to the package.json, so I just had to use it...

Within the file microsoftGraph.component.ts I imported the client and tried to use it by calling by this code:

```<code>   if (this.isLoggedIn) {
        this.adalService.acquireToken('https://graph.microsoft.com').subscribe((token) => {
            console.log(token);

            this.graphClient = Client.init({
                debugLogging: true,
                authProvider: (done) => {
                    done(undefined, token);
                }
            });
        });
    }
</code>```

As soon as I insert that code and build the project, I get an error message in the browser console (NOT from the compiler):

```<code>GET http://localhost:3000/@microsoft/microsoft-graph-client 404 (Not Found)
</code>```

so i started to configure the systemjs.config.js file within the project and added the map and package configuration:

```<code>map: {
    ...
    '@microsoft/microsoft-graph-client': 'npm:@microsoft/microsoft-graph-client/lib/src',
    ...
},
packages: {
    ...
    '@microsoft/microsoft-graph-client': {
        main: 'index.js',
        defaultExtension: 'js'
    }
    ...
}
</code>```

After build and reload I got some error messages, complaining about missing es6-promise and superagent:

```<code>GET http://localhost:3000/es6-promise 404 (Not Found)
GET http://localhost:3000/superagent 404 (Not Found)
</code>```

So I added but packages accordingly, like I added the graph client above. But this leads no to a pletora of missing packages (e.g. formidable, form-data, url, stream, mime, util, zlib, ...).

If I would continue to add all of them, I guess I would get further missing packages, down the road of all npm dependencies that each of these packages have declared.

Conclusion

I made something wrong and another way exists to configure system.js to make all this stuff automatically and not by hand. But how? Please give me some insights on how to configure system.js correctly to use the microsoft-graph-client.

答:
I am able to reproduce your error and also don't really understand why. I checked the @microsoft/microsoft-graph-client and saw that they have the dependency list which is matched with the library it tried to load. So let's see If there are any more answer from experts.

```<code>  "dependencies": {
    "es6-promise": "^4.1.0",
    "superagent": "^3.5.2"
  }
</code>```

One dirty way we can make it work is to refer to the js file on index.html. And add declare var MicrosoftGraph: any on the component when we need to use to bypass TypeScript check. I think you have already known about. After that just refer to the Javascript api with the usage like MicrosoftGraph.Client.xxx

```<code><script type="text/javascript" src="node_modules/@microsoft/microsoft-graph-client/libgraph-js-sdk-web.js"></script>
</code>```

Body:
Currently I'm trying to get ng2-adal to work within my project, but I ran into some trouble.

Fortunately I got an answer from Fei Xue, but it still hangs. By trying to reproduce the problem I published a sample project on GitHub, but Fei had problems in the first run to get it to work and he provided a working sample from his side. I cloned the repo and tried it out and after removing the e2e test and updating rx.js to version 5.4.2 it worked.

Then I tried to add the microsoft-graph-client to the project. Fei already added it to the package.json, so I just had to use it...

Within the file microsoftGraph.component.ts I imported the client and tried to use it by calling by this code:

   if (this.isLoggedIn) {
        this.adalService.acquireToken('https://graph.microsoft.com').subscribe((token) => {
            console.log(token);

            this.graphClient = Client.init({
                debugLogging: true,
                authProvider: (done) => {
                    done(undefined, token);
                }
            });
        });
    }

As soon as I insert that code and build the project, I get an error message in the browser console (NOT from the compiler):

GET http://localhost:3000/@microsoft/microsoft-graph-client 404 (Not Found)

so i started to configure the systemjs.config.js file within the project and added the map and package configuration:

map: {
    ...
    '@microsoft/microsoft-graph-client': 'npm:@microsoft/microsoft-graph-client/lib/src',
    ...
},
packages: {
    ...
    '@microsoft/microsoft-graph-client': {
        main: 'index.js',
        defaultExtension: 'js'
    }
    ...
}

After build and reload I got some error messages, complaining about missing es6-promise and superagent:

GET http://localhost:3000/es6-promise 404 (Not Found)
GET http://localhost:3000/superagent 404 (Not Found)

So I added but packages accordingly, like I added the graph client above. But this leads no to a pletora of missing packages (e.g. formidable, form-data, url, stream, mime, util, zlib, ...).

If I would continue to add all of them, I guess I would get further missing packages, down the road of all npm dependencies that each of these packages have declared.

Conclusion

I made something wrong and another way exists to configure system.js to make all this stuff automatically and not by hand. But how? Please give me some insights on how to configure system.js correctly to use the microsoft-graph-client.

Body:
I am able to reproduce your error and also don't really understand why. I checked the @microsoft/microsoft-graph-client and saw that they have the dependency list which is matched with the library it tried to load. So let's see If there are any more answer from experts.

  "dependencies": {
    "es6-promise": "^4.1.0",
    "superagent": "^3.5.2"
  }

One dirty way we can make it work is to refer to the js file on index.html. And add declare var MicrosoftGraph: any on the component when we need to use to bypass TypeScript check. I think you have already known about. After that just refer to the Javascript api with the usage like MicrosoftGraph.Client.xxx

<script type="text/javascript" src="node_modules/@microsoft/microsoft-graph-client/libgraph-js-sdk-web.js"></script>


问:
url or content as a variable in the header of the page
I am designing a site where external links form various are being shown on my page. I am using

```<code>$url=$_GET['url'];
$website_data = file_get_contents($url);
echo $website_data;
</code>```

so essentially a user would click on a hyperlink which is something like www.test.com/display_page.php?url=http://www.xyz.com/article/2.jpg

My page, list_of_images.php, typically has a list of images with href for each image as above on the page and when any image is clicked it would go to display_page.php, which would show our banner on the top of this page, some text and then this image beneath that. This image could be from any website.

I am currently sending the url directly and grabbing it using GET. I understand that users/hackers can actually do some coding and send commands for the url variable and could break the server or do something harmful and so i would like to avoid this method or sending the url directly in the header. what is the alternate approach for this problem?

答:
The safe approach is to use a fixed set of resources stored in either an array or a database, and the appropriate key as a parameter.</p>

```<code>$ress = Array('1' => 'http://www.google.com/', ...);

$res = $ress[$_GET['res']];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am designing a site where external links form various are being shown on my page. I am using

$url=$_GET['url'];
$website_data = file_get_contents($url);
echo $website_data;

so essentially a user would click on a hyperlink which is something like www.test.com/display_page.php?url=http://www.xyz.com/article/2.jpg

My page, list_of_images.php, typically has a list of images with href for each image as above on the page and when any image is clicked it would go to display_page.php, which would show our banner on the top of this page, some text and then this image beneath that. This image could be from any website.

I am currently sending the url directly and grabbing it using GET. I understand that users/hackers can actually do some coding and send commands for the url variable and could break the server or do something harmful and so i would like to avoid this method or sending the url directly in the header. what is the alternate approach for this problem?

Body:
The safe approach is to use a fixed set of resources stored in either an array or a database, and the appropriate key as a parameter.

$ress = Array('1' => 'http://www.google.com/', ...);

$res = $ress[$_GET['res']];


问:
ContentDecodingError when getting text with beautiful soup
I have a list of URLs (from HuffPost UK) I need to get text from. I store them in a csv file but I just copy/pasted them below as a list. I have two problems with my code (which used to work fine with some other publishers...).

It randomly stops with ContentDecodingError.

It randomly fails to generate text.

I say randomly because when I run it several times it stops at different URLs. Sometimes it prints text, sometimes it prints an empty string for the same URL. I have no idea what is going on. Could anyone suggest what is wrong? I'll greatly appreciate your help.

My code:

```<code>import codecs
import translitcodec
import requests
from bs4 import BeautifulSoup

def get_text(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "lxml")
    # delete unwanted tags:
    for s in soup(['h2', 'figure', 'script', 'style', 'table']):
        s.decompose()
    # use separator to separate paragraphs and subtitles!
    article_soup = [s.get_text(separator="\n", strip=True) for s in soup.find_all( 'div', {'class': 'content-list-component text'})]
    text = ' '.join(article_soup)
    text = codecs.encode(text, 'translit/one').encode('ascii', 'replace') #replace traslit with ascii
    text = u"{}".format(text) #encode to unicode
    print text
    return text

urls = ['http://www.huffingtonpost.co.uk/2017/06/21/damian-green-tories-housing-education_n_17244280.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/the-waugh-zone-thursday-june-22-2017_n_17253136.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/argos-toys-christmas-2017_n_17248026.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/ore-oduba-strictly-come-dancing-joanne-clifton_n_17253186.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/joanne-clifton-flashdance-strictly-come-dancing_n_17253268.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/grenfell-tower-cladding-may-have-released-hydrogen-cyanide_n_17252776.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/uk-will-have-to-trawl-through-19000-eu-laws-to-decide-which-ones-to-keep-after-brexit_n_17242732.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-theresa-may_n_17241446.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/piers-morgan-good-morning-britain-bbc-breakfast-dan-walker-ratings_n_17252222.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/worst-bridezilla-stories-ever-reddit_n_17253210.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/donald-trump-uk-state-visit-shelved-after-no-mention-in-queens-speech-2017_n_17239686.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/failure-may-state_n_17242710.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-13-things-missing-from-theresa-mays-first-one_n_17239692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/heartbroken-best-man-gatecrashes-bride-and-grooms-wedding-photos-and-its-comedy-gold_n_17253104.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-mocks-theresa-mays-imploding-minority-government_n_17242692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/asda-the-little-mermaid-swimsuit-topless_n_17253262.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/chaotic-brexit-theresa-may_n_17248024.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/the-waugh-zone-special-queens-speech-2017_n_17246444.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-residents-to-be-rehoused-in-luxury-kensington-row-flats_n_17242518.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/gin-does-not-help-relieve-hay-fever-experts-say_n_17243102.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/theresa-may-savoy_n_17227558.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/crewe-crane-collapse_n_17243884.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/rebecca-burger-french-fitness-blogger-killed-by-exploding-cream-dispenser_n_17253286.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/05/31/the-waugh-zone-may-31-201_0_n_16891450.html?ir=UK+Politics', 'http://www.huffingtonpost.co.uk/2017/06/22/theresa-may-reveals-tests-show-other-towers-combustible-following-grenfell-tower-fire_n_17253204.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/owen-jones-gleefully-brands-daily-mail-an-open-sewer_n_17253464.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/laura-kenny-interview-ambition-after-pregnancy_n_17252498.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/boris-johnson-radio-4-eddie-mair-two-ronnies_n_17245044.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-homes-theresa-may_n_17246764.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/dup-pushover-deal_n_17253218.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/khan-remain-rights_n_17243656.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/love-island-zara-holland-sex-miss-great-britain_n_17242768.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/man-sent-home-from-work-wearing-shorts_n_17243276.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/courteney-cox-fillers-surgery-face_n_17252410.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/jeremy-corbyn-observed-protocol-by-not-bowing-to-the-queen_n_17240658.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/alexandra-shulman-british-vogue-good-morning-britain-the-queen_n_17253200.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/teaching-excellence-framework-results-universities-gold-ranking_n_17253426.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/prince-harry-slams-decision-to-make-him-walk-behind-princess-dianas-coffin_n_17253188.html?utm_hp_ref=uk']
for url in urls:
    print url
    text = get_text(url)
</code>```

The error:

```<code>---------------------------------------------------------------------------
ContentDecodingError                      Traceback (most recent call last)
<ipython-input-12-54bdf2585415> in <module>()
     21 for url in urls:
     22     print url
---> 23     text = get_text(url)

<ipython-input-12-54bdf2585415> in get_text(url)
      5
      6 def get_text(url):
----> 7     r = requests.get(url)
      8     soup = BeautifulSoup(r.content, "lxml")
      9     # delete unwanted tags:

/Applications/anaconda/lib/python2.7/site-packages/requests/api.pyc in get(url, params, **kwargs)
     68
     69     kwargs.setdefault('allow_redirects', True)
---> 70     return request('get', url, params=params, **kwargs)
     71
     72

/Applications/anaconda/lib/python2.7/site-packages/requests/api.pyc in request(method, url, **kwargs)
     54     # cases, and look like a memory leak in others.
     55     with sessions.Session() as session:
---> 56         return session.request(method=method, url=url, **kwargs)
     57
     58

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    486         }
    487         send_kwargs.update(settings)
--> 488         resp = self.send(prep, **send_kwargs)
    489
    490         return resp

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in send(self, request, **kwargs)
    628
    629         # Resolve redirects if allowed.
--> 630         history = [resp for resp in gen] if allow_redirects else []
    631
    632         # Shuffle things around if there's history.

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in resolve_redirects(self, resp, req, stream, timeout, verify, cert, proxies, **adapter_kwargs)
    188                 proxies=proxies,
    189                 allow_redirects=False,
--> 190                 **adapter_kwargs
    191             )
    192

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in send(self, request, **kwargs)
    639
    640         if not stream:
--> 641             r.content
    642
    643         return r

/Applications/anaconda/lib/python2.7/site-packages/requests/models.pyc in content(self)
    795                 self._content = None
    796             else:
--> 797                 self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
    798
    799         self._content_consumed = True

/Applications/anaconda/lib/python2.7/site-packages/requests/models.pyc in generate()
    722                     raise ChunkedEncodingError(e)
    723                 except DecodeError as e:
--> 724                     raise ContentDecodingError(e)
    725                 except ReadTimeoutError as e:
    726                     raise ConnectionError(e)

ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing: incorrect header check',))
</code>```

答:
I finally managed to solve this problem. I needed to use Selenium & PhantomJS before opening each url to allow the page to load properly.

This piece of code I added before creating my soup helped to solve the problem:

```<code>driver = webdriver.PhantomJS(executable_path='PATH TO phantomjs')
driver.get(url)
waitForLoad(driver)
html = driver.page_source
soup = BeautifulSoup(html, "lxml")
</code>```

I also used the function waitForLoad(driver): described in this O'Reilly book.

This is the final working code:

```<code>import codecs
import translitcodec
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import StaleElementReferenceException

def waitForLoad(driver):
    elem = driver.find_element_by_tag_name("html")
    count = 0
    while True:
        count += 1
        if count > 20:
            print("Timing out after 10 seconds and returning")
            return
        time.sleep(.5)
        try:
            elem == driver.find_element_by_tag_name("html")
        except StaleElementReferenceException:
            return

def get_text(url):
    driver = webdriver.PhantomJS(executable_path='PATH TO phantomjs')
    driver.get(url)
    waitForLoad(driver)
    html = driver.page_source
    soup = BeautifulSoup(html, "lxml")
    # delete unwanted tags:
    for s in soup(['h2', 'figure', 'script', 'style', 'table']):
        s.decompose()
    # use separator to separate paragraphs and subtitles!
    article_soup = [s.get_text(separator="\n", strip=True) for s in soup.find_all( 'div', {'class': 'content-list-component text'})]
    text = ' '.join(article_soup)
    text = codecs.encode(text, 'translit/one').encode('ascii', 'replace') #replace traslit with ascii
    text = u"{}".format(text) #encode to unicode
    print text
    return text

urls = ['http://www.huffingtonpost.co.uk/2017/06/21/damian-green-tories-housing-education_n_17244280.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/the-waugh-zone-thursday-june-22-2017_n_17253136.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/argos-toys-christmas-2017_n_17248026.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/ore-oduba-strictly-come-dancing-joanne-clifton_n_17253186.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/joanne-clifton-flashdance-strictly-come-dancing_n_17253268.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/grenfell-tower-cladding-may-have-released-hydrogen-cyanide_n_17252776.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/uk-will-have-to-trawl-through-19000-eu-laws-to-decide-which-ones-to-keep-after-brexit_n_17242732.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-theresa-may_n_17241446.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/piers-morgan-good-morning-britain-bbc-breakfast-dan-walker-ratings_n_17252222.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/worst-bridezilla-stories-ever-reddit_n_17253210.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/donald-trump-uk-state-visit-shelved-after-no-mention-in-queens-speech-2017_n_17239686.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/failure-may-state_n_17242710.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-13-things-missing-from-theresa-mays-first-one_n_17239692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/heartbroken-best-man-gatecrashes-bride-and-grooms-wedding-photos-and-its-comedy-gold_n_17253104.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-mocks-theresa-mays-imploding-minority-government_n_17242692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/asda-the-little-mermaid-swimsuit-topless_n_17253262.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/chaotic-brexit-theresa-may_n_17248024.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/the-waugh-zone-special-queens-speech-2017_n_17246444.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-residents-to-be-rehoused-in-luxury-kensington-row-flats_n_17242518.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/gin-does-not-help-relieve-hay-fever-experts-say_n_17243102.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/theresa-may-savoy_n_17227558.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/crewe-crane-collapse_n_17243884.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/rebecca-burger-french-fitness-blogger-killed-by-exploding-cream-dispenser_n_17253286.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/05/31/the-waugh-zone-may-31-201_0_n_16891450.html?ir=UK+Politics', 'http://www.huffingtonpost.co.uk/2017/06/22/theresa-may-reveals-tests-show-other-towers-combustible-following-grenfell-tower-fire_n_17253204.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/owen-jones-gleefully-brands-daily-mail-an-open-sewer_n_17253464.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/laura-kenny-interview-ambition-after-pregnancy_n_17252498.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/boris-johnson-radio-4-eddie-mair-two-ronnies_n_17245044.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-homes-theresa-may_n_17246764.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/dup-pushover-deal_n_17253218.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/khan-remain-rights_n_17243656.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/love-island-zara-holland-sex-miss-great-britain_n_17242768.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/man-sent-home-from-work-wearing-shorts_n_17243276.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/courteney-cox-fillers-surgery-face_n_17252410.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/jeremy-corbyn-observed-protocol-by-not-bowing-to-the-queen_n_17240658.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/alexandra-shulman-british-vogue-good-morning-britain-the-queen_n_17253200.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/teaching-excellence-framework-results-universities-gold-ranking_n_17253426.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/prince-harry-slams-decision-to-make-him-walk-behind-princess-dianas-coffin_n_17253188.html?utm_hp_ref=uk']
for url in urls:
    print url
    text = get_text(url)
</code>```

Body:
I have a list of URLs (from HuffPost UK) I need to get text from. I store them in a csv file but I just copy/pasted them below as a list. I have two problems with my code (which used to work fine with some other publishers...).

It randomly stops with ContentDecodingError.

It randomly fails to generate text.

I say randomly because when I run it several times it stops at different URLs. Sometimes it prints text, sometimes it prints an empty string for the same URL. I have no idea what is going on. Could anyone suggest what is wrong? I'll greatly appreciate your help.

My code:

import codecs
import translitcodec
import requests
from bs4 import BeautifulSoup

def get_text(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, "lxml")
    # delete unwanted tags:
    for s in soup(['h2', 'figure', 'script', 'style', 'table']):
        s.decompose()
    # use separator to separate paragraphs and subtitles!
    article_soup = [s.get_text(separator="\n", strip=True) for s in soup.find_all( 'div', {'class': 'content-list-component text'})]
    text = ' '.join(article_soup)
    text = codecs.encode(text, 'translit/one').encode('ascii', 'replace') #replace traslit with ascii
    text = u"{}".format(text) #encode to unicode
    print text
    return text

urls = ['http://www.huffingtonpost.co.uk/2017/06/21/damian-green-tories-housing-education_n_17244280.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/the-waugh-zone-thursday-june-22-2017_n_17253136.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/argos-toys-christmas-2017_n_17248026.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/ore-oduba-strictly-come-dancing-joanne-clifton_n_17253186.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/joanne-clifton-flashdance-strictly-come-dancing_n_17253268.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/grenfell-tower-cladding-may-have-released-hydrogen-cyanide_n_17252776.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/uk-will-have-to-trawl-through-19000-eu-laws-to-decide-which-ones-to-keep-after-brexit_n_17242732.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-theresa-may_n_17241446.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/piers-morgan-good-morning-britain-bbc-breakfast-dan-walker-ratings_n_17252222.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/worst-bridezilla-stories-ever-reddit_n_17253210.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/donald-trump-uk-state-visit-shelved-after-no-mention-in-queens-speech-2017_n_17239686.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/failure-may-state_n_17242710.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-13-things-missing-from-theresa-mays-first-one_n_17239692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/heartbroken-best-man-gatecrashes-bride-and-grooms-wedding-photos-and-its-comedy-gold_n_17253104.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-mocks-theresa-mays-imploding-minority-government_n_17242692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/asda-the-little-mermaid-swimsuit-topless_n_17253262.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/chaotic-brexit-theresa-may_n_17248024.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/the-waugh-zone-special-queens-speech-2017_n_17246444.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-residents-to-be-rehoused-in-luxury-kensington-row-flats_n_17242518.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/gin-does-not-help-relieve-hay-fever-experts-say_n_17243102.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/theresa-may-savoy_n_17227558.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/crewe-crane-collapse_n_17243884.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/rebecca-burger-french-fitness-blogger-killed-by-exploding-cream-dispenser_n_17253286.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/05/31/the-waugh-zone-may-31-201_0_n_16891450.html?ir=UK+Politics', 'http://www.huffingtonpost.co.uk/2017/06/22/theresa-may-reveals-tests-show-other-towers-combustible-following-grenfell-tower-fire_n_17253204.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/owen-jones-gleefully-brands-daily-mail-an-open-sewer_n_17253464.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/laura-kenny-interview-ambition-after-pregnancy_n_17252498.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/boris-johnson-radio-4-eddie-mair-two-ronnies_n_17245044.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-homes-theresa-may_n_17246764.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/dup-pushover-deal_n_17253218.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/khan-remain-rights_n_17243656.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/love-island-zara-holland-sex-miss-great-britain_n_17242768.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/man-sent-home-from-work-wearing-shorts_n_17243276.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/courteney-cox-fillers-surgery-face_n_17252410.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/jeremy-corbyn-observed-protocol-by-not-bowing-to-the-queen_n_17240658.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/alexandra-shulman-british-vogue-good-morning-britain-the-queen_n_17253200.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/teaching-excellence-framework-results-universities-gold-ranking_n_17253426.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/prince-harry-slams-decision-to-make-him-walk-behind-princess-dianas-coffin_n_17253188.html?utm_hp_ref=uk']
for url in urls:
    print url
    text = get_text(url)

The error:

---------------------------------------------------------------------------
ContentDecodingError                      Traceback (most recent call last)
<ipython-input-12-54bdf2585415> in <module>()
     21 for url in urls:
     22     print url
---> 23     text = get_text(url)

<ipython-input-12-54bdf2585415> in get_text(url)
      5
      6 def get_text(url):
----> 7     r = requests.get(url)
      8     soup = BeautifulSoup(r.content, "lxml")
      9     # delete unwanted tags:

/Applications/anaconda/lib/python2.7/site-packages/requests/api.pyc in get(url, params, **kwargs)
     68
     69     kwargs.setdefault('allow_redirects', True)
---> 70     return request('get', url, params=params, **kwargs)
     71
     72

/Applications/anaconda/lib/python2.7/site-packages/requests/api.pyc in request(method, url, **kwargs)
     54     # cases, and look like a memory leak in others.
     55     with sessions.Session() as session:
---> 56         return session.request(method=method, url=url, **kwargs)
     57
     58

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    486         }
    487         send_kwargs.update(settings)
--> 488         resp = self.send(prep, **send_kwargs)
    489
    490         return resp

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in send(self, request, **kwargs)
    628
    629         # Resolve redirects if allowed.
--> 630         history = [resp for resp in gen] if allow_redirects else []
    631
    632         # Shuffle things around if there's history.

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in resolve_redirects(self, resp, req, stream, timeout, verify, cert, proxies, **adapter_kwargs)
    188                 proxies=proxies,
    189                 allow_redirects=False,
--> 190                 **adapter_kwargs
    191             )
    192

/Applications/anaconda/lib/python2.7/site-packages/requests/sessions.pyc in send(self, request, **kwargs)
    639
    640         if not stream:
--> 641             r.content
    642
    643         return r

/Applications/anaconda/lib/python2.7/site-packages/requests/models.pyc in content(self)
    795                 self._content = None
    796             else:
--> 797                 self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
    798
    799         self._content_consumed = True

/Applications/anaconda/lib/python2.7/site-packages/requests/models.pyc in generate()
    722                     raise ChunkedEncodingError(e)
    723                 except DecodeError as e:
--> 724                     raise ContentDecodingError(e)
    725                 except ReadTimeoutError as e:
    726                     raise ConnectionError(e)

ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing: incorrect header check',))

Body:
I finally managed to solve this problem. I needed to use Selenium & PhantomJS before opening each url to allow the page to load properly.

This piece of code I added before creating my soup helped to solve the problem:

driver = webdriver.PhantomJS(executable_path='PATH TO phantomjs')
driver.get(url)
waitForLoad(driver)
html = driver.page_source
soup = BeautifulSoup(html, "lxml")

I also used the function waitForLoad(driver): described in this O'Reilly book.

This is the final working code:

import codecs
import translitcodec
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import time
from selenium.webdriver.remote.webelement import WebElement
from selenium.common.exceptions import StaleElementReferenceException

def waitForLoad(driver):
    elem = driver.find_element_by_tag_name("html")
    count = 0
    while True:
        count += 1
        if count > 20:
            print("Timing out after 10 seconds and returning")
            return
        time.sleep(.5)
        try:
            elem == driver.find_element_by_tag_name("html")
        except StaleElementReferenceException:
            return

def get_text(url):
    driver = webdriver.PhantomJS(executable_path='PATH TO phantomjs')
    driver.get(url)
    waitForLoad(driver)
    html = driver.page_source
    soup = BeautifulSoup(html, "lxml")
    # delete unwanted tags:
    for s in soup(['h2', 'figure', 'script', 'style', 'table']):
        s.decompose()
    # use separator to separate paragraphs and subtitles!
    article_soup = [s.get_text(separator="\n", strip=True) for s in soup.find_all( 'div', {'class': 'content-list-component text'})]
    text = ' '.join(article_soup)
    text = codecs.encode(text, 'translit/one').encode('ascii', 'replace') #replace traslit with ascii
    text = u"{}".format(text) #encode to unicode
    print text
    return text

urls = ['http://www.huffingtonpost.co.uk/2017/06/21/damian-green-tories-housing-education_n_17244280.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/the-waugh-zone-thursday-june-22-2017_n_17253136.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/argos-toys-christmas-2017_n_17248026.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/ore-oduba-strictly-come-dancing-joanne-clifton_n_17253186.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/joanne-clifton-flashdance-strictly-come-dancing_n_17253268.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/grenfell-tower-cladding-may-have-released-hydrogen-cyanide_n_17252776.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/uk-will-have-to-trawl-through-19000-eu-laws-to-decide-which-ones-to-keep-after-brexit_n_17242732.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-theresa-may_n_17241446.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/piers-morgan-good-morning-britain-bbc-breakfast-dan-walker-ratings_n_17252222.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/worst-bridezilla-stories-ever-reddit_n_17253210.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/donald-trump-uk-state-visit-shelved-after-no-mention-in-queens-speech-2017_n_17239686.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/failure-may-state_n_17242710.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-13-things-missing-from-theresa-mays-first-one_n_17239692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/heartbroken-best-man-gatecrashes-bride-and-grooms-wedding-photos-and-its-comedy-gold_n_17253104.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/queens-speech-2017-jeremy-corbyn-mocks-theresa-mays-imploding-minority-government_n_17242692.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/asda-the-little-mermaid-swimsuit-topless_n_17253262.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/chaotic-brexit-theresa-may_n_17248024.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/the-waugh-zone-special-queens-speech-2017_n_17246444.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-residents-to-be-rehoused-in-luxury-kensington-row-flats_n_17242518.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/gin-does-not-help-relieve-hay-fever-experts-say_n_17243102.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/20/theresa-may-savoy_n_17227558.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/crewe-crane-collapse_n_17243884.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/rebecca-burger-french-fitness-blogger-killed-by-exploding-cream-dispenser_n_17253286.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/05/31/the-waugh-zone-may-31-201_0_n_16891450.html?ir=UK+Politics', 'http://www.huffingtonpost.co.uk/2017/06/22/theresa-may-reveals-tests-show-other-towers-combustible-following-grenfell-tower-fire_n_17253204.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/owen-jones-gleefully-brands-daily-mail-an-open-sewer_n_17253464.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/laura-kenny-interview-ambition-after-pregnancy_n_17252498.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/boris-johnson-radio-4-eddie-mair-two-ronnies_n_17245044.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/grenfell-tower-homes-theresa-may_n_17246764.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/dup-pushover-deal_n_17253218.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/khan-remain-rights_n_17243656.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/love-island-zara-holland-sex-miss-great-britain_n_17242768.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/man-sent-home-from-work-wearing-shorts_n_17243276.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/courteney-cox-fillers-surgery-face_n_17252410.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/21/jeremy-corbyn-observed-protocol-by-not-bowing-to-the-queen_n_17240658.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/alexandra-shulman-british-vogue-good-morning-britain-the-queen_n_17253200.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/teaching-excellence-framework-results-universities-gold-ranking_n_17253426.html?utm_hp_ref=uk', 'http://www.huffingtonpost.co.uk/2017/06/22/prince-harry-slams-decision-to-make-him-walk-behind-princess-dianas-coffin_n_17253188.html?utm_hp_ref=uk']
for url in urls:
    print url
    text = get_text(url)


问:
Submit ajax form on enter press in textbox
I have a textbox that is my message textbox.
At the moment, my ajax form works by the click of a button.
Im guessing because the button's name.

I want it so that when I press enter in my textbox, it submits the form but without refreshing the page.

Adding some jquery on enter makes my page refresh.

Below is the code to my refreshing page current state.
My working state with a button is included with this form instead:

```<code>    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control" type="text" name="chat" id="chatbox" placeholder="Type something.." />
        <input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
    </form>
</code>```

My php script is :

```<code>    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control entryMsg" type="text" name="chat" id="chatbox" placeholder="Type something.." />
    </form>
</code>```

My Javascript  / Jquery is :`

```<code><script>
    // Javascript function to submit new chat entered by user
    function submitchat(){
            if($('#chat').val()=='' || $('#chatbox').val()==' ') return false;
            $.ajax({
                url:'chat/chat.php',
                data:{chat:$('#chatbox').val(),ajaxsend:true},
                method:'post',
                success:function(data){
                    $('#result').html(data); // Get the chat records and add it to result div
                    $('#chatbox').val(''); //Clear chat box after successful submition
                    document.getElementById('result').scrollTop=document.getElementById('result').scrollHeight; // Bring the scrollbar to bottom of the chat resultbox in case of long chatbox
                }
            })
            return false;
    };

    // Function to continously check the some has submitted any new chat
    setInterval(function(){
        $.ajax({
                url:'chat/chat.php',
                data:{ajaxget:true},
                method:'post',
                success:function(data){
                    $('#result').html(data);
                }
        })
    },1000);

    // Function to chat history
    $(document).ready(function(){
        $('#clear').click(function(){
            if(!confirm('Are you sure you want to clear chat?'))
                return false;
            $.ajax({
                url:'chat/chat.php',
                data:{username:"<?php echo $_SESSION['username'] ?>",ajaxclear:true},
                method:'post',
                success:function(data){
                    $('#result').html(data);
                }
            })
        })
    })
</script>
<script>
    $(document).ready(function() {
        $('.entryMsg').keydown(function(event) {
            if (event.keyCode == 13) {
                this.form.submit();
                return false;
             }
        });
    });
</script>`
</code>```

答:
from below code you can call ajax function after user press enter button

```<code>$('#msg').keypress(function(e){

        if(e.keyCode == 13){
            var keyword   = this.value;
            console.log(keyword);
            if(keyword.length>0){

                $.ajax({
                    url: 'aj_support_chat.php',
                    method: 'POST',
                    data: {holder: 'chat_start',type: 'in',keyword: keyword,},
                    success: function(res){
                        console.log(res)
                        return false;
                    }
                });
            }
        }
});
</code>```

you can also check entered text has some value or not

Body:
I have a textbox that is my message textbox.
At the moment, my ajax form works by the click of a button.
Im guessing because the button's name.

I want it so that when I press enter in my textbox, it submits the form but without refreshing the page.

Adding some jquery on enter makes my page refresh.

Below is the code to my refreshing page current state.
My working state with a button is included with this form instead:

    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control" type="text" name="chat" id="chatbox" placeholder="Type something.." />
        <input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
    </form>

My php script is :

    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control entryMsg" type="text" name="chat" id="chatbox" placeholder="Type something.." />
    </form>

My Javascript  / Jquery is :`

`

Body:
from below code you can call ajax function after user press enter button

$('#msg').keypress(function(e){

        if(e.keyCode == 13){
            var keyword   = this.value;
            console.log(keyword);
            if(keyword.length>0){

                $.ajax({
                    url: 'aj_support_chat.php',
                    method: 'POST',
                    data: {holder: 'chat_start',type: 'in',keyword: keyword,},
                    success: function(res){
                        console.log(res)
                        return false;
                    }
                });
            }
        }
});

you can also check entered text has some value or not


问:
Check if ALL elements of list A within list B
I have done my research, however all these techniques return true, i need them to return false.

```<code>print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True
</code>```

The lists I'm comparing have duplicate numbers

答:
I'm still uncertain what you're really asking. Let's go with:

```<code>A = [2,2]
B = [2,3,3]
</code>```

And the question being if you can make A by choosing without replacement out of B. That is, not only should the items in A be a subset of those in B, there must be at least as many of each in B as there are in A.

One way to test this is using collections.Counter:

```<code>from collections import Counter
countsA = Counter(A)
countsB = Counter(B)
difference = countsA - countsB # any extra items in A
print difference, not difference
</code>```

Output: Counter({2: 1}) False

Since collections are true if they contain anything, we can negate it for the False value you asked for. This difference can also be used to show exactly which items A had that couldn't be taken out of B, in this case 1 count of the item 2.

Body:
I have done my research, however all these techniques return true, i need them to return false.

print set([2, 2]).issubset([2, 3, 3]) #returns True
print set([2, 3, 3]).issuperset(set([2, 2])) #returns True
print all(x in {2, 3, 3} for x in [2, 2]) #returns True
print set([2, 2]) <= set([2, 3, 3]) #returns True

The lists I'm comparing have duplicate numbers

Body:
I'm still uncertain what you're really asking. Let's go with:

A = [2,2]
B = [2,3,3]

And the question being if you can make A by choosing without replacement out of B. That is, not only should the items in A be a subset of those in B, there must be at least as many of each in B as there are in A.

One way to test this is using collections.Counter:

from collections import Counter
countsA = Counter(A)
countsB = Counter(B)
difference = countsA - countsB # any extra items in A
print difference, not difference

Output: Counter({2: 1}) False

Since collections are true if they contain anything, we can negate it for the False value you asked for. This difference can also be used to show exactly which items A had that couldn't be taken out of B, in this case 1 count of the item 2.


问:
how to find out the configured maximum of java heap size?
I am working on windows system and configure the maximum of java heap size in my java application like this:

JavaOptions= -Xmx6G

in the .proberties file.

Question 1: How to verify that this change is taking place? is it possible from the cmd?

Question 2:  I know that I can configure the max java heap as 4G on 32bit system. What is the maximum on 64bit system? 8G?

答:
I don't have a Windows machine, but this should do it. tasklist | FIND "java"

There's no limit on 64-bit systems, it's only limited by your system memory.


问:
Angular: change value on input event
I have textarea. I try to restrict width of value to 10 symbols. I am trying to cut value on input event.

```<code><textarea [(ngModel)]="smsMessage" (input)="changeSMSMessage()"></textarea>

changeSMSMessage() {
  this.smsMessage = this.smsMessage.substr(0, 10);
  console.log(this.smsMessage);
}
</code>```

But it doesn't work. I see that value was cut in changeSMSMessage() method, but on UI I see not changed value.

Plunker

When I changed event from input to keyup, it starts work properly. All characters after the tenth are deleted.

So, could someone explain why is input event doesn't update value in textarea?

答:
You have several options :

1 - use the maxlength="10" tag of the text area :

```<code><textarea [(ngModel)]="smsMessage" maxlength="10"></textarea>
</code>```

2 - Use a reactive form control with a built-in validator :

3 - Control the input :

```<code><textarea [(ngModel)]="smsMessage" (change)="changeSMSMessage()"></textarea>

// TS
changeSMSMessage() {
    this.smsMessage = this.smsMessage.length > 10 ? this.smsMessage.substr(0, 10), this.smsMessage;
}
</code>```

Title: Angular: change value on input event

Body:
I have textarea. I try to restrict width of value to 10 symbols. I am trying to cut value on input event.

<textarea [(ngModel)]="smsMessage" (input)="changeSMSMessage()"></textarea>

changeSMSMessage() {
  this.smsMessage = this.smsMessage.substr(0, 10);
  console.log(this.smsMessage);
}

But it doesn't work. I see that value was cut in changeSMSMessage() method, but on UI I see not changed value.

Plunker

When I changed event from input to keyup, it starts work properly. All characters after the tenth are deleted.

So, could someone explain why is input event doesn't update value in textarea?

Body:
You have several options :

1 - use the maxlength="10" tag of the text area :

<textarea [(ngModel)]="smsMessage" maxlength="10"></textarea>

2 - Use a reactive form control with a built-in validator :

3 - Control the input :

<textarea [(ngModel)]="smsMessage" (change)="changeSMSMessage()"></textarea>

// TS
changeSMSMessage() {
    this.smsMessage = this.smsMessage.length > 10 ? this.smsMessage.substr(0, 10), this.smsMessage;
}


问:
How to set my .apk file to run on different screen resolution in android?
I am using a "WVGA800" for my app. I try to run it on different resolution screens. It it is not perfectly scratching in that resolution .
I read and implement issues form this link.
http://developer.android.com/guide/practices/screens_support.html
But still not result. Please let me know if any one hase a perfect solution.
Main issue are that I am fixing hight & width of Image, textsize etc. When these are displayed
to screen of "WVGA800". But when I test them on "HVGA", "QVGA" then problem arise.
I want to avoid the "if else" conditions by getting the screen resolution at Runtime. If any one hase any solution for this...let me know. Thanks in advance.
I am also wondring when there will be new devices with new screen resolutions? </p>

答:
Main issue are that I am fixing hight & width of Image, textsize etc

Don't do that.


问:
cout value without touching variable C++
When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value.
What can be the explanation behind it?

```<code>#include<iostream>
using namespace std;

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}
</code>```

答:
When you print the addresses of a and b, that forces the variables to actually have a memory address. Otherwise a value might be stored in a register, or not at all if never used.

It is a very common optimization for compilers to transform

```<code>const int a = 9;
cout << a;
</code>```

into

```<code>cout << 9;
</code>```

and never store a anywhere.

And anyway, there are no rules saying where and in what order the variables are to be stored in memory. That is totally up to the compiler. So your assumption that &a == &b + 1 (or &b - 1) is not valid.

Body:
When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value.
What can be the explanation behind it?

#include<iostream>
using namespace std;

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}

Body:
When you print the addresses of a and b, that forces the variables to actually have a memory address. Otherwise a value might be stored in a register, or not at all if never used.

It is a very common optimization for compilers to transform

const int a = 9;
cout << a;

into

cout << 9;

and never store a anywhere.

And anyway, there are no rules saying where and in what order the variables are to be stored in memory. That is totally up to the compiler. So your assumption that &a == &b + 1 (or &b - 1) is not valid.


问:
HTML / CSS - Tree Layout / Flowchart Options
I have looked at the available libraries that are available and none seem to do exactly what I want.

I want to be able to produce a tree layout/flow chart which is horizontal.

Here is a very basic image:

Each box will have a parent and it needs to be able to flow automatically as I provide the data.

Another sample is this:

答:
that's a screenshot of pyhole!

That was done using KineticJS, a defunct project that provides abstraction on top of HTML canvas. Each oval was positioned manually/absolutely by doing a little math on the layout of the map/chain.


问:
Where can I find the API KEY for Firebase Cloud Messaging?
I am trying to figure out how the new version of GCM or Firebase Cloud Messaging works so I moved one of my projects to the new Firebase console, If I did not have the API KEY or I want to create a new one... where can I do it?</p>

答:
STEP 1: Go to Firebase Console

STEP 2: Select your Project

STEP 3: Click on Settings icon and select Project Settings

STEP 4: Select CLOUD MESSAGING tab


问:
"'undefined' is not an object" from Native Module in React Native
I am getting the following error when trying to invoke a method in a Native Module:

'undefined' is not an object (evaluating 'ScaleController. updateScaleFromJSON')

My native module Objective-C files -

RCTScaleController.h:

```<code>#ifndef RCTScaleController_h
#define RCTScaleController_h

#import "RCTBridgeModule.h"

@interface RCTScaleController : NSObject <RCTBridgeModule>
@end

#endif /* RCTScaleController_h */
</code>```

RCTScaleController.mm:

```<code>#import "RCTScaleController.h"
#import "ScaleControllerObjC.h"
#import "RCTLog.h"

@implementation RCTScaleController

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(updateScaleFromJSON:(NSString *)jsonString)
{
    RCTLogInfo(@"About to send json: %@", jsonString);
    ScaleControllerObjC *scaleController = [[ScaleControllerObjC alloc] init];
    [scaleController updateScaleFromJSON:jsonString];
}
</code>```

Here it is being required in my JS file:

```<code>var ScaleController = require('react-native').NativeModules.RCTScaleController;
</code>```

And here it is being invoked causing the error:

```<code>ScaleController.updateScaleFromJSON (JSON.stringify (scale));
</code>```

I've followed the examples I've seen and not sure whats wrong here..

答:
For anyone in the future who comes across this issue and thinks that this error is a result of the native libraries not being linked properly during build time:
Follow Step 2 on the manual installation instruction of linking libraries

Click on your main project file (the one that represents the .xcodeproj) select Build Phases and drag the static library from the Products folder inside the Library you are importing to Link Binary With Libraries

the idea is to make sure that the custom native library is included when building the native libraries used by react-native.

Body:
I am getting the following error when trying to invoke a method in a Native Module:

'undefined' is not an object (evaluating 'ScaleController. updateScaleFromJSON')

My native module Objective-C files -

RCTScaleController.h:

#ifndef RCTScaleController_h
#define RCTScaleController_h

#import "RCTBridgeModule.h"

@interface RCTScaleController : NSObject <RCTBridgeModule>
@end

#endif /* RCTScaleController_h */

RCTScaleController.mm:

#import "RCTScaleController.h"
#import "ScaleControllerObjC.h"
#import "RCTLog.h"

@implementation RCTScaleController

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(updateScaleFromJSON:(NSString *)jsonString)
{
    RCTLogInfo(@"About to send json: %@", jsonString);
    ScaleControllerObjC *scaleController = [[ScaleControllerObjC alloc] init];
    [scaleController updateScaleFromJSON:jsonString];
}

Here it is being required in my JS file:

var ScaleController = require('react-native').NativeModules.RCTScaleController;

And here it is being invoked causing the error:

ScaleController.updateScaleFromJSON (JSON.stringify (scale));

I've followed the examples I've seen and not sure whats wrong here..