text:
Q: .NET Core add Claim after AzuerAD Authentication My application signs in via AzureAD, but now I need to get information from the DB and then store the Role as a Claim.
So my question is: How can I store the Role as Claim after authentication ?
This is what I tried:
var user = User as ClaimsPrincipal;
var identity = user.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

But when I go to another controller, the claim does not exist anymore ?
Thanks

A: You can achieve that during the authentication , in OIDC middleware , OnTokenValidatedoffers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {
            //query the database to get the role

            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});

Then in controller , you can get the claim like :
var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;

A: In OnTokenValidated event, you can throw specific exception when user does not exists your database. and then OnRemoteFailure event redirect user to specific action method for that particular exception
options.Events = new OpenIdConnectEvents()
                 {
                     OnTokenValidated = async context =>
                     {

                         // get email claim
                         var emailClaim = context.Principal.Claims.SingleOrDefault(x => x.Type == ClaimTypes.Email);

                         UserEntity cu = null;

                         using (var accountService = context.HttpContext.RequestServices.GetService<IAccountService>())
                         {
                             cu = await accountService.Authorize(emailClaim.Value);
                         }

                         if (cu == null)
                         {
                             throw new UnauthorizedAccessException(string.Format("Could not find user for login '{0}' ", emailClaim.Value));
                         }

                         var newIdentity = new ClaimsIdentity(context.Principal.Identity.AuthenticationType);

                         // keep the id_token for logout
                         newIdentity.AddClaim(new Claim("id_token", context.ProtocolMessage.IdToken));

                         // add email claim
                         newIdentity.AddClaim(emailClaim);

                         // add email value as name claim
                         newIdentity.AddClaim(new Claim(ClaimTypes.Name, emailClaim.Value));

                         // add other claims here like roles

                         context.Properties.IsPersistent = true;
                         context.Properties.ExpiresUtc = DateTime.UtcNow.AddHours(3);

                         // overwrite existing authentication ticket
                         context.Principal = new ClaimsPrincipal(newIdentity);
                     },
                     OnRedirectToIdentityProviderForSignOut = async context =>
                     {
                         var idTokenHint = context.HttpContext?.User?.FindFirst("id_token");
                         if (idTokenHint != null)
                             context.ProtocolMessage.IdTokenHint = idTokenHint.Value;
                         await Task.FromResult(0);
                     },
                     OnRemoteFailure = async context =>
                     {
                         if (context.Failure is UnauthorizedAccessException)
                         {
                             context.Response.Redirect("/Account/UnAuthorized");
                         }
                         else
                         {
                             context.Response.Redirect("/Account/Error");
                         }
                         context.HandleResponse();
                         await Task.FromResult(0);
                     }
                 };

AccontController.cs
   public class AccountController : Controller
   {
        [AllowAnonymous]
        public IActionResult UnAuthorized()
        {
            HttpContext.Session.Clear();
            await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
            await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignOutAsync(HttpContext, OpenIdConnectDefaults.AuthenticationScheme);
        }
   }


text:
Q: Miro Video Problem I had a situation about subtitles on VLC. I wasn't able to solve it, then I decided to find another video player on Linux. I googled "Best Media players for Linux". I actually found several options, and MIRO was one of the best. I've installed it without any problems but it does not work or I did something wrong.
Miro opens every video/music I got, but there is only sound. I can't find video screen and it does not show any video screen. Also, when I try to search for a folder on my computer it is not listing MP4, MKV and AVI files.
Is there any solution for this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What VBA code options are there to group data into time buckets, copy it to another sheet, and loop for multiple parts (criterion) I have two files:
File#1 contains customer with demand information.  There are only three columns that matter to me:
Part#
Demand Qty
Demand Date
The file has thousands of lines.
File#2 is my own file which has more of an MRP setup:
columns are labeled with dates (weekly)
For each Part: There are the following rows:
Demand
Incoming Inventory
Net Inventory
My general idea was that I could somehow filter both files by part#, then have the code "sumif" the total demand by week, and copy it from the customer file to my file on the corresponding demand row.  Then loop this for all part #s.
Part #s are constantly being added/removed  in my spreadsheet(as new projects develop, and old ones phase out), so it would be ideal if the code didnt need to be maintenenced as my file is updated with new parts.

A: It seems like you could use a SUMPRODUCT formula to bring those numbers in without code.  This example uses two sheets in the same workbook so you'd have to adjust slightly for different workbooks.  In Sheet1 you have three ranges which I've named rngPartNum, rngDemandDate, and rngDemandQty.  I used dynamic range names that expand with the data, but you could use cell references that cover a sufficient number of rows.  The data looks like this
PartNum Demand Qty  DemandDate
1           18          3/28/2011
1           6           3/30/2011
1           6           4/2/2011
2           18          3/28/2011
2           6           3/30/2011
2           6           4/2/2011
2           16          3/28/2011
3           3           3/30/2011
3           15          4/2/2011
3           9           3/28/2011
3           18          3/30/2011

Sheet2 has a week-end date and a part number on each row.
Part    Week       Demand
1       4/1/2011    24
1       4/8/2011    6
1       4/15/2011   0
2       4/1/2011    40
2       4/8/2011    6
2       4/15/2011   0
3       4/1/2011    30
3       4/8/2011    15
3       4/15/2011   0

The formula in the demand column is this
=SUMPRODUCT((rngPartNum=A2)*(rngDemandDate<=B2)*(rngDemandDate>B2-7)*(rngDemandQty))

That sums everything in rngDemandQty where rngPartNum matches A2 AND rngDemandDate is less than or equal to B2 AND rngDemandDate is greater than a week before B2.  As long as you have every part number and enough weeks on your Sheet2, the total should match Sheet1.


text:
Q: How many subsets does $S_{n+1}$ have? $S_n$ has $2^n$ subsets?
I don't understand how $S_{n+1}$ should have $2^{n+1}$ subsets instead of $2^n + 1$ subsets.
$$S_{n+1} = \{s_1,s_2,\ldots,s_n, s_{n+1}\}$$
There is only 1 more elements! No?

A: Let's look at a simple example. The $2$-element set $S_2=\{0,1\}$ has four subsets: $\varnothing,\{0\},\{1\}$, and $\{0,1\}$. Now expand it to $S_3=\{0,1,2\}$. Here are the subsets:
$$\begin{array}{c|c}
\text{Already subsets of }S_2&\text{New subsets}\\ \hline
\varnothing&\{\color{red}{2}\}\\
\{0\}&\{0,\color{red}{2}\}\\
\{1\}&\{1,\color{red}{2}\}\\
\{0,1\}&\{0,1,\color{red}{2}\}
\end{array}$$
The number of subsets has doubled, not just increased by $1$. The reason is that we have all of the old subsets of $S_2$ and also the four sets obtained by adding the element $2$ to each of the old subsets.
The same idea works not just for $S_2$, but for any $S_n$.

A: Your $2^{n+1}$ means there are double the subsets, but you are seeing only one more, right?.
When you have a problem like this, try a small example and see if it helps.
The set $\{1,2\}$ has four subsets: $\{\}, \{1\}, \{2\}$ and $\{1,2\}$.  Now try listing the subsets of $\{1,2,3\}$.  There should be 8.

A: $S_0=\{\}$ has no elements, but $1$ subset, namely $\{\}$.
If $S_n$ has $P_n$ subsets, then $S_{n+1}$ has $2P_n$ subsets; it has the $P_n$ subsets that $S_n$ had, then for each of those $P_n$ subsets, it has another subset with the $n+1^{\text{st}}$ element as well. Thus, $P_{n+1}=2P_n$.
Putting these two statements together, we get that $P_n=2^n$.


text:
Q: Magento2: Error validating extension in marketplace I have developed a module for magento 2. Trying to submit in the marketplace its give the following errors:
Environment: Operating System - Centos 7, PHP Version - 7.0.21, Magento Platform - 2.0.17 CE Varnish, Sampla Data
Command:
vendor/bin/phpunit
Installation issue:
http://magento.dev/gear.html page doesn't contain HIT in cache header.
http://magento.dev/gear/bags.html page doesn't contain HIT in cache header.
http://magento.dev/gear/fitness-equipment.html page doesn't contain HIT in cache header.
http://magento.dev/gear/watches.html page doesn't contain HIT in cache header.
http://magento.dev/home page doesn't contain HIT in cache header.
http://magento.dev/enable-cookies page doesn't contain HIT in cache header.
http://magento.dev/privacy-policy-cookie-restriction-mode page doesn't contain HIT in cache header.
http://magento.dev/about-us page doesn't contain HIT in cache header.
http://magento.dev/customer-service page doesn't contain HIT in cache header.
http://magento.dev/gear/bags/joust-duffle-bag.html page doesn't contain MISS in cache header.   Show less

Environment: Operating System - Centos 7, PHP Version - 7.0.21, Magento Platform - 2.1.11 CE Varnish, Sampla Data
Command:
vendor/bin/phpunit
Installation issue:
http://magento.dev/gear.html page doesn't contain HIT in cache header.
http://magento.dev/gear/bags.html page doesn't contain HIT in cache header.
http://magento.dev/gear/fitness-equipment.html page doesn't contain HIT in cache header.
http://magento.dev/gear/watches.html page doesn't contain HIT in cache header.
http://magento.dev/joust-duffle-bag.html page doesn't contain HIT in cache header.
http://magento.dev/strive-shoulder-pack.html page doesn't contain HIT in cache header.
http://magento.dev/crown-summit-backpack.html page doesn't contain HIT in cache header.
http://magento.dev/wayfarer-messenger-bag.html page doesn't contain HIT in cache header.
http://magento.dev/home page doesn't contain HIT in cache header.
http://magento.dev/enable-cookies page doesn't contain HIT in cache header.
http://magento.dev/privacy-policy-cookie-restriction-mode page doesn't contain HIT in cache header.
http://magento.dev/about-us page doesn't contain HIT in cache header.
http://magento.dev/customer-service page doesn't contain HIT in cache header.
http://magento.dev/joust-duffle-bag.html page doesn't contain HIT in cache header.   Show less

A: This is caching validation issue in Magento 2. To resolve this remove <block class="Block\Class" name="blockname" cacheable="false" /> from the layout xml.
Never set $this->_isScopePrivate to true in the block. Both these breaks the cache and magento marketplace throws errors.
$this->_isScopePrivate = false from all the blocks.

Hopefully, it will resolve the issue


text:
Q: Event sourcing, replaying and versioning I am designing a system that uses Event Sourcing, CQRS and microservices. I am lead to understand this isn't an uncommon pattern. A key feature of the service needs to be the ability to rehydrate/restore from a system of record. Microservices will produce commands and queries on a MQ (Kafka). Other microservices will respond (events). Commands and queries will be persisted on S3 for purpose of auditing and restoring.
The current thought process was that, for the purposes of restoring the system, we could extract the event log from S3 and simply feed it back into Kafka.
However, this fails to acknowledge changes in both producers and consumers over time. Versioning at the command/query level seems to go some way toward solving the problem but I can't wrap my head around versioning consumers such that I could enforce that when a command, during a restore, is received and processed, it's the exact same [version of the] code that's performing the processing as it was the first time the command was received.
Are there any patterns I can use to solve this? Is anyone aware of other systems that advertise this feature?
EDIT: Adding an example.
A 'buyer' sends a 'question' to a 'seller' on my auction site. The flow looks as follows:

UI      -> Web App:           POST /question {:text text :to seller-id :from user-id}
Web App -> MQ:                SEND {:command send-question :args [text seller-id user-id]}
MQ      -< Audit:             <command + args appended to log in S3>
MQ      -< Questions service: - Record question in DB
                              - Email seller 'You have a question'

Now, as a result of a new business requirement, I adjust the 'Questions service' consumer, to persist a count of all unread questions. The DB schema is changed. We have had no notion of whether or not a question was read by the seller, until now. The last line becomes:

MQ      -< Questions service: - Record question in DB
                              - Email seller 'You have a question'
                              - Increment 'unread questions count'

Two commands are issues, one before the change, one after the change. The 'unread questions count' equals 1.
The system crashes. We restored by replaying the commands through the new code. At the end of the restore, our 'unread questions count' equals 2. Even though, in this contrived example, the result is not a catastrophe, the state that has been restored is not what it previously was.

A:
Commands and queries will be persisted on S3 for purpose of auditing and restoring.

For auditing, sure.  For restoring ?  That's weird, and likely to cause you headaches.
If you are going to be event sourcing, you want to be rehydrating state from events (things that happened in the past) not commands.  This saves you from most of the problems associated with changes to command implementation -- you only need to deal with the persisted state changes.
Versioning is still a concern.  In particular, you want to make sure that your persisted events are as supple as possible (DTOs representations, rather than direct serializations of the concepts in your domain).  When reading events from the store, you have an opportunity to update them as necessary prior to applying them to the rehydrating state.

A: First, it is important to understand and be able to leverage the difference between Commands and Events.
As this question succinctly points out, Commands are things we would like to happen, and Events are things that have already happened.  A command does not necessarily result in a significant event in the system, but it usually does. For example, a send message command may be rejected, in which case no event happens (typically an error would not be considered an event in this sense, though we may still choose to log it in a diagnostic log).  Now, if the send message command is accepted, the message sent event occurs, and event details could describe the sender, the receiver, and the content.
When we talk about the system state, we are actually discussing not a culmination of commands, but of events.  Only events reflect changes of state in the system. To draw from a life example, suppose I go to the local Publix supermarket and buy a Florida lottery ticket.  The command was "Buy Ticket" and the event was "Ticket issued." My next command then is to the lottery to draw my numbers for the PowerBall. The lottery is going to ignore my command (but I have no knowledge), and the event "PowerBall numbers chosen" takes place irrespective of my wishes.  If my numbers match, the event "Jackpot won" happens to me (and I think my command was heard).  If not, I realize my command was ignored.
From a historical perspective, the lottery is only interested in a subset of events. The lottery only cares that (a) a ticket was issued, (b) the numbers were chosen, and (c) the jackpot was won. Those are the items of interest. The act of purchasing the ticket, wanting to win, etc. are all irrelevant, as is what I do with my ticket after I lose. While the real world does change for mundane events, we only need to record those events which are significant to our system.
In theory, under an event-sourcing technique, a stream of events may be replayed from the beginning of time to arrive at the current state.  This relies upon the assumption that the underlying system conditions are constant and deterministic.  However, these assumptions are not valid in many systems.  The data associated with an event, as well as the types of events we are interested in, may change as our computer software evolves. In addition, it can be computationally expensive to re-compute the current state in response to every query.  For this reason, snapshots of the system state are often taken to represent known points in time, which most recent events can then be added to.
While it is still possible to replay an event stream across multiple versions, the amount of human effort involved in doing so is likely to be cost-prohibitive. Unless there is a justifiable reason to design that capability into the system, you are better off building your system to utilize snapshots.
Example in Question
In the example given in the question, the architecture is not truly event-based; it is command-based.  Replaying commands creates the system state.  This is an anti-pattern and should be fixed.  Instead, the primary events are:

*

*Buyer asks question

*Seller responds to question

Each of these events can be "replayed" to give the current state. For example, in the act of asking a question, the system behavior might be to email the seller and increment the unanswered question counter. This behavior can be changed; however, the fact that the question was asked does not.  Similarly, the system might decrement the unanswered question counter when the seller responds. This behavior is changable, but the fact that the seller responded is not.
Most event-sourcing systems would dynamically compute the count of unanswered questions by replaying the specific event stream in response to a query.


text:
Q: Cocoapod 0.38.0 and AFNetworking 2.5 AF_APP_EXTENSIONS compilation error My project has 9 targets :
- Prod
- Prod_app_extension_1
- Prod_app_extension_2
- Beta
- Beta_app_extension_1
- Beta_app_extension_2
- Dev
- Dev_app_extension_2
- Dev_app_extension_2

I'm using 0.38.2 cocoapod version and 2.5.4 AFNetworking.
I'm trying to use AFNetworking with cocoapod but I get the AF_APP_EXTENSIONS error while compiling. After searching for the solution on the web, I understand the problem and found that defining the 'preprocessor macros' AF_APP_EXTENSIONS can fix the problem.
But here is the struggle : By default, AF_APP_EXTENSIONS is correctly added into my 6 app_extensions. In the other hand, when I navigate through my Pods target, each Pods are separated :
- NSDate+TimeAgo
- AFNetworking
- iRate
- AppUtils
- Prod
- Prod_app_extension_1
- Prod_app_extension_2
- Beta
- Beta_app_extension_1
- Beta_app_extension_2
- Dev
- Dev_app_extension_2
- Dev_app_extension_2

In another project I made, all pods are generated this way :
- Prod
- Pods-Prod-NSDate+TimeAgo
- Pods-Prod-AFNetworking
- Pods-Prod-iRate
- Pods-Prod-AppUtils

- Prod_app_extension_1
- Pods-Prod_app_extension_1-NSDate+TimeAgo
- Pods-Prod_app_extension_1-AFNetworking
- Pods-Prod_app_extension_1-iRate

- Prod_app_extension_2
- Pods-Prod_app_extension_2-NSDate+TimeAgo
- Pods-Prod_app_extension_2-AFNetworking
- Pods-Prod_app_extension_2-iRate

- Beta
- Pods-Beta-NSDate+TimeAgo
- Pods-Beta-AFNetworking
- Pods-Beta-iRate
- Pods-Beta-AppUtils

- Beta_app_extension_1
- Pods-Beta_app_extension_1-NSDate+TimeAgo
- Pods-Beta_app_extension_1-AFNetworking
- Pods-Beta_app_extension_1-iRate

- Beta_app_extension_2
- Pods-Beta_app_extension_2-NSDate+TimeAgo
- Pods-Beta_app_extension_2-AFNetworking
- Pods-Beta_app_extension_2-iRate

- Dev
- Pods-Dev-NSDate+TimeAgo
- Pods-Dev-AFNetworking
- Pods-Dev-iRate
- Pods-Dev-AppUtils

- Dev_app_extension_1
- Pods-Dev_app_extension_1-NSDate+TimeAgo
- Pods-Dev_app_extension_1-AFNetworking
- Pods-Dev_app_extension_1-iRate

- Dev_app_extension_2
- Pods-Dev_app_extension_2-NSDate+TimeAgo
- Pods-Dev_app_extension_2-AFNetworking
- Pods-Dev_app_extension_2-iRate

I think this is why my 'preprocessor macros' AF_APP_EXTENSIONS isn't define into the 'AFNetworking' Pods target.
Here is my Podfile :
platform :ios, '7.0'

xcodeproj 'myProj.xcodeproj'

def generic_pods
    pod 'NSDate+TimeAgo'
    pod 'AFNetworking', '~> 2.0'
end

def app_pods
    pod 'iRate'
    pod 'AppUtils',
end

target "Prod" do
    generic_pods
    app_pods
end

target "Prod_app_extension_1" do
    generic_pods
end

target "Prod_app_extension_2" do
    generic_pods
end

target "Beta" do
    generic_pods
    app_pods
end

target "Beta_app_extension_1" do
    generic_pods
end

target "Beta_app_extension_2" do
    generic_pods
end

target "Dev" do
    generic_pods
    app_pods
end

target "Dev_app_extension_1" do
    generic_pods
end

target "Dev_app_extension_2" do
    generic_pods
end

I don't know what the problem is, and it's driving me crazy.

A: Since 0.38.0 cocoapod version, pod target are De-duplicate. It means, instead of bulding an AFNetworking for each of your project target ('Pods-MyApp-AFNetworking', 'Pods-MyExtension-AFNetworking', ...) only one AFNetworking pod target is generated ('Pods-AFNetworking').
AFNetworking require 'AF_APP_EXTENSIONS' flag into the GCC_PREPROCESSOR_DEFINITIONS to compile when added to app-extensions.
Until the 0.37.2 cocoapod version, it was possible to add the flag from your project Podfile by adding a post-install routine :
post_install do |installer_representation|
    installer_representation.pods_project.targets.each do |target|
        if ar.include? target.name
            target.build_configurations.each do |config|
                config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)', 'AF_APP_EXTENSIONS=1']
            end
        end
    end
end

Unfortunatly, with the De-duplicate cocoapod feature, it's no longer possible to add the AF_APP_EXTENSIONS flag to the app extention pod targets separately.
The only way I found is to compile is to create a file : ~/.cocoapods/config.yaml (not present by default when you use cocoapod, you can create it with the terminal) with this content :
deduplicate_targets: false

This way, pods aren't not de-duplicated and you can post-install add the AF_APP_EXTENSIONS into your app extensions GCC_PREPROCESSOR_DEFINITIONS.
I just hope they will found a good way to prevent this problem.
references :
https://github.com/CocoaPods/CocoaPods/blob/master/CHANGELOG.md#highlighted-enhancement-that-needs-testing => cocoapod change log
https://github.com/CocoaPods/CocoaPods/issues/3794 => discussed issue


text:
Q: Sorting by two substrings of the same column with only one reversed I have a file that looks like this:
2836344588  ...  ...  N  fs1q
2836344589  ...  ...  N  fp2q
2836374222  ...  ...  N  fp3q
2836374223  ...  ...  N  fp6q
2836374224  ...  ...  N  fp7q
2836384836  ...  ...  N  fs2q
2836384837  ...  ...  N  fp1q
2836384838  ...  ...  N  fp4q
2836384839  ...  ...  N  fp5q
2836384957  ...  ...  N  fs3q
2836384958  ...  ...  N  fs7q
2836404416  ...  ...  N  fs5q
2836414186  ...  ...  N  fs6q
2836434267  ...  ...  N  fs4q

I would like to sort it by the second and the third characters of the fifth column: sorting on the second character should be done in reverse alphabetic order (s should come before p) and sorting on the third character should be done in a regular (i.e. non-reversed) numeric order.
I thought I could achieve this with:
sort -k5.2r -k5.3n

but this results in:
2836384958  ...  ...  N  fs7q
2836414186  ...  ...  N  fs6q
2836404416  ...  ...  N  fs5q
2836434267  ...  ...  N  fs4q
2836384957  ...  ...  N  fs3q
2836384836  ...  ...  N  fs2q
2836344588  ...  ...  N  fs1q
2836374224  ...  ...  N  fp7q
2836374223  ...  ...  N  fp6q
2836384839  ...  ...  N  fp5q
2836384838  ...  ...  N  fp4q
2836374222  ...  ...  N  fp3q
2836344589  ...  ...  N  fp2q
2836384837  ...  ...  N  fp1q

where sorting on the third character of the fifth column is also reversed.
How can I sort this file so that that reverse sorting happens only on the second character (all 's' lines come before all the 'p' lines) but not on the third character? In other words, how do I get to this desired output:
2836344588  ...  ...  N  fs1q
2836384836  ...  ...  N  fs2q
2836384957  ...  ...  N  fs3q
2836434267  ...  ...  N  fs4q
2836404416  ...  ...  N  fs5q
2836414186  ...  ...  N  fs6q
2836384958  ...  ...  N  fs7q
2836384837  ...  ...  N  fp1q
2836344589  ...  ...  N  fp2q
2836374222  ...  ...  N  fp3q
2836384838  ...  ...  N  fp4q
2836384839  ...  ...  N  fp5q
2836374223  ...  ...  N  fp6q
2836374224  ...  ...  N  fp7q

Many thanks in advance.

A: Because the reverse flag applies to all -k in that command, you could pipe it through two sort commands instead of trying to do them at the same time? (I saved the text in the file s.txt). It also worked better for me with the -b option...?
[I NEEDED the -s option as well to make it not keep sorting beyond the specified field.]
sort s.txt -n -k5.3,5.3 -b | sort -r -k5.2,5.2 -b -s

Output sorted by column 2 in reverse, then within that numerically (I modified the input file to be more variable). Needed to specify start and stop column with ,. So now in the 5th field, the second column in sorted t->p and the third column 1->9.
2836384837  ...  ...  N  ft1q
2836404416  ...  ...  N  ft5q
2836414186  ...  ...  N  ft6q
2836344588  ...  ...  N  bs1q
2836384836  ...  ...  N  fs2q
2836384957  ...  ...  N  fs3q
2836434267  ...  ...  N  fs4q
2836384958  ...  ...  N  cs7q
2836344589  ...  ...  N  fp2q
2836374222  ...  ...  N  fp3q
2836384838  ...  ...  N  bp4q
2836384839  ...  ...  N  fp5q
2836374223  ...  ...  N  ap6q
2836374224  ...  ...  N  fp7q

In this case, specifying the position twice and using the -s option will make sure it is limiting the sort to that column and not continuing to the end of the line.


text:
Q: how to find cosinus betwen two vector? i have task in linear-algebra.
Condition:
we have triangle angles
A(-4,2);
B(-1,6);
C(8,-3);

How to find cosinus between BA and BC vectors?
please help :( what is solution for this task?

A: The dot product gets you just what you want.  The dot product of two vectors $\vec u \cdot \vec v = |\vec u||\vec v|\cos \theta$ where $\theta$ is the angle between the vectors.  So  $\cos \theta =\frac{\vec u \cdot \vec v}{|\vec u||\vec v|}$.  The dot product is calculated by summing the products of the components $\vec {BA} \cdot \vec {BC} = -4 \cdot -1 + 2 \cdot 6=4+12=16$


text:
Q: LookupError: Resource omw-1.4 not found I'm working on the Kaggle competition, 'Feedback Essay Evaluation'.
The competition rules require me to submit the notebook on Kaggle's notebook with internet acccess disabled.
I need to use the NLTK library for one of my feature extraction algorithms, but when I submit the notebook it throws this error:
LookupError:
**********************************************************************
  Resource omw-1.4 not found.
  Please use the NLTK Downloader to obtain the resource:

  >>> import nltk
  >>> nltk.download('omw-1.4')

  For more information see: https://www.nltk.org/data.html

  Attempted to load corpora/omw-1.4

  Searched in:
    - '/root/nltk_data'
    - '/opt/conda/nltk_data'
    - '/opt/conda/share/nltk_data'
    - '/opt/conda/lib/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'

I have tried to download the nltk packages and uploading them to the input dataset of Kaggle, but the kernel doesn't recognize the package. I tried overwriting and linking it to the uploaded package but it doesn't work.
How can I download omw-1.4 with internet access disabled?


text:
Q: Conversion Tools, Layer to KML I have converted the GIS layer to KML.
When I open it in Google Earth, it opens my map in the sea.
What's wrong?

A: Could be one of two things;

*

*Check your layers coordinate systems, make sure that it's WGS84,
EPSG:4326 pre/post conversion. If this layer is a shapefile you
can see the projection in the .prj file (or in layer properties).

*If its point data and you're generating this layer yourself, make sure you
have the correct fields specified for lat/lon.


text:
Q: PHP Mailchimp API v3 , passing arguments other than fields ignored I cannot get the mailchimp api to return more than 10 items or "see" any query parameters.  The documentation lists the query parameters allowed but never shows an example, in php.
    //boilerplate
    $client = new MailchimpMarketing\ApiClient();
    $client->setConfig([
        'apiKey' => 'YOUR_API_KEY',
        'server' => 'YOUR_SERVER_PREFIX',
    ]);
    $client->lists->getListMembersInfo('xx_list_id_xxx',
["fields" => 'members.email_address,members.status,members.full_name,members.ip_signup,members.location.latitude,members.location.longitude,members.location.country_code',
"count" => 300]);

The above does not work as expected, but if I remove the 'count' entry it does.
I have also tried the named argument format is follows:
$client->lists->getListMembersInfo($list_id='xxxxx', $fields='members.email_address,members.status,members.full_name', $count=20);

Does anyone have any experience with the php mailchimp api that can give me some examples of how to send the query parameters?
PS: ping works fine, and my API_KEY and SERVER are correct


text:
Q: Inheriting class properties from parent class after initialize sets value Trying to make a component that will allow utilizing more than one payment gateway (Yes, I realize it's been done before).  I created a 'PaymentsComponent', and some gateway-specific components that extend it.
The problem is, I can't get the variables set/initialized in the parent component to be accessible in the child.  They ARE accessible, but only with the default value, not with the value after initializing.  What am I missing?
Within a Controller:
private function processPayment($requestData) {
    $this->Payments = $this->Components->load('Payments');
    $this->Payments->initialize($this);
    debug($this->Payments->apiSecretKey); // shows: '123456789'
    $result = $this->Payments->charge($requestData);
    //...
}

PaymentsComponent
<?php
App::uses('Component', 'Controller');
class PaymentsComponent extends Component {

    public $apiSecretKey = null;

    public function initialize() {
        $this->apiSecretKey = Configure::read('PaymentGateway.secret_key');
    }

    public function charge($data) {
        $result = $this->Authnet->charge($data);
    }
    // ...
}

Authorize.net Component
class AuthNetComponent extends PaymentsComponent {
    public $components = array('Session');
    public function charge($data) {
        debug($this->apiSecretKey); // shows: null
        // ...
    }
    // ...
}


text:
Q: Hooking sys_execve() on Linux 3.x I'm trying to hook the sys_execve() function on the Linux 3.x kernel by modifying the system call table. The problem is that sys_execve() is only supposed to return an error code if execution is unsuccessful. With the wrapper function that I'm using (see below), when sys_execve() is called on a valid executable, it executes fine and everything works out. However, when it's called on a nonexistent file or something else that causes an error condition, the calling program will crash with:
segfault at 3b ip 000000000000003b...

Using strace to examine the return value from the hooked sys_execve() shows -1 or ENOSYS instead of the correct error code, which confuses me since I've checked the assembly of my wrapper function as well as the Linux source code for sys_execve(). Any suggestions on why my wrapper isn't properly passing the error code?
asmlinkage long new_execve(const char* name, const char const** argv, const char const** envp, struct pt_regs* regs) {
    return orig_func(name, argv, envp, regs);
}

A: You can't hook execve by modifying the system call table in a such a way as on x86_64 the sys_execve is called from the stub_execve. So the call chain is sys_call_table[NR_execve] -> stub_execve -> sys_execve -> do_execve ... Take a look at stub_execve on LXR.

A: In the past, hooking syscalls in the Linux kernel was an easier task, however, in newer kernels, assembly stubs were added to the syscalls. In order to solve this problem, I patch the kernel's memory on the fly.
You can view my full solution for hooking sys_execve here: https://github.com/kfiros/execmon


text:
Q: How to write an SQL query to fetch the id in a column that has all the required data in some other column? Suppose I have the following table,
+---------+------------+
|   id    |    names   |
+---------+------------+
|   1     |      a     |
|   1     |      b     |
|   1     |      c     |
|   1     |      d     |
|   2     |      b     |
|   3     |      a     |
|   3     |      b     |
|   3     |      c     |
|   4     |      c     |
+---------+------------+

I want to fetch the id using SQL query, which has all the names "a", "b", and "c".
Here the answer would be 1 and 3.
Please edit the title more suitable for the question above.

A: Using GROUP BY and HAVING COUNT(DISTINCT names), you can get the expected result:
SELECT id
FROM TableName
WHERE names IN ('a', 'b', 'c')
GROUP BY id
HAVING COUNT(DISTINCT names) = 3

A: You can use group by and having.  Assuming no duplicates:
select id
from t
where names in ('a', 'b', 'c')
group by id
having count(*) = 3;

If duplicates are permitted, use:
having count(distinct name) = 3

A: I think this will better solve the problem
SELECT * from (SELECT id, GROUP_CONCAT( TRIM(names) ORDER BY names  SEPARATOR',') agg_name FROM table GROUP BY id)A where A.agg_name = 'a,b,c';


text:
Q: How to write a function that returns two variable from a dataframe So I am currently working on a project from school.
This is my dataframe.
Div Date    Time    HomeTeam    AwayTeam    FTHG    FTAG    FTR HTHG    HTAG    ... AvgC<2.5    AHCh    B365CAHH    B365CAHA    PCAHH   PCAHA   MaxCAHH MaxCAHA AvgCAHH AvgCAHA
0   E0  09/08/2019  20:00   Liverpool   Norwich 4   1   H   4   0   ... 3.43    -2.25   1.91    1.99    1.94    1.98    1.99    2.07    1.90    1.99
1   E0  10/08/2019  12:30   West Ham    Man City    0   5   A   0   1   ... 2.91    1.75    1.95    1.95    1.96    1.97    2.07    1.98    1.97    1.92
2   E0  10/08/2019  15:00   Bournemouth Sheffield United    1   1   D   0   0   ... 1.92    -0.50   1.95    1.95    1.98    1.95    2.00    1.96    1.96    1.92
3   E0  10/08/2019  15:00   Burnley Southampton 3   0   H   0   0   ... 1.71    0.00    1.87    2.03    1.89    2.03    1.90    2.07    1.86    2.02
4   E0  10/08/2019  15:00   Crystal Palace  Everton 0   0   D   0   0   ... 1.71    0.25    1.82    2.08    1.97    1.96    2.03    2.08    1.96    1.93
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
283 E0  07/03/2020  15:00   Wolves  Brighton    0   0   D   0   0   ... 1.74    -0.75   1.98    1.92    2.01    1.92    2.03    1.99    1.94    1.93
284 E0  07/03/2020  17:30   Burnley Tottenham   1   1   D   1   0   ... 1.74    0.00    1.95    1.95    1.96    1.97    2.00    2.01    1.94    1.92
285 E0  08/03/2020  14:00   Chelsea Everton 4   0   H   2   0   ... 2.13    -0.50   1.85    2.05    1.88    2.04    2.00    2.11    1.86    2.01
286 E0  08/03/2020  16:30   Man United  Man City    2   0   H   1   0   ... 1.97    0.75    1.87    2.03    1.85    2.07    1.91    2.11    1.87    2.01
287 E0  09/03/2020  20:00   Leicester   Aston Villa 4   0   H   1   0   ... 2.28    -1.00   1.85    2.05    1.88    2.05    1.91    2.08    1.86    2.01

I am asked to write a function that takes one row and returns two variable, number of points form the home team and the away team from the column FTHG and FTAG.
The project also added
The rules of point calculations is the following: If two teams score the same number of goals by the end of the game, each receives 1 point. Otherwise, the team that scores more goals, receives 3 points, while the losing team receives 0 points.
I am struggling with this question, currently I can't think of a way to came up with this question. Can anybody help me?

A: You can define a custom function and using with pandas.DataFrame.apply:
def give_point(row):

    if row['FTHG'] > row['FTAG']:
        row['PointsHG'] = 3
        row['PointsAG'] = 0

    elif row['FTHG'] < row['FTAG']:
        row['PointsHG'] = 0
        row['PointsAG'] = 3

    else:
        row['PointsHG'] = 1
        row['PointsAG'] = 1

    return row

df = df.apply(lambda row: give_point(row), axis=1)


text:
Q: How to display the output of function in a controller to nested view in angularjs I have a parent view index.html

Profile

Dashboard

In app.js
  var app = angular.module('myApp',['ui.router']);

   app.config(['$stateProvider', '$urlRouterProvider',function($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('profile', {
            url: "modules/profile/templates",
            templateUrl: "modules/profile/templates/profile.html",
            controller: 'ProfileController'
        }).state('dashboard', {
            url: "modules/dashboard/templates",
            templateUrl: "modules/dashboard/templates/index.html"
        }).state('profile.viewprofile', {
            url: "modules/profile/templates",
            templateUrl: "modules/profile/templates/viewprofile.html",
            controller: 'ProfileController'
        }).state('profile.createprofile', {
            url: "modules/profile/templates",
            templateUrl: "modules/profile/templates/createprofile.html",
            controller: 'ProfileController'
        });
    }
]);

This is my profile.html

Profile

View Profile

Create Profile

Edit Profile

in my ProfileController
app.controller('ProfileController',function($scope, $http){
        $scope.allProfiles = function(){
       $http.get('objects/getallprofiles.php').success(function (data, status, headers, config) {
    console.log(data);
    });
}

In console the data displayed is
Array
(
    [0] => Array
    (
        [id] => 1
        [0] => 1
        [fname] => sdds
        [1] => sdds
        [lname] => sddssd
        [2] => sddssd
        [mobile] => 333
        [3] => 333
    )
)

When I click on viewprofile in profile.html page the viewprofile.html is getting rendered. But, I want to get the values of the function allProfiles() to the child view viewprofile and bind them to html tags
How can I get the allProfiles() function output which is in controller to the child view viewprofile.html

A: You can bind data inside allProfile() function to some rootScope variable. Like this:
$scope.allProfiles = function(){
       $http.get('objects/getallprofiles.php').success(function (data, status, headers, config) {
      $rootScope.profiles=data;
    console.log(data);
    });

And then you can access this variable in any controller you want using $rootScope.
Don't forget to inject $rootscope in cotroller.
Another way of doing this is to store data in service and inject the service in a controller you want to access data.


text:
Q: Can you turn off usb protocol and use the USB port as a regular serial port? I am trying to make my pic16f84a micro controller communicate directly to my computer without a uart to usb bridge but I have been told that the way usb is handled wouldn't allow me to do that with such a slow micro controller. Is there any way to turn the USB port into a regular serial port so that I could bypass that restriction?

A: You will need a cable to connect the MCU up to the computer no matter what you do. If you were using USB transport end to end then obviously that would be a USB cable.
Since it appears that you want to use the UART out of the MCU to communicate and you do not want to put a UART to USB bridge IC on your circuit board then the solution you need is simply a different style of cable with the bridge chip built into the cable end. One that would do nicely is the TTL232R-3V3.

Picture Source

A: No. USB port uses USB protocol and can't function as a regular serial port. You need a separate USB to serial chip or a.microcontroller that has support for USB protocol.


text:
Q: Having trouble creating VMWare image from physical machine - memory being restricted to 880MB I have an old laptop I'm trying to create a VM image from.  I'm using the latest version of the VMware Converter app.
The machine is an Intel Core Duo with 1GB of RAM running WinXP Pro.
When I get to the "View/Edit Options" step in VMWare Converter there's a warning next to Memory.  The warning states:

The memory allocated for the destination machine has been set to the maximum supported for the guest operating system by the target host.  The allocated memory is less than the source memory setting.

It shows that the maximum amount of memory I can allocate is 880MB.
What does this error mean?  Why would the converter be restricting me to 880MB of RAM?  I know VMWare can handle more than that, as can WinXP.

A: You can't allocate more then 70% of physical memory to a virtual machine. Virtual Machine managers will give a warning since this will not leave enough physical memory for the host machine to run.
Virtual Machines are only allocated physical memory.
PS: The 70% I can't confirm at the moment but this has been my experience with most virtual machine managers. Hyper-V allows 80% on HyperVisor but only 60% when running on a full version of Server 2008. Others only allow up to 50% for example.
In your case the VM itself will be created as if you will be running it on the same machine acting as host.
Edit: The VM can still be created using the specified memory size. It is a warning only that the virtual machine may not run on that particular machine. I am not sure if this has changed in the newer VMWare converter.

A: The amount of memory assigned to the VM can be changed later, but I think that you already figured it out :).
I solved the blue screen issues after converting a physical machine to a virtual one by changing the virtual disk adapter from IDE to SCSI.
HTH!


text:
Q: How do I add sdk tools manually to android studio I downloaded android studio without sdk tools, but I have them already from the eclipse IDE
I want to manually place them where they should be, as when I open android studio it starts downloading the sdk tools automatically, but my data pack is running out, I can't download it!.
Where should I place the sdk tools folder in the android studio files, so that it doesn't attempt to install the sdk tools automatically and just launch the studio directly.

A: you can setup in first setting.. first time you opened android studio..
android studio will ask which sdk you will use

A: I reinstalled the software and added the sdk in install configuration process


text:
Q: How to remove few characters in VB.Net? So, how can I remove 7 or 6 characters in VB.net?
For example, I have this text in vb.net
Sherlock Holmes || tvn
Arsene Lupin || tf

I want to save the data to database, but only the name, like this
Sherlock Holmes
Arsene Lupin

I have tried this
txtBox.Text.ToString.TrimEnd(" ", "|", "t", "v", "n")
but the result always give me like this
Sherlock Holmes
Arsene Lupi

The n from Lupin is also missing.
So, How can I remove the characters?

A: You could use the Split function, which returns an array of string that become separated when removing a delimiter.  Then you could just grab the first element in that array that is returned.  For example:
txtBox.Text.ToString.Replace(" || ", "#").Split("#")(0)

A: For this time you can use .SubString() along with .IndexOf() So the snippet will be like this:
Dim input= "Sherlock Holmes || tvn"
Console.WriteLine("First output : {0}",input.Substring(0, input.IndexOf("||")))

Here is working example

A: You may use this,
Dim Str1 AS STRING = ""
Dim Str2 AS STRING = ""

Str1 = TextBox.Text 'Holds your textboxName

for i = 0 to Str1.length-1

    IF (STR1(i) = "|")
        Exit for
    END IF
STR2 = STR2 + Str1(i) 'Your new textbox name
next
'Now use STR2


text:
Q: How to measure change in altitude at high frequency with Apple Watch I am trying to measure changes in altitude with an Apple Watch in a sport activity (Kite Surfing). Currently my App is just collecting data for analysis. I am recording barometric and GPS altitude for comparison at a frequency of 10 measurements per second. Basically, it works and data is recorded, but it seems these data are just worthless. In both measurements there are sudden jumps in the dataset of up to +-10m and spikes in GPS readings of up to 75m. Does anyone have an idea how to get somehow accurate readings? I basically do not care about absolute altitude; I am just interested in the change of altitude.

A: Use startRelativeAltitudeUpdates(to:withHandler:) and when your done remember to stopRelativeAltitudeUpdates()
Here is a link to doc.
Also you can ignore anomalies. for example: if the max possible change in altitude in 100 milliseconds is 2 meters (72 km/h). Then if you see any changes more than 2 meters in 100 millisecond just ignore the data and wait for the next reading.
remember when you ignore one reading to account for the time difference.


text:
Q: Delete duplicate rows with Active flag false in Postgresql I have a table with columns "ID", "Name" , "Email" , "Active". I added some duplicate values to the table.

I want to delete duplicate rows with flag false not all rows with active flag false. In the table I want to delete 2nd row only.

A: You may try below co-related sub-query (Before actual delete, You might want to to see the result using SELECT query)-
DELETE FROM YOUR_TABLE T1
WHERE EXISTS (SELECT NULL
                FROM YOUR_TABLE T2
               WHERE T1.ID = T2.ID
                 AND T1.NAME = T2.NAME
                 AND T1.EMAIL = T2.EMAIL
                 AND T1.ACTIVE <> T2.ACTIVE)
  AND UPPER(T1.ACTIVE) = 'FALSE'

A: Try the below query:
DELETE t1 FROM tablename t1
INNER JOIN tablename t2
WHERE t1.id > t2.id AND t1.Name = t2.Name AND t1.Email =t2.Email AND t1.Active='FALSE'

A: DELETE FROM users T1
    USING users T2
WHERE  T1.ID <> T2.ID
    AND T1.Name = T2.Name
    AND T1.Email = T2.Email
    AND T1.Active = FALSE;

DEMO
CREATE TABLE IF NOT EXISTS users (
    ID serial PRIMARY KEY,
    Name VARCHAR ( 50 ) NOT NULL,
    Email VARCHAR ( 50 ) NOT NULL,
    Active BOOLEAN NOT NULL
);

INSERT INTO users(Name, Email, Active) VALUES
('John', 'john.gmail.com', TRUE),
('John', 'john.gmail.com', FALSE),
('Bob', 'bob.gmail.com', FALSE);

SELECT * FROM users;

DELETE FROM users T1
    USING users T2
WHERE  T1.ID <> T2.ID
    AND T1.Name = T2.Name
    AND T1.Email = T2.Email
    AND T1.Active = FALSE;

SELECT * FROM users;

A: DELETE FROM some_table
WHERE id IN (SELECT id FROM some_table GROUP BY id HAVING COUNT(*)>1)
  AND NOT active;


text:
Q: Auto Generate @String reference in Android Studio I know that this is possible in eclipse by following the advice here: Android: resource String automatic generation
But I can't seem to find if this is possible in android studio yet. Anybody know how to do this?
Basically I would like to take a hardcoded string and auto create a @string reference in my main values.xml or strings.xml.

A: alt+Enter work when your setting string resource is on,
how to on string resource extractor

Goto Android studio 'Help' -> Find action -> type "extract string resource"

You will find a ON / OFF button. Switch on the option.

A: What seems to be missing from the above answers is that, in Android Studio, you must place the cursor in the string, click the mouse, and press Alt + Enter to bring up the Extract String Resource dialog

A: Alt+Enter, Extract String Resource while the caret is inside the hardcoded string:

The same should work in XML files as well, and it does work in IntelliJ IDEA, but seems to be broken in the current version of the Android Studio:

Android Studio 0.1.3 shows the folded text in XML layouts that it extracts from the string resources, but it fails to navigate back to the resource and doesn't offer to extract resources from the hardcoded strings inside XML. It appears to be a bug.


text:
Q: Extract substring with regular expression, always None of re.match() I would like to extract some information from a string by regex, but the result is always None. The source code is as follows:
line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
x = re.match(r'property=".+?"',line)
print(x)

I want to extract content and property tuples, how can I fix it?

A: I would suggest something more suitable.
Using beautifulsoup:
from bs4 import BeautifulSoup

line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
soup = BeautifulSoup(line, 'lxml')

print("Content: {}".format(soup.meta["content"]))
print("Property: {}".format(soup.meta["property"]))

OUTPUT:
Content: Allrecipes
Property: og:site_name

A: The answer from @DirtyBit is better than using regex. But, if you still want to use regex, it may helps (RegexDemo):
line = '<meta content=\"Allrecipes\" property=\"og:site_name\"/>'
regex = re.search("content=\\\"(?P<content>.*)\\\".*property=\\\"(?P<prop>.*)\\\"\/>",line)
print (regex.groups())

Output:
('Allrecipes', 'og:site_name')


text:
Q: OpenNLP NameFinder Custom Feature generation I would like to train a own model to use in OpenNLP NameFinder.
Searched a lot and finally came up with a working code to train a model, but its not accurate. The documentation also says you need 15000 sentences to have a accurate model.
So you need to have 15000 sentences with a good context and at the name every time <START> <END>. To do this you would have to spend hours
days/months writing a .txt file.
I did some futher search to train a model without writing all by your self and came on Custom Feature generation of OpenNLP.
http://opennlp.apache.org/docs/1.8.1/manual/opennlp.html#tools.namefind.training.tool
But it says not much about how to use it. The documentation gives this :
AdaptiveFeatureGenerator featureGenerator = new CachedFeatureGenerator(
     new AdaptiveFeatureGenerator[]{
       new WindowFeatureGenerator(new TokenFeatureGenerator(), 2, 2),
       new WindowFeatureGenerator(new TokenClassFeatureGenerator(true), 2, 2),
       new OutcomePriorFeatureGenerator(),
       new PreviousMapFeatureGenerator(),
       new BigramNameFeatureGenerator(),
       new SentenceFeatureGenerator(true, false)
       });

Does somebody knows how to use this? Or much better, is someone already successful to train his own model for OpenNLP NER without typing him self the data set?
Thanks in advance.

A: You still need annotated training text. The feature generators are used during the training to create a better model. Unfortunately, there is no substitute for annotated training text.


text:
Q: how to make an entire row as a link using jquery in bootstrap

            S.no
            Name
            Points

            1
            random
            91

I have used the following code to add multiple rows using jquery
function tablename() {
    $(document).ready(function () {
        var tr = $("

");
        tr.addClass("clickable-row");
        tr.attr('data-href', 'link.html');
        for (i = 0; i < 3; i++) {
            var td = $("	").text("dilkush");
            tr.append(td);
        }
        $("tbody").append(tr);
    });
}
jQuery(document).ready(function ($) {
    $(".clickable-row").click(function () {
        window.document.location = $(this).data("href");
    });
});

the function "tablename()" is called after the body is been loaded ()...
in the table the all the fields are added but when I click over it  does not move to the next page...
I have used bootstrap you someone please figure out the error

A: You have to use event delegation for dynamically added elements
Instead of:
$(".clickable-row").click(function () {

Use .on() :
$(document).on('click', ".clickable-row", function () {

Even better practice is to add an id attribute to the table
 and then:
$('#my-table').on('click', ".clickable-row", function () {

A: The proper way to call function on body load is as below:

Do not keep $(document).ready() inside a named function. So either use function which could be called on body load or use $(document).ready without wrapping it in a function as below:
$(document).ready(function () {
        var tr = $("

");
        tr.addClass("clickable-row");
        tr.attr('data-href', 'link.html');
        for (i = 0; i < 3; i++) {
            var td = $("	").text("dilkush");
            tr.append(td);
        }
        $("tbody").append(tr);
});

Now since the element with classname clickable-row is added dynamically you need to do event delegation. Say your table has id= table1. Event delegation will be as follows:
$('#table1').on('click',".clickable-row",function () {
      window.document.location = $(this).data("href");
});

A: on click of table row class, assign the location href to clicked row href
$(".clickable-row").click(function(){
    location.href = $(this).data("href");
});

A: You need to bind your click event on the go.
Here is the fix.
$(".clickable-row").on('click',function () {
        window.document.location = $(this).data("href");
    });


text:
Q: VBA; Multiple footer and header allignment, How can I allgine left Center and right footer? I know that there are codes like:
 With ActiveDocument.Sections(i).Footers(wdHeaderFooterPrimary).Range
  .Text = myFooterValue1
  .ParagraphFormat.Alignment = wdAlignPageNumberLeft
  .Font.Size = 10 'size 10 font
 End With

But I want to add, left (company name) Right (Date) and Middle the page number.

A: You can do it with TabStops.
You need to work out the width of the page (minus the margins), add a center and right TabStop and separate your values by tabs.
Sub insertFooters()

    Dim pageWidth As Double, section As section

    For Each section In ActiveDocument.Sections
        With section.PageSetup
            pageWidth = (.pageWidth) - .LeftMargin - .RightMargin
        End With
        With section.Footers(wdHeaderFooterPrimary).Range
            .Text = "Left" & vbTab & "Center" & vbTab & "Right"
            With .ParagraphFormat
                .TabStops.ClearAll
                .TabStops.Add pageWidth / 2, Alignment:=WdAlignmentTabAlignment.wdCenter
                .TabStops.Add pageWidth, Alignment:=WdAlignmentTabAlignment.wdRight
            End With
            .Font.Size = 10
        End With
    Next

End Sub


text:
Q: How to install picasa with wine Whenever I try to install picasa with wine it get this,
mr-yeomans@mryeomans-Dell-DE051:~$ wine ~/picasa39-setup.exe
fixme:wininet:InternetLockRequestFile STUB
fixme:wininet:CommitUrlCacheEntryInternal entry already in cache - don't know what to do!
wine: Unhandled page fault on read access to 0x00000008 at address 0x7e5585e3 (thread 0029), starting debugger...
winedbg: Internal crash at 0x7e8685e3
mr-yeomans@mryeomans-Dell-DE051:~$

I don't know where to go on this.

A: The easiest way to do this is by using playonlinux. You can get it from Ubuntu software center. Then, open it, click install, in search enter picasa, and select it, and then click install. Follow the very simple instructions and play on linux will do the rest(set wineprefix, download the right version of wine, and you can even select to download pcasa automatically). For me, this is the easiest way. If you need further support, fell free to comment this post and ask.


text:
Q: Bulk change of URIs in RDF/OWL ontologies I am writing a program which cleans up ontology files (OWL files) which were created manually using Protege. The problem is that (among other issues) the manually created files have the wrong base URIs.
Is there a way to change the ontology file's base URI or should I change the URI of each individual independently? Could somebody guide me on how I could do that using Apache Jena?
example file:
<rdf:RDF
  xmlns="http://www.semanticweb.org/pnatsiavas/ontologies/input_ontology"
  xml:base="http://www.semanticweb.org/pnatsiavas/ontologies/input_ontology"
  ...
  xmlns:input_ontology="http://www.semanticweb.org/pnatsiavas/ontologies/input_ontology#"

  <owl:NamedIndividual rdf:about="http://www.semanticweb.org/pnatsiavas/ontologies/input_ontology#individual1">
  <rdf:type rdf:resource="http://www.semanticweb.org/pnatsiavas/ontologies/reference_ontology#Class1"/>
  </owl:NamedIndividual>
  ...

Could I change the http://www.semanticweb.org/pnatsiavas/ontologies/input_ontology URI to something else using Apache Jena? I would like to change the file's base URI to update all individuals of the ontology at once, but even if this is not possible, I should be able to change the URI of each individual separately (see the following snippet). Right? However, I cannot find a "setURI" method. Am I missing something?
List<Individual> individuals =
inputOntology.listIndividuals().toList();
for(Individual individual: inputOntology){
    individual.asNode().setURI(newURI); // setURI method does not exist
}


text:
Q: Showing that $f_n:[0,1]\to\mathbb{R}$ when $f_n=nx(1-x)^n$ converges pointwise but not uniformly Suppose $f_n:[0,1]\to\mathbb{R}$ such that $f_n=nx(1-x)^n$, then I need to show that $f_n$ converges pointwise but not uniformly. I can see that since $f$ is defined on $[0,1]$, the part $(1-x)^n$ is smaller than $1$ and therefore will converge, but what about $nx$? This will go to infinity...
Therefore, I can't even see that it converges pointwise, but let's suppose it converges to some function, how do I show that it doesn't converge uniformly? I should find an $\epsilon$ such that it's not valid for all $n>n_0(\epsilon)$ that $|f_n-something|<\epsilon$, right?

A: $f_n$ converges pointwise to the $0$ function. It is trivial to see it for $x=0,1$ so let $x\in(0,1)$ be fixed and notice that $$f_n(x)=nx(1-x)^n=xe^{n\log(1-x)+\log n}.$$
As $x>0$ we know that $\log(1-x)$ is a negative number, so $n\log(1-x)+\log n\to-\infty$ as $n\to\infty$; i.e. $f_n(x)\to0$ as $n\to\infty.$
So we know that $f_n$ converges pointwise to $0$ as $n\to\infty$.
To see that this convergence is not uniform let's first find the maximum of $f_n$. This polynomial is positive in $(0,1)$ and $0$ in $x=0,1$ so it must attain its maximum at some $x_n\in(0,1)$. As $\log x$ is an increasing function we can maximize $\log f_n$ instead of $f_n$. As
$$
\frac{d}{dx}\log f_n(x)=\frac{d}{dx}\left[\log n+\log x+n\log(1-x)\right]=\frac{1}{x}-\frac{n}{1-x}=\frac{1-x-nx}{x(1-x)}
$$
equals zero only for $x=\frac{1}{1+n}$, this is the only critic point of $f_n$ and therefore $x_n=\frac{1}{1+n}$. Now we are done because
\begin{align}
\sup_{0\leq x\leq1}f_n(x)=f_n(x_n)=&\frac{n}{1+n}\left(1-\frac{1}{1+n}\right)^n\\ =&\frac{n}{1+n}\underbrace{\left(1-\frac{1}{1+n}\right)^{-1}}_{=(1+n)/n}\left(1+\frac{-1}{1+n}\right)^{1+n}\underset{n\to\infty}{\to}e^{-1}>0.
\end{align}

A: Clearly $f_n(x)\to f(x)=0$ as $n\to\infty$ in [0,1]. Let $f_n'(x)=0$ and then $x=\frac{1}{n+1}$. It is easy to see that $f''_n(\frac{1}{n+1})<0$ and hence $f_n(x)$ reaches the maximum $f(\frac{1}{n+1})=(\frac{n}{n+1})^{n+1}$ at  $x=\frac{1}{n+1}$.
Thus
$$ \max |f_n(x)-f(x)|=(\frac{n}{n+1})^{n+1}\to\frac1e\neq0$$
as $n\to\infty$. Thus $f_n(x)$ does not converge uniformly to $0$.


text:
Q: Is the latest version of eclipse fully compatible with windows 10? So, I'm finally staring to consider updating my windows 7 PC to windows 10. However, I'd like to make sure that eclipse will continue to work. To be specific, is the latest version of the eclipse IDE for Java developers (64 bit) fully and completely compatible with the Windows 10 OS. Download link:http://www.eclipse.org/downloads/packages/eclipse-ide-java-developers/marsr
File: eclipse-java-mars-R-win32-x86_64.zip.

Thanks!
Edit:
Mostly looking for official confirmation from eclipse website, Microsoft, or oracle. Im also good with confirmation from someone who has personally used eclipse on windows 10. Just want to be sure! Otherwise if I can get enough resources that say it works that's fine.

A: I upgraded to Windows 10 about 3 weeks ago. I don't have an official confirmation from Eclipse or Microsoft, just writing from my own experience.
Eclipse is running fine, as long as you use it. There is just one bad thing that I noticed on Eclipse since I upgraded to Windows 10:
If you let Eclipse with a server running (I use Tomcat v8.0) through the night, the server, also Eclipse become unresponsive to the point that you have to force close both from the Task Manager.
I don't have any more information about this, since I just started searching for this issue, will update my answer for further info after I check the root cause for this.

A: Update:
After much use of eclipse in Windows 10, I would just like to put this information out there so everyone can see. It works fine, no bugs, no issues except for a minor problem. On high resolution laptop displays the icons become so small on native resolution that they are barely even usable. However, this can be easily fixed by temporarily changing screen resolution to 1920 * 1080.


text:
Q: remove elements within an iframe I have a VF page that embeds a dashboard inside of an iframe.  I'm not sure this is possible, but I am trying to use JQuery to hide a few elements in the dashboard page.  So, I was trying this:
<apex:includeScript value="{!URLFOR($Resource.JQuery, '/js/jquery-1.11.0.min.js')}" />
<script type="text/javascript">
    var j$ = jQuery.noConflict();

    j$(document).ready(function() {
        var f=j$("#iFrame");
        f.load(function() {
            f.contents().find(".viewHeaderValue").hide();
        });
    });
</script>

Initially, I didn't think this would be a cross domain scripting issue because the dashboard and the VF are within the same salesfore environment, but now, I'm wondering if cross domain scripting is the problem.
My VF page with the iframe has a domain of: https://c.na11.visual.force.com/apex/myVFpage
The domain of the dashboard which is in the same org that I'm embedding into the VF page has the following domain: https://na11.salesforce.com/
Is this a cross domain scripting issue?
Thanks.

A: The code you posted is fine, that is to say it contains no obvious mistakes or typos and works as expected when the two iframes are on the same domain.
I therefore conclude that either a) it is a cross domain scripting issue, or b) another factor is at play.
Chrome always complains when you violate the same origin policy, so why not open your page in Chrome and have a look at what your console is saying.


text:
Q: How to insert and call new data in wordpress website database through a plugin I have a dropbox button that user interact with it to get some data like video's id and video's name using Js code.
What I want to do is insert these data in the database using pair data structure and calling it in when it needed.
I found out that I can do this using add_metadata or add_options which one shoukd i use? and is there better sutiable way.
Second thing: I have the button here implemented through add_shortcode using a tag but I want to replace the tag with html class in the page because I've to to write the tag like [] to add the button.

A: The right place to store the data depends on how you will be using the data. From the context, it sounds like metadata might be the right place. There is usermeta if the data relates to one of your site users, or postmeta if the data relates to a specific post/page/CPT.
Options are best reserved for data that affects the site as a whole. So, if you were going to use the data to populate a video that appears sitewide, options would be an appropriate place to store the data. But the options table can tend to get bloated and impact site performance, so it's especially inappropriate if the data doesn't relate to the site as a whole, or a large part of the site.


text:
Q: Search using LIKE in a table I want to retrieve data of 'Match' and 'Average' columns from the following table if '2'
exists using LIKE.

I have tried by writing the following  query but it failed.
SELECT * FROM batsman_profile
WHERE (Match LIKE '%2%') AND (Average LIKE '%2%');
Can anyone help me how to retrieve data as I want.

A: In order to treat these numbers as a String you should use function CONVERT(varchar(10), field_name) like this:
SELECT *
FROM batsman_profile
WHERE (CONVERT(varchar(10), Match) LIKE '%2%')
       AND
      (CONVERT(varchar(10), Average) LIKE '%2%');


text:
Q: Tracking Concurrent Web Service Requests with Timestamps I have an ASP.NET 4.0 Web Service that accepts transmission of XML files.  In the past (with a different implementation of the same web service) we have tracked the concurrency (# of XML files being received/processed at the same time) using timestamps.  I have replicated this behavior in the new version of the web service as such:
In the constructor for the Web Service class I record ConnectionStartTime using HttpContext.Current.Timestamp
public class MyWebService : System.Web.Services.WebService
{
  public MyWebService()
  {
    ConnectionStartTime = HttpContext.Current.Timestamp
  }
}

After I'm done processing the XML file within the WebMethod I insert the file into a database (recording ConnectionEndTime) and return the response to the user.  I execute the database insert in a new Thread so the end user doesn't have to wait for the insert to occur to receive their response.
new Thread (() =>
  {
    insertIntoDatabase(ConnectionStartTime, ConnectionEndTime=Datetime.Now, xmlFile);
  }).Start();
return responseToUser;

Now I'm trying to gauge how many concurrent XML transmissions we've reached with two methods:
1. Performance Counters

*

*ASP.NET Apps v4.0\Requests Executing - This counter peaked at 52.

*ASP.NET Apps v4.0\Requests Queued - This counter peaked at 19.

To me this means I should see a point where we have 33 records with overlapping ConnectionStartTime and ConnectionEndTime.
2. Querying Against Timestamps
 - In this question I reference the query I'm using to calculate the number of concurrent transmissions based on ConnectionStartTime and ConnectionEndTime.  These are datetime fields in a SQL Server database.  Note: The query in that question is a reworked version of the algorithm we've been using for the past 3 years to determine concurrency so it may not be 100% correct but the other implementations of the algorithm (Excel macros, etc) have been validated.
My problem is that the two methods never align.  The maximum results from querying the timestamps hit 10 while the performance counters suggested the maximum should be 30+. I'm having a hard time locating where the discrepancy is.  Am I making a mistake in how I'm recording my timestamps?  Does the HttpContext.Current.Timestamp value not record the beginning of a transmission to the web service?

A: Using thread start WILL cause a discrepancy between your data and the ASP.NET counters (mainly because of the way you've written your thread function.  I would change it to:
DateTime EndTime = DateTime.Now
new Thread (() =>
{
    insertIntoDatabase(ConnectionStartTime, ConnectionEndTime=EndTime, xmlFile);
}).Start();
return responseToUser;

Not sure if it is the only source of a difference, but with your code you are measuring the time it takes to process the request AND spin up a thread and issue a command to the database to record the times.
My code measures the time to process the request only by capturing the endtime in a closure before spinning up the thread.  It should come out closer to the ASP.NET performance counters.  Not sure if it will account for the entire discrepancy, but it should help.
I agree with previous commenters that you shouldn't be starting a new thread with every request like this.  Spinning up new threads takes time and is very memory intensive.  If this is a high performance application it will definitely have an effect.   Using QueueUserWorkItem would be better, although using ThreadPool comes with its own set of concerns and limitations.
As a final comment, the pattern you are using has some other potential gotchas that will surface as your request rate increases (queuing, concurrency and bottleneck issues).  I'd bet that in your current implementation the discrepancy grows with the request rate.  If this is a high performance or performance sensitive application I would use a different approach to measuring concurrency entirely.


text:
Q: Retrieve or Access Phone Numbers from Facebook Contacts in Windows Phone 7 (WP7) When I try to access the contacts list in Windows Phone 7 using Contacts.SearchAsync, I get back a list of all the contacts on my phone.
However, iterating through the PhoneNumber property (list of ContactPhoneNumber's), it does not contain any phone numbers from facebook...
i.e., if the contact has 2 numbers in the "People" hub, one that was manually added to the phone or through Live, and another that got integrated directly from facebook, the facebook phone number doesn't show up in the PhoneNumber list for the contact.
Any thoughts on how to retreive the facebook contact phone number as well?
Here's my code:
public MainPage()
{
     Contacts myContacts = new Contacts();
     myContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(myContacts_SearchCompleted);
     myContacts.SearchAsync(String.Empty, FilterKind.None, "");
}

void myContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
     List<Contact> myContacts = e.Results.ToList<Contact>();
     int numbers = myContacts[1].PhoneNumbers.Count(); //Returns 0 if the contact was from facebook, returns 1 if the contact had a number from Live.
}

}

A: I'm pretty sure this is restricted on purpose by the operating system and you would need to request it as a feature on their user voice site.  You can't normally access friends phone numbers from the Facebook API (even if you created your own Facebook app) so I'm guessing Facebook made Microsoft restrict access to those values from third party apps.


text:
Q: Optimal Code Layout in Mathematica? I have now seen different elegant ways to layout code on this forum.
As a beginner, I would like to have your advises on the best way to layout code like the one below.
It is ugly,not optimal, probably even stupid, but may the expert programmers pardon me, I use it as a "worst case scenario".
The purpose for the novice I am is clarity.
rejection[disp_, fixationNOtoConsiderForDuration_, durationLimit_,
 minDistance_] :=

With[{fakedata = consider[t4dataLAEH10, 9, disp, {17, 18, 11}]},

With[{num =
 Flatten[Position[
   Take[fakedata[[All, 3]], fixationNOtoConsiderForDuration],
   x_ /; (x > durationLimit)]]},

If[num =!= {},
With[{fakedata1 = Drop[fakedata[[All, {1, 2}]], Last@num]},
 With[{num1 =
    Flatten[Position[
      Table[
       Sqrt[((fakedata1[[fixation1, 1]] -
           centerX)^2 + (fakedata1[[fixation1, 2]] -
           centerY)^2)],
       {fixation1, 1, Length@fakedata1}],
      x_ /; (x < minDistance)]]},

  If[num1 =!= {},
   Delete[fakedata1[[All, {1, 2}]], List /@ num1],
   fakedata[[All, {1, 2}]]]]],
With[{fakedata2 = fakedata[[All, {1, 2}]]},
 With[{num2 =
    Flatten[Position[
      Table[
       Sqrt[((fakedata2[[fixation2, 1]] -
           centerX)^2 + (fakedata2[[fixation2, 2]] -
           centerY)^2)],
       {fixation2, 1, Length@fakedata2}],
      x_ /; (x < minDistance)]]},
  If[num2 =!= {},
   Delete[fakedata2[[All, {1, 2}]], List /@ num2],
   fakedata[[All, {1, 2}]]]]]]]]

A: *

*In the case of your code above, I'd split the Flatten[Position[...]] out into a separate function.

*I'd also use a single scoping construct instead of a nested With.
like:
Block[{fakedata, fakedata1, fakedata2, num, result},
  fakedata = ...;
  num = ...;

  If[num =!= {},
    fakedata1 = ...;
    result = localPoints[fakedata1];
    ];

  num1 = ...;
  If[num1 =!= {},
    fakedata2 = ...;
    result = localPoints[fakedata2];
    ];

  result
  ]

*

*I don't like to use typesetting (subscripts, superscripts, square roots, etc...) in code, since for me that tends to be a text environment (whether it's Workbench, or email, or on the web, ...)  Anywhere else, it's fair game.

A: I have a saying, "don't be clever", meaning prefer clarity of code above other priorities when possible.  Some day someone will revisit this code and he or she will appreciate knowing what the code is doing.  This is related to formatting (format for clarity), but also nesting of function calls.  It's easy to write very nested incomprehensible code in Mathematica.  To keep things clear, I tend to use temporary or intermediate variables and break my long, nested function calls into little meaningful chunks.  Even if you reuse the variable, it's much easier to follow the steps or insert Print[]'s in there to see what's going on at each step.  Helper functions are good too.
From a formatting standpoint, I tend to format like this:
   If[test,
        expr1,
   (* ELSE *)
        expr2
    ]

My previous comments mean that I tend to have multiple lines instead of lots of long nested things which makes also makes formatting simpler.  Try to keep expr1 / expr2 to less than about 80 chars.  I think that's a reasonable length and decent test if it's getting too long.  These are just guidelines, and can and should be broken at times, but I think they're helpful and hope you find them helpful too.
* UPDATE *
This is how I would purely format this code.... Note the rather long lines...
rejection[disp_, fixationNOtoConsiderForDuration_, durationLimit_, minDistance_] :=
With[{fakedata = consider[t4dataLAEH10, 9, disp, {17, 18, 11}]},
    With[{num = Flatten[Position[Take[fakedata[[All, 3]], fixationNOtoConsiderForDuration], x_ /; (x > durationLimit)]]},

        If[num =!= {},
            With[{fakedata1 = Drop[fakedata[[All, {1, 2}]], Last@num]},
                With[{num1 = Flatten[Position[Table[Sqrt[((fakedata1[[fixation1, 1]] - centerX)^2 + (fakedata1[[fixation1, 2]] - centerY)^2)], {fixation1, 1, Length@fakedata1}], x_ /; (x < minDistance)]]},
                    If[num1 =!= {},
                        Delete[fakedata1[[All, {1, 2}]], List /@ num1],
                    (* ELSE *)
                        fakedata[[All, {1, 2}]]
                    ]
                ]
            ],
        (* ELSE *)
            With[{fakedata2 = fakedata[[All, {1, 2}]]},
                With[{num2 = Flatten[Position[Table[Sqrt[((fakedata2[[fixation2, 1]] - centerX)^2 + (fakedata2[[fixation2, 2]] - centerY)^2)], {fixation2, 1, Length@fakedata2}], x_ /; (x < minDistance)]]},
                    If[num2 =!= {},
                        Delete[fakedata2[[All, {1, 2}]], List /@ num2],
                    (* ELSE *)
                        fakedata[[All, {1, 2}]]
                    ]
                ]
            ]
        ]
    ]
]

More involved refactoring:
(* Try to put types on these variables. It'll be easier to identify what's going in *)
rejection[disp_, fixationNOtoConsiderForDuration_, durationLimit_, minDistance_] :=
Module[{fakedata, num1, fakedata1, num, fakedata2, num2},
    fakedata = consider[t4dataLAEH10, 9, disp, {17, 18, 11}];
    num = Flatten[Position[Take[fakedata[[All, 3]], fixationNOtoConsiderForDuration], x_ /; (x > durationLimit)]];
    If[num =!= {},
        fakedata1 = Drop[fakedata[[All, {1, 2}]], Last@num];
        num1 = Table[Sqrt[((fakedata1[[fixation1, 1]] - centerX)^2 + (fakedata1[[fixation1, 2]] - centerY)^2)], {fixation1, 1, Length@fakedata1}];
        num1 = Flatten[Position[num1, x_ /; (x < minDistance)]];
        If[num1 =!= {},
            Delete[fakedata1[[All, {1, 2}]], List /@ num1],
        (* ELSE *)
            fakedata[[All, {1, 2}]]
        ],
    (* ELSE *)
        fakedata2 = fakedata[[All, {1, 2}]];
        num2 = Table[Sqrt[((fakedata2[[fixation2, 1]] - centerX)^2 + (fakedata2[[fixation2, 2]] - centerY)^2)], {fixation2, 1, Length@fakedata2}];
        num2 = Flatten[Position[num2, x_ /; (x < minDistance)]];
        If[num2 =!= {},
            Delete[fakedata2[[All, {1, 2}]], List /@ num2],
        (* ELSE *)
            fakedata[[All, {1, 2}]]
        ]
    ]
]

There are more variables here than necessary, and I'm not happy with the num1/2=Table[] line. It's still a long and I'd probably either try to make a helper function out of it or use Normal[] which seems similar to what this code is trying to do.

A: I chose to do a full rewrite because the original is simply too far from my own style for me to format it as I would my own code.
I did not attempt to test this, so it is entirely possible something is broken, but I believe that most of it is correct.
I use Text Cells to describe the syntax of my functions.  I typically embed (* comments *) to explain the code, but if the explanations become very long, I move them to Text Cells as well.
I included a comment explaining func1.  It is not a very helpful comment, but it serves as an example.
Here is an image of my notebook at 75% magnification:

Cell expression for copy&paste:
Cell[CellGroupData[{Cell["Rewrite", "Subsection"],

Cell[TextData[{
 StyleBox["distance", "Program"],
 "[{",
 StyleBox["x1",
  FontSlant->"Italic"],
 ", ",
 StyleBox["y1",
  FontSlant->"Italic"],
 "}] gives EuclideanDistance from {x1, y1} to global {centerX, \
centerY}\n",
 StyleBox["distance", "Program"],
 "[{",
 StyleBox["x1",
  FontSlant->"Italic"],
 ", ",
 StyleBox["y1",
  FontSlant->"Italic"],
 "}, {",
 StyleBox["x2",
  FontSlant->"Italic"],
 ", ",
 StyleBox["y2",
  FontSlant->"Italic"],
 "}] gives EuclideanDistance from {x1, y1} to {x2, y2}"
}], "Text"],

Cell[BoxData[
 RowBox[{
  RowBox[{"distance", "[",
   RowBox[{"a_", ",",
    RowBox[{"b_:",
     RowBox[{"Hold", "@",
      RowBox[{"{",
       RowBox[{"centerX", ",", "centerY"}], "}"}]}]}]}], "]"}], ":=",
  RowBox[{"EuclideanDistance", "[",
   RowBox[{"a", ",",
    RowBox[{"ReleaseHold", "@", "b"}]}], "]"}]}]], "Input"],

Cell[TextData[{
 StyleBox["rejection", "Program"],
 "[",
 StyleBox["disp, fixation, durationLimit, minDistance",
  FontSlant->"Italic"],
 "]\n\nfilters data from ",
 StyleBox["t4dataLAEH10", "Program"],
 " according to:\n\t",
 StyleBox["disp",
  FontSlant->"Italic"],
 " : (description of argument disp)\n\t",
 StyleBox["fixation",
  FontSlant->"Italic"],
 " : (description of argument fixation)\n\t",
 StyleBox["durationLimit",
  FontSlant->"Italic"],
 " : (description of durationLimit)\n\t",
 StyleBox["minDistance",
  FontSlant->"Italic"],
 " : (description of minDistance)"
}], "Text"],

Cell[BoxData[
 RowBox[{
  RowBox[{"rejection", "[",
   RowBox[{
   "disp_", ",", "fixation_", ",", "durationLimit_", ",",
    "minDistance_"}], "]"}], ":=", "\[IndentingNewLine]",
  RowBox[{"Module", "[",
   RowBox[{
    RowBox[{"{",
     RowBox[{"fakedata", ",", "num", ",", "func1"}], "}"}], ",",
    "\[IndentingNewLine]",
    RowBox[{"(*", " ",
     RowBox[{"description", " ", "of", " ", "fakedata"}], " ", "*)"}],
     "\[IndentingNewLine]",
    RowBox[{
     RowBox[{"fakedata", "=",
      RowBox[{"consider", "[",
       RowBox[{"t4dataLAEH10", ",", "9", ",", "disp", ",",
        RowBox[{"{",
         RowBox[{"17", ",", "18", ",", "11"}], "}"}]}], "]"}]}], ";",
     "\[IndentingNewLine]", "\[IndentingNewLine]",
     RowBox[{"(*", " ",
      RowBox[{"description", " ", "of", " ", "num"}], " ", "*)"}],
     "\[IndentingNewLine]",
     RowBox[{"num", "=",
      RowBox[{"Position", "[",
       RowBox[{
        RowBox[{
         RowBox[{"fakedata", "\[LeftDoubleBracket]",
          RowBox[{"All", ",", "3"}], "\[RightDoubleBracket]"}], "~",
         "Take", "~", "fixation"}], ",",
        RowBox[{"x_", "/;",
         RowBox[{"x", ">", "durationLimit"}]}]}], "]"}]}], ";",
     "\[IndentingNewLine]", "\[IndentingNewLine]",
     RowBox[{"(*", " ",
      RowBox[{
       RowBox[{"func1", ":", " ",
        RowBox[{
        "Take", " ", "the", " ", "first", " ", "two", " ", "columns",
         " ", "of", " ", "fakedata"}]}], ",", " ",
       RowBox[{
        RowBox[{
         RowBox[{
         "and", " ", "drop", " ", "rows", " ", "specified", " ", "by",
           " ",
          RowBox[{
           StyleBox["dropspec",
            FontSlant->"Italic"], ".", "\[IndentingNewLine]",
           "Delete"}], " ", "any", " ", "rows", " ", "for", " ",
          "which", " ",
          StyleBox["distance", "Program"]}], " ", "<", " ",
         StyleBox["minDistance",
          FontSlant->"Italic"]}], ";", " ",
        RowBox[{
        "if", " ", "no", " ", "rows", " ", "are", " ", "deleted"}]}],
       ",", "\[IndentingNewLine]", "   ",
       RowBox[{
       "return", " ", "the", " ", "first", " ", "two", " ", "columns",
         " ", "of", " ", "fakedata"}], ",", " ",
       RowBox[{"ignoring", " ",
        RowBox[{"dropspec", "."}]}]}],
      StyleBox[" ",
       FontSlant->"Italic"], "*)"}], "\[IndentingNewLine]",
     RowBox[{
      RowBox[{"func1", "[", "dropspec_", "]"}], ":=",
      RowBox[{"Module", "[",
       RowBox[{
        RowBox[{"{",
         RowBox[{"part", ",", "fake"}], "}"}], ",",
        "\[IndentingNewLine]",
        RowBox[{
         RowBox[{"part", "=",
          RowBox[{"fakedata", "\[LeftDoubleBracket]",
           RowBox[{"All", ",",
            RowBox[{"{",
             RowBox[{"1", ",", "2"}], "}"}]}],
           "\[RightDoubleBracket]"}]}], ";", "\[IndentingNewLine]",
         RowBox[{"fake", "=",
          RowBox[{"part", "~", "Drop", "~", "dropspec"}]}], ";",
         "\[IndentingNewLine]",
         RowBox[{
          RowBox[{
           RowBox[{"If", "[",
            RowBox[{
             RowBox[{"#", "=!=",
              RowBox[{"{", "}"}]}], ",",
             RowBox[{"fake", "~", "Delete", "~", "#"}], ",", "part"}],
             "]"}], "&"}], "@", "\[IndentingNewLine]",
          RowBox[{"Position", "[",
           RowBox[{
            RowBox[{"distance", "/@", "fake"}], ",",
            RowBox[{"x_", "/;",
             RowBox[{"x", "<", "minDistance"}]}]}], "]"}]}]}]}],
       "]"}]}], ";", "\[IndentingNewLine]", "\[IndentingNewLine]",
     RowBox[{"If", "[",
      RowBox[{
       RowBox[{"num", "=!=",
        RowBox[{"{", "}"}]}], ",",
       RowBox[{"func1", " ", "@", " ",
        RowBox[{"num", "\[LeftDoubleBracket]",
         RowBox[{
          RowBox[{"-", "1"}], ",", "1"}], "\[RightDoubleBracket]"}]}],
        ",",
       RowBox[{"func1", "@", "0"}]}], "]"}]}]}], " ",
   "]"}]}]], "Input"]
}, Open  ]]


text:
Q: v-tooltip showing anywhere on screen. Not showing next to the v-icon after scrolling I am using vuetify version 2.3.10. The issue I am facing here is that the tooltip messages for the secong container shows any where on the screen rather than showing next to tooltip icon. For the first container it shows next to the icon. Please help me find where I am going wrong. Below is my code.
<template>
    <v-card class="mb-12">
      <v-form :model='user'>
        <v-container fluid>
          <v-layout row wrap>
            <v-flex xs12 md6 class="add-col-padding-right tip-align">
              <v-text-field
                      label='Name'
                      v-model='user.name'>
              </v-text-field>
              <v-tooltip attach=".tip-align" left>
                <template v-slot:activator="{ on, attrs }">
                  <v-icon class="icon-align" small slot="activator" dark color="primary">info</v-icon>
                </template>
                Please enter name.
              </v-tooltip>
            </v-flex>
            <v-flex xs12 md6 class="add-col-padding-left tip-align">
              <v-text-field
                      label='Address'
                      v-model='user.address'>
              </v-text-field>
              <v-tooltip attach=".tip-align" left>
                <template v-slot:activator="{ on, attrs }">
                  <v-icon class="icon-align" small slot="activator" dark color="primary">info</v-icon>
                </template>
                Please enter your address
              </v-tooltip>
            </v-flex>
          </v-layout>
        </v-container>
        <v-container fluid>
          <v-layout row wrap>
            <v-flex xs12 md6 class="add-col-padding-right tip-align">
              <v-text-field
                      label='Position'
                      v-model='user.position'>
              </v-text-field>
              <v-tooltip attach=".tip-align" left>
                <template v-slot:activator="{ on, attrs }">
                  <v-icon class="icon-align" small slot="activator" dark color="primary">info</v-icon>
                </template>
                Please enter position.
              </v-tooltip>
            </v-flex>
            <v-flex xs12 md6 class="add-col-padding-left tip-align">
              <v-text-field
                      label='Number'
                      v-model='user.number'>
              </v-text-field>
              <v-tooltip attach=".tip-align" left>
                <template v-slot:activator="{ on, attrs }">
                  <v-icon class="icon-align" small slot="activator" dark color="primary">info</v-icon>
                </template>
                Please enter your number
              </v-tooltip>
            </v-flex>
          </v-layout>
        </v-container>
      </v-form>
    </v-card>
</template>

A: I was able to replicate this issue on small screen where you need to scroll the content of the card. It might have something to do with your <v-tooltip attach=".tip-align"/> that attempts to attach the element that has a class of .tip-align. However, there are 4 elements (the <v-flex/> elements) that have the class of .tip-align and there might be a problem with that.
You can just remove the attach=".tip-align" prop since it will be attached to the default slot by default (to your <v-icon/> elements in your case).
P.S. If you're using Vuetify 2.x, you can improve your layout using <v-row/> and <v-col/>.
Here is a demo.


text:
Q: Using the AWS CDK bundler with resolved URL attributes I'm using the CDK bundler to build my static files (HTML, JavaScript), and upload them to an S3 bucket which is part of my deployment. However, my source files need to know the final URL they will be deployed at, since that will affect internal URLs. Therefore I try to pass in an environment variable derived from the API Gateway's URL.
const api = new apigateway.RestApi(this, 'restApi');
const staticRoute = api.root.addResource('static');
new s3deploy.BucketDeployment(this, 'DeployWebsite', {
    sources: [s3deploy.Source.asset("./path/to/source/files", {
        bundling: {
            image: cdk.DockerImage.fromRegistry("node:latest"),
            command: [
                'bash', '-c', `
            cd /asset-input \
            && npm install \
            && npm run build \
            && mv build/* /asset-output
    `,
            ],
            environment: {
                'PUBLIC_URL': api.urlForPath(staticRoute.path)
            }
        },
    })],
    destinationBucket: this.websiteBucket,
});

However, in practise this code doesn't work, because it just interpolates the CloudFormation tokens into the PUBLIC_URL variable, and I get something like 'https://${Token[TOKEN.380]}.execute-api.us-east-1.${Token[AWS.URLSuffix.10]}/${Token[TOKEN.399]}/static/', which obviously won't work. How can I resolve these tokens to actual string components at build time, which is when I compile my static content?

A: If you say build time, do you mean before the stack is executed? Because that is impossible. CDK uses these tokens, because it is not possible to have these values before you actually deploy the stack.
There are several options to work around this, you could for example split up the stacks, deploy the stack with the API GW and use the URL of the API as a parameter in your second stack. You could either just pass the URL along as a parameter, or you could combine the CDK with the aws-sdk in order to retrieve the necessary parameter. You could either retrieve it from the service itself, or define it as an output in the first stack and retrieve it that way.


text:
Q: Django with Vue on sub page in history mode I have been able to render a Vue app in a Django template when the django url is /. But in this case we want the Django url for the Vue page to be /dashboard. / is just a static Django page.
The issue is that the Vue page is showing, but the routes do not work. When I disable history mode, the routes work fine, even on /dashboard/#.
So in urls.py I added these lines at the end:
re_path(
    "^dashboard.*$",
    TemplateView.as_view(template_name="dashboard.html"),
    name="app",
),

in router.ts I have the following configuration:
import Vue from 'vue';
import Router from 'vue-router';
import Home from './views/Home.vue';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: `${process.env.BASE_URL}`,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
    },
  ],
});

I also tried to set base: '${process.env.BASE_URL}/dashboard' which didn't work either.
And vue.config.js has the following setup:
const BundleTracker = require('webpack-bundle-tracker');

module.exports = {
  baseUrl: 'http://0.0.0.0:8080',
  outputDir: './dist/',

  chainWebpack: (config) => {
    config.optimization
      .splitChunks(false);

    config
      .plugin('BundleTracker')
      .use(BundleTracker, [{ filename: '../frontend/webpack-stats.json' }]);

    config.resolve.alias
      .set('__STATIC__', 'static');

    config.devServer
      .public('http://0.0.0.0:8080')
      .host('0.0.0.0')
      .port(8080)
      .hotOnly(true)
      .watchOptions({ poll: 1000 })
      .https(false)
      .headers({ 'Access-Control-Allow-Origin': ['\*'] });
  },
};

That can I do to get the Vue app running on /dashboard in Django?

A: Not an expert, but here's what I did to get it to work...
In your router update the base to /dashboard/
export default new Router({
    mode: 'history',
    base: '/dashboard/',
    routes: [
    ...

In your urls.py you have to add two paths...
path('', TemplateView.as_view(template_name='dashboard.html')),
path('<path:path>', TemplateView.as_view(template_name='dashboard.html')),

This will allow your router to use /dashboard/ without hitting a new url


text:
Q: Why can binomial distribution for a binomial random variable S ... Why can binomial distribution for a binomial random variable S be approximated by a continuous normal distribution, in regards to convergence in probability and convergence in distribution?
We did not have time to cover this in lecture this week and it is one of my homework questions. If anyone could point me in the right direction I would greatly appreciate it!


text:
Q: Bind Textbox to model in MVC4 In my MVC application, I have specified two conditions based on the Model.Count to display the values in View.

View
  @model IEnumerable<SampleECommerce.Models.DetailsModel>
  @using (Html.BeginForm("Details", "Grid", new { UserID = Request.QueryString["UserID"], partnerid = Request.QueryString["Partnerid"] }, FormMethod.Post))
    {
    if (Model.Count() == 0)
    {
    @foreach (var item in Model)
    {

                    @Html.DisplayNameFor(model => model.FirstName)
                    <input id="FirstName" type="text" class="TextBoxBorder" name="FirstName" value="@item.FirstName" /> // When the Model count is zero, the label and textbox is not displayed.

    }
    else
    {
    @foreach (var item in Model)
    {

                    @Html.DisplayNameFor(model => model.FirstName)
                    <input id="MFirstName" type="text" class="TextBoxBorder" name="FirstName" value="@item.FirstName" />

    }

Controller
    public ActionResult Details()
       {
           string userid = Request.QueryString["UserID"];
           string partnerid = Request.QueryString["Partnerid"];

           con.Open();
           SqlCommand cmd = new SqlCommand("select FirstName from Details where UserID = +userid+", con);

       SqlDataReader dr = cmd.ExecuteReader();
       List<DetailsModel> objmodel = new List<DetailsModel>();
       while (dr.Read())
       {
           objmodel.Add(new DetailsModel()
           {
               FirstName = dr["First Name"].ToString(),

           });
       }
       dr.Close();

       return View(objmodel);
   }

When the Model.Count is zero, the label and textbox are not displayed.
I am trying to insert new value to textbox when the model.count is zero based on the userid

I tried to bind the textbox to model all the ways specified in the Link.

1. @Html.TextBoxFor(model => model.FirstName)
Error in FirstName stating "System.Collections.Generic.IEnumerable doesnot find definition for FirstName or no extension method "
2. @Html.TextBox(model=>model.FirstName)
"Error stating Cannot convert Lamba expression to string type"
How to bind and display the textbox value to the model when the model.count is zero.
Any suggestions ??

A: when the Model.Count is 0, foreach does nothing .
  @model IEnumerable<SampleECommerce.Models.DetailsModel>
  @using (Html.BeginForm("Details", "Grid", new { UserID = Request.QueryString["UserID"], partnerid = Request.QueryString["Partnerid"] }, FormMethod.Post))
    {

        if (Model.Count() == 0)
        {

                        @Html.DisplayNameFor(model => model.FirstName)
                        <input id="FirstName" type="text" class="TextBoxBorder" name="FirstName" /> // When the Model count is zero, the label and textbox is not displayed.

        }
        else
        {
                @foreach (var item in Model)
                {

                                @Html.DisplayNameFor(model => model.FirstName)
                                <input id="MFirstName" type="text" class="TextBoxBorder" name="FirstName" value="@item.FirstName" />

                }
        }

                <input type="submit" value="submit" />

    }


text:
Q: MockK spy on top-level private function in Kotlin I need to verify if bar function is called or not using MockK library.
MyFile.kt
fun foo() {
    bar()
}

private fun bar() { ... }

How can I mock the 'bar' function?
I am trying the following.
@Test
fun test() {
    mockkStatic("com.mypkg.MyFileKt")

    every { bar() } returns Unit

    foo()

    verify(exactly = 1) { bar() }
}

This gives compile-time error: Cannot access 'bar': it is private in file.
It works fine if I make the bar function internal. Probably I will have to spy on it but cannot find an example to do that.

A: Although I don't think it's a good idea to mock private methods, since they should most likely be tested in conjunction with the method calling them, MockK does support this:
https://mockk.io/#private-functions-mocking--dynamic-calls
So your code would look something like this:
class TheClass {
    fun foo() {
        bar()
    }

    private fun bar() {}
}

@Test
fun theTest() {

    val mock = spyk<TheClass>(recordPrivateCalls = true)
    every { mock["bar"]() } returns Unit

    mock.foo()

    verify(exactly = 1) { mock["bar"]() }
}


text:
Q: Migrated questions that got closed miss the close message The following question was migrated from superuser to stackoverflow, and got closed somehow.
How? this information doesn't there. I have know idea why it closed, except that it is.

A: Migrated questions are closed by definition.