Formula for the maximum smallest-distance between $m$ points in a regular $n$-gon?

Question: Let the smallest distance between $m$ points in a regular $n$-gon be denoted by $D$. Is there a general formula for $D_{\mathrm{max}}$? In other words, how should $m$ points be placed so that they are all spread as far apart as possible. For example, for a triangle and $m \leq 3$ we would place all the points on the vertices. This can be extended to any $n$-gon: place $m \leq n$ points on all the vertices. Then I imagine the $(n+1)$-th point should be placed in the center. From there I don't know if it should be on the midpoint of the edges or somewhere in the middle of the shape.
I don't know if this has an answer (maybe it is more simple than I think), I just saw a similar question and was curious if it could be generalized.
Comment: Could you share a link to this similar question you mentioned?
Comment: [link] (https://www.quora.com/There-are-8-points-chosen-in-an-equilateral-triangle-the-minimum-distance-between-any-2-points-is-D-what-is-the-maximum-possible-value-of-D) is the general idea.
Comment: Packing problems are hard.  You could look at [Packomania](http://www.packomania.com/) to see what strange configurations are optimal.
Answer: Instead of having points at distance $D$ or more from each other, you might also consider disks of radius $\frac D2$ that don't overlap. Having the points inside a regular polygon means having the disk centers in that polygon, which in turn means having the whole disks in a polygon which is a larger copy of the original, with the edges moved $\frac D2$ to the outside. Instead of asking to maximize $D$ for a given number of points and a given $n$-gon you can also keep $D=1$ and ask for the smallest $n$-gon containing this many unit disks. So now you are in the realm of packing a regular polygon with disks. Which is a hard problem.
Erich's Packing Center lists a few of these: disks in triangles, squares, pentagons and hexagons. Observe how there is no simple formula describing all of these cases, but each combination $(m,n)$ is described individually. Observe how many of the configurations look far from regular. Also observe the distinction between "Proved by …" and "Found by …". The latter usually describe the best known solution, but no known proof of optimality. At the time of writing, but even if some of these might have been proven by now, the general message of "this is really hard" still holds.
Comment: The $(3,4)$ case is a counterexample to one of the conjectures in the question: "place $m≤n$ points on all the vertices". However the other conjecture, "the $(n+1)$-th point should be placed in the center", does seem to hold.


Goldberg variations - chord progression changes between variations

Question: The Wikipedia article on the Goldberg variations sets out the chord progression which all variations follow. In some bars, different options are separated by commas and it says there are different options taken by different variations.
What is meant by the comma notation here? In particular, what options are being indicated? For example, the first label is '3,5,6#'. Presumably one of the options is E major (E,G#,B), corresponding to '3,5' (or perhaps just to '3'?). What are the alternatives? In the case of 6#, is it supposed to be (E,G#,C#), (E,G#,B,C#), or perhaps something else? How many possibilities are being listed here?
Comment: Hi Doktor Mayhem, I'm new to the site - curious why the second question asking for a reference setting out which variation follows which chord options was deleted. It may be a silly question - if so, understanding why might help my confusion!
Comment: you can see the comment on the edit to tell why it was deleted. it says it was because there were multiple questions in a post.
Answer: TL;DR
By 3,5,6# (Kirkpatrick actually writes "3,5, or 6#" — the "or" making things much more clear) Kirkpatrick is saying that sometimes only the third above the bass is included (3), sometimes a complete root position chord appears (5), and sometimes a first inversion chord (6#).

Kirkpatrick's explanation
Here is and excerpt of what Kirkpatrick has to say about the harmonic structure (see also the image below).

The fundamental bass is never state entirely in its most elemental form, as quoted here (Ex. 1), not even in the Aria....

Certain alterations to the fundamental bass are to be found. For example, chords of the sixth are interchanged with their root positions, and vice versa. It even happens that a six-four is substituted for a sixth-chord. The bass, the third, the sixth, or even the fifth is occasionally sharpened or flattened. In some places there is a certain interchange or ambiguous hesitation between the fifth and the sixth, with much use of the third alone against the bass, in order to leave this ambiguity free of limitation or definition.

Examples
Taking the third measure of Kirkpatrick's outline as an example, instances of each option can be found as follows.
3: Variation 1, m. 3
Variation 1 contains only the bass note (E) and the third above (G), leaving open whether it's a root position E minor chord or a first inversion C# diminished chord. Note that the C# occurring during beat 3 is not part of the bass-E chord. Rather, it's part of an A major chord leading to the D minor chord in the next measure.

5: Variation 3, m. 2
In variation 3, the first two beats of measure 2 comprises a root position E minor chord. The C# here is a passing tone and does not affect the harmony.

6#: The Aria, m. 3
Here is shown measure 3 of the Aria. It contains the chord E-G-C#, which is a first inversion C# diminished triad, the C# being a raised sixth above the bass E.
Comment: Thanks for your very detailed reply. I had looked at variation 1 and incorrectly concluded that the C# was part of the bass E chord - how could I tell that this is not the case? Based on this and variation 3, am I right to interpret your comment as saying that there is no unambiguous conclusion about which option is being taken in each of these cases?

I was going to ask if there is a reference listing out which option is taken by each variation, but perhaps no such definitive list could exist?
Comment: @octopus The primary evidence that the C# is not part of a diminished chord is the prominent placement of A on beat 3 and the "&" of three. A isn't part of either a C#dim or Emin chord, and it's placement draws the ear toward A major. Although Kirkpatrick mentions ambiguous scenarios, I didn't look for one, and Vars 1 and 3 are, in my view, unambiguous. Var 1 is "unambiguously ambiguous" — meaning, it's just a third, with no commitment or even hint at a specific chord; and Var 3 is definitely a root position E minor chord.
Comment: @octopus Regarding the reference: unfortunately, Kirkpatrick seems not to lay out a detailed analysis, and I'm not aware of another one.
Answer: The numbers correspond to figured bass numerals of interval sizes (adjusted with accidentals as necessary) above the notated bass note. Note that interval sizes with no accidentals are assumed to take their notes from the home key only.
Note that the first appearance of the "3,5,6♯" figured bass numerals is above an E note in the bass. This means that you can play E-G, E-B, and E-C♯.
The true Goldberg variations according to your provided https://en.wikipedia.org/wiki/Goldberg_Variations#Form are more complicated than just picking among 3, 5, and 6♯. In fact, a good argument can be made that Variatio 5. a 1 ô vero 2 Clav. uses the entire 3/5/6♯ shebang with its use of E, G, B, and C♯:
Comment: Thanks for your answers. So in the "3,5,6#" example, does that just mean the chord is E, G, B, C#? I'm confused by the text underneath which says "where digits are separated by comma, they indicate different options taken in different variations". I had assumed 3,5,6# would correspond to different options?
Comment: @octopus - Oops, I forgot to investigate that phrase further - turns out that the Goldberg variation actually does ambiguously flip between all 3 options and even combinations thereof. I edited my answer accordingly.
Comment: The measure is a 6# chord. The B is not part of the harmony in this case.
Comment: Note that the B — which would be the chordal seventh — does not properly resolve in the following measure.
Comment: @Aaron - I have a tough time believing that the A at Beat 4.5 of Bar 3 of Variation 5 is a chord tone, and therefore an even tougher time believing that the B approached by leap and departed by step at Beat 4.25 is a nonchord tone, especially since we can explain it as a chord tone so easily and still stay within common practice period harmony.
Comment: (I assume you mean beat 3.5, rather than 4.5). The A isn't a chord tone (unless one interprets it as an anticipation of m. 4's d minor). The chord is C# dim in first inversion.
Answer: These are the intervals played above the bass note. As we aren't able to notate them vertically like blockchords they are written with  a comma. Usually the 3 and 5 isn't notated for every one it's clear they are played. 6 means first inversion. 5,6 means the dominant 7th chord first inversion.


How to fade in background image by CSS3 Animation

Question: I am making a menu that each item has a text like item1, item2 and etc.  in hover the background colour changes, text becomes transparent and a background image replaces. I used this code to ease in and out the style. but it only works for background colour and not the image.
#nav li:hover {
    color:transparent !important;
    text-shadow: none;
    background-color: rgba(255, 0, 0, .5);

    -webkit-transition: all 1s ease-in;
    -moz-transition: all 1s ease-in;
    -o-transition: all 1s ease-in;
    -ms-transition: all 1s ease-in;
    transition: all 1s ease-in;
}

Here is the online version:
http://jsfiddle.net/q4uHz/
Answer: Background images cannot be animated; there would be no algorithm for that.  A simple solution is to include  with the icon in your HTML instead with opacity: 0 and animate that.  Something like.

Home

#nav li {
    position: relative;
}
#nav li img {
    opacity: 0;
    position: absolute;
    transition: all 1s ease-in;
    top: 0;
    left: 0;
}
#nav li:hover img {
    opacity: 1;
}

Full example on this snippet:

#nav {
    font: 14px 'LeagueGothicRegular', Arial, sans-serif;
    color: #f9f8cc;
    width:300px;
    clear: both;
    height: 58px;
    margin: 5px 0px 0px 50px;
    background:#c2c2c2;
    opacity:.8;
}

#nav ul {
    margin: 0;
    padding: 0;
}
#nav li {
    list-style-type: none;
    background-image: none;
    color: #FDE99D;
    float: left;
    height:48px; width:85px;
    border-right:1px #333333 solid;
    text-align:center;
    padding-top:10px;
    position: relative;

    -webkit-transition: all 1s ease-out;
    -moz-transition: all 1s ease-out;
    -o-transition: all 1s ease-out;
    -ms-transition: all 1s ease-out;
    transition: all 1s ease-out;
}

#nav li a {
    color: #000;
    text-shadow: 0px 2px 2px #222;
    text-transform: uppercase;
}

#nav li:hover a {
    color: #999;
    color:transparent !important;
    text-shadow: none;

}

#nav li:hover {
    color:transparent !important;
    text-shadow: none;
    background-color: rgba(255, 0, 0, .5);

    -webkit-transition: all 1s ease-in;
    -moz-transition: all 1s ease-in;
    -o-transition: all 1s ease-in;
    -ms-transition: all 1s ease-in;
    transition: all 1s ease-in;
}
#nav li img {
    opacity: 0;
    position: absolute;
    transition: all 1s ease-in;
    top: 0;
    left: 0;
}
#nav li:hover img {
    opacity: 1;
}

         Home

         Contact


Virtualization vs Cloud

Question:
Possible Duplicate:
What is the difference between a cloud server a virtual server and a dedicated server?

Can anyone explain the difference between virtualization and cloud (w.r.t. citrix and openstack) ???
I have a server installed with Citrix and another with openstack; local- in my office. In their own documentation, Citrix says it is virtualization where as openstack says it is a private cloud....
I have searched on many blogs. They are saying both are different. I am really confused. I could'n find any differences !!!!!
Comment: Bijo, folks on this site don't pull punches.  If they don't like a question they down vote it.  If they do like it they up vote it.  That's pretty much the way the site works.
Comment: Yes... I read it. Only the tags are same. I couldn't find my answer. ErikA, could you just point out the differences from the above link you entered ????????????? Thanks in advance...........
Comment: "Cloud" is marking BS for manageable virtualization technologies. It's not a concrete technology.
Comment: Thanks  Chris......... BS? any branding or standard ??? other than this, citrix and openstack are same???
Comment: Somebody 'down voted' my reputation (-2) . May be due to a similarity of tags or subject. Anyways that was REALLY NICE !!  VERY FRIENDLY PORTAL to new ones !! I WILL RECOMMEND ALL MY FRIENDS to use http://serverfault.com/ !!!!!!!
Comment: indeed, its mostly aimed at it professionals so some questions get downvoted if they're considered a bit below the bar. Everyone gets the odd downvote now and then though.
Answer: Virtualization is a technology where many servers are run on a single piece of hardware.  IBM has been doing it for decades called LPARs.  Currently platforms like vSphere, and Hyper-V, are the virtualization platforms used by the most people.
Private cloud is pretty marketing speak for running a group of virtualization hosts (the physical machines) so that you can quickly and easily deploy new servers into the "cloud".
Citrix isn't really a virtualization platform like vSphere or Hyper-V (or Zen or any of the smaller packages).  It gives you a physical system that applications are installed on.  The end user then connects to the Cirtix server basically over RDP running the application on the server, but showing the application on the users desktop.  Microsoft has a competing technology called App-V (Application Virtualization).
I can't speak to openstack as I'm not familiar with it.

Virtualization vs Cloud


WebApi AuthorizationFilterAttribute: ActionArguments are empty

Question: I'm implementing an AuthorizationFilterAttribute for a WebApi controller, but I don't seem to have access to the parameters that are being passed into the controller:
In MVC4, this works fine:
public class MyMVCController : Controller
{
    [CanAccessMyResourceApi]
    public MyViewModel Get(int id)
    {
       //...
    }
}

public class CanAccessMyResourceMVCAttribute : CanAccessAttributeBase
{
   public override void OnAuthorization(AuthorizationContext filterContext)
   {
       var param = filterContext.Controller.ValueProvider.GetValue("id")
       /// ...
   }
}

But in WebAPI, I think the parameter should be in the ActionArguments, but "param" here is empty:
public class MyWebApiController : ApiController
{
   [CanAccessMyResourceWebApi]
   public MyViewModel Get(int id)
   {
      //...
   }

}

public class CanAccessMyResourceWebApiAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext filterContext)
    {
        // the debugger shows that ActionArguments is empty:
        var param = filterContext.ActionArguments["id"]
        /// ...
    }
}

Is the parameter that's being passed into the controller available somewhere else?  (I  verified that the controller's action is getting the Id value correctly when I remove the filter attribute.)
Comment: Looks like it can be done with an ActionFilterAttribute instead: http://stackoverflow.com/questions/12817202/accessing-post-or-get-parameters-in-custom-authorization-mvc4-web-api
Comment: ParameterBinding happens after AuthorizationFilters are run in Web API, so i believe what you are seeing is expected behavior.
Answer: Have you taken a look at the solutions from this StackOverflow page?
Specifically:
var variable = HttpContext.Current.Request.Params["parameterName"];

public class CustomAuthorizeAttribute : AuthorizeAttribute
  {
     protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
     {
        var clientId = actionContext.ControllerContext.RouteData.Values["clientid"];

     }
  }

Hope this helped!


ASP.NET Core. How can I invalidate JWT-Token after password change

Question: Sorry for my bad English. I'm writing an application in ASP.NET Core using Vue.JS for client-side. For authenticate user I'm using JWT and ASP.NET Identity. I have a method for change the password. But I can't understand: How to invalide token after password change? I want that the user authenticated in another browser will logout after that. Is there a man who haved a problem like this?
Comment: Hi, Refer this link [https://stackoverflow.com/questions/31919067/how-can-i-revoke-a-jwt-token] for JWT-Token Revoke
Answer: You normally don't invalidate JWT's because they are meant to be short-lived access tokens and therefore after the password change, request for new token will prompt the user to reenter credentials.
If you do absolutely need to invalidate the JWT immediatelly after password change - you need to look into Introspection where your backend api essentially has a backchannel to your token issuer and it can then re-validate token every request. This way if you invalidate token at the issuer side - it will reflect on the api side immediately.
Comment: Thansk for an answer. I have a one variant. Can I change a life time of token?
Comment: @General2001 - usually - yes, but it depends on which JWT token provider you are using.
Comment: I make everything like here: https://metanit.com/sharp/aspnet5/23.7.php.
Comment: Sorry if I can't to explain more extensively. I started doing this recently. I'm about JWT.
Comment: @General2001 in your example, there is configuration for token lifetime `expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),` in `AccountController`
Comment: An how can I invalidate that?
Comment: Is I understod, I should to generate JWT-Token again?
Comment: You can't, just set lifetime to like 30minutes or something like that and it will be
Comment: Can you show some code, please? I may noob. I will be grateful.
Comment: If I invalide a lifetime of token (set 10 seconds, for example), I'll have to login again (every 10 seconds). I'm right?
Answer: I've been thinking about this and the inability to invalidate a JWT that's already out there may not be built into anything, but is possible.
Here's the narrative: You have an alarm system installed that can be controlled via web and your ex-S/O is logged in to your previously shared account. They are upset and they keep enabling the alarm at random times.
If the web app uses JWTs to store session, you could change your password but the JWT your ex possesses will still be usable for a period of time until the timeout is reached.

Solution 1: short timeout. but what if you want to stay logged in for longer periods (such as a password manager)
Solution 2: logout ALL users by changing the Signing Key of your Certified Authority, basically invalidating ALL JWTs across the board. This is still a less ideal route as I'm sure you can imagine.
Solution 3: track the current JWT for each user in your Users table. If the JWT they possess is different from the current one, then they aren't authenticated. If the user logs out, nullify the stored JWT-data in your Users table which would equally unauthenticate JWTs for that user and force a relogin.
I'd also recommend storing a bool of "logged in" for the user. DO NOT RELY ON THIS. This would be a value to set to true when they log in, set it to false when they log out, and validate the value is 'true' if they ever pass you a JWT. This will ensure that the moment they logout they are forced to reauthenticate.

Assuming you go with solution 3:
When storing JWT data for this solution, I'm leaning towards not storing the entire JWT because it's rather large text to begin with. Alternatively just store the JWS (JWT Signature) which will make the stored value both smaller and unusable if captured for any reason.
Next, it's a hash to begin with so we could just store the last maybe 9 values (9 because int32 max is 2147483647). We just need a bit of uniqueness, not much.
Next, we could avoid the string comparison for validating that the JWS passed is the active one if we use regex to pull the integers out of the JWS and again take maybe the first 9 numbers you encounter.
Following this method, and returning to the narrative, if you were to log out your user would be marked as logged out resulting in both yourself and your S/O being required to reauthenticate. (assuming you've changed your password you're golden, otherwise it's time to contact Customer Support)
If you were to log back in, you'd get a fresh JWT and a new signature would be stored in the Users table. If your S/O were to try to use the site, they would not be authenticated with the their old JWT and would be forced to sign back in.
Trade-off: If we only store the JWS, or a part of it as I suggested, multiple users can't be signed in to the same account at once. How you feel should feel about that really depends on your app.
Comment: I'd say option one, and maybe option two in some rare cases
Answer: After creating table in ms sql server
CREATE TABLE [dbo].[AspNetRevokeUserToken](
    [Email] [nvarchar](256) NOT NULL,
    [HashToken] [nvarchar](70) NOT NULL,
    [Expiration] [datetime] NULL,
 CONSTRAINT [PK_AspNetRevokeUserToken] PRIMARY KEY CLUSTERED
(
    [Email] ASC,
    [HashToken] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

addin model class
[PrimaryKey(nameof(Email), nameof(HashToken))]
public class AspNetRevokeUserToken
{
    public string Email { get; set; }

    public string HashToken { get; set; }

    public DateTime Expiration { get; set; }
}

adding DbSet in MyDbContext
public class MyDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
{
    public MyDbContext (DbContextOptions<AlphaVisionDbContext> options) : base(options)
    {
        Database.EnsureCreated();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public DbSet<AspNetRevokeUserToken> AspNetRevokeUserToken { get; set; }
}

I do like this in Programm.cs
builder.Services.AddScoped<UserTokenValidation>();

builder.Services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.SaveToken = true;
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = builder.Configuration.GetSection("Jwt:Issuer").Value,
            ValidateAudience = true,
            ValidAudience = builder.Configuration.GetSection("Jwt:Audience").Value,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration.GetSection("Jwt:Key").Value!)),
            ValidateIssuerSigningKey = true
        };
        options.EventsType = typeof(UserTokenValidation);
    });

then in other class UserTokenValidation.cs doing magic))
public class UserTokenValidation : JwtBearerEvents
{
    public override Task TokenValidated(TokenValidatedContext context)
    {
        ClaimsPrincipal userPrincipal = context.Principal;

        if (userPrincipal == null) context.Fail("No user");

        var email = context.Principal.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value;

        if (email.Equals("admin@.....ru")) {
            return Task.CompletedTask;
        }

        var _userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
        var user = _userManager.FindByEmailAsync(email).Result;

        if (user != null)
        {
            if (!user.ApiEnabled ?? false)
            {
                context.Fail("User has blocked");
                return Task.CompletedTask;
            }

            var accessToken = _userManager.GetAuthenticationTokenAsync(user, "provider", "AccessToken").Result;
            if (!string.IsNullOrEmpty(accessToken))
            {
                var tokenTmp = new JwtSecurityTokenHandler().ReadJwtToken(accessToken);
                var hash = SHA256.HashData(Encoding.UTF8.GetBytes(accessToken));
                var hashString = Convert.ToBase64String(hash);

                var _dbContext = context.HttpContext.RequestServices.GetRequiredService<MyDbContext>();
                if (_dbContext.AspNetRevokeUserToken.Any(x => x.Email == email && x.HashToken == hashString))
                {
                    context.Fail("Token has blocked");
                    return Task.CompletedTask;
                }
            }
        }
        else
        {
            context.Fail("User not in DB");
            return Task.CompletedTask;
        }

        return Task.CompletedTask;
    }
}

I hope it helps


How to get first submenu item path?

Question: I need to create a link to first submenu item from specific menu. The link will be placed in custom block.
To be more precise, I have a menu with following structure:
parent-menu
 item-1
 item-2
 item-3
 ..

I need that after clicking "parent-menu" user would end up in item-1 page. Also, there will be several links in some blocks, linking to "parent-menu" - they need to open 'item-1' item too.
My current approach is to create 'parent-menu' page template override which finds top child item from 'parent-menu'. That page will be linked from content and main menu.
Problem is that I need a way to find first menu sub item from code.
UPDATE:
Ended up on using query:
$link_path = db_select('menu_links', 'n')
->fields('n', array('link_path'))
->condition('n.plid', '269', '=')
->orderBy('weight', 'ASC')
->range(0, 1)
->execute()
->fetchField();

Is there any alternative way to do this, without querying database?
Answer: I found this module Menu Firstchild maybe it will do what you want it to do.
Comment: Sadly, this module works with menu only, and it is impossible (or I just don't know how) to create a link in content pointing to same  item.
Answer: You can use the ctools page manager to do a redirect. ( Page manager is basically a GUI for hook_menu_alter(); ) If you aren't familiar with it, the quickest way to learn it is to watch Johan Falk's screencast series at Nodeone.se
Using page manager, you can easily redirect one page to another.
Sub-menu Tree is another module you may want to try out. It will make a page for the parent menu item that lists all of the child items.
Answer: I have added this piece of code at the bottom of my tepmlate file (before closing body), it takes the name and target of the parent link and then injects it as the first item in the sub-menu. It will work with morst browsers, what was good enough for my client.

Answer: You can use menu_tree() and menu_link()
menu_tree creates the
 wrapping while menu_link creates the menu list items

Inside menu_link() you can find $submenu, this contains an array with the submenu.
This function return this

' . $output . $sub_menu . "
\n";
Cheking the variable $element you can find the all the things for the list item
i.e. Title, link etc...
So, if you want to do this for all the link in the first level:
if ($variables['element']['#original_link']['depth'] == 1)

or you can find the objects that say "has a sub menu and it's expanded"
Then you can rewrite your $output giving the item name with the first submenu item link.
I hope it's clear.

How to get first submenu item path?


bind named server - forward some requests to other servers

Question: Is there a way to make bind answer some queries but forward all other queries (of the same domain) to another server, as in:
example.com A 127.0.0.1
www.example.com A 127.0.0.1

everything not on this list (example.com MX, ftp.example.com A etc) - ask 192.168.0.1 (another DNS server)
Essentially I want to intercept some (but not all) queries going to (in this example) 192.168.0.1 and answer for it.
example.com A- intercept
www.example.com - intercept
example.com MX - pass trough
ftp.example.com - pass trough

Answer: Your BIND server will by default use the DNS servers in /etc/resolv.conf to resolve records that it isn't authoritative for, but only for localhost (i.e. itself) and localnets (see below). You should make sure that these are set accordingly.
Definition of localnets:

matches all the IP address(es) and subnetmasks of the server on which BIND is running. For example, if the server has a single interface with an IP address of 192.168.2.3 and a netmask of 255.255.255.0 (or 192.168.2.2/24) then localnets will match 192.168.2.0 to 192.168.2.255 and 127.0.0.1 (the loopback is always present and has a single address, that is a netmask of 255.255.255.255). Some systems do not provide a way to determine the prefix lengths of local IPv6 addresses. In such a case, localnets only matches the local IP addresses, just like localhost though in this case it will apply to external and internal (same host) requests.

You can also explicitly define global forwarders like this, remembering to secure your environment:
options {
  recursion yes;
  allow-recursion-on {
    192.168/24;
  };

  forwarders {
    184.108.40.206;
    188.8.131.52;
  };
};

If you want to direct queries for a specific domain to specific servers, you can do this by configuring forwarders for individual domains:
zone "myothernet.local" {
  type forward;
    forwarders {
      192.168.50.11;
      192.168.50.12;
    };
};

Further reading:

http://www.zytrax.com/books/dns/ch2/index.html#recursive
http://www.zytrax.com/books/dns/ch7/queries.html
Comment: But can I split a domain, that is - lookup example.com locally, but ftp example.com from the other server (I'll edit the question to better explain it).
Answer: This is rather tricky to do with BIND.  While it isn't quite what you asked have you considered using another DNS server like DNSMasq where this sort of thing is relatively simple?
Comment: Actually, DNSMasq looks like exactly what I want. Thank you
Answer: I think you need subdomain delegation.. However, it is usually set up to point a specific subdomain in a zone to another server.
In your case, it might be easier to give the zone to your secondary server, set up a wildcard record in there, and set up subdomain delegation for that specific subdomain pointing to your primary server..
Comment: This was my first though as well, but the problem is that "example.com" should be answered by the primary server. Essentially I want to intercept some queries.
Comment: Yeah, unfortunately wildcards are not valid in zones (although I could be mistaken) so it's hard to delegate "everything else" in that sense.


addTools is giving exception in rappidjs

Question: In context of one of my assignment I was trying to use RappidJS. I was trying the below code for connecting an element by dropping it over another element.
https://resources.jointjs.com/tutorial/connecting-by-dropping
But I am getting exception as below
rappid.min.js:14 Uncaught TypeError: Cannot read property 'start' of null
at child.update (rappid.min.js:14)
at child.onRender (rappid.min.js:14)
at child.e.render (rappid.min.js:14)
at child.configure (rappid.min.js:14)
at child.addTools (rappid.min.js:14)
at child.element:pointerup (diagram.js:106)
at triggerEvents (backbone.js:338)
at triggerApi (backbone.js:322)
at eventsApi (backbone.js:110)
at child.Events.trigger (backbone.js:312)

I also took reference from below link
https://resources.jointjs.com/tutorial/link-tools .
Can any one suggest me what wrong I am doing here.
My code snippet is as below
 function attachLinks(paper) {
                paper.on({
            'element:pointerdown': function (elementView, event) {
                event.data = elementView.model.position();
            },
            'element:pointerup': function (elementView, event, x, y) {
                var coordinates = new joint.g.Point(x, y);
                var elementAbove = elementView.model;
                var elementBelow = this.model.findModelsFromPoint(coordinates).find(function (el) {
                    return (el.id !== elementAbove.id);
                });
                // If the two elements are connected already, don't
                // connect them again (this is application-specific though).
                if (elementBelow && self.graph.getNeighbors(elementBelow).indexOf(elementAbove) === -1) {

                    // Move the element to the position before dragging.
                    elementAbove.position(event.data.x, event.data.y);
                    // Create a connection between elements.
                    var link = new joint.shapes.standard.Link();
                    link.source(elementAbove);
                    link.target(elementBelow);
                    link.addTo(this.model);
                    // Add remove button to the link.
                    var removeLinkTool = new joint.linkTools.Remove();

                    var tools = new joint.dia.ToolsView({
                           tools: [ removeLinkTool]
                    });

                    var linkView = link.findView(this);
                    linkView.addTools(tools); // getting exception at this place.
                }
            }
        });
        }

Answer:
This issue is reproducible only in the paper async mode.

Make sure the view for the link is rendered when you add the link tools. For this please use joint.dia.Paper.prototype.requireView().
// It is fine to use the method in the `sync` mode as the view is rendered/updated
// synchronously as soon as the link is added to the graph.
var linkView = link.findView(paper);

// This method makes sure the view is ready to use in the `async` mode.
// It forces the view to render/update synchronously.
var linkView = paper.requireView(link);

Alternatively, you could pass async = false flag when adding the link to the graph to tell the paper to render the particular view synchronously.
link.addTo(graph, { 'async': false });


C mktime() printing issue

Question: iam working on program which separates characters by meaning. Currently i got issue with function konverzia. It should add name of day (wed, thu, fri...) to date string, but it doesnt give a shit. Date have to look like this Wed 2012-02-01 Thanks for any ideas.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>

 void vstup (int i, char buffer[], int s, int c)
  {
        printf("\n Type text for analysis: \n ");
        scanf ("%80s", buffer);      /* Read a string into buffer  */
  }
 void detekcia (int i, char buffer[], int s, int c, int z)
  {
         while(buffer[i] != '\0') {
            if(isalpha(buffer[i]))
                 s++;                /* Increment letter count     */
            if(isdigit(buffer[i++]))
                 c++;                /* Increment digit count      */
            if(ispunct(buffer[i++]))
                 z++;
                                  }
        if (s >= 1 && c >= 1)
          printf("\n word: %s \n", buffer);     /*kombinacia cisla a pismena*/
        if (s >= 1 && c == 0)
          printf("\n word: %s \n", buffer);     /*WORD*/
        if (s == 0 && c >= 1 && z == 0)
          prvocislo (i,buffer,s,c);             /*NUMBER*/
        if (s >= 0 && c >= 1 && z >= 1)
          datum (i,buffer,s,c,z);               /*DATE*/
 }
  int prvocislo (int i, char buffer[], int s, int c) /*prime number fun*/
  {
        int x,count=0;
        int k = atoi(buffer);

        for (x=2; x<=k/2;x++){
            if (k%x==0){
                count++;
                   break;
                }
        }
        if (count==0 && k!=1 && k!=0)
            printf("\n number: %d (prime)\n",k);
        else
            printf("\n number: %d",k);
  }
  int datum (int i, char buffer[], int s, int c, int z)
  {
        int q = 0;
        char d[2];
        char m[2];
        char r[4];

        if (buffer[4]=='-' && buffer[7]=='-')
           q++;
    if (q==1 && buffer[5]<='1')
           q++;
        if (q==2 && buffer[8]<='3')
           q++;
        if (q==3){
           q++;
           d[1]==buffer[9];
           d[0]==buffer[8];
           m[1]==buffer[6];
           m[0]==buffer[5];
           r[3]==buffer[3];
           r[2]==buffer[2];
           r[1]==buffer[1];
           r[0]==buffer[0];
                 }
        if (q==4)
           konverzia (d,m,r);
   }
   int konverzia (char d[], char m[], char r[])
  {
        int rr = atoi(r);
        int dd = atoi(d);
        int mm = atoi(m);
        int ret;
        struct tm info;
        char date[10];

        info.tm_year = rr - 1900;
        info.tm_mon = mm - 1;
        info.tm_mday = dd;
        info.tm_wday = dd;

        ret = mktime(&info);
        if (ret == -1){
        printf("time error");
                      }
        else{
           strftime(date, sizeof(date),"%c",&info);
           printf(date);
            }

        return(0);
  }
  int main() {

  char buffer[80];
  int i = 0;
  int s = 0; /*pismeno*/
  int c = 0; /*cislo*/
  int z = 0;
  vstup (i,buffer,s,c);
  detekcia (i,buffer,s,c,z);
  return 0;
  }

Comment: Ten chars is not even enough to print a regular data like 2015-10-16, let alone one with a weekday. If you want to enforce a certain date format, you can construct it on your own instead of relying on the preferred format `%c`.
Comment: "info.tm_wday" gives you 0-6 for Mon, Thu, ... - so go to google and look for "switch/case" and solve it.
Answer: If you want a particular format, you have to constructa custom format string. The possible entries are listed in the documentation for strftime. The %c format that you use is just the preferred format of your locale.
There are some issues with your code:

You shouldn't set tm_wday to the day of the month. tm_wday is an index of the weekday, starting with 0 for Sunday.
You should initialise your struct tm to zero, so that fields that you don't assign don't have nonsense values.
Your date buffer is too short. strftime guards against overflow, but the date will be truncated.
Don't printf strings directly, use printf("%s", str) instead. In particular, the format string shouldn't be a string you don't control. For example, an unknown % sequence in strftime might not get converted and will falsely be interpreted as printf format without the correct argument. Some static analysis tools insist on using only string literals as format strings. Good practice, I think.

So:
int konverzia(const char d[], const char m[], const char r[])
{
    int rr = atoi(r);
    int dd = atoi(d);
    int mm = atoi(m);

    struct tm info = {0};

    info.tm_year = rr - 1900;
    info.tm_mon = mm - 1;
    info.tm_mday = dd;

    if (mktime(&info) == -1) {
        printf("time error\n");
        return -1;
    } else {
        char date[20];

        strftime(date, sizeof(date), "%a %Y-%m-%d", &info);
        printf("%s\n", date);
    }

    return 0;
}

Comment: Thank you very much for your time, i really appreciate your help, but look what it did to output:::::::.....                                                                      Type text for analysis:
 2001-11-11
**Tue -1-11-30**:................... and it doesnt matter which input i type, it is always giving this Tue date
Comment: I haven't looked much at your program outside the `konverzia` function and I have tested it with a few dates explicitly, like `konverzia("16", "10", "2015");` I suggest you check the strings that you pass in. Doing a few more tests, I see that `mktime` "normalises" bad input, so that 31 June is really 1 July. That means that you should add extra checks for validity instead of relying on `mktime` returning -1.
Comment: Thanks a lot! finally i found the mistake, and now it works great :)

C mktime() printing issue


Getting verify.dll not found error message while opening Eclipse IDE

Question: My Eclipse IDE(INDIGO) was working perfectly till last week. But Now, while I try to open my eclipse am getting "This application has failed to start because verify.dll was not found. Re-installing the application may fix this problem." I googled about this error and I did some tries but it doesn't works. :(

Tries which I made:

downloaded verify.dll and placed in plugins folder under eclipse root directory.
downloaded verify.dll and placed in windows32 folder.
Downloaded different Eclipse versions and getting same error messages for those versions also.

Pls... help me to resolve this error.
Answer: I solved this problem as follows:
Searched on my C:\ drive for "verify.dll".
Found it in C:\Program Files\Java\jdk1.7.0_17\bin
In my PATH environment variable, I had a path to C:\Program Files\Java\jre7\bin, which doesn't contain a verify.dll file.
Changed the path to C:\Program Files\Java\jdk1.7.0_17\bin in the PATH variable, and re-started Eclipse successfully.
Answer: Well, have you tried to uninstall, and re-install it completely? This should help, as stated in the dialog.
Comment: I have not using eclipse as installed in my machine. I am just using it as a plug and play. I have just opening it by executing eclipse.exe file.
Comment: Download the zipped version.
Answer: I've changed the path of Java (I had the problem with Juno 4.2) to C:\Program Files (x86)\Java\jdk1.7.0_45\jre\bin (Windows 8 OS).
Answer: Try to copy a valid verify.dll here:
C:\Program Files\Java\jdk1.7.0_??\jre\bin
Answer: I had this problem. I uninstalled java and eclipse.
Then I reinstalled them by first installing java than eclipse as I read that java must be installed before eclipse and it fixed it for me.


Sorting in Java from external text file

Question: This data is saved in data.txt I am trying to write a program that can arrange
18b0885  // this is the registration number, bullet points to show indentation
   SS844 Parallel Algorithms        //  These are course taken by student
   SS555 Calculus for Distributed Computing
   SS501 Quantum Communication

17b0585
   SS828 Problem Based Programming
   SS660 Genetic Computation
   SS567 Hacking Quantum Network

17b2582
   SS567 Hacking Quantum Network
   SS876 Positronics
   SS880 Quark-based Logic

A big list of data like this, And need to write a program to short this data is ascending order by registration number and course will follow the registration number. so the expected out put is like this.

17b2582
   SS567 Hacking Quantum Network
   SS876 Positronics
   SS880 Quark-based Logic

17b0585
   SS828 Problem Based Programming
   SS660 Genetic Computation
   SS567 Hacking Quantum Network

18b0885
   SS844 Parallel Algorithms
   SS555 Calculus for Distributed Computing
   SS501 Quantum Communication

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Sort {
    public static void main(String[] args) throws Exception {
     BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
     Map<String, List<String>> map = new TreeMap<String, List<String>>();
     String line = reader.readLine();//read header
     while ((line = reader.readLine()) != null) {
      String key = getField(line);
      List<String> l = map.get(key);
      if (l == null) {
       l = new LinkedList<String>();
       map.put(key, l);
      }
      l.add(line);

     }
     reader.close();
     FileWriter writer = new FileWriter("sorted_numbers3.txt");
     writer.write("");
     for (List<String> list : map.values()) {
      for (String val : list) {
       writer.write(val);
       writer.write("\n");
      }
     }
     writer.close();
    }

    private static String getField(String line) {
     return line.split(",")[0];//
    }
}

The above program out puts into another text file like this
    SS501 Quantum Communication
    SS555 Calculus for Distributed Computing
    SS567 Hacking Quantum Network
    SS567 Hacking Quantum Network
    SS660 Genetic Computation
    SS828 Problem Based Programming
    SS844 Parallel Algorithms
    SS876 Positronics
    SS880 Quark-based Logic

    17b2582
    17b0585
    18b0885

It shorts all the coureses by ascending order then registration numbers but not what I want. What should I change?
Comment: I don't understand what sorting you expect to happen. Your sample output doesn't seem to be sorted...?
Comment: You should really just include the raw text formatted as is in the data file and also how you want the output. You can use spaces (like code formatting) to make sure the line/space formatting is retained. Most people will ignore the syntax highlighting if you say it is input/output text (or you can tell the syntax highlighter that it is text)
Comment: And you haven't asked a question.
Answer: Well, as others have said your example output is not in any sorted order I can see.  If you actually want alphabetical order of serials, then this will do it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Sorter {

    static List<Data> read() throws FileNotFoundException, IOException {
        BufferedReader reader = new BufferedReader(new FileReader("data.txt"));
        List<Data> list = new ArrayList<>();
        String line;
        Data data = null;
        while ((line = reader.readLine()) != null) {
            if (line.matches("\\s*")) {
                continue; // skip blank lines
            }
            // Assume line that begins with space is a course.
            if (Character.isSpaceChar(line.charAt(0))) {
                //  Add new course to data if it's there.
                if (data == null) {
                    System.err.println("Missing serial for course " + line);
                } else {
                    data.courses.add(line);
                }
            } else {
                // Add completed data to list if there is one.
                if (data != null) {
                    list.add(data);
                }
                // Make new data with this serial.
                data = new Data(line);
            }
        }
        // Add the last data to the list if there is one.
        if (data != null) {
            list.add(data);
        }
        return list;
    }

    public static void main(String[] args) {
        try {
            // Read.
            List<Data> list = read();

            // Sort based on serials.
            Collections.sort(list, new Comparator<Data>() {
                @Override
                public int compare(Data a, Data b) {
                    return a.serial.compareTo(b.serial);
                }
            });

            // Print.
            for (Data data : list) {
                data.print();
            }
        } catch (Exception ex) {
            System.err.println("Read failed.");
        }
    }
}

// Local class to hold data: a serial and related courses.
class Data {

    String serial;
    List<String> courses;

    Data(String serial) {
        this.serial = serial;
        courses = new ArrayList<>();
    }

    void print() {
        System.out.println(serial);
        for (String course : courses) {
            System.out.println(course);
        }
    }
}

Comment: It worked, Thank you @Gene. Can you have a look here.  [link](http://stackoverflow.com/questions/19781772/sorting-in-java-string-comparison)

Sorting in Java from external text file


What is the difference between analog and digital effects pedals?

Question: What are the main differences between digital and analog effects?
Do they have different circuitry? Sounds? Features?
Comment: I wouldn't accept an answer until someone who knows can discuss how analog effects and/or circuitry work.  Nothing below here answers it.
Answer: "Digital" means that the signal from your guitar is first run through an A/D (analog to digital) converter to translate it into a digital signal (meaning a series of 1's and 0's).  The effect then performs computations on that digital signal, altering it somehow.  In this regard, it's no different from a computer---in fact, a digital effect is just a computer with the specific task of processing audio signals.  Then the altered signal is run back through a D/A converter before being output.
"Analog" means the signal is processed as-is, with little-to-no translation before or after (sometimes it's run though a buffer amp, sometimes not).
So yes, they have very different circuitry.  That doesn't mean one is better and the other worse, though.  As with all things musical, only your ears can decide which you prefer.
Comment: It's simple to surmise what digital means.  But you say little of how analog circuits work.  Do you know?
Comment: @JasonPSallinger I do, but as this is a forum on music practice and theory and not electrical engineering, I feel a detailed explanation of analog circuitry is out of scope. What is it you'd like to know?
Comment: You explain the mechanism of a digital circuit.  Please do the same for an analog circuit.  Or remove the explanation for the digital circuit.  After all, the OP asked about differences in circuitry.  Nowhere on this page does anyone explain how analog circuitry works.  Therefore, none of these answers satisfy the question.
Answer: In short, an "analog" effect is an electrical circuit that does something with the signal that comes from the guitar due to the nature of its components.
A "digital" effect is powered by a microprocessor (pretty much like the one you have on your computer) that uses instructions (like a computer program) to modify the signal.
The main consequences of this is that a digital effect unit can be programmed to produce any sound, considering it's fast enough to do the calculations before a noticeable latency is perceived.
On the other hand, and for kinda obvious reasons, analog effects tend to sound more "natural" and are considered to have - generally - a higher quality. Some higher-level digital effect units do a very good job of "impersonating" famous analog effects (like distortion and delay), for example.
With a digital effects unit (sometimes called multi-effects rig), you also have the advantage of having many many sounds available in a single equipment.
In addition, some effects (like the Harmonizer - which adds a harmony note to your playing based on a chosen scale) are basically inviable by analog means, and thus digital effects can go some places analog ones don't.
Comment: With regard to analog effects having "higher quality", taking the example of delay, digital is far better suited to creating that effect. Analog delays used a continuous loop of tape which was constantly being erased and re-recorded on, so you had to replace the tape regularly as it would degrade, and you would of course get some audible hiss from the tape. Generally I'd argue that if people perceive digital effects as sounding less natural, it's got more to do with psychology and their expectations. People rarely do a proper blind trial of these things to test if it's true!
Comment: Other features typically inviable on analog circuitry include tap tempos for bucket brigade echo effects. Several companies have built hybrids of digital and analog components in an attempt to bridge the gap however.
Comment: Analog delays can refer to tape delays, or solid-state bucket-brigade chips. [Analog Delay](http://en.wikipedia.org/wiki/Delay_(audio_effect)#Analog_delay)
Comment: I think that digital effects (the cheap ones I buy, anyway ;) *do* sound less natural, but sometimes that's exactly what I want.
Comment: This answer is completely inadequate.  You had a lot to say about digital circuits, but it seems you don't know anything about analog circuits.
Comment: @JasonPSallinger I don't think I get it, what exactly do you want explained?
Comment: "In short, an "analog" effect is an electrical circuit that does something with the signal that comes from the guitar due to the nature of its components." --> how does this provide any insight on analog circuitry? Do know how they work? How can you compare the two types without explaining half of the question?
Answer: There are great sounding analog effects and poor sounding ones.
There are great sounding digital effects and poor sounding ones.
One is not better than the other per se.
Analog effects are said to sound "warmer" than digital, but this can be explained, at least in part, due to the more limited high frequency response of analog effects.
Digital effects, while having a more broad frequency response, do not necessarily sound better.  Many digital products have an "iciness" that sounds fake or unnatural.
Digital is used more and more as the cost of the circuits comes down.  Most multieffects are digital.
As far as delays, there have been several types of analog circuits.  While the most commonly known is the "tape delay" mentioned above, there are also "oil can" delays, "disk delays", and other electro-mechanical devices.  There are also non-mechanical devices such as the Boss DM2 and DM3.  While analog delays do not precisely replicate the original sound (like a digital can do), many musicians like the sound better.  In fact, if you yell into a canyon and get an echoed response, it doesn't sound exactly like your original yell either, does it?
Answer: All answers here forgot about one quite important thing.
Power consumption. The analog effect takes from 10mA to 50mA on the other hand digital ones take from 50mA and highter (most TC Electronic requires above 100mA, Joyo Delay is 70mA). This kills battery quite fast (if you are John5) or requires stronger power supplies.


Como não permitir o usuário acessar a página anterior de login/registro após fazer login ou registrar-se

Question: Estou desenvolvendo uma aplicação ASP.NET e quando o usuário faz login e clica no botão do navegador para voltar ele consegue acessar a página de login/registro, mesmo eu fazendo a verificação da key do usuário logado na session.
Segue os prints:
1 - Fiz login

2 - Estou logado, o site me redireciona para o index e eu clico no botão voltar.

3 - Após isso eu volto para a tela de registro/login o que não pode acontecer:

Depois da foto 3, se eu volto para o index, eu fico logado normalmente, para prevenir isso eu fiz uma verificação no controller verificando se o usuario está logado ou não, se sim ele volta para o index, porém quando o usuario clica em voltar parece que o navegador que faz esse controle. Já vi sites que não permite voltar na tela de login, alguém sabe como resolver isso? Segue a verificação no controller:
<code>    public ActionResult LoginRegister()
    {
        if (Session["UserStatus"] != null)
        {
            return RedirectToAction("Index", "Home");
        }

        return View();

    }

    [HttpPost]
    public ActionResult LoginRegister(string fr,string t,string ReT)
    {
        if (Session["UserStatus"] != null)
        {
            return RedirectToAction("Index", "Home");
        }
        //Validação e outros processos.
    }
</code>
Answer: Basta acrescentar no construtor da página de login para não armazenar cache, acredito que isto resolva seu problema.

Para .net 4x.

<code>[OutputCache(NoStore = true, Duration = 0)]
public ActionResult LoginRegister()
    {
        if (Session["UserStatus"] != null)
        {
            return RedirectToAction("Index", "Home");
        }

        return View();

    }
</code>

Para .net core use:

<code>[ResponseCache(NoStore = true, Duration = 0)]
 public ActionResult LoginRegister()
        {
            if (Session["UserStatus"] != null)
            {
                return RedirectToAction("Index", "Home");
            }

            return View();

        }
</code>
Answer: Use o ActionFilterAttribute
Primeiro crie uma classe LoginFiltro(por exemplo):
<code>public class LoginFiltro : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        object usuarioLogado = filterContext.HttpContext.Session["Nome"];

        if (usuarioLogado == null)
        {
            filterContext.Result = new RedirectToRouteResult(
                      new RouteValueDictionary(
                          new { action = "Index", controller = "Login" }));
        }
    }
}
</code>
que verifica se o usuário esta logado ou não. Senão estiver ele sera redirecionado para o Controller Login.
No Controller
Depois "decore" os controllers que deseja ter este controle de login com:
<code>[LoginFiltro]
</code>
que ficara encima do nome do Controller.
Comment: Cassio vou aplicar sua solução em breve retorno com o resultado, VLW


How To Kill Background Process on C#

Question: I want to build my own Rdp programs with c#. That's why i made a login page screen and i took the login input from user. After that in order to start rdp process i used this code.
<code> Process rdcProcess = new Process();
        rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\cmdkey.exe");
        rdcProcess.StartInfo.Arguments = $"/generic:TERMSRV/{ipaddressbox.Text} /user: {usernamebox.Text} /pass: {passwordbox.Text}";

        rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(@"%SystemRoot%\system32\mstsc.exe");
        rdcProcess.StartInfo.Arguments = $"/v {ipaddressbox.Text}"; // ip or name of computer to connect
        rdcProcess.Start();
</code>
When I log in using my user information, a form opens and the rdp program works without any problems. However, when I close that form screen, the remote desktop connection does not end, it continues to work in the background. My request is that when I close the form, the remote desktop connection is disconnected and kill the rdp process. How can I achieve this?
Comment: To kill a process you can use `Process.GetProcessesByName("rdp...").FirstOrDefault().Kill();`
I'm not sure if its possible to disconnect RDP gracefully.
Comment: You're right but i want to do it programmatically, i mean process kill should happen when the form is closed
Comment: `tsdiscon sessionid`, and `LOGOFF sessionid` seem to work. See: https://sourcedaddy.com/windows-7/disconnecting-sessions.html
Comment: i will try it, thanks a lot
Answer: I solved the problem. When I closed the rdp screen, the mstsc process was dying. I wrote an if block that checks for this and exited the program if the mststc process was not running.
<code>    Process[] pname = Process.GetProcessesByName("mstsc.exe");
    if (pname.Length == 0)
    {
        Application.Exit();
    }
</code>
Comment: According to this: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.getprocessesbyname process name should be a friendly name so in this case, you always end up with pname.Length == 0 because "mstsc.exe" is not a friendly name to the mstsc process

How To Kill Background Process on C#


Grouped boxplot with two Y axis

Question: I want to make two boxplots with different information for the same category, with two Y axes, using GGPLOT2.
Looks like this chart below:

I have two category information (speed and angle of rotation) for the areas (AM and AR) and I want to combine these two movement patterns in a graphic grouped according to the areas.
so far my code looks like this:
areaveleang <- ggplot(dados2, aes(x = area)) +
        geom_boxplot(aes(y = speed, color="Bruto" ), fill = "darkblue", alpha=0.7) +
  geom_boxplot(aes(y = angulo_modulo), color="#a50026", position = "dodge") +
        scale_y_continuous(name = "speed (km/h)", sec.axis = sec_axis(~ . *6,name=expression("turn angle (graus)"))) +
                           #breaks = seq(0, 175, 25),
                           #limits=c(0, 175)) +
        scale_x_discrete(name = "Area") +
        #ggtitle("Boxplot of mean ozone by month") +
        theme_bw() +
        theme(plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
              text = element_text(size = 12, family = "Tahoma"),
              axis.title = element_text(face="bold"),
              axis.text.x=element_text(size = 11),
              legend.position = "bottom") +
        scale_fill_brewer(palette = "Accent")

Part of my data:
structure(list(lon = c(-38.8745, -38.8676, -38.9445, -38.9811,
-38.9322, -38.9386), lat = c(-14.09437, -14.25664, -14.34518,
-14.51857, -14.95994, -15.41684), bmode = c(1.396, 1.375, 1.346,
1.248, 1.074, 1.289), bmode.5 = c(1, 1, 1, 1, 1, 1), ID = structure(c(53L,
53L, 53L, 53L, 53L, 53L), .Label = c("10946.05", "20162.03",
"21792.03", "21800.03", "21810.03", "24640.03", "24641.05", "24642.03",
"27258.05", "27259.03", "27261.03", "27261.05", "27261.07", "33000.05",
"37231.07", "37234.05", "37288.07", "42521.07", "50682.07", "50687.07",
"60004.07", "81122.09", "81123.09", "81124.09", "81125.09", "81126.09",
"84497.1", "87632.12", "87759.08", "87761.08", "87762.08", "87763.08",
"87764.08", "87765.08", "87766.08", "87768.08", "87768.11", "87769.11",
"87770.08", "87773.08", "87773.1", "87773.11", "87774.09", "87774.11",
"87775.08", "87776.08", "87776.11", "87777.1", "87778.08", "87783.09",
"88724.1", "88727.09", "111868.11", "111871.12", "112702.12",
"112712.12", "112714.12", "120947.12", "121189.12", "121192.12",
"121196.12", "1211931.12"), class = "factor"), sex = structure(c(3L,
3L, 3L, 3L, 3L, 3L), .Label = c("F", "Fc", "M"), class = "factor"),
    speed = c(0.921691675, 2.990097297, 2.137609076, 3.259383146,
    8.173674567, 8.413534172), area = structure(c(3L, 3L, 3L,
    3L, 3L, 3L), .Label = c("AA", "AM", "AR"), class = "factor"),
    angulo = c(41.027, -43.41, 29.056, 18.241, -7.125, -4.702
    ), angle_rel = c(0.7160619, -0.7576522, 0.5071251, 0.3183724,
    -0.1243479, -0.08206201), bat.depth = c(-45L, -397L, -32L,
    -29L, -21L, -3L), dist = c(5.53015005, 17.94058378, 12.82565446,
    19.55629887, 49.0420474, 50.48120503), angulo_modulo = c(41.027,
    43.41, 29.056, 18.241, 7.125, 4.702), curva = structure(c(1L,
    1L, 1L, 1L, 1L, 1L), .Label = c("curva", "reta"), class = "factor")), row.names = 2:7, class = "data.frame")

PS: Sorry for my poor english, I hope you can understand my question xD
Comment: Hey Anne, just to clarify ggplot2 is very limited with respect of producing two y axis. So if you really need two y axis, you will have a hard time. See this post for more information: https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales
Answer: Not sure whether I got you right but maybe this what you are looking for:

To get the scale of the secondary axis right you have to apply the inverse transformation on your data, i.e. as your are multiplying by 6 you have to divide angulo_modulo by 6 in the data.

To get the two boxplots dodged I would suggest to use tidyr::pivot_longer so that your two variables become two categories of one variable which by default is named name while the values go to value. This way you can map value on y and name on color, alpha and fill. By default ggplot2 will give you two side-by-side boxplots per area.

library(ggplot2)
library(tidyr)
library(dplyr)

dados2 %>%
  mutate(angulo_modulo = angulo_modulo / 6) %>%
  pivot_longer(cols = c(speed, angulo_modulo)) %>%
  mutate(name = factor(name, levels = c("speed", "angulo_modulo"))) %>%
  ggplot(aes(x = area)) +
  geom_boxplot(aes(y = value, color = name, alpha = name, fill = name)) +
  scale_y_continuous(name = "speed (km/h)", sec.axis = sec_axis(~ . * 6, name = expression("turn angle (graus)"))) +
  scale_x_discrete(name = "Area") +
  scale_color_manual(values = c(angulo_modulo = "darkblue", speed = "#a50026")) +
  scale_alpha_manual(values = c(0.7, 1)) +
  theme_bw() +
  theme(plot.title = element_text(size = 14, family = "sans", face = "bold"),
        text = element_text(size = 12, family = "sans"),
        axis.title = element_text(face="bold"),
        axis.text.x=element_text(size = 11),
        legend.position = "bottom") +
  scale_fill_brewer(palette = "Accent")

Comment: It's exactly what I need! Thanks @Stefan

Grouped boxplot with two Y axis


How do I make a SQL constraint in one table affect a different table

Question: I have Three tables

Bill
Recording
House

In Recording, I have a column called DateRecored. In bill, I have a column called duedate and in House, I have a column called Operational.
I need to make a constraint so that when the bill is 60 days overdue, the Operational column will change to deactivated.
Let me know if you need for info, but I feel this is all you ll need.
Comment: DBMS would be one of Oracle/SQL Server/MySQL/PostgreSQL etc., You mean to say Oracle?
Answer: Constraints take effect only when you are inserting/updating/deleting records. In your case, the age of a given record in Bill table should trigger a change in a different table and you need a periodic job to perform this operation. DBMS doesn't facilitate this kind of auto-updates (either through triggers or constraints) without any user-triggered DML operation.
Answer: As previously answered, what you are looking for is triggers, not constraint. Using DBMS_SCHEDULER in Oracle, the trigger will look something like this:
<code>BEGIN
  DBMS_SCHEDULER.create_job (
    job_name        => 'update_operational_after',
    job_type        => 'PLSQL_BLOCK',
    job_action      => 'BEGIN UPDATE house set operational=false where id in (select house.id from House join Bill on (bill.house_id=house.id) where duedate > sydate+60; END;',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'freq=daily; byminute=0;byhour=0;byminute=0;bysecond=0',
    end_date        => NULL,
    enabled         => TRUE,
    comments        => 'Updates all operational to false if they've passed the due date');
END;
/
</code>
This schedules the given update to be executed each day at midnight.


Break recursion the right way

Question: Trying to solve Leetcode problem 55. Jump Game; i decided to break recursion with a try except block and custom Exception, do you see a more clever way of doing it ? I feel like I am doing the wrong way to break recursion ...
class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        reachable = [False]*len(nums)
        class BreackRecursion(Exception):
            pass
        def jump(nums,pos):
            max_step = nums[pos]
            reachable[pos]=True
            if reachable[-1]==True:
                raise BreackRecursion
            for step in range(1,max_step+1):
                print(pos,step,max_step,list(range(1,max_step+1)),reachable)
                try:
                    reachable[pos+step]=True
                    jump(nums,pos+step)
                except IndexError:
                    pass

        try:
            jump(nums,0)
        except BreackRecursion:
            return True
        return False

S= Solution()
inputs =[[2,3,1,1,4],[3,2,1,0,4]]
for input in inputs:
    print("input:",input)
    s = S.canJump(input)
    print(s)

Comment: jump is the recursive function here, i embeded it to keep an external container (the list named "reachable")
Comment: will it break? inside the function you have a try that will capture an exception and do nothing.
Comment: When you find yourself using exceptions as "goto", you're barking up the wrong tree.
Answer: Here is a proposal
class SolutionNew:
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        def jump(nums, pos):
            max_step = nums[pos]

            # 1 -- you are just breaking when reaching last position
            if pos == len(nums) - 1:
                # 2 -- just use a flag to end your recursion
                return False

            for step in range(1, max_step + 1):
                print(pos, step, max_step, list(range(1, max_step + 1)))

                # 3 -- an "if" statement may be more elegant here
                next_pos = pos + step
                if next_pos < len(nums):
                    # 4 -- propagate your "False" flag
                    if not jump(nums, next_pos):
                        return False

            # 5 -- when normal ending, you just flag that a new loop can be performed
            return True

        # 6 -- ensure the logic is ok
        return not jump(nums, 0)

Setting reachable[pos] to True and then checking for last value of reachable is just like looking if pos == len(reachable)-1 (or len(nums)-1 since len(reachable) == len(nums).
Instead of raising an Exception, you could just set a flag. Then you should just take care of propagating that flag, through #4 (you want to stop immediately if False flag is returned) and #5 (normal ending -> proceed with next iteration).
Instead of try ... except you can just see if next_pos fits in. Notice also that reachable[pos + step] = True before calling jump(nums, pos + step) was reduntant, since the jump call sets it to True almost immediately. At this point, indeed, you do not even need reachable anymore.
See #2.
See #2.
Just to adjust the logic, in order to return True when recursion stops (i.e. BreackRecursion was raised).

Here some test code:
S = Solution()
S_new = SolutionNew()
inputs = [
    [2, 3, 1, 1, 4],
    [3, 2, 1, 0, 4],
    [5, 1, 6, 10, 2, 3, 4, 7, 5, 2],
    [123, 321, 25, 87, 6],
    [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
]
for input in inputs:
    print("input:", input)
    s = S.canJump(input)
    s_new = S_new.canJump(input)
    assert s == s_new, 'Solutions are different!'
    print(s_new)

Comment: Obviously there are infinite ways to achieve a result, and the best use of self arguments strongly depends on use case. I believe that for your class, you may avoid it since it is not stricly necessary (and you may end up with a mess if you lack of attention in recursion). On the other hand, it might simplify your coding. If you are interested, I think you may ask a new question with few approaches, asking for best one :)
Comment: Thanks a lot! If i understand well there is a propagation of the flag (i can turn False to True and erase the not keyword to simplify i suppose) so it takes a little more time since it doesn't stop immediately ?
Comment: Actually, testing the solution on many many inputs, it seems to me that the proposed solution is 2 to 3 times faster. Consider that `Exception`s are back propagated too, you just don't see it, while here you are making it explicit. Anyway, if you are concerned about performance, you should rethink your `for step in range(...)` loop, since you are calling several times your `jump` function with the same arguments (and since it is recursive, your complexity would explode).
Comment: i took that problem from leetcode, do you think it is a better way to put a self argument in jump function (i can see this practice in most solutions from other contestnts); if yes why ? :)

Break recursion the right way


Use the chain rule to determine $\frac{d}{dt}g(\mathbf{r}(t))$.

Question: The functions $\mathbf{r}:\mathbb{R}\mapsto \mathbb{R}^2$ and $g:\mathbb{R}^2\mapsto \mathbb{R}$ are defined by
\begin{equation*}
\mathbf{r}(t) := \begin{bmatrix}
\sinh{(t)} \\
t^2
\end{bmatrix} \quad \textit{and} \quad g(x,y) := x^2y.
\end{equation*}
Use the chain rule to determine $\frac{d}{dt}g(\mathbf{r}(t))$.
Okay so $g(\mathbf{r}(t)) = t^2\sinh^2{(t)}$ so $\frac{d}{dt}g(\mathbf{r}(t)) = 2t\sinh^2{(t)}+2t^2\cosh{(t)}$. Is this correct? Thanks!
Answer: It is not correct and you also did not use Chain Rule. The second term is $2t^{2} \sinh t\cosh t$.
We have $(g(r(t))'=g_x\frac {dx} {dt}+g_y \frac {dy} {dt}=2xy\frac {dx} {dt}+x^{2} \frac {dy} {dt}$. Now verify that this gives the same answer.


Creating an API via module routing files that includes csrf verification headers

Question: I am working on migrating a custom API from D7 to D8 and am doing so by using module routing. I have a routing.yml file that looks like so:
ytp_user.api.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::login'
  methods: [POST]
  requirements:
    _csrf_request_header_token: "TRUE"
ytp_user.api.get_current_user:
  path: "/api/v2/user/me"
  defaults:
    _title: "User API Get Current User"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::getCurrentUser'
  methods: [GET]
  requirements:
    _custom_access: '\Drupal\ytp_user\Controller\UserAPIController::authorize'

In the first route, I am trying to validate a csrf token provided in the headers, via the requirement _csrf_request_header_token: "TRUE", however, this does absolutely nothing. It doesn't validate or even check that the header exists as the documentation suggests it should.
I've tried replacing this with _csrf_token: 'TRUE' which at least checks that the token exists in the query, but I can't get a valid token!!! If I grab a token from /session/token and then pass it along in the query as ?token=<token-from-session/token> then I just get an error saying the CSRF token is invalid.
Am I missing another step or is the documentation just straight up incorrect? I have been searching for hours and everything suggests that what I have should work, so why is the CSRF token not being validated properly?
Comment: I read something recently that mentioned anon users don't have real sessions, that sessions are reinitialized for each request. To Andy's point, I wonder if you need to authenticate before these tokens can work.
Comment: I've not used `_csrf_request_header_token` but I believe it's entirely separate from `_csrf_token`. The latter is the vanilla way of requiring a CSRF token to a route (eg. Devel uses it on the _Clear cache_ route), and it's supplied as a query parameter: see https://www.drupal.org/node/3048359. IIUC the header token was extracted from the REST module, uses the token from the `/session/token` endpoint and is for remote API use. Are you issuing a post/patch/put? Have you authenticated?
Comment: Yeah, that's exactly what the documentation says, but it's not working as suggested. When using _csrf_token it checks for the token, but says it's invalid when the token is from /session/token. When using _csrf_request_header_token, it doesn't check the header at all. I'm issuing a post call, and I'm trying to authenticate, thats what I'm trying to get the csrf token for, to login a user. Is /session/token suppose to create cookie headers or something? I'm not sure what to connect, the documentation is absolute garbage.
Comment: That doesn't make sense, wouldn't you want to verify CSRF before you authenticate a user?
Comment: It doesn't look like it? https://drupal.stackexchange.com/a/221045/48114 (I really don't have any first hand experience with this though.)
Comment: Instead of controllers, you might want to use the REST API and create `@RestResource` plugins. CSRF authentication then comes from the `cookies` auth provider.
Answer: The requirement _csrf_request_header_token: "TRUE" works only if user is connected because CsrfRequestHeaderAccessCheck use session informations.
If you look at CsrfRequestHeaderAccessCheck in the access method there is:
 if ($account
      ->isAuthenticated() && $this->sessionConfiguration
      ->hasSession($request)) {

To check if the user is connected and it there is a session identifier in the request if it's not it will go directly to:
// Let other access checkers decide if the request is legit.
    return AccessResult::allowed()->setCacheMaxAge(0);

so it will not check if X-CSRF-Token is in the headers or not even if you set the route requirement _csrf_request_header_token: "TRUE".
Code
MODULE.routing.yml
MODULE.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\MODULE\Controller\UserAPIController::login'
  methods: 'POST'
  requirements:
    _csrf_request_header_token: 'TRUE'

UserAPIController.php
class UserAPIController extends ControllerBase {

  public function login(Request $request) {
    $response['data'] = 'Some test data to return';
    $response['method'] = 'POST';

    return new JsonResponse( $response );
  }

}

Test

With Connected user

with anonymous user


Python UnicodeDecodeErro no jupyter notebook. Trabalhando com .csv

Question: Estou aprendendo a fazer manipulações com arquivos .csv no Python com o jupyter notebook.
Extraí um arquivo do sistema, em csv, separado por vírgulas, mas quando fui abrir recebi esse erro:
arqsb2 = open('arquivos/sb2.csv','r')

sb2 = arqsb2.read()

    ---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-2-084f7ffc9ea2> in <module>()
----> 1 sb2 = arqsb2.read()

C:\ProgramData\Anaconda3\lib\encodings\cp1252.py in decode(self, input, final)
     21 class IncrementalDecoder(codecs.IncrementalDecoder):
     22     def decode(self, input, final=False):
---> 23         return codecs.charmap_decode(input,self.errors,decoding_table)[0]
     24
     25 class StreamWriter(Codec,codecs.StreamWriter):

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 1022110: character maps to <undefined>

Alguém poderia me ajudar?
Comment: Rafael, no método de abertura do arquivo, tenta passar o encoding já, algo como: `arqsb2 = open('arquivos/sb2.csv',encoding='utf-8','r')`, pesquei isso da [doc](https://docs.python.org/3/howto/unicode.html#reading-and-writing-unicode-data)
Answer: Rafael você pode abrir o documento da seguinte maneira:
open('arquivos/sb2.csv',encoding='utf-8','r')

Caso continue dando esse erro olhe qual o encoding do seu documento.
Outra forma muito interessante de trabalhar com csv, alias a melhor lib de todas e utilizar o pandas:
import pandas as pd
data = pd.read_csv('caminho/do/documento.csv')

O pandas e extremamente poderoso para se lidar com documentos do tipo csv e você terá uma ferramenta completa de definitiva.
Comment: y = open('arquivos/estoque.csv', encoding='utf-8', 'r')
Comment: File "", line 1
    y = open('arquivos/estoque.csv', encoding='utf-8', 'r')
                                                      ^
SyntaxError: positional argument follows keyword argument
Comment: não funcionou -> File "", line 1
    y = open('arquivos/estoque.csv', encoding='utf-8', 'r')
                                                      ^
SyntaxError: positional argument follows keyword argument
Comment: Isso é um erro muito comum. A função leva dois tipos de argumentos o  de chave e valor e o posicional. No caso os argumentos posicionais vem antes. Então tenta.                                        Y= open ('arquivos/estoque.csv','r', encoding='utf-8')
Comment: y = open("estoque.csv", 'r', encoding='utf-8')
Comment: UnicodeDecodeError      Traceback (most recent call last)
 in ()
----> 1 print(y.read())

~\Anaconda3\lib\codecs.py in decode(self, input, final)
    319         # decode input (taking the buffer into account)
    320         data = self.buffer + input
--> 321         (result, consumed) = self._buffer_decode(data, self.errors, final)
    322         # keep undecoded input until the next call
    323         self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe7 in position 28: invalid continuation byte


The Euler-Lagrange first integral

Question: How to calculate $\frac{d\phi}{dz}$ from following equation:
$$A\frac{d^2\phi}{dz^2}+\cos(\phi)\sin(\phi)=0,$$
where $A$ is a constant?
Comment: $\int \frac1{\sin x \cos x}dx$
Comment: @Math-fun How is that relevant?
Comment: @Dylan ups, you are right!
Answer: Multiply both sides by $\frac{d\phi}{dz}$ and then integrate (using the chain rule to help...).
Answer: Since $2A\phi'\phi''+\phi'\sin 2\phi=0$, $C:=A\phi'^2-\frac{1}{2}\cos 2\phi$ is constant. In particular $z=\int\dfrac{d\phi}{\sqrt{(C+\frac{1}{2}\cos 2\phi)/A}}$, which you can reduce to an elliptic integral of the first kind. Inverting this gives $\phi$ in terms of $z$, or if you just want $\phi'=(dz/d\phi)^{-1}$ in terms of $\phi$ no elliptic integrals are needed.
Comment: I wrongly copied solution. It should solely by $A$
Comment: In answer sheet it says that the solution is $\left(\frac{d\phi}{dz}\right)^2=\frac{1}{A^2}\left(\frac{1}{C^2}-\sin^2(\phi)\right)$ (I assume $C$ comes from integration).
Comment: @TGram I can't see how a $1/A^2$ ended up in there; either that exponent is a misprint on their part, or in your question you copied out the problem without it. But their answer is basically mine; note $\frac{1}{2}\cos 2\phi=\frac{1}{2}-\sin^2\phi$. This is in fact how it reduces to using an elliptic integral.
Answer: $$A\frac{d^2\phi}{dz^2}+\cos(\phi)\sin(\phi)=0,$$
Substitute $$p=\frac {d \phi}{dz} \implies \frac{d^2\phi}{dz^2}=p\frac {dp} {d \phi} $$
$$App'=-\cos(\phi)\sin(\phi)$$
$$A\int pdp=-\frac 12\int \sin(2\phi) d\phi$$
$$Ap^2= \frac 12\cos (2\phi) +K_1$$
$$\frac {d \phi}{dz} =\pm \sqrt {\frac {\cos (2\phi) +K_1} {2A}}$$
$$.......$$
@tgram
$$Ap^2= \frac 12\cos (2\phi) +K_1$$
note that
$$\cos (2\phi)=2\cos^2 \phi -1=2(1-\sin^2 \phi )-1=1-2\sin^2 \phi$$
The constant $K_1$ absorb all the constants...
And $$p=\frac {d \phi}{dz}$$
Comment: In answer sheet it says that the solution is $\left(\frac{d\phi}{dz}\right)^2=\frac{1}{A}\left(\frac{1}{C^2}-\sin^2(\phi)\right)$ (I assume $C$ comes from integration).
Comment: It cant be $A^2$ it's A .... you can change the sin function by $1-\cos^2 \phi$ the constant will absorb the number 1 @TGram
Comment: @TGram I added some line you should get the same result as that of your book
Comment: Thanks, however I am still a bit confused regarding the origin of $C^2$.
Comment: @TGram it's just a constant thats all writing it $1/C$ or C dosent change that much
Answer: $$
A\phi'\phi'' +\cos\phi\sin\phi\phi' = 0\Rightarrow \frac 12A(\phi'^2)'+\frac 12(\sin^2\phi)' = 0
$$
hence
$$
A\phi'^2+\sin^2\phi = C_1\Rightarrow \phi' = \pm\frac{1}{\sqrt{A}}\sqrt{C_1-\sin^2\phi}
$$

The Euler-Lagrange first integral


The floor function and a limit

Question: Is it possible to simlify the follwing expression with a floor function:
$$\lim_{n\to \infty}\frac{1}{n}\left(\left\lfloor \frac{n\tau}{T}\right\rfloor-1\right)$$
Comment: Why the tag "probability-theory"?
Answer: For a real number $x$, $\lim_{n\to +\infty}\frac{\lfloor nx\rfloor}n=x$. Indeed, $$nx-1\leq\lfloor nx\rfloor\leq nx,$$
then we divide by $n$ and apply squeeze theorem.

The floor function and a limit


Diferentes objetos do tipo Model mapeados a partir de uma única tabela

Question: É possível mapear de uma só tabela do banco de dados diferentes objetos do tipo Model com ActiveRecord em um projeto Ruby on Rails?
Supondo que eu tenha no banco de dados uma tabela com o nome clientes que será populada por clientes do tipo físico e tipo jurídico (onde a existência do atributo CPF ou CNPJ define qual seu tipo)

e precise que as classes do tipo Model de minha aplicação sejam mais que uma, sendo elas ClienteFisico e ClienteJuridico, utilizando herança de uma classe do tipo Pessoa.

Como o ActiveRecord pode fazer esse mapeamento? Caso não seja possível por ele, existem outras formas de fazer isso?
E neste mesmo contexto, quando necessito que os atributos CPF e CNPJ da classe cliente sejam objetos do tipo Model na aplicação, o que posso fazer?
Tenho esta dúvida pois gostaria de implementar as validações dos campos CPF e CPNJ em suas respectivas classes, deixando meu projeto mais coeso, mas não criar mais tabelas e relações no banco de dados.
Answer: O ActiveRecord suporta sim esse tipo de herança. Para isso funcionar primeiro temos que adicionar um atributo type para o modelo Pessoa. Criação dessa tabela seria algo assim:
rails g model Pessoa nome cpf cnpj type

Ceito isso basta você criar as duas classes que herdam de Pessoa
# app/models/pessoa_fisica.rb
class PessoaFisica < Pessoa
end

e
# app/models/pessoa_juridica.rb
class Juridica < Pessoa
end

Pronto, agora todos os modelos acessam a mesma tabela. Se você utilizar a classe Pessoa, o ActiveRecord vai sempre retornar todas as linhas desta tabela, mas se usar PessoaFisica ou PessoaJuridica ele somente tratará os registros com o tipo especificado. Vale tanto para inserção quando para recuperação.
A Validação então pode ser colocada em cada model separadamente, sugiro que você extraia essa validação para um custom validator, fora do arquivo do modelo.
Na párica
 PessoaFisica.create(cpf: '111.222.333-44')
 => #<PessoaFisica id: 1, nome: nil, cpf: "111.222.333-44", cnpj: nil, type: "PessoaFisica", created_at: "2016-07-16 17:03:29", updated_at: "2016-07-16 17:03:29">

 PessoaJuridica.create(cnpj: '78.425.986/0036-15')
 => #<PessoaJuridica id: 2, nome: nil, cpf: nil, cnpj: "78.425.986/0036-15", type: "PessoaJuridica", created_at: "2016-07-16 17:04:13", updated_at: "2016-07-16 17:04:13">

 Pessoa.all
 => #<ActiveRecord::Relation [#<PessoaFisica id: 1, nome: nil, cpf: "111.222.333-44", cnpj: nil, type: "PessoaFisica", created_at: "2016-07-16 16:53:59", updated_at: "2016-07-16 16:53:59">, #<PessoaJuridica id: 2, nome: nil, cpf: nil, cnpj: "78.425.986/0036-15", type: "PessoaJuridica", created_at: "2016-07-16 17:04:13", updated_at: "2016-07-16 17:04:13">]>

 PessoaFisica.all
 => #<ActiveRecord::Relation [#<PessoaFisica id: 1, nome: nil, cpf: "111.222.333-44", cnpj: nil, type: "PessoaFisica", created_at: "2016-07-16 16:53:59", updated_at: "2016-07-16 16:53:59">]>

 PessoaJuridica.all
 => #<ActiveRecord::Relation [#<PessoaJuridica id: 2, nome: nil, cpf: nil, cnpj: "78.425.986/0036-15", type: "PessoaJuridica", created_at: "2016-07-16 17:04:13", updated_at: "2016-07-16 17:04:13">]>

Comment: Obrigado pela ajuda, removeu minha dúvida sobre herança, mas e no caso em que necessito que os atributos CPF ou CNPJ sejam classes do tipo Model, mas mantendo-as como colunas da tabela **clientes** no banco de dados?

![Exemplo](http://i.stack.imgur.com/3J9jm.png).
Comment: @rafakx não sei o que motivaria você a transformar CPF e CNPJ em Modelos, mas creio que na maioria dos casos não seria uma boa ideia. Qual seria o motivo?
Comment: Neste caso, para deixar meu código mais coeso quanto a métodos de validação. Faço tudo em suas respectivas classes (classe cpf valida cpf, classe cnpj valida cnpj).

Mas pretendo aplicar em outros lugares, como em RG, aqui no Brasil existe o número e orgão emissor, numa internacionalização o documento de registro nacional não vai ser mais o RG, então prefiro relacionar por meio de composição a classe PessoaFisica com  outra chamada DocumentoNacional e nessa, ter uma classe herdada chamada RG, ID, etc (Se for EUA, será chamada ID...).
Comment: Nesse caso acho que você vai ter que usar o mesmo esquema de relacionamento de pessoa física e jurídica... Não conheço nenhum esquema de composição em Rails. Ou ainda pra ficar mais próximo de composição, use relacionamentos mesmo que você pode atribuir vários documentos a uma pessoa. Acho que não tem como fugir muito disso não.


How to Make Script Flexible when New Item is Loaded in SharePoint Folder

Question: I am seeking help with my JavaScript script to make it expandable when a new item (video) is added to my SharePoint folder.  I created a counter that counts each time the video button is selected and displays the new count inside a div.  The script works as expected but I like to expand its capability to automatically adjust when a new video is added into the SharePoint video folder.  The video is dynamically added to an HTML page when dropped into the folder.  However, when I add a new video its loads into the zero-index position and move the others video down one; making the previous video in the zero-index position to the one position and so on.  Can someone view my script and see; if possible, how I can make my current script adjust accordingly when the new video is loaded?  I like to make it where I do not have to go back into script and renumber everything by hand when a new video is added.   I hope this question make sense.
jQuery(document).on("click", "#column5", function() {

    videoHits();

    getFilesFromFolder("/sites/dcsa/ep/epMainFiles/BI/video").done(function(data) {
        $.each(data.d.results, function(i, item) {

            var spDate = new Date(item.TimeCreated.split('T')[0]) //example: '2015-10-30T05:00:00Z'
            var newTillDate = new Date();
            spDate.setDate(spDate.getDate() + 2);

            if (spDate <= newTillDate) {

                jQuery("#hiddenWrapper").fadeIn();

                $("#column1 ol").append('

Play Video
<video width="100%" height="auto" controls onended="videoEnded1()" id="videoClip' + i + '"><source src="' + item.ServerRelativeUrl + '" type="audio/mpeg" >' + item.Name.replace(/\.[^/.]+$/, "") + " - " + '' + item.TimeCreated.split('T')[0] + '' + '</video>' + item.Name.replace(/\.[^/.]+$/, "") + " - " + item.TimeCreated.split('T')[0] + '

Views:

');

                $("#column1 h3").html("Videos");

            } else {

                jQuery("#hiddenWrapper").fadeIn();

                $("#column1 ol").append('

Play Video
<video width="100%" height="auto" controls onended="videoEnded1()" id="videoClip' + i + '"><source src="' + item.ServerRelativeUrl + '" type="audio/mpeg" >' + item.Name.replace(/\.[^/.]+$/, "") + " - " + '' + item.TimeCreated.split('T')[0] + '' + '</video>' + item.Name.replace(/\.[^/.]+$/, "") + " - " + item.TimeCreated.split('T')[0] + '

Views:

');

                $("#column1 h3").html('Videos');

            }
        });
    });

});

///Read hits from growVideoHits List

function videoHits() {
    jQuery(document).ready(function() {
        var chartData = getListData("growVideoHits"); //vidHit
        var data = [];
        for (var i = 0; i < chartData.length; i++) {
            data.push({
                "label": chartData[i].Title
            });
        }
        initChart(data);

    });

    function initChart(chartData) {

        //console.log(chartData);

        //Filter List Column for Specific Column Item
        var view0 = chartData.filter(function(d) {
            if (d["label"] == "Test Video") {
                return d;
            }
        })

        var view1 = chartData.filter(function(d) {
            if (d["label"] == "GROW HHM Guest Speaker") {
                return d;
            }
        })

        var view2 = chartData.filter(function(d) {
            if (d["label"] == "GROW Meeting 26 Aug 2020") {
                return d;
            }
        })

        var pageCount0 = view0.length;
        var pageCount1 = view1.length;
        var pageCount2 = view2.length;

        d3.select('#vidHit0 span').html(pageCount0);
        d3.select('#vidHit1 span').html(pageCount1);
        d3.select('#vidHit2 span').html(pageCount2);

    } //End of D3 function For Column Chart

    function getListData(listName) {
        var results;
        var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=Title";
        $.ajax({
            url: requestUri,
            type: "GET",
            async: false,
            headers: {
                "ACCEPT": "application/json;odata=verbose"
            },
            success: function(data) {
                results = data.d.results;
            },
            error: function() {
                //alert("Failed to get details");
            }
        });
        return results;
    }
}

////Play Buttons
jQuery(document).on("click", '[id^=growPlayPauseBtn]', function(e) {
    growBtn_Event(e);
});

function growBtn_Event(e) {

    if ($(e.target).attr("id") == 'growPlayPauseBtn0') {
        //alert('0');
        var title = "Test Video";
        AddListItem(title);
        videoClip0.play();
        jQuery("#growPlayPauseBtn0").html("Pause");
        jQuery("#growPlayPauseBtn0").fadeOut();
    }

    if ($(e.target).attr("id") == 'growPlayPauseBtn1') {
        //alert('1');
        var title = "GROW HHM Guest Speaker";
        AddListItem(title);
        videoClip1.play();
        jQuery("#growPlayPauseBtn1").html("Pause");
        jQuery("#growPlayPauseBtn1").fadeOut();
    }
    if ($(e.target).attr("id") == 'growPlayPauseBtn2') {
        /// alert('2');
        var title = "GROW Meeting 26 Aug 2020";
        AddListItem(title);
        videoClip2.play();
        jQuery("#growPlayPauseBtn2").html("Pause");
        jQuery("#growPlayPauseBtn2").fadeOut();
    }

}

function AddListItem(TitleField) {
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: "growVideoHits", //vidHit
        valuepairs: [
            ["Title", TitleField]
        ],
        completefunc: function(xData, Status) {
            //alert("Data Saved! and Please check your List");
        }
    });
}

How I add content to the HTML:  I use the REST API get option to detect a new item loaded into the SharePoint folder.
getFilesFromFolder("/sites/dcsa/ep/epMainFilesBI/video").done(function(data){

Then I concatenate the items from the folder onto the HTML page with the below script:
$("#column1 ol").append('

Play Video
<video width="100%" height="auto" controls onended="videoEnded1()" id="videoClip'+ i +'"><source src="' +  item.ServerRelativeUrl + '" type="audio/mpeg" >' + item.Name.replace(/\.[^/.]+$/, "") + " - "  + '' + item.TimeCreated.split('T')[0] + ''  + '</video>' + item.Name.replace(/\.[^/.]+$/, "")  + " - "  + item.TimeCreated.split('T')[0]  + '

Views:

');

Comment: i dont understant what part of your code detects when a new video is added, and the function which includes the new video in html code..could you precise?
Comment: I updated my question to show how I add the content to the HTML page.  In the script please notice the item.Name.replace(/\.[^/.]+$/, "") part.  This call pulls the video from the SharePoint folder.
Comment: so you know you have a new video with the date of now (daily date), and the date of creation of video, so the most recent video has the more recent date ? and you rebuild the html each time , i mean completely with all names videos?
Comment: Do you know a better way of doing this video view concept.  Currently it works.  But when I add a new video, I have to physically go into the JavaScript and renumber my items.  When the video is add, video that was in the first position (zero index) in not in the second position (one index).  I have to change to JavaScript according to reflect this shift in numbering.  I'm thinking I can do this in a dynamic way
Answer: if i have well understood your code, the new item are created in the else part so i suggest you to do a first loop to detect old videos from new videos and create html after:
getFilesFromFolder("/sites/dcsa/ep/epMainFiles/BI/video").done(function(data) {
    $.each(data.d.results, function(index, item) {

        var spDate = new Date(item.TimeCreated.split('T')[0]) //example: '2015-10-30T05:00:00Z'
        var newTillDate = new Date();
        spDate.setDate(spDate.getDate() + 2);

        var newitems = [], olditems= [];
        if (spDate <= newTillDate) {
            olditems.push(item);
        } else {
            newitems.push(item);
        }

        var nbrolditems = olditems.length;
        for(let i = 0;i < nbrolditems; i++){
            let item = olditem[i];

            jQuery("#hiddenWrapper").fadeIn();

            $("#column1 ol").append('

Play Video
<video width="100%" height="auto" controls onended="videoEnded1()" id="videoClip' + i + '"><source src="' + item.ServerRelativeUrl + '" type="audio/mpeg" >' + item.Name.replace(/\.[^/.]+$/, "") + " - " + '' + item.TimeCreated.split('T')[0] + '' + '</video>' + item.Name.replace(/\.[^/.]+$/, "") + " - " + item.TimeCreated.split('T')[0] + '

Views:

');

            $("#column1 h3").html("Videos");
        }

        for(let j = 0;j < newitems.length; j++){
            let item = olditem[j;
            let i = j + nbrolditems;

            jQuery("#hiddenWrapper").fadeIn();

            $("#column1 ol").append('

Play Video
<video width="100%" height="auto" controls onended="videoEnded1()" id="videoClip' + i + '"><source src="' + item.ServerRelativeUrl + '" type="audio/mpeg" >' + item.Name.replace(/\.[^/.]+$/, "") + " - " + '' + item.TimeCreated.split('T')[0] + '' + '</video>' + item.Name.replace(/\.[^/.]+$/, "") + " - " + item.TimeCreated.split('T')[0] + '

Views:

');

            $("#column1 h3").html('Videos');
        }
    });
});

Another idea is to sort the list by date of creation of video....


What is the method of solving $2^x = 2\sqrt2$?

Question: Kindly assist me in solving for $x$ in $$2^x = 2\sqrt2.$$
Answer: \begin{align}
2^x & = 2 \sqrt2 \\
& = 2^1 \cdot 2^{\frac{1}{2}} \\
& = 2^{1+\frac{1}{2}} \\
& = 2^{\frac{3}{2}} \\
\implies x & = \frac{3}{2} \\
\end{align}
We can do this because if the base is the same, then by index laws we can equate the index.
Hence $x=\frac32$.
Comment: This helped me get to my answer. Excellent way of explaining it.
Answer: Write:
$$2^x=2^{\frac{3}{2}}$$ and you'll get it.
Comment: Nice answer, but given the understanding of the OP, maybe you should add that $2^{x}$ is injective?
Comment: I think it's obvious. No?
Comment: Your answer made sense to me after I re-wrote the square-root as an exponent. Thank you
Answer: $$2^x = 2 \sqrt2 $$
$$2^x  = 2 \times 2^ {\frac 1 2} $$
$$2^x  =2^ {1+\frac 1 2} $$
$$2^x  =2^ {\frac 3 2} $$
$$2^x \times 2^ {-\frac 3 2}=1 $$
$$2^ {x-\frac 3 2}=1 $$
$$2^ {x-\frac 3 2}=2^0 $$
$$ {x-\frac 3 2}=0 $$
$$ {x=\frac 3 2} $$
Comment: Another beautiful way of arriving at the solution. Nicely done!
Answer: Taking log of base 2 both sides we get
$$\log_{2} 2^x= \log_2 2\sqrt 2$$
$$\Rightarrow x=\log_2 2+ \log_2 \sqrt 2$$
$$\Rightarrow x=1+\frac {1}{2}=\frac {3}{2}$$
Comment: This is an excellent way of tackling it using log. Another very useful answer. However, can you please explain how you ended up adding the two logs after the equals sign?
Comment: You are welcome.  On this site you'll notice several methods can be given to solve a single problem. So enjoy Math.SE :-)
Comment: I understand now, for multiplying logs we must add! Thank you again!!
Comment: Yep just a property of logarithms. $$\log_x ab= \log_x a+ \log_x b$$ provided that $ab\gt 0, x\gt 0$ and $\neq 1$ and also $a, b\gt 0$


opening an URL in safari while iPhone button is clicked

Question: I want to add a button to my iPhone application which will open an URL in safari on iPhone when clicked (my application will terminate right?)
Thanks.
Raihan
Answer: You need to use - (BOOL)openURL:(NSURL *)url in UIApplication.
UIApplication is a singleton, so your code would look something like this:
NSURL *url;
[[UIApplication sharedApplication] openURL:url];

Answer: Your app will close if you are simply opening in Safari.
You can, however, use a WebView control to embed the web browser in your app.  This way your app will not terminate.
Comment: Thanks for your reply. However, the application needs to be in that way. Could you let me know what API I need to call so that the URL is opened in safari and my application is closed?