text:
Q: Using Windows Domain accounts AND application-managed accounts It's easy to create an ASP.NET MVC application that authenticates based on windows domain user.  It's also easy to create one that uses individual accounts stored using Entity Framework.  In fact, there are project templates for both.
But I want to utilize BOTH kinds of authentication in the same application.  I tried to combine the code from both project templates.  I have a problem in Startup.Auth.cs.
// from "Individual Accounts" template
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

The existence of cookie authentication owin middleware seems to cause domain identities to become un-authenticated.  If I take this line out, the domain authentication works.  But without it, I can't seem to support individual user accounts.
I've downloaded the katana project source code and examined CookieAuthenticationHandler.cs, but I don't quite understand how it works in the context of an OWIN pipeline.
How can I use the ASP.net identity framework to allow my application to authenticate users from the windows domain OR an application-specific user store?

A: It's for this reason that I haven't been able to use pre-baked solutions for authentication. In our project, the passing years (and agile approach) have left us with 4 different ways to authenticate which is annoying, but we support all legacy versions of apps in the field so we have to preserve it all (at least for now).
I ended up creating a factory that figures out the authentication mechanism (through any of several means such as token format, presence of some other thing) and then returns a wrapper that carries the logic for validating that authentication method and setting the principal.
This gets kicked off in a custom HTTP module so that the principal is built and authenticated before the request gets to the controller. In your case, windows Auth would be the final fallback, I think. In our Web API application, we took the same approach but through a delegating handler instead of HTTP module. It's a type of local token federation, you could say. The current implementation allows us to add or modify any validation procedure, or add any other token format; in the end, the user ends up with a proper identity or gets denied. Only took a few days to implement.

A: It seems to me the best answer to this question is to use an authentication and authorization framework.  There are plenty to choose from (both commercial and free).  You could, of course, write your own but I would discourage it.  Lots of very smart people get this wrong.
I would take a look at IdentityServer3.  It's certainly not the only solution but its a pretty good authentication and authorization framework.  It's open source and pretty easy to get up and running in a hurry.  Your use case is a common one and you will find some very useful information at the link above. Clean separation between authorization and authentication, social authentication options, easy to work with json web tokens that encapsulate user claims, etc.
How it can help you
IdentityServer3 allows you to configure Identity Providers to handle authentication and there are plenty of extension points that will allow you to implement a chain of responsibility that can handle both of your scenarios.  From the docs:

IdentityServer supports authentication using external identity providers. The external authentication mechanism must be encapsulated in a Katana authentication middleware.
Katana itself ships with middleware for Google, Facebook, Twitter, Microsoft Accounts, WS-Federation and OpenID Connect - but there are also community developed middlewares (including Yahoo, LinkedIn, and SAML2p).
To configure the middleware for the external providers, add a method to your project that accepts an IAppBuilder and a string as parameters.

IdentityServer3 supports AD as an identity providor via a browser login window and will support a more programmatic implementation via a custom grant.  You can also take a look here for some more information on IdentityServer3 and AD authentication.
It will support windows authentication as well and you can take a look at here for information and examples on implementing that.
There is a pretty good getting started example here as well.
With the right configuration IdentityServer3 can handle your requirements.  You will need to implement your own authentication providers and plug them into the framework but there isn't much more to it than that.  As for authorization goes, there are plenty of options there as well.

A: The simplest approach is to have 2 different presentation Projects only for Authentication/Authorization.
This has the advantage of leaning on existing framework and standard configuration.
From there, you decide to either

*

*create an AD user for every internet user, or

*create a DB/Internet user for every AD user.

Creating an Identity user for each AD user is easier to implement further. Then the same cookies and filters can exist in the entire app.
In that case you can either

*

*use subdomain(s) for your app

*AD Authentiction Project can have the singular purpose of Authentication / Authorization, then the Web App can represent the rest of your app.

Alternatively, If you want a truly Unified Solution, use MohammadYounes/Owin-MixedAuth
MohammadYounes/Owin-MixedAuth
Install-Package OWIN-MixedAuth
In Web.config
<location path="MixedAuth">
  <system.webServer>
    <security>
      <authentication>
        <windowsAuthentication enabled="true" />
      </authentication>
    </security>
  </system.webServer>
</location>

In in Startup.Auth.cs
app.UseMixedAuth(cookieOptions);

:
:
How it works:
The handler uses ApplyResponseChallengeAsync to confirm the request is a 401 challenge. If so, it redirects to the callback path to request authentication from IIS which is configured to query the AD.
        AuthenticationResponseChallenge challenge = Helper.LookupChallenge(
              Options.AuthenticationType, Options.AuthenticationMode);

A 401 challenge is caused by an unauthorized users attempting to use a resource that requires Authentication
The handler uses InvokeAsync to check if a request is coming from a callback path (IIS) and then calls AuthenticateCoreAsync
    protected async override System.Threading.Tasks.Task<AuthenticationTicket>
                AuthenticateCoreAsync()
    {
        AuthenticationProperties properties = UnpackStateParameter(Request.Query);

        if (properties != null)
        {
            var logonUserIdentity = Options.Provider.GetLogonUserIdentity(Context);

            if (logonUserIdentity.AuthenticationType != Options.CookieOptions.AuthenticationType
                && logonUserIdentity.IsAuthenticated)
            {
                AddCookieBackIfExists();

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(
                    logonUserIdentity.Claims, Options.SignInAsAuthenticationType);

                //  ExternalLoginInfo GetExternalLoginInfo(AuthenticateResult result)
                claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier,
                  logonUserIdentity.User.Value, null, Options.AuthenticationType));

                //could grab email from AD and add it to the claims list.
                var ticket = new AuthenticationTicket(claimsIdentity, properties);

                var context = new MixedAuthAuthenticatedContext(
                   Context,
                   claimsIdentity,
                   properties,
                   Options.AccessTokenFormat.Protect(ticket));

                await Options.Provider.Authenticated(context);

                return ticket;
            }
        }
        return new AuthenticationTicket(null, properties);
    }

AuthenticateCoreAsync uses AddCookieBackIfExists to read the claims cookie created by AD and creates it's own Claims based.
AD users are provided a Claims based Cookie identical to Web Users. AD is now like any other 3rd party authenticator (Google, FB, LinkedIN)


text:
Q: Windows Domain Admin rights insufficient? I have a lab(ish) environment where I have a single domain in a single forest.  I have a Windows 7 image for the clients that was given to my by my organization (I didn't build it, not entirely sure who did) and I'm finding that there are a number of items that users (even admin users, even domain admin users) can't change in the Windows 7 environment, including but not limited to Trusted Sites in IE, Power Options (specifically, configuring when to lock the display), etc.  Those are the main two that I want to affect, but am presented the message that "some settings are controlled by your administrator.." that I've seen about a million posts about.
What I've tried so far
- Group Policies
- Registry settings
- Local Security Policies
- Unlocking the 'hidden' admin & using them
- Adding the users to the 'restricted group'
None of these seem to have an effect.  The Group policies are applied, and GPResult show the as I would expect.  As an example, I see a custom power profile that I applied in a GPO, and it even sets all the settings as I had it, except the 'disable display' setting, which is still set to what it was w/o my policy, and is still grayed out to prevent change.
Is there anything else I can look at to regain control over my client machines?
**** UPDATE ****
I didn't call it out before explicitly, but I have moved the computer into a new OU that doesn't inherit the GPO, and per suggestion I removed the machine from the domain.  The settings remained in place.  When that failed, I re-enabled the local admin and logged on as same to see if that would solve the issue, it did not. I suspected from the beginning that whatever the issue is was done at the image level, since all the workstations are built off the same image and (as demonstrated) it seems to be a setting that's neither set by the domain nor ignorable via group policies (at least not by means that I'm aware of)

A: The settings you "can't change" that give you the some settings are controlled by your administrator message are settings that are being controlled by GPO.
"Correcting" this involves stopping the GPOs that force these settings down from applying to the machine in question.  You mention that you have domain admin rights, so...
[If you haven't done it already, you'll want to use RSAT.]
What you probably should do is create a Testing OU in AD, using Active Directory Users and Computers (%SystemRoot%\system32\dsa.msc), and move this machine into it.  Then, using Group Policy Management (%SystemRoot%\system32\gpmc.msc), you'd want to block inheritance to that OU.  Since you just created it, there shouldn't be any GPOs linked in it directly.  Run gpupdate /force from a command line to apply the new [lack of] GPOs, and reboot.  Then you'll be free to change the settings you want, or test GPOs on the machine as you see fit (by creating and linking them in that OU you created).
Alternately, as a one-off approach, you could always remove the machine from the domain, which will stop the GPOs from being applied to it as well.
I suppose you could also just change/remove the GPOs in question, but that's a global change that would apply to more than just your machine, so be careful.  Also a great way to piss off your AD admin(s), if they exist, or discover why should have a professional admin handling your AD environment if they don't exist.
EDIT:  As pointed out by MDMarra, this won't magically reverse [most of] the settings applied by GPO, but will allow you to change them to what you want.  Changing them to what you want, after the GPOs are no longer applying, is a matter of using GPEdit.msc to edit the local policies, or using regedit to remove the following keys, as suggested here:
[HKEY_CURRENT_USER\Software\Policies\Microsoft]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Group Policy Objects]
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies]
(Apologies, I got focused in on how to "regain control" from the domain, and didn't think about reversing the applied GPOs.)

A: If the GPOs for these settings aren't defined on your domain, chances are that they are set in the Local Policy for the image.
Run gpedit.msc from the local machine and examine the settings there, I bet you'll find what you're looking for.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I correctly import an header and a footer page into a FreeMarker page? I am working on a Spring MVC application that use FreeMarker for my views.
I am absolutly new in FreeMarker and I have the following problem: in my projct I have 3 files that have to be assemblet togheter into a single page.
So I have:
1) header.ftl representing the header of all my pages, somthing like:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Registrazione -  MY WEBSITE</title>
        <meta name="robots" content="noindex,nofollow">

        <link rel="stylesheet" href="resources/css/webfont.css">
        <link rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css">
        <link rel="stylesheet" href="resources/bootstrap/css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="resources/plugins/bs-select/bootstrap-select.min.css">
        <link rel="stylesheet" href="resources/plugins/bs-dialog/bootstrap-dialog.min.css">
        <link rel="stylesheet" href="resources/css/style.css" />


text:
Q: disallow certain url in robots.txt We implemented a rating system on a site a while back that involves a link to a script. However, with the vast majority of ratings on the site at 3/5 and the ratings very even across 1-5 we're beginning to suspect that search engine crawlers etc. are getting through. The urls used look like this:
http://www.thesite.com/path/to/the/page/rate?uid=abcdefghijk&value=3

When we started we add the following to our robots.txt:
User-agent: *
Disallow: /rate

Is this incorrect or are googlebot and others simply ignoring our robots.txt?

A: You should use POST for actions which change things as search engine usually do not submit forms. Additionally, this will prevent users who download your website recursively (e.g. with wget) from submitting tons of votes.
Depending on your site, handling voting though javascript might be a solution, too.
Regarding your robots.txt:
It has to be in the root path - i.e. http://www.thesite.com/robots.txt - and if your rating system is at /blah/rate you need to use Disallow: /blah/rate instead of Disallow: /rate

A: User-agent: *
Disallow: /path/to/the/page/rate

You have to use the full path.
Might want to read up here a bit: http://www.javascriptkit.com/howto/robots.shtml

A: Looks incorrect to me. You're only disallowing access to http://www.thesite.com/rate (and pages below it IIRC). Plus some crawlers ignore robots.txt!
Better to make it so that ratings are only ever altered in response to a POST, rather than a GET. Search engines never use POST.


text:
Q: Hough Transformation OPENCV C++ http://inside.mines.edu/~whoff/courses/EENG512/lectures/HoughInOpenCV.pdf
Hi, i am going through the pdf tutorial in the link above.
I encounter problem on page 6 of the slides.
As we seee that the output of the code after inserting the canny edge detector, it should trace out all the edges on a photo.
I cannot get what is shown at page 6.
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{
    printf("Hello world\n");
// read an image
Mat imgInput = imread("a.png");
// create image window named "My Image"
namedWindow("My Image");

// Convert to gray if necessary
if (imgInput.channels() == 3)
    cv::cvtColor(imgInput, imgInput, CV_BGR2GRAY);

// Apply Canny edge detector
Mat imgContours;
double thresh = 105; // try different values to see effect
Canny(imgInput, imgContours, 0.4*thresh, thresh); // low, high threshold

// show the image on window
imshow("My Image", imgInput);
// wait for xx ms (0 means wait until keypress)
waitKey(5000);
return 0;
}

And also, there is a line double thresh = xxx;//try different values
What values should i put? and what are the values mean?
Thank you

A: Just replace your imshow function with ,
imshow("My Image", imgContours);
and you can use thresh value approximately around 200.
Change threshold value and see effect of it and according to that you can select your threshold value.

A: The imgContours is your output map with all the edges. You should use imshow with imgContours.
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char* argv[])
{
printf("Hello world\n");
// read an image
Mat imgInput = imread("a.png");
// create image window named "My Image"
namedWindow("My Image");

// Convert to gray if necessary
if (imgInput.channels() == 3)
    cv::cvtColor(imgInput, imgInput, CV_BGR2GRAY);

// Apply Canny edge detector
Mat imgContours;
double thresh = 105; // try different values to see effect
Canny(imgInput, imgContours, 0.4*thresh, thresh); // low, high threshold

// show the image on window
imshow("My Image", imgContours);
// wait for xx ms (0 means wait until keypress)
waitKey(5000);
return 0;
}

Reference:
http://docs.opencv.org/modules/imgproc/doc/feature_detection.html?highlight=canny#canny


text:
Q: Variadic Templated Factory Function I'm looking to create a "factory function" for a mathematical Vector class that is templated for size and type.  Here is the declaration of the class:
template<class T, std::size_t n>
class Vector {
  std::array<T, n> elements;

public:
  Vector();
  explicit Vector(std::array<T, n>& elements_);
  explicit Vector(const Vector<T, n>& v);
  explicit Vector(Vector<T, n>&& v);
  ~Vector() noexcept = default;
  Vector<T, n>& operator =(const Vector<T, n>& v);
  Vector<T, n>& operator =(Vector<T, n>&& v);
  T& operator [](std::size_t i);
};

The idea is that it is annoying to have to first create an array and then make a vector from it.  I want a variadic function called make_vector that takes n arguments of the same type T and returns a vector of that type and size.  Here is my attempt:
  template<class T, class... Ts>
  Vector<T, sizeof...(Ts) + 1> make_vector(T v1, Ts... args) {
    const std::size_t sz = sizeof...(Ts) + 1;
    std::array<T, sz> vals = {v1, args...};
    return Vector<T, sz>{vals};
  }

However, I get the following bewildering errors:
In file included from main.cpp:6:
In file included from ./oglmath.hpp:3:
In file included from ./vector.hpp:79:
./vector.tpp:14:31: warning: suggest braces around initialization of subobject
      [-Wmissing-braces]
    std::array<T, sz> vals = {v1, args...};
                              ^~~~~~~~
                              {       }
main.cpp:32:17: note: in instantiation of function template specialization
      'ogl::make_vector<float, float, float>' requested here
  vertices[0] = make_vector(-1.0f, -1.0f, 0.0f);
                ^
In file included from main.cpp:6:
In file included from ./oglmath.hpp:3:
In file included from ./vector.hpp:79:
./vector.tpp:15:12: error: no matching constructor for initialization of 'Vector<float,
      sizeof...(Ts) + 1>'
    return Vector<T, sz>{vals};
           ^~~~~~~~~~~~~~~~~~~
./vector.hpp:13:5: note: candidate constructor not viable: requires 0 arguments, but 1
      was provided
    Vector();
    ^
In file included from main.cpp:6:
In file included from ./oglmath.hpp:3:
In file included from ./vector.hpp:79:
./vector.tpp:42:12: error: non-const lvalue reference to type 'Vector<[2 * ...]>' cannot
      bind to a temporary of type 'Vector<[2 * ...]>'
    return Vector<T, n>(v);
           ^~~~~~~~~~~~~~~
main.cpp:32:15: note: in instantiation of member function 'ogl::Vector<float,
      3>::operator=' requested here
  vertices[0] = make_vector(-1.0f, -1.0f, 0.0f);
              ^
1 warning and 2 errors generated.

Really?  The only constructor it can find is the trivial one?  What's going on!?  I totally expected this to fail in a weird way if I tried to use different types in my Ts, but I was careful to make them all floats!  Also, why is it getting angry at my initialization of my std::array?  I tried adding the bracers, and it errored instead of warned.

A: We can't see your usage but we can tell that, in several places, your copy-initialisations rely on implicit conversion, where no such conversion is available.
explicit on a copy ctor is unusual; don't think I've ever seen a case in which it's desirable.
Remove explicit from the copy ctor.


text:
Q: What does "that's too fine" mean? I commented on Stack Overflow, and someone replied "that's too fine" to me.
What does this sentence mean?

A: It appears like they were trying to say "that is fine too" or, in other words, "that is also an acceptable way of doing it".
If they really meant "that's too fine" (which I really doubt), it would mean something like:

*

*that way of doing it is too satisfactory

That is just nonsensical. It is most likely a typo or a non-native English speaker. Looking at their other answers/comments, it would appear they are from a non-Enligh speaking country. See this other example:

where the brackets are needed

That is out of order, and should be: "where are the brackets needed?" That isn't the kind of mistake a lazy native speaker would make.
In a very different context, it could be understood as a compliment. But that is only for urban slang, and it only refers to attractiveness of another person (or body part).

That booty is too fine.

I feel embarrassed just typing that, but I figured you should know it could be said. That is definitely not what that user was trying to say though. That's just some trivia.

A: In an engineering discussion, "that's too fine" would refer to something like the thread pitch of a screw or a surface finish which can be defined as too fine for the purpose and thus unnecessarily expensive. In the context of that original post, I would too say he/she mean "that's also fine".


text:
Q: two pairs with same max sum in c Given an array a[].Find the two pairs (a,b) and (c,d) such that a+b==c+d.And the sum (a+b==c+d)value as maximum as possible we just have to print that sum value if it is forming the two pairs with same sum value else -1
Note->NO cpp only c language allowed which makes this problem more difficult for me
Example: N = 6, S[] = { 2, 3, 6, 4, 1, 5 } You can select pair of (6, 3) and (5, 4), two numbers can be same ,but same number can not be part of both pair.
My Thinking 1 -> I tried to make all possible pairs store the pairs sum in sorted array ,then i started searching form end to check if it is possible that we can find two teams with maxsum But unable to handle like case 0 0 1 1(which contain duplicates)
My Thinking 2 ->all ways to choose 1st, 2nd and 3rd student and check whether you have 4th one with skill equal to (S1+S2−S3)? And then choose maximum among all possible teams. But since n<=500 it will be O(n^4) can give TLE.
please help!

A: Let's use pairs (a, b) as being:

*

*a: the index of a number in the array

*b: the index of other number in the array (a != b)

Let's create a dictionary D to store lists of those pairs. If a pair (a, b) is such that S[a] + S[b] = 10, then (a, b) should be included in the list D[S[a] + S[b]].
That means that the key to find a pair in D is the sum of both elements represented by this pair in the original array.
If another pair (c, d) also satisfies S[c] + S[d] = 10, then (c, d) would be in the same list D[S[a] + S[b]].
We can iterate through the array and save all pairs in their correct lists:
for(int i = 0; i < |S| - 1; i++){
    for(int j = i + 1; j < |S|; j++){
        D[S[i] + S[j]].Add( new pair(i, j) );
    }
}

With your dictionary filled, you have a lot of lists of pairs whose sum (in the original array) is the same. For each key k (that represents a sum), ask if the length of the list D[k] is at least 2, which means there are at least 2 pairs holding that same sum. If it is, search for a two pairs in the list that don't have anyone in common, this will be your answer. Search from the biggest key to the smallest for better performance. This approach is O(n²).

A: A straightforward algorithm:
 1) Find all two-sized subset of the array and their sums (n(n-1)/2)
 2) Now, sort these \Theta(n^2) numbers in \Theta(n^2 log(n))
 3) Then traverse this list in descending order two find duplicates
 4) This duplicate value in sums could be reported as a result

Hence, the problem could be solved in \Theta(n^2 log(n)).


text:
Q: How do you get a list picker like the kind shown in the alarm clock? How do you create the big, scrolling list picker, like the kind that is created for datePicker and timePicker which is used on the WP7 default alarm clock?  The remaining list pickers don't have quite the same effect.  I would be using the list pickers only to choose integer values.
Thanks

A: The DatePicker and TimePicker are controls that are provided by the Silverlight Toolkit for WP7. What they actually do is present the selection in one control in your page, then navigate to a separate page that allows you to actually select a new date/time. In these separate pages they use a collection of LoopingSelector controls (one per item) that enable the user to select the parts of the date/time.
If you want to display a similar picker but for numeric values, then you need to implement the same infrstructure but using a single LoopingSelector and you need to provide the correct data source (that implements the ILoopingSelectorDataSource interface) that specifies the values for your control.
There is a great series of 3 posts on the LoopingSelector on WindowsPhoneGeek.com


text:
Q: Getting empty string after parsing bash associative array to json using jq I have a bash associative array containing dynamic data like:
declare -A assoc_array=([cluster_name]="cpod1" [site_name]="ppod1" [alarm_name]="alarm1")

I have to create the JSON data accordingly.
{
"name": "cluster_name",
"value": $assoc_array[cluster_name],
"regex": False
}
{
"name": "site_name",
"value": $assoc_array[site_name],
"regex": False
}
{
"name": "alert_name",
"value": $assoc_array[alert_name],
"regex": False
}

I have used the following code for it:
for i in "${!assoc_array[@]}"; do
    echo $i
    alarmjsonarray=$(echo ${alarmjsonarray}| jq --arg name "$i" \
                                                --arg value "${alarm_param[$i]}" \
                                                --arg isRegex "False" \
                                                '. + [{("name"):$name,("value"):$value,("isRegex"):$isRegex}]')
done
echo "alarmjsonarray" $alarmjsonarray

I am getting empty string from it. Can you please help me in it?

A: Assuming the ASCII record separator character \x1e can't occur in your data (and given your assertions that newlines will never be present), one way to handle this would be:
for key in "${!assoc_array[@]}"; do
  printf '%s\x1e%s\n' "$key" "${assoc_array[$key]}"
done | jq -Rn '
[
  inputs |
  split("\u001e") | .[0] as $key | .[1] as $value |
  {"name": $key, "value": $value, "regex": false}
]'

...feel free to change \x1e to a different character (like a tab) that can never exist, as appropriate.

A: #!/bin/bash
declare -A assoc_array=([cluster_name]="cpod1" [site_name]="ppod1" [alarm_name]="alarm1")
for i in "${!assoc_array[@]}"; do
  alarmjsonarray=$(echo "${alarmjsonarray:-[]}" |
                   jq --arg name "$i" \
                      --arg value "${assoc_array[$i]}" \
                      --arg isRegex "False" \
                      '. + [{("name"):$name,("value"):$value,("isRegex"):$isRegex}]')
done
echo "alarmjsonarray" "$alarmjsonarray"

array was supposed to be initialized before using it. I thought in bash, scope is there out of block also.
Its more simpler way to generate json from bash associative array.


text:
Q: how to get the position of the pattern in a string matched from the end $a = "this is school of sachin";
$pattern = "sch";

I want to get the position of the pattern matched from the end. For example in this case, sch matches school -- so the position of the pattern should be 3, i.e. from the end:
as mentioned below the index for the word school are arranged in this manner,so if the match of sch is successful than the position from the end of the word which is getting matched(school) and to the start of the pattern(from the end) should be returned.
s c h o o l
5 4 3 2 1 0

^---^

matched pattern.
I have tried strpos() but could not make it to serve my purpose.
echo strpos($a, $pattern); // this is wrong

The output of strpos() should be 3 according to my question.

A: <?php
$a = "this is school of sachin";
$pattern = "sch";
$words = explode(" ", $a);
$pattern = strrev($pattern);
foreach($words as $word){
$pos = strpos(strrev($word), $pattern);
    if($pos !== false){
    print($pos);
    break;
    }
}
?>

OR
<?php
$a = "this is sachinùs school of sachin";
$pattern = "sach";
if(preg_match("/[^ [:punct:]]*".$pattern."([^ [:punct:]]*)/u", $a, $match)){
print(mb_strlen($match[1], "UTF-8"));
    if($pattern == $match[0]){
    print(" (full word)");
    }
}
?>

A: Without the whole approach suggested by Sharanya
$haystack = 'this is a verygood school of sachin';
$pattern = 'sch';

$match = strstr($haystack, $pattern);

for ($i = 0;$i < strlen($match);$i++) {
    if ($match[$i] == ' ') {
        $match = substr($match, 0, $i);
        break;
   }
}
$result = strlen($match) - strlen($pattern);
echo $result;

Note that it will find the FIRST occurence starting from left, so for example 'schschool' would output 6.

A: NOTE - This also, tells you if the found word is full word or not
Take a look -  http://3v4l.org/i94Lr
  $pattern = "sch";
  $b = explode(' ','this is school of sachin');
  $b = array_reverse($b);
  for($i=0;$i < count($b);$i++){
     if(strpos($b[$i],$pattern) !== false){
       echo $i+1;
       $full = ', not a full word';
       if($b[$i] == $pattern){
         $full = ', full word';
       }
       echo $full;
       break;
     }
  }

A: Use a regular expression with word boundaries (\b) to find the word that matches the supplied pattern and then capture everything after the pattern using a capturing group. Then, simply return the length of that string:
$a = "this is school of sachin";
if (preg_match('/\b(sch(\w+))\b/', $a, $matches)) {
    echo strlen($matches[2]); // => 3
}

If you also want to account for non-English characters, then you  can use the u modifier:
$a = "this is sachinùs school of sachin";
if (preg_match('/\b(sch(\w+))\b/u', $a, $matches)) {
    echo strlen($matches[2]); // => 3
}


text:
Q: SharePoint 2010: Disable / Hide references to SPSDisco.aspx After upgrading some of our external websites running on SharePoint 2007 to 2010, we ran a link checker to find problems. We noticed the log showed requests for a file called spsdisco.aspx. Indeed, when examining the source of our web pages, SharePoint is adding the following link element to the page HEAD:
<link href="_vti_bin/spsdisco.aspx" rel="alternate" type="text/xml" />

This is a web service discovery file listing out the names and locations of all of SharePoint's web service endpoints. Even worse, this file is starting to show up in search indexes. At best it is embarrassing; at worst it's a potential vulnerability (these are external websites). Because it's a virtual file, it shows up under every site and subsite, so a manual approach to "hiding" each one is difficult and clumsy.
I can't seem to find any actual documentation about it -- a few references on updating it to include a custom web service, but that's about it. How might we approach a reliable, top-down approach to disabling access to these pages? I think we can find a way to suppress the LINK element in the page, but that's just obscuring the problem.
Is there a location in SharePoint (Site or Central Admin) to turn it off? Would you just add some request filtering to IIS to disallow access to SPSdisco.aspx and the ASMX files?

Update: On Kev's suggestion, I've cross-posted to sharepoint.stackexchange.com.

Update 2: See, I hadn't abandoned this question. We finally had time to get some MS guidance and build a deployable SharePoint solution to address the issue.

A: As a quick fix I would add a request filtering rule to deny access to SPSDisco.aspx.
But you might want to ask on the new SharePoint Stack Exchange site about a more robust fix:

https://sharepoint.stackexchange.com/

A: Here is the solution that we arrived at. It was in part based on recommendations by our Microsoft representative, so you might consider this an unofficial, "official" approach.
First, we need keep SharePoint from advertising the disco file to the world (i.e. Google). Simply remove the following line in your master pages:
<SharePoint:SoapDiscoveryLink runat="server"/>

This will suppress the <link href="/_vti_bin/spsdisco.aspx" rel="alternate" type="text/xml"> reference in the HEAD of your pages.
Next, we want to make sure that unauthorized users don't have access to the web services described by the disco file, or anything in _vti_bin for that matter. If your site only runs internal to your firewall (an intranet, for example), then this isn't as important. But if you've got anonymous endpoints that can be accessed externally, you want them locked down.
This is an excellent application for an HttpModule. We'll build one that intercepts any request containing _vti_bin in the path, and if the current user is unauthorized will return a 404 NOT FOUND status code. I chose to return a 404 rather than a 401 UNAUTHORIZED because I don't just want to lock those paths down, I want to hide the fact that anything even exists at those paths.
Our HttpModule looks like this:
using System;
using System.Web;

namespace Custom.SharePoint.HttpModule.SpSecureVtiBin {

    public class SpSecureVtiBinModule : IHttpModule {

        #region IHttpModule Members

        public void Dispose() { }

        public void Init( HttpApplication context ) {
            context.AuthorizeRequest += new EventHandler( context_AuthorizeRequest );
        }

        protected virtual void context_AuthorizeRequest( object sender, EventArgs e ) {
            HttpApplication app = (HttpApplication)sender;
            string requestedPath = app.Request.Path;

            if ( requestedPath.ToLowerInvariant().Contains( "_vti_bin" ) ) {
                if ( !app.Request.IsAuthenticated ) {
                    app.Response.StatusCode = 404;
                    app.Response.StatusDescription = "Not Found";
                    app.Response.Write( "404 NOT FOUND" );
                    app.Response.End();
                }
            }
        }

        #endregion
    }
}

Simple enough. To use the HttpModule, it needs to be registered in the site's web.config file with an entry under \configuration\system.webServer\modules:
<add name="SpSecureVtiBinModule" type="Custom.SharePoint.HttpModule.SpSecureVtiBin.SpSecureVtiBinModule, Custom.SharePoint.HttpModule.SpSecureVtiBin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[your_public_key_token]" />

Of course, we don't want to modify a SharePoint application's web.config file manually. We'll create an SPFeatureReceiver to do the job:
using System.Collections.ObjectModel;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Custom.SharePoint.HttpModule.SpSecureVtiBin {

    public class ModuleFeatureReceiver : SPFeatureReceiver {

        private static string _owner = "SpSecureVtiBinModule";

        public override void FeatureActivated( SPFeatureReceiverProperties properties ) {
            SPWebApplication app = (SPWebApplication)properties.Feature.Parent;

            app.WebConfigModifications.Add( GetModificationForSystemWebServer() );
            app.WebService.ApplyWebConfigModifications();
            app.Update();
        }

        public override void FeatureDeactivating( SPFeatureReceiverProperties properties ) {

            SPWebApplication app = (SPWebApplication)properties.Feature.Parent;
            Collection<SPWebConfigModification> mods = app.WebConfigModifications;

            int modCount = mods.Count;
            bool modRemoved = false;

            for ( int i = modCount - 1; i >= 0; i-- ) {
                SPWebConfigModification mod = mods[i];
                if ( mod.Owner.Equals( _owner ) || mod.Owner.Equals( "CHK.SharePoint.HttpModule.SpSecureVtiBin.SpSecureVtiBinModule" ) ) {
                    app.WebConfigModifications.Remove( mod );
                    modRemoved = true;
                }
            }

            if ( modRemoved ) {
                app.WebService.ApplyWebConfigModifications();
                app.Update();
            }
        }

        private SPWebConfigModification GetModificationForSystemWebServer() {
            return new SPWebConfigModification {
                Name = "add[@name='SpSecureVtiBinModule']",
                Owner = _owner,
                Path = "configuration/system.webServer/modules",
                Value = @"<add name=""SpSecureVtiBinModule"" type=""Custom.SharePoint.HttpModule.SpSecureVtiBin.SpSecureVtiBinModule, Custom.SharePoint.HttpModule.SpSecureVtiBin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=[your_public_key_token]"" />",
                Sequence = 0
            };
        }
    }
}

Now all that's left is to package up the HttpModule. You'll need to define a Feature in the package and reference the SPFeatureReceiver class. This will cause the web.config entry to be added when the Feature is activated, and the entry to be removed when the Feature is deactivated. Target the Feature for a WebApplication and the assembly deployment target to GlobalAssemblyCache.


text: Q: ajax call for apache fileupload in jsr 286 I am using apache fileupload in the form for portlets. I noticed that the class PortletFileUpload serves only action requests. I am using JSR286 and I want to call serveresource method whenever I click submit button. Is this possible or is there any work around to achieve this ?


text:
Q: Why logs show a different ssh connection port # than the one specified? My Ubuntu runs ssh on port 22. But my /var/log/auth.log says different port numbers when connections are made. And the port numbers are seemingly random:
Connection from xxx.xxx.xxx.xxx port 33692
Connection from xxx.xxx.xxx.xxx port 32970

Why are these port numbers not 22? And is there a pattern behind which port numbers are picked?

A: That's the remote port, not the local port. The remote OS picks a random number in a high range for the SSH client to bind to, then the client connects to port 22 on the server.


text:
Q: Xamarin.UWP RichTextBlock Hanging Indentation I used custom renderer to display a Label as RichTextBlock.  Using Paragraph, there is a TextIndentProperty to indent first line. However, I also need "Hanging Indentation" found in RichEditBox or SetIndent found in ITextParagraphFormat.
Is there a way to implemnent "Hanging Indentation" in RichTextBlock?

A: I have found the solution to this question.
Use left-padding to shift the entire paragraph in (say 10px)
Then, use text-indent with negative value to shift the first line of the paragraph out again (say -10px).
With this method, a hanging indentation can be achieved.


text:
Q: yii SEO редирект Есть yii 1.1.
После правки алиасов страниц в базе, возникла необходимость сделать 301 редирект со старых урлов на новые. Когда в классе CApplicationComponent, в методе init() ставлю для теста простую проверку на $_SERVER['REQUEST_URI'] с последующим редиректом на корректный урл - сразу же отправляет на 404 страницу. Есть мысли, как это грамотно сделать?

A: Если изменились только алиасы то сделайте редирект в самом контроллере. Который отвечает за обработку запросов этих страниц. То есть до каких либо действий проверьте есть ли в базе страница имеющая старый алиас, совпадающий с запрашиваемым. Если есть - зная её новый алиас - делайте редирект. При запросе страниц с новым алиасом редиректа не будет, потому что страницы с таким именем нет.
Если же поменялись пути в корне то это легко делается на уровне urlManager + новый контроллер специально сделанный для редиректов. Если приведете примеры адресов старых и новых страниц распишу подробнее с примером.


text:
Q: Creating Pie Chart from SQL Table I'm trying to build a pie-chart with data provided from an SQL Table. The result of my query is like following:
Total  A    B    C     D     E     F
11005  0  1485  3667  2665  2579  609

The problem is that I have many 'series' that contains only one data for each. I think that I have to build only one 'serie' to be able to display a pie chart.
My code is:
 Dim RequeteByTpe As String = "SELECT COUNT(*) as Total,
Sum(CASE
  WHEN [Type] = 'A' THEN 1
   ELSE 0
    END) A,
  Sum(CASE
   WHEN [Type] = 'B' THEN 1
    ELSE 0
     END) B,
  Sum(CASE
  WHEN [Type] = 'C' THEN 1
   ELSE 0
    END) C,
  Sum(CASE
  WHEN [Type] = 'D' THEN 1
   ELSE 0
    END) D,
 Sum(CASE
  WHEN [Constructeur] = 'E' THEN 1
   ELSE 0
    END) E,
 Sum(CASE
  WHEN [Constructeur] = 'F' THEN 1
   ELSE 0
    END) F
 From DBase.dbo.MyTable"

    Dim DA As New SqlDataAdapter(RequeteByType, ConnexionMyBase)
    Dim DS As New DataSet()
    DAConstC.Fill(DS, "ByType")

    Dim ChartType As New Chart

    Dim ChartArea2 As New ChartArea()

    ChartConstC.ChartAreas.Add("ChartArea2")

    ChartConstC.ChartAreas(0).Area3DStyle.Enable3D = True

    Dim Series21 As Series = New Series("A")
    Dim Series22 As Series = New Series("B")
    Dim Series23 As Series = New Series("C")
    Dim Series24 As Series = New Series("D")
    Dim Series25 As Series = New Series("E")
    Dim Series26 As Series = New Series("F")

    Series21.ChartArea = "ChartArea2"
    Series22.ChartArea = "ChartArea2"
    Series23.ChartArea = "ChartArea2"
    Series24.ChartArea = "ChartArea2"
    Series25.ChartArea = "ChartArea2"
    Series26.ChartArea = "ChartArea2"

    ChartByType.DataSource = DS.Tables("ByType")

    ChartByType.Series.Add(Series21)
    ChartByType.Series.Add(Series22)
    ChartByType.Series.Add(Series23)
    ChartByType.Series.Add(Series24)
    ChartByType.Series.Add(Series25)
    ChartByType.Series.Add(Series26)

    ChartByType.Series(0).YValueMembers = "A"
    ChartByType.Series(1).YValueMembers = "B"
    ChartByType.Series(2).YValueMembers = "C"
    ChartByType.Series(3).YValueMembers = "D"
    ChartByType.Series(4).YValueMembers = "E"
    ChartByType.Series(4).YValueMembers = "F"

    ChartByType.Titles.Add("Type proportions")
    ChartByType.Titles(0).Font = New Font("Arial", 12, FontStyle.Regular)

    ChartByType.Titles(0).Alignment = System.Drawing.ContentAlignment.TopCenter

    ChartByType.Location = New System.Drawing.Point(15, 45)

    ChartByType.Size = New System.Drawing.Size(760, 260)

    Me.Controls.Add(ChartByType)

I don't know if I must change my sql query to get an other type of data or if there is a possibility to fix this with some data attribution method or else. Can anyone please help?

A: instead of columns, you need rows...
rather than putting A, B, C in their own column,
total each by row
example sql...
select [Type], count(*) as Total From DBase.dbo.MyTable group by [Type]

i noticed there are two columns in the case statement,
you could union the results together if needed...
select [Type] as Label, count(*) as Total From DBase.dbo.MyTable group by [Type]
union all
select [Constructeur] as Label, count(*) as Total From DBase.dbo.MyTable group by [Constructeur]


text:
Q: Can't update sudo to latest version CVE-2021-3156 Due to latest CVE-2021-3156, I try to update my centos 7.9 with the following command :
yum update sudo*

But the command return the follwing :
Loading mirror speeds from cached hostfile
 * atomic: www5.atomicorp.com
 * epel: mirror.hostnet.nl
No packages marked for update

I also try yum clean all but still the same result.
My Centos run Plesk. Plesk update don't fix issue, sudo still not update to unvulnerable version.
UPDATE
The only check I have done after update is the version and I expected to see a sudo in version 1.9.x, but it's still to 1.8.x I don't remeber the minor version is previously.
But it's updated, because when I do the test, the Segmentation fault message was gone.
sudoedit -s '\' `perl -e 'print "A" x 65536'`

and I get the following message expected:
usage: sudoedit [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout]

Thanks for your help

A: From the change log this patch is applied through a regular update:
2021-01-20 - Radovan Sroka <rsroka@redhat.com> - 1.8.23-10.1
- RHEL 7.9.Z ERRATUM
- CVE-2021-3156
Resolves: rhbz#1917729

Binary package sudo-1.8.23-10.el7_9.1.x86_64.rpm changelog.
Checking sudo vulnerability with the following command:
sudoedit -s /

Patched sudo versions should print the usage:
usage: sudoedit [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p
                prompt] [-T timeout] [-u user] file ...

Vulnerable sudo version should print:
sudoedit: /: not a regular file

A: Firstly, be aware that using unescaped asterisks may lead to shell expansion which could result in the exact issue you're experiencing.
Secondly, there's no need to use an asterisk at all, yum update sudo will perfectly suffice.
Thirdly, if you have other packages related to sudo, e.g. sudo-logsrvd then you could run yum update 'sudo*'.
Lastly, please report your sudo version via rpm -q sudo


text:
Q: Displaying User custom field in wordpress (ACF) I made a custom field in User. I want to show some details of the user. The fields are displaying in Users but if I write some content and call the field with this method:
the_field('user_description');

It is not displaying the content in the author archive page. Any help will be highly appreciated :)

A: For user options you'll need to use a second argument for the the_field. The second argument need to start with user_ and end with the user ID. So, to retrieve an option from the current user, you'll do like this:
?php the_field('field_name', 'user_' . get_current_user_id()); ?>


text:
Q: Why does timestamp increase after a call to chill() but vtimestamp and walltimestamp do not? I'd like to understand why calling chill() in a DTrace action block increases the timestamp variable, but not vtimestamp and walltimestamp.
Here's an example showing timestamp increasing after a call to chill():
# dtrace -w -c true -n 'pid$target:::entry {self->t = $1; chill(1); printf("%d\n", $1 - self->t);}' timestamp
dtrace: description 'pid$target:::entry ' matched 3082 probes
dtrace: allowing destructive actions
dtrace: pid 6734 has exited
CPU     ID                    FUNCTION:NAME
  5  83475          _r_debug_postinit:entry 11258

  5  85771                     atexit:entry 2218

  5  86468              __libc_atexit:entry 491

  5  86428                       exit:entry 441

  5  85397    __cxa_thread_call_dtors:entry 441

  5  86213             __cxa_finalize:entry 447

  5  86213             __cxa_finalize:entry 565

  5  83470            _rtld_addr_phdr:entry 454

  5  86213             __cxa_finalize:entry 431

  5  83470            _rtld_addr_phdr:entry 1645

  5  84405                      _exit:entry 432

If we run the same script but use walltimestamp (or vtimestamp), we'll see the counter did not increase:
# dtrace -w -c true -n 'pid$target:::entry {self->t = $1; chill(1); printf("%d\n", $1 - self->t);}' walltimestamp
dtrace: description 'pid$target:::entry ' matched 3082 probes
dtrace: allowing destructive actions
dtrace: pid 6707 has exited
CPU     ID                    FUNCTION:NAME
  4  83475          _r_debug_postinit:entry 0

  4  85771                     atexit:entry 0

  4  86468              __libc_atexit:entry 0

  4  86428                       exit:entry 0

  4  85397    __cxa_thread_call_dtors:entry 0

  4  86213             __cxa_finalize:entry 0

  4  86213             __cxa_finalize:entry 0

  4  83470            _rtld_addr_phdr:entry 0

  4  86213             __cxa_finalize:entry 0

  4  83470            _rtld_addr_phdr:entry 0

  4  84405                      _exit:entry 0

This is understandable for vtimestamp, as it does not increase when executing DTrace code, but I don't understand walltimestamp's behavior here.
I'm running FreeBSD 13.1-RELEASE-p1 here on amd64.

A: Apparently, it's a bug in DTrace. Apparently, the implementation of chill() only invalidates the cached value of the timestamp variable but not for walltimestamp, which is incorrect.
Thanks to Mark Johnston for providing the answer on the FreeBSD DTrace mailing list.


text:
Q: ghost connecting to mariadb gives connection error I am trying to to get my ghost data to be saved on a mariadb docker container rather than ghosts inbuilt database. Its on docker-compose, where I have:
docker-compose.yml
version: '3'

services:
  mariadb-container:
    image: mymariadb:latest
    restart: always
    ports:
      - 3306:3306
    # volumes:
    #   - ~/blog/mariadb:/var/lib/mysql

  ghost-container:
    image: myghost:latest
    restart: always
    ports:
      - 2368:2368
    depends_on:
      - mariadb-container
    # volumes:
    #   - ~/blog/content:/var/lib/ghost/content
    links:
      - mariadb-container

myghost/Dockerfile
FROM ghost:latest

EXPOSE 2368

ADD ./config.production.json /var/lib/ghost

myghost/config.production.json
{
    "url": "http://localhost:2368/",
    "server": {
      "port": 2368,
      "host": "0.0.0.0"
    },
    "database": {
        "client": "mysql",
        "connection": {
          "host": "localhost",
          "port": 3306,
          "user": "root",
          "password": "pass123456",
          "database": "ghostblog",
          "socketPath": "/var/run/mysqld/mysqld.sock"
        }
    },
    "mail": {
      "transport": "Direct"
    },
    "logging": {
      "transports": [
        "file",
        "stdout"
      ]
    },
    "process": "systemd",
    "paths": {
      "contentPath": "/var/lib/ghost/content"
    }

mymariadb/Dockerfile
FROM mariadb:latest

EXPOSE 3306

ENV MYSQL_ROOT_PASSWORD=pass123436
ENV MYSQL_DATABASE=ghostblog

ERRORS::
But with this i get:
ghost-container_1    | NAME: RollbackError
ghost-container_1    | CODE: ENOENT
ghost-container_1    | MESSAGE: connect ENOENT /var/run/mysqld/mysqld.sock
ghost-container_1    |
ghost-container_1    | level:normal
ghost-container_1    |
ghost-container_1    | OuterError: The server has encountered an error.
ghost-container_1    | RollbackError: connect ENOENT /var/run/mysqld/mysqld.sock

Now, I included the socketPath in config.production.json because without it I got:
ghost-container_1    | NAME: RollbackError
ghost-container_1    | CODE: ECONNREFUSED
ghost-container_1    | MESSAGE: connect ECONNREFUSED 127.0.0.1:3306
ghost-container_1    |
ghost-container_1    | level:normal
ghost-container_1    |
ghost-container_1    | OuterError: The server has encountered an error.
ghost-container_1    | RollbackError: connect ECONNREFUSED 0.0.0.0:3306

I've also made sure the 'bind-address' is commented out in the configuration for mariadb, as this was the first things I saw when googling the error, I've also tried replacing localhost with 0.0.0.0 or 127.0.0.1 in the config.production.json and also in docker-compose.yml but with no change in error.
Also, I'm regulary doing the docker build --no-cache and docker-compose up --force-recreate to make sure the changes I made are actually being loaded.
Does anyone know what I am doing wrong?

A: Your database and ghost are in different containers, you can create network to allow them communicate with each other via network.
docker-compose.yml
version: '3'

services:
  mariadb:
    image: mymariadb:latest
    restart: always
    ports:
      - 3306:3306
    # volumes:
    #   - ~/blog/mariadb:/var/lib/mysql
    networks:
        - web-network

  ghost:
    image: myghost:latest
    restart: always
    ports:
      - 2368:2368
    depends_on:
      - mariadb-container
    # volumes:
    #   - ~/blog/content:/var/lib/ghost/content
    networks:
        - web-network

networks:
  web-network:
    driver: bridge

ghost config (database part only)
"database": {
    "client": "mysql",
    "connection": {
      "host": "mariadb", // your database container's name in network
      "port": 3306,
      "user": "root",
      "password": "pass123456",
      "database": "ghostblog"
    }
},

A: Maybe it helps you if you are looking on a running docker environment with nginx, letsencrypt, ghost and mariadb:
Sources

*

*Nginx Proxy Setup: https://github.com/evertramos/docker-compose-letsencrypt-nginx-proxy-companion

*Ghost + MariaDB Setup: https://github.com/LuisArteaga/docker-ghost-mariadb-letsencrypt
Important Note
Right now there is a docker bug when you trying to pull from ghost:latest.
If you are pulling from ghost:1.22.1 - it works. (You have to change it in the docker-compose.yml)


text:
Q: How many user can access the xelatex.exe at the same time when istalled texlive on server share folder We are plan to install texlive on server share folder (windows) in our institution. I have a doubt regarding How many user can access the Xelatex.exe and latex.exe at the same time for compilation
nearly 70 users can access the exe at the same time?
if users are access at the same time the compilation will be very slow?
please suggest

A: Donald Arseneau's comment on fontspec font caching is spot-on. Add a line
FC_CACHEDIR = $TEXMF-VAR/fonts/cache

to [root]\texmf.cnf
For quite some time I maintained a shared TL installation for my university and wrote a launcher replacing the usual TL system integration for windows. This package is available in TL as tlaunch. Its manual also has something to say about the xetex font cache.


text:
Q: How to know one system is significantly better than another one? I am studying lexical semantics. I have 65 pairs of synonyms with their sense relatedness. The dataset is derived from the paper:
Rubenstein, Herbert, and John B. Goodenough. "Contextual correlates of synonymy." Communications of the ACM 8.10 (1965): 627-633.
I extract sentences containing those synonyms, transfer the neighbouring words appearing in those sentences to vectors, calculate the cosine distance between different vectors, and finally get the Pearson correlation between the sense relatedness given by Rubenstein and Goodenough and our distances.
I get the Pearson correlation for Method 1 is 0.79, and for Method 2 is 0.78, for example. How do I measure if Method 1 is significantly better than Method 2 or not?

A: You can try the R package of cocor, which provides statistical tests between correlation coeffients. It seems that cocor.dep.groups.overlap() function works for you.


text:
Q: Use a model (resource) attribute (accessor) with metrics in Laravel Nova I have a MySQL table called purchases and a model called Purchase in Laravel that is related to it. My table has two columns, quantity and unit_cost. The total cost of a purchase is not a column in my table. Instead, it is defined by an accessor in Laravel that multiplies unit_cost by quantity and returns it as total_cost.
Now I am trying to define a trend metric in Laravel nova that is supposed to output the value of my daily sales in the selected range. When I try to use return $this->sumByDays($request, Purchase::class, 'total_cost') it gives me an error that says total_cost is not a column.
Fair enough! So, I tried to use Purchase::selectRaw(DB::RAW('unit_cost * quantity AS total_cost')) in the second argument, but it didn't work. I saw multiple posts, none of them could solve the problem of accessing a model accessor in Laravel Nova metrics. Any help is appreciated.

A: Unfortunately you can't use the built-in sumByDays helper function.
But good news! You can still implement it yourself within the calculate function. Just make sure your function returns a Laravel\Nova\Metrics\TrendResult.
Something like this:
$purchases = DB::table('purchases')
    ->select(DB::raw('quantity * unit_cost as total_cost'))
    ->groupBy(DB::raw('DATE(created_at) DESC'))
    ->get();

return new TrendResult()
    ->trend($purchases);

I don't have time to test this at the moment but it should get you started.

A: While trying to fix this problem, I checked through the sum by day or hours code and I realised that the column is an instance of Query Expression.
So that means you can still use the built in nova sum by days.
Make sure you import use Illuminate\Database\Query\Expression;
Just do this
$xpression = new Expression('quantity * unit_cost');
return $this->sumByDays($request, Purchase::class, $xpression);

It worked for me easily, I hope it does for others too.
The expression could be used in various ways in my case it was to perform a different calculation.


text:
Q: need custom LibraryPicker with initial image on custom cameraOverlay UIImagePickerController iOS8 I'm wondering how I can add the default Library picker button that can be found on an iPhone's default Camera app(can also be accessed via dashboard). The button looks like this, though this is an app custom implementation:

So I know that it can be done, but how? It's the library image picker that you can see the taxi car in. I'm using a completely customized UIImagePickerController through the use of the imagePickerController's property customOverlay view and I need to add this very same button to my overlayView. If someone could guide me towards a solution that'd be of great help, thanks!
I can imagine using UIImagePickerControllerSourceTypePhotoLibrary for the button and simply setting the button's imageView property to the first picture in the camera roll, but how would I go about doing this?
Also, is this somehow controllable by iOS default UIImagePickerController


text:
Q: Converting PHP variables into bash variables I have a CakePHP database.php config file that I'd like to leverage to open a command line mysql client instance.
The goal would be to be able to run a shell script like ./db-login.sh from the project root and have it pull the database details (host, port, database name, username, password) from the PHP config file and pass them to the mysql command line as arguments. This is to avoid having to enter the details every time.
I understand it's possible to create a shell alias that has the values hard-coded: I would like a portable script that could be included with any of my Cake projects. I also would like to keep the task of getting the DB credentials into bash variables separate from launching the mysql client. This would open up the ability to re-use the DB credentials in other shell scripts easily (such as a mysqldump backup script.)
Here's what I have so far:
database.php
Consider this file immutable for the purposes of this question. It must exist exactly as you see it.
<?php
class DATABASE_CONFIG {
    public $default = array(
        'host'        => 'localhost',
        'login'       => 'cakephpuser',
        'password'    => 'c4k3 roxx!',
        'database'    => 'my_cakephp_project',
    );
}

db-cred.sh
Acts as middleware to convert the PHP variables into bash (friendly) variables.
#!/usr/bin/env php
<?php
include 'database.php';
$db = new DATABASE_CONFIG();

// Selectively wrap quotes. Has no real effect(?)
$p = (!empty($db->default['password']) ? "\"$db->default['password']\"" : '');

echo <<<EOD
DB_HOST="{$db->default['host']}"
DB_NAME="{$db->default['database']}"
DB_USER="{$db->default['login']}"
DB_PASS={$p}
EOD;

db-login.sh
#!/usr/bin/env bash
# Uses Cake's database.php file to log into mysql on the
# command line with the correct arguments.

# Holy yuck, but nothing else works!
eval $( db-cred.sh )

# Try to set an appropriate password clause.
PATTERN=" |'"
if [ -n "$DB_PASS" ]; then
    if [[ $DB_PASS =~ $PATTERN ]]; then
        PASS_CLAUSE=" -p'${DB_PASS}'"
    else
        PASS_CLAUSE=" -p${DB_PASS}"
    fi
else
    PASS_CLAUSE=""
fi

# Get a rough look at what we're about to run.
echo mysql --host=${DB_HOST} --database=${DB_NAME} --user=${DB_USER}${PASS_CLAUSE}

# Call MySQL.
mysql --host=${DB_HOST} --database=${DB_NAME} --user=${DB_USER}${PASS_CLAUSE}

Things that need help:

*

*The db-login.sh script uses eval to suck in the variables. Yuck.

*The MySQL password is leaked on the command line. This is not a dealbreaker, but if there's a clean/portable way to avoid it, I'm open to it.

*Spaces and quotes in the mysql password don't get passed to bash properly.

*

*A password like my Pass will cause DB_PASS to be set to my in db-login.sh.

*Quoting the string in db-cred.sh produces "my instead.

*Likewise, my attempts at quoting PASS_CLAUSE are not effective: Only passwords without spaces/quotes will successfully log into the mysql client.

A: *

*The db-login.sh script uses eval to suck in the variables. Yuck.

Instead of eval, you can use the source command:

source db-cred.sh

*The MySQL password is leaked on the command line. This is not a dealbreaker, but if there's a clean/portable way to avoid it, I'm open to it.

You can just unset the MySQL password after it is used:

unset DB_PASS

However, you will always have this problem if you are supplied the password to MySQL via the command line. You could remove the -pPassword clause and force the user to enter the password when MySQL prompts for it, but from your use-case this does not seem feasible.

*Spaces and quotes in the mysql password don't get passed to bash properly.

*Likewise, my attempts at quoting PASS_CLAUSE are not effective: Only passwords without spaces/quotes will successfully log into the mysql client.

For 3 and 4, I believe all you need to do is properly quote your variable values.
In PHP:
echo <<<EOD
DB_HOST="{$db->default['host']}"
DB_NAME="{$db->default['database']}"
DB_USER="{$db->default['login']}"
DB_PASS="{$p}"
EOD;

Note the added quotes in DB_PASS="{$p}".
As a reminder, you can also escape the quotes in PHP with addslashes().

A: Okay, so @nickb's suggestions led me down the right track with enough modifications.
Explanation
Issues arise if you try to pass the MySQL password through multiple bash variables. Here's a stripped down example:
#!/bin/bash
set -x
DB_PASS="pass with space and 'quote"
PASS_CLAUSE=" -p'$DB_PASS'"

# Doesn't work.
mysql $PASS_CLAUSE

# Works.
mysql -p"$DB_PASS"

Note that with the set -x we're able to see the commands that are actually being run. This is what helped me identify the double-escaping. The string in $DB_PASS gets re-escaped when it gets saved into $PASS_CLAUSE. Since it gets passed to MySQL with one level of escaping still in place the first connection fails, but using the original variable succeeds.
Final Scripts
db-cred.sh
#!/usr/bin/php
<?php
include 'database.php';
$db = new DATABASE_CONFIG();
echo <<<EOD
DB_HOST="{$db->default['host']}"
DB_NAME="{$db->default['database']}"
DB_USER="{$db->default['login']}"
DB_PASS="{$db->default['password']}"
EOD;

db-login.sh
#!/bin/bash

# Holy yuck, but nothing else works!
eval $( db-cred.sh )

CMD="mysql --host=${DB_HOST} --database=${DB_NAME} --user=${DB_USER}"
PATTERN=" |'"

if [[ ${DB_PASS} =~ ${PATTERN} ]]; then
    ${CMD} -p"${DB_PASS}"
elif [ -n "${DB_PASS}" ]; then
    ${CMD} -p${DB_PASS}
else
    ${CMD}
fi

Final Thoughts

*

*I haven't specifically tested for it, but there may still be issues with passwords that contain double-quotes.

*This could still be improved by somehow removing the need for eval. @Dave's idea about using CSV as a go between has potential, but in my tests it further complicated things by adding another level of escaping/unescaping necessary to get the variables into bash cleanly.

*The MySQL password is still used on the command line. Writing a mysql config file, using it with --defaults-extra-file=filename and afterwards deleting it might be a way around that.

*db-login.sh now represents a pattern for executing command lines with the database credentials and can be easily modified/extended for other tools like mysqldump.


text:
Q: Using Box-Muller Method to Generate Gaussian Random Numbers in Python Right now, I am using the Box-Muller method to generate 10 24 Gaussian random numbers in python. I am supposed to plot the power spectrum, and see a Gaussian curve. My code is below:
import numpy as np
import matplotlib.pyplot as plt
def fast_fourier_transform(y):
    '''Return the fast Fourier transform of y.'''
    Y = np.fft.fft(y)
    f = np.fft.fftfreq(len(y),1.0/1024)
    return f,Y

    rlist=[]

    for i in range((2**10)/2):
        mu=0
        sigma=1

    u = np.random.random()
    v = np.random.random()

    z1 = np.sqrt(-2.0 * np.log(u)) * np.sin(2.0 * np.pi * v)
    z2 = np.sqrt(-2.0 * np.log(u)) * np.cos(2.0 * np.pi * v)

    x1 = mu + z1 * sigma
    x2 = mu + z2 * sigma
    rlist.append(x1)
    rlist.append(x2)
    print u, v, x1, x2
f,Y=fast_fourier_transform(rlist)
plt.plot(f,Y)

plt.show()

However, when I plot this, I don't get a Gaussian distribution. My question is this: why am I not getting a Gaussian distribution in my Gaussian-generated white noise power spectrum? Am I plotting something wrong? Thank you in advance.

A: To see the Gaussian curve, you want a histogram rather than a power spectrum.  The power spectrum of independent random variables is uniform (flat).  The term "white noise" is itself a big hint - white light is comprised of equal amounts of light at all frequencies.


text:
Q: catboost eval_metrics return value I'm using CatBoostClassifier's eval_metrics to compute some metrics on my test set, and I'm confused about its output. For a given metric, by default, it seems to return an array, of size equaling the number of iterations.
This seems to be inconsistent with the predict function, which returns a single value only. Which number in the array returned by eval_metrics is consistent with the predict function?
I checked the documentation at https://catboost.ai/docs/concepts/python-reference_catboostclassifier_eval-metrics.html#python-reference_catboostclassifier_eval-metrics__output-format, but it's still not clear to me.

A: The Catboost classifier is a type of Ensemble Classifiers which uses Boosting Methods. Simply put, Boosting algorithms iteratively train weaker algorithms (Decision Trees in this case) to make predictions. Each Tree that is created learns from the collective errors that the previous weaker trees made and tries to learn from those errors. Catboost is based on Gradient Boosting which I won't dwell to deep into. What is relevant here is that a number of weaker trees are generated in the process, and when you call the eval_metrics() method you are getting the eval metric for each of the generated trees. You specify the number of trees generated when you provided iterations, num_boost_round, n_estimators or num_trees when creating the model (If not specified it has a default value of 1000).
The other arguments you specify to the eval_metrics() method will define the range of trees taken ntree_start to ntree_end at intervals of eval_period. If these aren't provided you will get the specified metrics for your data for all of the weaker trees generated, which is why you get a list of values.


text:
Q: kivy opencv android Estoy tratando de construir un apk con una aplicación que me funciona perfectamente en la pc pero al pasarla a la tablet la instala correctamente y cuando quiero ejecutarla me aparece el error de que la aplicación se detuvo. La apk la construí con buildozer y ahí creo que puede estar el problema, la aplicación es la siguiente:
from kivy.app import App
from kivy.uix.image import Image
from kivy.clock import Clock
from kivy.graphics.texture import Texture
import cv2
from kivy.uix.camera import Camera

class KivyCamera(Image):
    def __init__(self, capture, fps, **kwargs):
         super(KivyCamera, self).__init__(**kwargs)
         self.capture = capture
         Clock.schedule_interval(self.update, 1.0 / fps)

    def update(self, dt):
         ret, frame = self.capture.read()
         if ret:
            # convert it to texture
            buf1 = cv2.flip(frame, 0)
            buf = buf1.tostring()
            image_texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
            image_texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte')
            # display image from the texture
            self.texture = image_texture

class CamApp(App):
    def build(self):
        self.capture = cv2.VideoCapture(0)
        self.my_camera = KivyCamera(capture=self.capture, fps=30)
        return self.my_camera

    def on_stop(self):
        #without this, app will not exit even if the window is closed
        self.capture.release()

if __name__ == '__main__':
    CamApp().run()

En cuanto al archivo buildozer.speec:
source.include_exts = py,png,jpg,kv,atlas
requirements = kivy, numpy, opencv
orientation = landscape
osx.python_version = 3
osx.kivy_version = 1.9.1
android.permissions = CAMERA
android.permission-group = HARDWARE_CONTROLS

Cuando lo corro en la tablet mediante logcat en la consola larga el siguiente error:

E/Corkscrew(  196): update_state: unexpected CFA register: 7
E/Corkscrew(  196): update_state: unexpected CFA register: 7
I/BootReceiver(  511): Copying /data/tombstones/tombstone_01 to DropBox (SYSTEM_TOMBSTONE)
E/JavaBinder(  511): !!! FAILED BINDER TRANSACTION !!!
W/ActivityManager(  511):   Force finishing activity org.test.opencv/org.kivy.android.PythonActivity
W/ufoGralloc(  197): registerBuffer() handle 0xf942b590/9 didn't require registration
E/JavaBinder(  511): !!! FAILED BINDER TRANSACTION !!!
W/ActivityManager(  511): Exception thrown during pause
W/ActivityManager(  511): android.os.TransactionTooLargeException
W/ActivityManager(  511):   at android.os.BinderProxy.transact(Native Method)
W/ActivityManager(  511):   at android.app.ApplicationThreadProxy.schedulePauseActivity(ApplicationThreadNative.java:667)
W/ActivityManager(  511):   at com.android.server.am.ActivityStack.startPausingLocked(ActivityStack.java:781)
W/ActivityManager(  511):   at com.android.server.am.ActivityStack.finishActivityLocked(ActivityStack.java:2489)
W/ActivityManager(  511):   at com.android.server.am.ActivityStack.finishTopRunningActivityLocked(ActivityStack.java:2366)
W/ActivityManager(  511):   at com.android.server.am.ActivityStackSupervisor.finishTopRunningActivityLocked(ActivityStackSupervisor.java:2147)
W/ActivityManager(  511):   at com.android.server.am.ActivityManagerService.handleAppCrashLocked(ActivityManagerService.java:9762)
W/ActivityManager(  511):   at com.android.server.am.ActivityManagerService.makeAppCrashingLocked(ActivityManagerService.java:9655)
W/ActivityManager(  511):   at com.android.server.am.ActivityManagerService.crashApplication(ActivityManagerService.java:10326)
W/ActivityManager(  511):   at com.android.server.am.ActivityManagerService.handleApplicationCrashInner(ActivityManagerService.java:9851)
W/ActivityManager(  511):   at com.android.server.am.NativeCrashListener$NativeCrashReporter.run(NativeCrashListener.java:86)
I/WindowState(  511): WIN DEATH: Window{26d51f00 u0 org.test.opencv/org.kivy.android.PythonActivity}
D/Zygote  (  198): Process 6116 terminated by signal (11)
I/WindowState(  511): WIN DEATH: Window{26d7ad30 u0 SurfaceView}
I/ActivityManager(  511): Process org.test.opencv (pid 6116) has died.
I/SecurityManagerService(  612): SMS received security event: App[STOP/org.test.opencv]
D/InputMethodManagerService(  511): --- calledFromForegroundUserOrSystemProcess ? calling uid = 1000 system uid = 1000 calling userId = 0, foreground user id = 0, calling pid = 511dalvik.system.NativeStart.run(Native Method)
D/        (  764): Pixel Format : GGL_PIXEL_FORMAT_RGBA_8888
W/UdcContextManagerHelper(  722): Empty context buffer. Thus might mean that the context is not synced down.
W/GetDeviceDataUploadOptInStatusOp(  722): Empty context model while retrieving upload opt-in status!
W/Conscrypt(  851): Could not set socket write timeout:
W/Conscrypt(  851):    java.lang.reflect.Method.invokeNative(Native Method)
W/Conscrypt(  851):    java.lang.reflect.Method.invoke(Method.java:515)
W/Conscrypt(  851): Could not set socket write timeout:
W/Conscrypt(  851):    java.lang.reflect.Method.invokeNative(Native Method)
W/Conscrypt(  851):    java.lang.reflect.Method.invoke(Method.java:515)

Tengo la sospecha de que puede llegar a ser algo de la resolución de la pantalla pero no sabria como solucionarlo.


text:
Q: Does Collapse and Scripting functions exist in Foundry Elasticsearch? Phono doc says that aggregations are based on Lime syntax, which is a layer on top of elasticsearch 6 (just a subset). Principally FILTER and AGGREGATION. First (filter) is clearly documented in Palantir doc but second is less and I often refer to Elasticsearch 6 (ES6) doc for inspiration.
Now I wonder if some ES6 behaviour are accessible in Phono
Collapse function https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-collapse.html
Scripting and Script Field https://www.elastic.co/guide/en/elasticsearch/reference/6.8/search-request-script-fields.html
Does anyone know if these functions exist in the Phonograph API ?


text:
Q: Android : TextView not show in TextWatcher listener I want to show text in text view if condition is satisfied with equal method in Text-watcher.I have a string variable used in a method, and I would like to compare the EditText value to that variable and text view is update and if not then display the string with wrong code.But ui is not updated in TextWatcher.
Here is my code
 private final TextWatcher vesselWatcher = new TextWatcher()
    {
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
            Log.e("beforeTextChanged  ", " here !!! ");
        }

        public void onTextChanged(CharSequence s, int start, int before, int count)
        {

        }

        public void afterTextChanged(Editable s)
        {
            if (s.length() == 0)
            {
                txtVesselName.setVisibility(View.GONE);
                Log.e("afterTextChanged View ", " is gone !!!");
                btnPost.setClickable(false);
                btnPost.setEnabled(false);
                Log.e("afterTextChanged  ", " btnPost.setEnabled(false); !!!");
            }
            else
            {

                if(notations.contains(etxtVesselCode.getText().toString().trim()))
                {
                    Log.e("AAA strNotations ", " Match !!! = " + etxtVesselCode.getText().toString().trim());
                    String notations = etxtVesselCode.getText().toString().trim();
                    SQLiteDatabase db = dbhelper.getWritableDatabase();

                    Cursor cursor = db.rawQuery("select * from VesselList where Notation " + "= ? ", new String[]{notations});

                    if (cursor.moveToFirst())
                    {
                        do
                        {
                            strVesselsTypeName = cursor.getString(cursor.getColumnIndex("VesselsTypeName"));

                            Log.e("strVesselsTypeName ", "= " + strVesselsTypeName );

                            SharedPreferences sp;
                            sp = getApplicationContext().getSharedPreferences(MyPREFERENCES, 0);
                            SharedPreferences.Editor e = sp.edit();
                            e.putString("xyz", etxtVesselCode.getText().toString().trim());
                            e.commit();

                            Log.e("Match","!!!!");
                            txtVesselName.setText(strVesselsTypeName);

                            btnPost.setClickable(true);
                            btnPost.setEnabled(true);
                            Log.e("afterTextChanged  ", " btnPost.setEnabled(true); !!!");

                        } while (cursor.moveToNext());
                    }  db.close();

                }
                else
                {
                    Log.e("Not "," Match !!");
                    txtVesselName.setText("Wrong Code !!");
                    btnPost.setClickable(false);
                    btnPost.setEnabled(false);
                }
            }
        }
    };

A: Make txtVesselName TextView VISIBLE again after calling txtVesselName.txtVesselName when if condition is true:
txtVesselName. setVisibility(View.VISIBLE);


text:
Q: Where should I declare my BehaviorSubject when using React Hooks with RxJS? I tried to follow along this implementation from React Hooks + RxJS or How React Is Meant to Be. It looks promising. You simply have this custom hook:
const useSharedState = subject => {
 const [value, setState] = useState(subject.getValue());
 useEffect(() => {
   const sub = subject.pipe(skip(1)).subscribe(s => setState(s));
   return () => sub.unsubscribe();
 });
 const newSetState = state => subject.next(state);
 return [value, newSetState];
};

And You can just basically use it as:
const subject = new BehaviorSubject({ message: '' });

const AwesomeComponent = () => {
 const [{ message }, setState] = useSharedState(subject); // Custom Hook
 return <div>{message}</div>;
};

The only thing I am not sure of is where exactly SHOULD I declare my subject ? If I put it on the file of the component, will it persist? I can't seem to imagine how the instance is persisted when the component is not used yet or if it will persist when the component is destroyed/unmounted? Especially when I do an API call (for example, using axios-observable), I don't know how exactly it should be done along with this custom hook.

A: This is what I like to do:
import { useCallback, useState } from "react";
import { BehaviorSubject } from "rxjs";

export const useBehaviorSubject = <T>(initialState: T): [BehaviorSubject<T>, (x: T) => void] => {
    const [observable] = useState(new BehaviorSubject<T>(initialState));

    const handleNext = useCallback(
        (value: T) => {
            observable.next(value);
        },
        [observable],
    );

    return [observable, handleNext];
};


text:
Q: How to properly modularize Angular 4 w/ customizability? I am trying to figure out how to create components that can be customized from the calling component. As an example, I am trying to build a text input called textbox that can be passed things like maxlength, validation-messages[], etc. in the following manner:
<textbox maxlength="40" validation-messages="['This field is required','This field is too long']></textbox>

And the template for textbox.component would look something like:

<input ... />

I have been attempting to accomplish this for a few days but can't seem to get it to work quite right. Using directives just leads me to dead ends (for example, changing innerHTML from the directive causes the *ngIf not to work correctly and the Validation messages to always be present, regardless of which lifecycle hook I use), and as far as I can tell, services can't be used to send data from the calling HTML to the receiving component, but I need to be able to send variables to textbox from the caller to change textbox's template and maintain modularity.
If anyone knows the proper way to accomplish something like the above, please let me know. Thanks in advance.

A: Found the answer. It was in this article. Simply put, use directive formatting, but just have the @Input in the component file. Like so:
Calling Component:
<textbox [maxlength]="40" [validation-messages]="['This field is required','This field is too long']></textbox>

Containing Component (Textbox.component.ts):
@Input validation-messages: string[];
@Input maxlength: number;

This way you can work with the inputs directly from the component.ts file and conditionally format the component.html file from there.


text:
Q: C# Cannot create an instance because Type.ContainsGenericParameters is true I'm attempting to deserialize a Generic<T> where T : struct but when I call ctor.Invoke(args);  I get the exception "Cannot create an instance because Type.ContainsGenericParameters is true".
How do I pass the generic type I want it to be?

A: You have to create a concrete type first using the MakeGenericType method on your generic type

A: Let's say you have a Type t of a generic class which has a parameter-less constructor, and an array of the types to use as the type parameters of the generic class:
Type t = someType;
Type[] genericTypeParameters = someArrayOfTypeParameters;

Call Type.MakeGenericType(), which

Substitutes the elements of an array of types for the type parameters
  of the current generic type definition and returns a Type object
  representing the resulting... type

Then construct the object as normal:
    t = t.MakeGenericType(genericTypeParameters);

    object instance = Activator.CreateInstance(t);

A: Type.MakeGenericType is probably what you are looking for...


text:
Q: Array Out Of Bounds, Args Issue So when I compile, everything will compile just fine.
When I go to run the program, I get this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
      at ClientForNoDupCollection.main(ClientForNoDupCollection.java:20)

I go to look at line 20(actually 19-21)
public static void main(String args[]) {
    File file = new File(args[0]);
    Scanner cReader = null;

I'm attempting to be able to do command line execution of the files.
I'm not 100% sure where I went wrong there.

A: You have not provided any command-line arguments to your application. Thus, args has no element 0.
Provide an argument (the path to the file of interest) when invoking your application:
java MyApp path/to/file

A: You need to specify a parameter when you run the application.


text:
Q: Shrinking a SQL Server database not working I'm not a DBA but I need to shrink a DB, I tried using the SSMS interface to shrink and it didn't work.
The stats are as follows:

*

*Size: 235,013.00 MB

*Space Available: 65,587.59 MB

I have also tried the DBCC SHRINKDATABASE ... TRUNCATEONLY command and didn't change anything either.
How can I shrink this DB (free up the unused space to the OS) without losing data?

A: By the way also check the initial size. If your initial size is 235,013 MB then you need to reduce your initial size first.
Secondly, shrinking is one of the worst things your could do to a data file. If you shrink a tlog file its okay, because tlogs dont use the data page structure. If you shrink your database data file, you can make a perfectly de-fragmented database into a perfectly fragmented database. It will mess the performance beyond recognition. Why do you want to shrink by the way? The db is 200 something GB and has 60 something free.... that's like around 30% free. Don't you think in the matter of some time, that space can be utilized?
If you still need to shrink the db, you can create a file group and move the data to that file group and delete the current file group or in case of primary file group you can reduce the size to the bare minimum.

A: *

*In SSMS try using Right Click on DB->Tasks->Shrink->Files to see how much space is used by data and transaction log files.

*It's likely that the Recovery Model for your DB is set to FULL in which case you'll not be able to shrink the transaction log unless you do a full db backup. If it's not a concern, just change the Recovery Model to Simple and try to shrink the transaction log and data files again.

A: Not enough points to comment but be careful about shrinking. It can affect performance due to fragmentation of your indexes
Explained in detail here:
http://www.theboreddba.com/Categories/indexes/SHRINK-a-data-file-Just-say-NO.aspx
Sam

A: I resolved the issue by the following steps:

*

*MAKE DATABASE BACKUP

*Set Database to Single-User-Mode

*Take Database Offline

*Take Database Online

*Lower the initial file size for the database and transaction log files

*Shrink the Database/File

*Set Database to Multi-User-Mode

A: Just hit this. Was trying to shrink via SSMS and the dialog would just close immediately regardless of the shrink option(s) selected (no errors or any indication that it couldn't shrink the DB or files).
I ended up creating another logical ROWS Data file, shrinking the main data file by emptying / migrating it to the new file and then shrinking / emptying back again to the original data file.
This is a dev DB so I'm not too worried about the performance impact (just looking to free up disk space).


text:
Q: Microsoft Unity HierarchicalLifetimeManager Deadlock I have a self hosted async c# webapi that is using OWIN and Unity 5.5.0.
I encountered an issue during some stress testing where after several hours the webapi would stop processing requests and the client calls would timeout.
I generated a crash dump using adplus in hang mode, opened the dump  in visual studio and found that my application was getting locked on the unity method SynchronizedLifetimeManager.GetValue()
Threads Blocked by SynchronizedLifetimeManager.GetValue
the code from that method should be
    /// <summary>
    /// Retrieve a value from the backing store associated with this Lifetime policy.
    /// </summary>
    /// <returns>the object desired, or null if no such object is currently stored.</returns>
    /// <remarks>Calls to this method acquire a lock which is released only if a non-null value
    /// has been set for the lifetime manager.</remarks>
    public override object GetValue()
    {
        Monitor.Enter(lockObj);
        object result = SynchronizedGetValue();
        if (result != null)
        {
            Monitor.Exit(lockObj);
        }
        return result;
    }

My understanding of the method is a request comes in to retrieve the object, if the object has not been set it returns but leaves the lock. When the object gets set the lock the monitor is exited and threads should be able to call.
My visible problem is that at some point unity does not have a value for that lifetime manager and blocks the threads, but set is not called to release them.
Option 1: at some point the value in the lifetime manager was changed to null. What would cause this to happen?
Option 2: The SetValue call to release the lock is failing or not being made at all. What causes the value to get set?
My assumption is that somewhere in my code an exception is not properly handled and is causing this issue, but I am not sure where to start looking and was hoping for a better understanding of what unity is trying to do.
The application has a class where we register interfaces to types for IOC. This is used for most mappings. However, it is a workflow application so at one point in all calls we look up what workflow class to call and tell unity to resolve the type string and inject any objects needed.


text:
Q: Laptop Autorotate Cannot be Disabled I'm having an issue where I can't disable the autorotate feature of my laptop. The display rotates from my preferred landscape view to the undesirable portrait view whenever I physically tilt the laptop past a certain point. I want this behavior completely turned off; I do not care for the rotation and I do not care for the tablet mode.
My laptop is an ASUS Q324UAK model running Windows 10 Home 64-bit.
Things I've tried that have been unsuccessful:

*

*changing the value of the rotation lock option in the action center

*setting the option for tablet mode to "don't ask me and don't switch"

A question similar to mine has been asked here Enable rotation lock by default in Windows 10 but does not have any answers or comments.
I would be fine with changing registry values if it will fix the problem, but I tried what the OP suggested from the above question, and indeed the laptop still autorotates regardless of the registry edits.

A: I had this problem too. I only ever want to type and use my laptop as a computer, not a tablet and I don't want it to autorotate if I am moving to a different room or something. Finally, as I was in the display settings, I physically lifted my computer and turned it sideways and rotated the screen to portrait, and then hit the screen lock because it wasn't grayed out anymore. Then after I locked it, I chose to do landscape from portrait mode in the settings. Voila! It locked on the landscape mode and when I tip my laptop upside down or sideways it doesn't auto rotate on me anymore. It is so nice to have it stop doing that to me. ( also not sure if this makes a difference, but my laptop is also in the "don't ask, don't switch" option in the table mode settings and start "in desktop" mode as well.)

A: We can try the following four way to lock screen rotation.
1: Turn On or Off Screen Rotation Lock using Keyboard Shortcut
2: Turn On or Off Screen Rotation Lock in Action Center
3: Turn On or Off Screen Rotation Lock in Settings
4: Turn On or Off Screen Rotation Lock using a REG file
For details we can refer this article: How to Turn On or Off Screen Rotation Lock in Windows 10
If all the above does not work, I have seen the method but never try it.
• Go to Device Manager
• Sensors
• Disable Invensense Sensor Collection

In addition, some tablets have a button that allows you to quickly disable the auto-rotate function. We'll need to check our manual to see if one of the buttons is meant for that function.


text:
Q: Android : Update other apps from own App Is it possible to update other installed apps from my own app.
Actually what I want to do is, I want to develop an app that checks for the installed apps on the deice, then checks if there are any updates available for those apps and id there are any, it will update them.
to check whether there is an update available for a particular app, I found out a third party API  click herehttps://groups.google.com/forum/?fromgroups=#!topic/android-market-api/-F2QfvGt1nU
So, now is it possibel to update the apps programatically from my app??

A: The Google Play Store app already does this for every app from the play store and I do not believe there is any publicly available API provided by Android to do this in your own app.

A: If you really want to work with unsupported API that will for sure break anytime soon, I suggest to do the following:
Check the user installed apps and their versions:

Use PackageManager and getPackageInfo() to get a PackageInfo object
  for the specific application, identified by its package (e.g.,
  com.commonsware.mygreatapp). The versionCode and versionName fields on
  the PackageInfo will have the information you seek.

Then compare it with latest version of the API:
EDIT:
Send the package name to the API: dev.appaware.com/1/doc/examples/example3.php and analyse this line "version": "2.4.0.263535", if this number is different from the version on phone, take the user to Google Play page.
This will be a total duplicate of already existing features...


text: Q: Xcode 13 build an interactive tutorial I have an app which is a little complicated to figure out details without a help document. I don't want to host the help document only on a web server for users who might not prefer to leave the app and go through the tutorial on a web page. So my question is: Is it possible to make use of DocC tutorial and present the tutorial to my users in the app without leaving the app? Is not, the only solution would be to provide a link for my users to open the web page in Safari I guess. My second question is: Is it possible to host DocC tutorial on an Amazon S3 bucket?


text:
Q: How I could change report presentation in Microsoft.ReportViewer.WinForms I'm loading a rdlc report in Microsoft.ReportViewer.WinForms:

How I could show the report with this presentation by programming in C# :

This presentation only can be shown with pressing printing designer button:

A: I found the answer in Open a reportViewer in printing view by default
ReportViewer1.SetDisplayMode(Microsoft.Reporting.WinForms.DisplayMode.PrintLayout)


text:
Q: iPhone network node library I'm trying to find a library for iPhone app that can represent a network with an arbitrary number of nodes and distances between the nodes. I need to then calculate shortest path between the nodes. Does anyone know if such is available for objective-c or c++ in general that can be used in an iPhone app?
Thanks

A: If it's a simple enough network, you can just do a normal BFS (Breadth-First Search) or DFS (Depth-First Search) and compute all the possible paths. Then just select the fastest one.  Remember, for graphs you have to store a list of nodes that you've already visited, otherwise you'll end up going in circles forever.


text:
Q: How to make my Cloud Function only be called from my GCP service account As seen below I am editing the permissions for access to my Cloud Function called task. I am following the advice from GCP that says the following:

This resource is public and can be accessed by anyone on the internet.
To remove public access, remove "allUsers" and "allAuthenticatedUsers"
from the resource's members.

so that my function can only be called from my GCP. So I removed the allUsers access for the Cloud Functions Invoker role. But now I am trying to add a new member (service account) with the Cloud Functions Invoker role:

However I don't know what service account my Cloud Tasks are fired from. I've created a new service account with only Cloud Tasks permissions but I don't know how to actually make my Cloud Tasks use this service account when executing. There doens't seem to be an option for that:

Any idea?

A: According to the Google docs, "Cloud Tasks can call HTTP Target handlers that require authentication if you have a service account with the appropriate credentials to access the handler."
You may need to create a service account and give the appropriate roles to it.
Please follow the official Google documentation [1] where the steps to follow are detailed.
[1] - https://cloud.google.com/tasks/docs/creating-http-target-tasks#sa


text:
Q: Different versions of "I have no question of my grandmother's dedication", which are acceptable?
"I have no question of my grandmother's dedication."
  "I have no question of whether my grandmother is dedicated."
  "I do not question my grandmother's dedication."

Which can be used, grammatically?

A: All can be correct grammatically. Whether they are correct, however, depends on the implication.
The first instance implies that your grandmother's dedication my have been questionable by another; but, you do not question her dedication.
The second instance implies that you have no question whether (or not) your grandmother's dedication exists now regardless of what it was previously or what it might be.
The third instance implies that it is not your place to question the dedication of your grandmother whatever her dedication is at any point. It is none of your business.


text:
Q: Neo4j HTTP error So, I thought that I configured everything correctly by following the installation and setup instructions in the neo4j documentation, but the REST API is not working.
http:7474/localhost works perfectly and detects nodes, but
curl http://localhost:7474/db/data/node/0

gets

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 Not Found</title>

HTTP ERROR 404

Problem accessing /db/data/node/0. Reason:

    Not Found

Powered by Jetty://

The older documentation had something about installing the neo4j-rest separately, but this is not in the current documentation. Thoughts?


text:
Q: Excel Numerical Precision Issue with COUNTIF: for few numerical values counting X as being larger than X itself While COUNTIF() for most numerical arguments rightly answers 0 when asked the triviality how many values among X are larger than X (i.e. COUNTIF(X,">X") yielding 0), for some weird numerical values of X, COUNTIF(X,">X") yields 1, thus wrongly claiming X would be larger than X.
Consider a constant value to be in Cell A1 (the X above).
Consider Cell A2 to count all values in A1 only (i.e. Range A1:A1), which are larger than A1 itself:
=COUNTIF(A1:A1,">"&A1)
For "normal" (i.e. most) values in A1, this rightly yields 0.
For some specific values, call them "weird" values, I find it to return 1, however.
A way to create an example of such a weird number manually is:
=564.777008837525+(564.777008837526-564.777008837525)/2 as value for A1
Use instead essentially nearly any other value for A1, and you find COUNTIF instead to work.
I reckon a bug related to numerical precision when calculating the COUNTIF result.
Is there any genuine fix to this? Or instead only workarounds?
Excel Version: Excel 2016
Note:

*

*This is not related to the special case of A1:A1 to be a 'collapsed' 1-cell-only range. Use larger ranges, filled with different values, and the same weird behavior obtains still.

*Also, it does not matter whether the criteria parameter contains a reference to the "weird" value in the range parameter, or instead to an independent copy of that value in some other cell.

*When you manually copy-paste the numeric form of the weird' value from the cell, and use the manually copied version, the problem disappears. I.e., when copying the value manually you seem to copy a slightly different numerical value; Excel does not seem to provide you the full precision of the number when giving you the numeric value in digits form; it seemingly errs instead on the side of showing less rather than more precision in the decimal number than what is truly stored in its binary format.

*Other weird values leading to the same wrong counting behavior exist.


text:
Q: Val Error, x and y must have the same dimension. [I tried to do np.array but it hasn't helped] x and y must have same first dimension, but have shapes (1, 400) and (400,)
I have search this forum and saw that people suggested to do np.array to solve this, but it didn't seem to work.
def function(a, v):
speedx = 0.0
yt = -1.0
val = []
for i in len(a):
    xt = a[0]
    vx = -2.0 * yt**2 * xt * (1 - xt**3)
    vy = -2.0 * xt**2 * yt * (1 - yt**3)
    angle = np.atan2(vy,vx)
    val.append(angle)
return np.array([val])

rge = np.arange(-0.2, 0.2, 0.001)
a = np.array(rg)
speedy = 0.1 #vy

ans = odeint(function, a, speedy)

plt.plot(ans, a)

A: When you return np.array([val]), that makes a two dimensional array because val is already an array. That is why the shape is (1,400) which makes it two dimensional with the size of the first dimension being 1. You can try:
return np.array(val)

That may help. Also, the code you have pasted has obvious bugs which I am assuming are typos like angle.append should have been val.append.