text:
Q: How does rocket thrust work? I can't seem to find a specific answer to this anywhere.
I understand that in a rocket there is a chemical reaction that causes gas particles to leave the rocket at high velocity. By Newton's third law, and the conservation of momentum, this caused the rocket to be propelled.
What is missing is a physical explaination of what exactly causes this force on the rocket, as most answers annoyingly miss this final bit!
People often use a skateboard-bowling ball analogy. However, in this analogy the person throws the ball and the ball provides an equal and opposite force on the person as it is thrown. The problem is, rocket doesn't 'throw' the exhaust out as it directly doesn't accelerate the particles - this is a result of a reaction. So what exactly causes the force on the rocket itself? Is it the case that in the explosion some gas particles collide with the rocket base, and the nossle is designed as to maximise collisions that will provide an upward force?
I have seen people say this is wrong, or suggest it is right. Wikipedia says:
'About half of the rocket engine's thrust comes from the unbalanced pressures inside the combustion chamber, and the rest comes from the pressures acting against the inside of the nozzle'
I want to be able to understand this in terms of particle collisions. I know there is a force due to the physical laws but people don't seem interested in the mechanics of the force itself.
Back to the analogy: if someone where to throw a bowling ball over your skateboard, you wouldn't move, just as particles leaving a rocket, without collision of any kind, wouldn't cause the rocket to move (I know that's not possible, but hopefully makes my point). Hope this question makes sense.

A: Assume that you want the rocket to move to the left.
In the combustion chamber there is a chemical reaction which leads to the increase in the kinetic energy of the atoms/molecules and these molecules move in all directions.
As momentum is conserved then the increase in momentum of the molecules moving to the right is balanced by the increase in momentum of molecules moving to the left.
The molecules moving to the right go out of the combustion chamber through a nozzle where the speed of the gases is greatly increased.  Molecules rebound off the inside of the nozzle due the force on them due to the walls of the nozzle and in turn the molecules exert a force on the nozzle in the forward direction which contributes a significant amount of the thrust of the rocket.
The molecules moving to the left hit the left hand side of the combustion chamber and rebound.
So the left hand side of the combustion chamber has exerted a force to the right on the molecules to make them rebound and by Newton's third law the molecules which were moving to the left have exerted a force to the left on the combustion chamber and also the rocket which is connected to the combustion chamber.
This is slightly different from the analogy of throwing a bowling ball in that it is obvious as to where the interaction between the thrower and the bowling ball occurs because that must be due to the contact forces between the bowling ball and the thrower.
Note that throwing the bowling ball in the direction of motion will results in the thrower having a momentum backwards and hence result in a backward force on the skateboard.
However if at the front of the skateboard there was a vertical plank which the forward moving bowling ball hit and rebounded from then the forward force on the skateboard due to the bowling ball rebounding would be greater than the backward force on the skateboard due to the thrower throwing the bowling ball.  So there will be a net force on the skateboard in the forward direction.

A: Even a chemical reaction would maintain conservation of momentum. So, the blocked side (rocket) moves forward, and the open side (exhaust gas) moves backward. The chemical reaction is needed to produce the gas. The speed/amount of exhaust alone is enough to compute overall forward thrust of rocket. If you open the mouth of an inflated balloon, it moves while the air comes out of it, in opposite direction. Same way rocket moves, with a difference that chemical reaction keeps producing hot gas with high pressure/speed.

A: There is a recurring flaw in nearly every explanation of how a rocket is propelled. Newton's Third Law states that "for every action there is an equal and opposite reaction". However, it is not good enough to simply say that this rocket driving force is "the reaction to another force". You still have to identify and explain what that force is!
In the case of a rocket, the force which drives the rocket forward and upwards is the imbalance of pressure forces within the combustion chamber.
Lets imagine a cubic container, lets say a biscuit tin, with 6 sides, each 1 foot (I'll use imperial units since they are much easier to visualise) long and with a lid on the bottom which is held but can be released by a catch. Lets put a valve on one side through which air can be pumped. The box is suspended free and is not incontact or close to the ground.
Now put a pressure of 1 psig (pound per square inch guage) in the box. (for understanding, atmospheric pressure is about 14.7 psia or 0psig (a = absolute, g= gauge) and a typical car tyre is about 35psig. So there is a differential pressure between the inside of the box and the outside of 1 pound per square inch. That means there is a total force acting on each side, the top and the bottom, of 144 (1x12x12) pounds of force. (if you are, say 65 kgs, or 144 pounds weight, you are exerting that force onto the ground so it is kinda like you standing on the box)
While the lid is on, all the forces are in balance. Each side force balances the opposite side and the force on the top balances the force on the lid. Now release the catch on the lid. Immediately, the force on the lid no longer pulls on the box and as a result the force on the opposite side, the top, is 144 pounds of force. THAT is the driving force for a rocket!! To maintain the thrust, you need to maintain the pressure in the chamber, so if air is continually added to the box, then it will continue to experience an imbalance of forces and will continue to move/accelerate.


text:
Q: patterns to feed a remote MySQL with data I would like to hear about from the community a nice pattern to the following problem.
I had a "do-everything" server, which were webserver, mysql, crawlers server. Since two or three weeks, using monitoring tools, i saw that always when my crawlers were running, my load average was going over 5 (a 4 core server, would be ok to have until 4.00 as load). So, i've got another server and i want to move my crawlers to there. My question is. As soon as i have the data crawled in my crawler server, i have to insert in my database. And i wouldn't like to open a remote connection and insert it in the database, since i prefer to use the Rails framework, btw i'm using rails, to keep easier to create all relationships, and etc.
problem to be solved:
server, has the crawled data (bunch of csv files) and i want to move it to a remote server and insert it in my db using rails.
restriction: I don't want to run mysql (slave + master) since it would require a deeper analysis to know where happens more write operations.
Ideas:

*

*move the csvs from crawlers to remove server using (ssh, rsync) and importing it during the day

*write an API in the crawler server that my remote server can pull (many times at day) and import the data
any other idea or good patterns around this theme?

A: With a slight variation to the second pattern you have noted you could have a API in your web-app-server/db-server. Which the crawler will use to report in his data. He could do this in batches, real-time or only in a specific window of time (day/night time...etc).
This pattern will let the crawler decide when to report in the data. rather than having the web-app do the 'polling' for data.

redpajama_set_name: RedPajamaStackExchange


text:
Q: F# - Use C# methods with out parameter (within arrays and void return) I've read the-f-equivalent-of-cs-out but still I can't make it work for my case (the simplest solution/syntax).
I have this method in a C# project:
//<Project Sdk="Microsoft.NET.Sdk">
//<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>

public static void ABC(out byte[] a, out byte[] b, byte[] c)
{
    var aaa = new byte[10];
    var bbb = new byte[10];
    a = aaa;
    b = bbb;
}

Now, I want to use it in a F# project:
I'm using FSharp.Core 4.7.2
(* <Project Sdk="Microsoft.NET.Sdk">
   <TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks> *)

let a,b = ABC(c)

I'm imitating the syntax of TryParse and this compiles without errors:
let success, number = System.Int32.TryParse("0")

The compiler on my ABC(c) call complains about the fact the signature asks for 3 parameters, not 1.
Compared to the TryParse I see 2 differences:

*

*It does not return void

*It uses Array objects

The compiler accepts this syntax:
let a = Array.empty<byte>
let b = Array.empty<byte>
ABC(ref a, ref b, c)

but:

*

*I think it is not correct to use ref here, not in this way (because a and b are not mutable)

*I'd like to use the clean syntax similar to TryParse and I WANT to know why it does not work here

I can change the C# project code, but replacing all the out parameters in that proejct will be a second step and maybe a new qeustion if I have difficulties or doubt.
[Update: parameter position]
I played a little with this and seems like I found when the "simple" syntax (without passing ref parameters) is broken.
public static void TryParseArray(string input, out int[] result) {
    result = new int[0];
}

public static void TryParseArray_2(out int[] result, string input) {
    result = new int[0];
}

let arr = csharp.TryParseArray("a")            // OK
let arr = csharp.TryParseArray_2("a")          // ERROR

It seems like the out parameter must be at the end (= not followed by normal parameters) in the C# methods, to make possible for F# to use them as returned tuple.

A: You correctly noticed that the "simplified" F# syntax for turning out parameters into returned tuples only works in very limited situations - only when you have one parameter and it is the last one. In other words, this feature helps with some common patterns, but it does not fully replace out parameters.
If you want to use out parameter in F#, you can either pass a reference to a local mutable variable using the &var syntax, or you can specify a reference cell of type int ref as an argument. The following shows the two options using the standard TryParse method:
// Using a local mutable variable
let mutable n = 0
Int32.TryParse("42", &n)
printfn "Got: %d" n

// Using a reference cell initialized to 0
let n = ref 0
Int32.TryParse("42", n)
printfn "Got: %d" n.Value


text:
Q: Undefined not a function: how to get LABjs to work with jQuery scripts I'm trying to improve the load time of my web page using LABjs. However I'm getting 'Undefined not a function' in relation to jQuery.cookie('mycookie') which I'm using in my own jQuery script.
I'd be grateful for some advice on how to implement LABjs to deal with this as I don't quite understand the documentation.
Here's the code I have so far:
HTML
I have jQuery and LAB.min.js in the footer of my HTML page
<script type="text/javascript" src="myfolder/jquery1.9.1.js"></script>
<script type="text/javascript" src="myfolder/LAB.min.js"></script>

LAB.min.js file
Here I load my scripts in order. ratings.js depends on jquery-cookie.js, so I've included a wait() first to make sure that jquery-cookie.js is loaded first.
//ALL THE LABjs code is here, but not included on this post!

$LAB.setGlobalDefaults({Debug:true});
.script("myfolder/bootstrap.min.js")
.script("myfolder/jquery-cookie.js")
.wait()
.script("myfolder/ratings.js");

ratings.js
ratings.js is a long piece of code contained within the jQuery(document).ready function.
jQuery(document).ready(function() {
 //LOTS OF CODE HERE
    if(jQuery.cookie('mycookie')==null){
        //LOTS OF CODE HERE
    }
//LOTS OF CODE HERE
});

I'm getting an error in ratings.js relating to the line of code containing jQuery.cookie('mycookie'). It says "Uncaught type error: undefined is not a function"
From what I understand, jQuery.cookie() isn't yet defined when I try to pass it to .wait(). What is the best way to get this to work, keeping in mind that I want to keep ratings.js in a separate js file because it contains a lot of code and is one of many similar js files that also throw up the same error when I load them with LABjs.
Many thanks!
Katie

A: You should be able to remove the link to jQuery in your HTML and just have LABJS to load all of the scripts. This will load jQuery before Bootstrap or your plugin:
$LAB
  .setGlobalDefaults({Debug:true}) // removed semi-colon
  .script("myfolder/jquery1.9.1.js")
  .wait()
  .script("myfolder/bootstrap.min.js")
  .script("myfolder/jquery-cookie.js")
  .wait()
  .script("myfolder/ratings.js");

(Note that you had a semicolon in your code that was likely breaking something too):


text:
Q: Python : Which Sort Method is used behind .sort()? I have always heard that usually merge sort is used for in built functions. But I cannot understand why. Quicksort is faster obviously with exact time complexity of 1.39NlogN and also it is in place! then why not quick sort?

A: timesort algo is used in the inbuilt sort


text:
Q: Validation of asp.net identity password I have an asp.net mvc application, in which I used the Asp.net identity. I implemented this method to validate a collaborator ( customisation of user) fields :
 [HttpPost]
    public bool ValidateCollaborateur(CollaborateurModel item)
    {
        if (item.Username == null || item.Email == null) return false;
        if (UserManager.FindByEmail(item.Email) != null) return false;

        return ModelState.IsValid;
    }

item contains the password property of asp.net identity user, so it must contains

*

*Special character

*number

*Lower character

*Upper character

I'd like to validate the item.Password field as described above.

*

*How can I accomplish this task?

*Is a method of asp.net identity password validation exists?

A: build an expression that matches your criteria:
 var password = "password_to_test";

 if (password.Any("!@#$%^&*".Contains)
  && password.Any(char.IsDigit)
  && password.Any(char.IsLower)
  && password.Any(char.IsUpper))
  {
      //valid!
  }

using this approach, you can add and remove any criteria easily without having to rework the validation.  It also gives you the ability to split out your conditions, and return an invalid password to the user with a specific reason.


text:
Q: Calculo de cantidad de cuotas a vencer según el mes actual Soy un entusiasta y he creado una rutina que me calcula la cantidad de cuotas a pagar según el mes en el que se carga el servicio.
Cada servicio puede tener 12,6, 4, 3, 2 o 1 cuota. dependiendo del servicio.
Si el día de caga del servicio es mayor a 20 esa cuota no se generará y se descontará a la cantidad de cuotas
La rutina funciona pero no es para nada elegante.
Cómo podría mejorarla??
agradeceré sus sugerencias.-
now = datetime.now()
def canCuotas(cuotas):
    if now.month == 1:
        if cuotas == 12:
            if now.day >20:
                return (cuotas -1)
        else:
            return cuotas
    elif now.month == 2:
        if cuotas == 12:
            if now.day > 20:
                return (cuotas - 2)
            else:
                return (cuotas - 1)
        elif cuotas == 6:
            if now.day > 20:
                return (cuotas -1)
            else:
                return cuotas
        else:
            return cuotas
    elif now.month == 3:
        if cuotas == 12:
            if now.day > 20:
                return (cuotas - 3)
            else:
                return (cuotas - 2)
        elif cuotas == 6:
                return (cuotas -1)
        elif cuotas == 4:
            if now.day > 20:
                return (cuotas -1)
            else:
                return cuotas
        else:
            return cuotas
    if now.month == 4:
        if cuotas == 12:
            if now.day > 20:
                return (cuotas - 4)
            else:
                return (cuotas - 3)
        elif cuotas == 6:
                if now.day > 20:
                return (cuotas - 2)
            else:
                return (cuotas - 1)
        elif cuotas == 4:
                return (cuotas -1)
        elif cuotas == 3:
            if now.day > 20:
                return (cuotas - 1)
            else:
                return cuotas
        else:
            return cuotas
    elif now.month == 5:
        if cuotas == 12:
            if now.day>20:
                return (cuotas- 5)
            else:
                return (cuotas - 4)
        elif cuotas == 6:
            return (cuotas - 2)
        elif cuotas == 4:
            return (cuotas -1)
        elif cuotas == 3:
            return (cuotas - 1)
        else:
            return cuotas
    elif now.month == 6:
        if cuotas == 12:
            if now.day > 20:
                return (cuotas - 6)
            else:
                return (cuotas - 5)
        elif cuotas == 6:
            if now.day > 20:
                return (cuotas - 3)
            else:
                return (cuotas - 2)
        elif cuotas == 4:
            if now.day > 20:
                return (cuotas - 2)
            else:
                return (cuotas - 1)
        elif cuotas == 3:
            return cuotas - 1
        elif cuotas == 2:
            if now.day > 20:
                return (cuotas -1)
            else:
                return cuotas
        else:
            return cuotas

y así sigue preguntando por cada mes.
lo cual lo hace extremadamente largo y difícil de mantener


text:
Q: How to print 0 to 100 interger without using loop or recursion? How can i print integer form 0 .. 100 without using any kind of manul loop or recursion ?

A: Simple way would be using
IntStream.range(0,101).forEach(::println)


text:
Q: How can I start a new activity within a separate process without losing onActivityResult callback? I want to start a new activity in a separate android process by defining it as android:process=":processname" inside AndroidManifest.xml. However, I need to return a response to the caller activity. So, I need to start this activity through startActivityForResult(intent, requestCode) instead of startActivity(intent).
However, when I do not add intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), the new Activity won't start in a new process. When I add this flag, onActivityResult callback method of the caller Activity is not called. To sum up, my main aim is to separate activities within different processes so that the newly pushed activity should not decrease the performance (FPS value, for instance) of the caller Activity. Besides, the caller one should get a response from the newly pushed activity after it is destroyed which collides with the flag usage.


text:
Q: Mandelbrot PPM drawing is always black I want to draw Mandelbrot to PPM file in C. My code is working but my drawing is always black. I have this code from wikia. The key to my success is to think "alfa" (i think so). I have no idea what alfa should be. Here's my code:
#include <stdio.h>
#include <stdlib.h>

#define W 800
#define H 800

//rgb struct
struct RGB {
    int r;
    int g;
    int b;
};
struct RGB picture[W][H];

void draw() {
int i, j, iteration, max_iteration, alfa, color;
float x, y, x0, y0, xtemp;

for(i=0;i<W;++i)
{
    for(j=0;j<H;++j)
    {
         x0 = 1; //scaled x (e.g interval(-2.5, 1))
         y0 = -1; //scaled y (e.g interval(-1, 1))
         x = 0.0;
         y = 0.0;
         iteration = 0;
         max_iteration = 1000;

         while (x*x + y*y < 2*2 && iteration < max_iteration)
         {
             xtemp = x*x - y*y + x0;
             y = 2*x*y + y0;
             x = xtemp;
             iteration = iteration+ 1;
             alfa = x*y; //???
         }

         color = alfa * (iteration / max_iteration);

         picture[i][j].r = color;
         picture[i][j].g = color;
         picture[i][j].b = color;
    }
}
}

int main() {

//variables
int i,j;

draw();

FILE *fp;
fp = fopen("picture.ppm", "w");
fprintf(fp,"P3\n#test\n%d %d\n256\n", W, H);

for (i=0; i < W; ++i)
    {
        for (j=0; j < H; ++j)
        {
        fprintf(fp,"%d %d %d ", picture[i][j].r, picture[i][j].g , picture[i][j].b);
        }
    fprintf(fp, "\n");
    }

fclose(fp);

return 0;
}

A: In this line
color = alfa * (iteration / max_iteration);

the divison iteration / max_iteration is int division whose result is always 0 (possibly 1 if ever iteration == max_iteration).
Try working in float, or rearrange like this
color = alfa * iteration / max_iteration;

removing the parentheses. But you'll have to watch out that the int range isn't broken.
Having said that, it seems you are not sure yourself what alfa is. I suggest 255 so you get a grey-scale image.


text:
Q: Is it possible to roll up multiple timelines in a project summary I want to create several project sites and then have a top level project site with a project summary that rolls up the tasks and events from all sub projects into a single project summary. Is it possible to customize a project summary to show more than one timeline?

A: I have found that it is not possible to roll up multiple task list timelines into a single project summary. However, I've found that a great alternative is to just create a page (or use an existing page) and add multiple Timeline web parts that are each connected to your relevant task list. This displays separate timelines, but for me that works well enough. I haven't tried doing this with project summary web part, but I will do so and update my answer if it works.
Reference this solution for the basic steps of how to add a timeline web part to a page and link it to the source task list. The basic gist of it is to:

*

*Edit the page.

*Insert a Web Part and choose the Timeline web part.

*Edit the web part properties.

*Enter the URL of the site/sub-site that the task list is under (if different from the site where the page is).

*Select the task list and click OK.

*Save your edits to the page.

EDIT/UPDATE
You CAN modify a Project Summary webpart to show items from multiple task lists or calendars in the project site, but only under Late and Upcoming. You cannot have multiple timelines from multiple task lists in one Project Summary.


text:
Q: Want to delete Jenkins jobs I have around 600+ Jenkins jobs which needs to be removed since those are no longer being used.
Could any one suggest what are the ways we can remove those jobs easily?

A: Go to Jenkins Console (https://<url>/script) and execute a groovy script like this one
import jenkins.model.*

def matchedJobs = Jenkins.instance.items.findAll { job ->
    job.name =~ /my_regex_here/
}

matchedJobs.each { job ->
    println job.name
    job.delete()
}

https://gist.github.com/nextrevision/d11b2df4e8b229c6855b
If the jobs are inside folders, look at the script shared by pjlbyrne


text:
Q: Linq left join with group join I have set of Users and Visits. (So user do visits)
Visit have User navigation property.
I need to find the users who don't visit.
I can do this by finding the users who visit, finding all of the users then taking the difference.
I was trying to find a solution which is faster.
This is what I have right now:
  var users = _db.Users.AsNoTracking().Include(c => c.City).Where(x => x.City.Id == city);

  var groupedUsers = _db.Visits.AsNoTracking().Include(c => c.City).Include(a=>a.VisitedBy).Where(x => x.City.Id == city).GroupBy(x => x.VisitedBy).Select(group => new { VisitedBy = group.Key, Count = group.Count() });

  var visitingUsers = groupedUsers.Select(user => user.VisitedBy);

  var dif = users.Except(visitingUsers);

However I was trying GroupJoin as below:
   var results = _db.Users.Include(c => c.City).Where(c => c.City.Id == city).
            GroupJoin(_db.Visits.Include(c => c.City).Include(u => u.VisitedBy), u => u.Id, v => v.VisitedBy.Id, (u, v) => new { User = u , Visits = v })
            .Select(o=>o.User);

But this gives me all of the Users, I want the users who don't exist in the Visit set.
Any help?

A: I am not too sure if the city filtering is what you are after however the following should achieve what you desire:
var visitsToCity = _db.Visits.Where(v => v.City.Id == city);
var usersOfCity = _db.Users.Where(u => u.City.Id == city);

var nonVisitingUsers = usersOfCity.Where(u => !visitsToCity.Any(v => v.VisitedBy == u));

The last Where combined with the Any should result in a SQL statement like:
SELECT * FROM Users u WHERE u.CityId = @p0 AND
    NOT EXISTS(SELECT 1 FROM Visits v WHERE v.CityId = @p0 AND
                  v.VisitedById = u.Id)

Where @p0 will be supplied with the value of city.

A: You may be able to avoid the correlated sub-query in the other answer by actually doing the left join with null check. Here's a quick example:
var A = new [] { new Foo { Bar = 1 }, new Foo { Bar = 2 }};
var B = new [] { new Foo { Bar = 2 }};

var C = from x in A
        join y in B on x.Bar equals y.Bar into z
        from y in z.DefaultIfEmpty()
        where y == null
        select x;

Check the emitted SQL...


text:
Q: Complexity of a quadratic program I have a quadratic program: $$\displaystyle\min_{\mathbf{X}} (\mathbf{X^TQX +C^TX}) \quad{} \text{subject to} \quad{} \mathbf{A X \leq Y}$$ $\mathbf{Q}$ is positive definite and is $N \times N$, $\mathbf{A}$ is $M \times N$ and $\mathbf{X}$ is an $N \times 1$ vector. I'm trying to compute the complexity in terms of multiplications, but can not figure out how to approach it. I'd appreciate it if anyone can provide help/guidance or any references I can check.
I'm using the interior point convex algorithm.

A: You asked for references...Convex Optimization by Boyd and Vandenberghe is a good jumping-off point. It's available online, at
http://www.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf
(be forewarned, it's a large PDF.) See in particular the start of section 11.8...what you do will partially depend whether Q is sparse.


text:
Q: Set groups polices on windows - active directory from PHP How I can set groups polices on Windows Server - Active Directory, using or from PHP.
I want push to Active Directory any groups polices, for example: max characters password permit, set ip authorizes to longing, so on...
Thanks in advances.

A: If adLDAP and PHP's native LDAP functions don't support this, you can write a PowerShell script and execute it from PHP using the exec() function.
See PowerShell Group Policy reference to get started. Searching the net will give you some ready to use examples of how to assign policies to a group using PowerShell.
Good luck!


text:
Q: Objects within objects in OCaml I'm trying to figure out how I can parameterize OCaml objects with other objects. Specifically I want to be able to create a link object which contains a forward node object and a backwards node object, and I want to be able to create a link by saying something like:
let link1 = new link node_behind node_ahead;;

A: Objects are normal expressions in OCaml, so you can pass them as function and class constructor arguments. For a deeper explanation, look at the related section in OCaml manual.
So for instance, you can write:
class node (name : string) = object
  method name = name
end

class link (previous : node) (next : node) = object
  method previous = previous
  method next = next
end

let () =
  let n1 = new node "n1" in
  let n2 = new node "n2" in
  let l = new link n1 n2 in
  Printf.printf "'%s' -> '%s'\n" l#previous#name l#next#name


text:
Q: Can I use `Semaphore.Release` as a readymade interlocked increment? I need a cross-process counter. I could map an integer in a memory-mapped file and use Interlocked.Increment on it, but it seems to me that Semaphore.Release would do the same thing and with less programming overhead. For example:
var mySem = new Semaphore(0, int.MaxValue, "mySemName");

// Get the next number.
int num = mySem.Release();

Does that seem reasonable?

A: Short answer: Yes
But... You'd have to increment (or decrement it) in order to read it. There is no property to read the current number of slots (which makes sense because it's not really what they are for).

A: Not sure "rigmarole" is a technical term. With less overhead?  No.
Semaphores implement a special algorithm to ensure that the semaphore counter value is kept consistent over all threads.  The counter value must be locked before it is inspected, and the lock has to persist until the counter increment or decrement has been completed.  While it is locked, other threads may wait (if blocking) or simply fail (if non-blocking) and sometimes retry a moment later.
Interlocked increment merely ensures that the increment operation is atomic.  The interlocked increment of a byte does not require any special logic because bytewise increment is a CPU-level instruction.  Word and DWord increment may or may not be atomic depending on the chipset; if it is atomic, the framework will take advantage of that, and if it isn't, the framework will set up a lock to ensure that different threads don't increment different portions of memory within the same word or dword at the same time.
Almost all of the time, interlocked increment and decrement will have far less overhead.

A: Yes, will work fine.  However this is not what the Semaphore class was designed to do.  Pity the poor guy that comes behind you to maintain the code.  He will be wondering where all the Semaphore.WaitOne() calls are.
Doing this same thing in shared memory is not hard.  Here is all you need...
            string mapname = "{EE9D59F3-18F7-4FB6-B76B-AC1E6902BD9B}";
            MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapname, sizeof(int));
            MemoryMappedViewAccessor mmva = mmf.CreateViewAccessor(0, sizeof(int));
            int count = Interlocked.Increment(ref *(int*)p.ToPointer());

But this is not code to be proud of either.  You would have to compile your code with /unsafe.
When there is no elegant approach, then you should revisit your design premise.  Why do you need a shared counter in the first place? If it is to make something unique, why not generate a GUID in each process?  If it is to aggregate a total, a more robust approach might be to post increments to a server.  If you really need high performance counting then perhaps C# is not the right vehicle for your ambitions.


text:
Q: How to set roles or policy in asp.net MVC 6 windows authentication I have ASP.Net MVC 6 Application with windows authentication
how do I create roles or policies in and where to set them.
I know that we set
        [Authorize(Roles ="editor")]

but I don't know how to add users to this editor role or groups
also where do I create these roles.
how these roles work, how the system authenticate, where the system authenticate

A: You'd set them in your Active Directory. Roles in Windows Authentication map to group membership.
However role checks for Windows auth are broken in RC1. This is fixed in RC2.


text:
Q: Why do arithmetic operations on unsigned chars promote them to signed integers? Many answers to similar questions point out that it is so due to the standard. But, I cannot understand the reasoning behind this decision by the standard setters.
From my understanding an unsigned char does not store the value in 2's complement form. So, I don't see a situation where let's say XORing two unsigned chars would produce unexpected behavior. Therefore, promoting them to int just seems like a waste of space (in most cases) and CPU cycles.
Moreover, why int? If a variable is being declared as unsigned, clearly the unsignedness is important to the programmer, therefore a promotion to an unsigned int would still make more sense than an int, in my opinion.
[EDIT #1] As stated out in the comments, promotion to unsigned int will take place if an int cannot sufficiently accommodate the value in the unsigned char.
[EDIT #2] To clarify the question, if it is about the performance benefit of operating over int than char, then why is it in the standard? This could have been given as a suggestion to compiler designers for better optimization. Now, if someone were to design a compiler which didn't do this that would make their compiler as one not adhering to the C/C++ standard fully, even though, hypothetically this compiler did support all other required features of the language. In a nutshell, I cannot figure out a reason for why I cannot operate directly over unsigned chars, therefore the requirement to promote them to ints, seems unnecessary. Can you give me an example which proves this wrong?

A: You can find this document on-line: Rationale for International Standard - Programming Languages - C (Revision 5.10, 2003).
Chapter 6.3 (p. 44 - 45) is about conversions

Between the publication of K&R and the development of C89, a serious divergence had occurred among implementations in the evolution of integer promotion rules.  Implementations fell into two major camps which may be characterized as unsigned preserving and value preserving.
The difference between these approaches centered on the treatment of unsigned char and unsigned short when widened by the integer promotions, but the decision had an impact on the typing of constants as well (see §6.4.4.1).
The unsigned preserving approach calls for promoting the two smaller unsigned types to unsigned int. This is a simple rule, and yields a type which is independent of execution environment.
The value preserving approach calls for promoting those types to signed int if that type can properly represent all the values of the original type, and otherwise for promoting those types to unsigned int.
Thus, if the execution environment represents short as something smaller than int, unsigned short becomes int; otherwise it becomes unsigned int. Both schemes give the same answer in the vast majority of cases, and both give the same effective result in even more cases in implementations with two's complement arithmetic and quiet wraparound on signed overflow - that is, in most current implementations. In such implementations, differences between the two only appear when these two conditions are both true:

*

*An  expression  involving an unsigned char or unsigned short produces   an  int-wide result in which the sign bit is set, that is, either a unary operation on such a type, or a binary operation in which the other operand is an int or "narrower" type.

*The  result  of  the  preceding  expression  is  used  in  a  context  in  which  its  signedness  is  significant:
• sizeof(int) < sizeof(long) and it is in a context where it must be widened to a long type, or
• it is the left  operand  of  the  right-shift  operator  in  an  implementation  where  this  shift  is  defined as arithmetic, or
• it is either operand of  /, %, <, <=, >, or >=.
In such circumstances a genuine ambiguity of interpretation arises.  The result must be dubbed questionably signed, since a case can be made for either the signed or unsigned interpretation.  Exactly the same ambiguity arises whenever an unsigned int confronts a signed int across an operator, and the signed int has a negative value.  Neither scheme does any better, or any worse, in resolving the ambiguity of this confrontation.  Suddenly, the negative signed int becomes a very large unsigned int, which may be surprising, or it may be exactly what is desired by a knowledgeable programmer.  Of course, all of these ambiguities can be avoided by a judicious use of casts.
One of the important outcomes of exploring this problem is the understanding that high-quality compilers might do well to look for such questionable code and offer (optional) diagnostics, and that conscientious instructors might do well to warn programmers of the problems of implicit type conversions.
The unsigned preserving rules greatly increase the number of situations where unsigned int confronts signed int to yield a questionably signed result, whereas the value preserving rules minimize such confrontations.  Thus, the value preserving rules were considered to be safer for the novice, or unwary, programmer.  After much discussion, the C89 Committee decided in favor of value preserving rules, despite the fact that the UNIX C compilers had evolved in the direction of unsigned preserving.
QUIET CHANGE IN C89
A  program  that  depends  upon  unsigned  preserving  arithmetic  conversions  will  behave  differently,  probably  without  complaint. This  was  considered  the  most  serious  semantic  change  made  by  the  C89  Committee  to  a  widespread  current  practice.

For reference, you can find more details about those conversions updated to C11 in this answer by Lundin.


text:
Q: Eclipse running very slow on Ubuntu I am new on Ubuntu. I am developing one application using Eclipse (Version: Kepler Service Release 1, Build id: 20130919-0819). I have dual os on my pc. Window 8 as well as Ubuntu.
But now a days I am mostly using Ubuntu for my development work. But problem is my Eclipse is stuck on every copy/selection command for 20-30 seconds, and whole Os running very slow. I can't figure out where is the problem.
Can someone help me to solve this problem?
thanks.

A: As easiest and fastest solution is reinstall your Eclipse.


text:
Q: Using post with link_to I have this route:
avatar_add_from_collection POST   /avatars/:avatar_id/add_from_collection(.:format)            {:action=>"add_from_collection", :controller=>"avatars"}

and I am trying to create a link using link_to that uses post. The reason I need to do that is because (apparently) you can't put an image on a button using button_to.
<%= link_to inline_avatar(avatar.fetch_avatar_image(:thumb)), add_from_collection_avatar_path(avatar),:method=>:post%>

brings up
No route matches "/avatars/3/add_from_collection"

If I change the routes file to make this a GET it works just fine.
The link_to looks like
link_to inline_avatar(avatar.fetch_avatar_image(:thumb)), avatar_add_from_collection_path(avatar),:method=>:post

EDIT:
Jade::Application.routes.draw do

  resources :avatar_categories do
    delete :remove_item
  end

  resources :avatars do
    member do
     post 'add_from_collection', :on=>:member
    end
  end

  resources :categories,:addresses,:calendars,:topics,:profile,:news,:account_setting
  resources :boards do
    member do
      get :move
      post :move_category
    end
  end

  post 'avatars/display_collection'
  get "user/index"
  get 'login/index'
  get 'login/new'
  post 'login/create'
  post 'login/authenticate'
  get 'login/forgot_password'
  put 'login/reset_password'
  get 'login/logout' #post?
  get 'admin/index'
  get 'admin/app_settings'
  get 'admin/user_settings'
  get 'admin/avatars'
  post 'admin/avatar_upload'
  post 'admin/update_app_settings'
  get 'news_configurations/index'
  put 'news_configurations/update'
  get 'message_board_configurations/index'
  put 'message_board_configurations/update'
  get 'profile_settings/edit'
  post 'profile_settings/update'

  resources :posts do
    get :new,:edit
    post :create,:update,:destroy
  end

  match '/login' => 'login#index', :as => 'login'
  match '/admin' => 'admin#index', :as => 'admin'

  resources :login do
    get :index
    post :authenticate,:logout
  end
root :to => "news#index"

end

A: resources :avatars do
  member do
    post 'add_from_collection'
  end
end

or
resources :avatars do
  post 'add_from_collection', :on => :member
end

EDIT
This is wrong
resources :avatars do
  member do
   post 'add_from_collection', :on=>:member
  end
end

use this
resources :avatars do
  post :add_from_collection, :on=>:member
end

But looks like this won't help


text:
Q: KDA metrics in cloudwatch different from Flink metrics I have a Flink application deployed on AWS Kinesis Data Analytics.
My current setting is:
Parallelism=128
Parallelism per KPU=4

The issue I have is, there is a big difference between the counts shown on the Flink web UI vs the Count shown in Cloudwatch even for Metrics that come out of the box.
Example:
Counts from Flink UI:
Records Sent: Close to 1 Billion

Count from Cloudwatch:
NumRecordsIn:

NumRecordsOut:

Both of these are close to 10.8Million.
The metrics for KDA are configured at Task level.
I am wondering why I am seeing this huge discrepancy. Is the parallelism having some effect on the counts?
FWIW, I added a custom metric which tracks the numRecordsIn. That also seems to be similar to the out of the box NumRecordsIn metric.

A: It appears that you are comparing the total numRecordsIn/Out across the lifetime of the job (roughly 1 billion) to the maximum ever seen in one minute (around 10 million).

A: What David has mentioned above is correct. I was finally able to find out how to get the values from Flink UI on to CloudWatch. The problem with CloudWatch is that, it does not include the parallelism. So in order to get the count of records emitted by a specific task, take the Average(numRecordsOut) of that task and multiply it by parallelism.


text:
Q: Calcluating division mod a prime I am unfamiliar with number theory but am trying to calculate the following for a coding challenge:
$$\frac{(N-M-1)!}{N!(M-1)!}\pmod{Q}$$
where $Q$ is prime. I know that I can calculate the "modular" factorial fairly easily:
$$(N-M-1)!\bmod{Q} \equiv (((N-M-1)\times (N-M-2))\bmod{Q} \times \dots))\bmod{Q}$$
However, I'm not sure how I calculate the division part, I know that we can rewrite the fraction:
$$\frac{(N+M-1)!}{N!(M-1)!}\equiv (N+M-1)!\cdot (N!(M-1)!)^{-1}\pmod{Q}$$
However, can I compute the "modular" factorial of $N$ and $(M-1)$ in the same way and then compute the modular inverse of their product, or is there something else I need to do?

A: It looks like your question boils down to: when can I divide an expression while reducing it $\pmod m$? Take this example:
\begin{align*}
    (8/2) \pmod 6 &\equiv \frac{8 \pmod 6}{2\pmod 6}\\
    &\equiv \frac{2 \pmod 6}{2\pmod 6}\\
    &\equiv 1\pmod 6\\
    4\pmod 6 &\equiv 4 \pmod 6.
\end{align*}
So, in general we know that
$$
\frac{a}{b}\pmod m \neq \frac{a \pmod m}{b \pmod m}.
$$
However as you pointed out, when $m$ is prime, we can divide without worrying about the above problem.
We summarize these findings in the following statement:

When $n$ is a prime number, it is valid to divide by any non-zero number - that is, for each $a \in\{1,2, \ldots, n-1\}$ there is one, and only one, number $u \in\{1,2, \ldots, n-1\}$ such that
$$au = 1 \quad(\bmod n) .
$$
Then, dividing by $a$ is the same as multiplying by $u$, i.e. division by $a$ is given by the rule
$$\frac{b}{a}=b u \quad(\bmod n) .
$$
For example, in mod $7$ , we have
$$\frac{1}{1}=1, \quad \frac{1}{2}=4, \quad \frac{1}{3}=5, \quad \frac{1}{4}=2, \quad \frac{1}{5}=3, \quad \frac{1}{6}=6.
$$

In your example, because $Q$ is prime we can solve the equation as you expressed.


text:
Q: How to change custom validation message in the validator class in spring boot? Below is my code
package com.jockeyclub.races.validation;

import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.springframework.beans.BeanWrapperImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class RaceReqConstraintValidator implements ConstraintValidator<RaceReq, Object> {

    private String raceNum;
    private String raceDate;
    private String message;

    @Override
    public void initialize(RaceReq constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        raceDate = constraintAnnotation.raceDate();
        raceNum = constraintAnnotation.raceNum();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String rn = (String) new BeanWrapperImpl(value).getPropertyValue(raceNum);
        String rd = (String) new BeanWrapperImpl(value).getPropertyValue(raceDate);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String d = formatter.format(LocalDate.parse(new String((String) rd), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        String u = String.format("https://racing.hkjc.com/racing/information/English/Racing/LocalResults.aspx?RaceDate=%s", d);

        try {
            URL url = new URL(u);
            WebRequest request = new WebRequest(url, HttpMethod.POST);
            WebClient webClient = new WebClient();
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setCssEnabled(false);
            webClient.getCookieManager().setCookiesEnabled(true);
            HtmlPage page = webClient.getPage(request);

            if (page.getElementById("errorContainer") != null) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(raceDate).addConstraintViolation(); //message: "No race on this date"
                return false;
            }
            if (!raceNum.equals("1") && page.getByXPath(String.format("/html/body/div/div[2]/table/tbody/tr/td[%s]/a", raceNum)).isEmpty()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(raceNum).addConstraintViolation(); //message: "Invalid race number"
                return false;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}

this is my validator class wherein I return false under 2 conditions. First if condition will return false if there is no race on that date. Second, if condition will return false if the race number is invalid
Here I want to send different messages if my first if condition returns false and if my second if condition returns false. Is there any way to do this? I have mentioned the messages as comments


text:
Q: Mapping a list of dictionaries from one type to another I have list of dictonaries.  I wish type iterate over this list and map it to a slightly different type of dictionary.
Original dictionary:
{'Test Name':blah, 'Test': blah, 'Att a': blah, 'Att b': blah}

New Dictionary:
{'Test Name':blah, 'Test': blah, 'Failure': failure, 'Project': project}

In the original I only care about the attributes Test Name and Test.  In the new dictionary, I add a few extra attributes.
To do this, I do:
mappedFailures = [];
for fixedFailure in fixedFailures:
    mappedFailure = {'Test Suite': fixedFailure['Test Suite'],
                     'Test':fixedFailure['Test'], 'Failure':failure,
                     'Project': 'project'}
    mappedFailures.append(mappedFailure);

This is easy to read, but I was wondering was there a more pythonic way Thanks.

A: You could use a list comprehension and the dict constructor to achieve the very short
mappedFailures = dict((key, fixedFailure[key]) for key in ('Test Name', 'Test'))
mappedFailures['Failure'] = failure
mappedFailures['Project'] = project

A: This is a classic use case for a list comprehension:
def map_failure(ff):
    return {'Test Suite': ff['Test Suite'], 'Test': ff['Test'],
            'Failure': failure, 'Project': 'project'}

mappedFailures = [map_failure(ff) for ff in fixedFailures]

A: It appears that mappedFailures is actually a list of dicts. For that, you simply want to use list comprehension to iterate over each fixedFailure and build a new dict from that.
mappedFailures = [
    {
        'Test Name': fixedFailure['Test Name'],
        'Test':      fixedFailure['Test'],
        'Failure':   failure,
        'Project':   project,
    }
    for fixedFailure in fixedFailures
]


text:
Q: For iOS development, is it better to adjust content in one MVC, or create multiple MVC's? I'm working on an iOS app with a Split View Controller that has a series of buttons in the master view. Each button will change the contents of the detail view, but all of the various detail views will share the same layout. Being pretty new to Swift, I originally intended to create one MVC for the Detail and adjust it's contents based on which button is pressed, but it seems that if I created a unique MVC for each I could do the whole thing with no actual coding at all.
Making multiple MVC's seems inefficient to me, but using the IB when possible seems to be the way to go in most instances. I'm sure I'm not the first person to wonder this, but I'm using the wrong nomenclature on searches or maybe I'm just missing something obvious. Any thoughts or links?


text:
Q: iframe Https site in UIWebView of iOS app - suddenly stops working (..but not in safari) I've just submitted an app to the Appstore that iframes an Https site (not mine) in UIWebView in one of the view controllers. The "framing" worked perfectly for about a week, then suddenly something happened. As of its sudden occurrence, I suspect the host of the framed site might have done something to protect my framing. I'm pretty sure that's not the case as it worked a couple of days ago and they rarely make updates to their site.
What now happens
Let me explain this a bit further. A few days ago, one could submit data through the WebView inside the app (which is the only purpose of the WebView) but now, all of a sudden trying to submit data generates to a custom error: "Something wen wrong, please contact system administrators". Not a 404 error or something, just a "custom error" that says that something went wrong. But, if one opens my iframe .html doc in mobile safari, submitting data inside the iframe works just fine. No errors are displayed in the console for my iframe html doc, except a favicon error but I'm sure that has nothing to do with it. I've also tried moving the file over to a different domain in case they've blacklisted my first domain but that didn't help.
(The company who owns this https site has granted me permission to frame their site in my app but they're really not that cooperative so asking them what happen will lead to nothing. I have of course, but no answer.)
I do realize this is probably something I should ask them about, but as they're not responding as it worked before, I'm guessing this could be the cause of something else. Any ideas what else I could try? Why does it work in safari but not in UIWebView (anymore)? I know, UIWebView != safari, but except from that?

A: I guess that the remote server is filtering the user agent of the UIWebView.... Not sure.


text:
Q: Templates causing Segmentation Fault in c++ There is a problem in the simple code snippet below that i can't uncover even with a debugger. Thanks for your help in advance.
Command.h
class word{

   private : static int next_word;
   private : int word_id;
   public : word();
   public : void grabIt();
   public : void raiseIt();
   public : void putItDown();
};
class Command{

   public : typedef void(word::*Method)();
   private : word* w;
   private : Method m;
   public : Command(word *w, Method m);
   public : void execute();
};
template<typename T>
class Queue{

  private : enum{
    SIZE=9
  };
  private : T* commandArray[SIZE];
  private : int m_added = 0, m_removed = 0;

  public : void enqueue(T* t){

        commandArray[m_added] = t;
        m_added = (m_added + 1) % SIZE;
    }
  public : T* dequeue(){
        int temp = m_removed;
        m_removed = (m_removed + 1) % SIZE;
        return commandArray[temp];
    }
};

Command.cpp
int word::next_word = 0;
word::word(){

   this->word_id = next_word++;
}
void word::grabIt(){
  std::cout << "Grabbed it" << std::endl;
}
void word::raiseIt(){
  std::cout << "Raised it" << std::endl;
}
void word::putItDown(){
   std::cout << "Put it down" << std::endl;
}
Command::Command(word *w, Method m){
   w = w;
   m = m;
}
void Command::execute(){
   (w->*m)(); // -------------->>>>> Causing Seg-Fault
}

Main.cpp
Queue<Command> queue;
Command *commandArray[9];
Command command1(new word, &word::grabIt);       commandArray[0] = &command1;
Command command2(new word, &word::raiseIt);      commandArray[1] = &command2;
Command command3(new word, &word::putItDown);    commandArray[2] = &command3;
Command command4(new word, &word::grabIt);       commandArray[3] = &command4;
Command command5(new word, &word::raiseIt);      commandArray[4] = &command5;
Command command6(new word, &word::putItDown);    commandArray[5] = &command6;
Command command7(new word, &word::grabIt);       commandArray[6] = &command7;
Command command8(new word, &word::raiseIt);      commandArray[7] = &command8;
Command command9(new word, &word::putItDown);    commandArray[8] = &command9;

for( int i=0 ; i < 9; i++){
   queue.enqueue(commandArray[i]);
}
for( int i=2 ; i < 6 ; i++){
   queue.dequeue()->execute();
}

Some word objects inside the queue appear NULL in the debugger, so cause Seg-Fault.

A: To fix the problem, change
Command::Command(word *w, Method m){
   w = w;
   m = m;
}

to
Command::Command(word *w, Method m) : w(w), m(m){}

For the exact reasoning, look at Can I use identical names for fields and constructor parameters?


text:
Q: OPENJSON does not get recognized in Azure SQL DB I want to use OPENJSON function in Azure SQL DB, but when I try to execute the function, I get the following error:

Msg 195, Level 15, State 10, Line 25 'OPENJSON' is not a recognized
  built-in function name.

I had researched and found this link saying

The OPENJSON function is available only under compatibility level 130 or higher. If your database compatibility level is lower than 130, SQL Server can't find and run the OPENJSON function. Other JSON functions are available at all compatibility levels.

As suggested, checked compatibility level with following
select * from sys.databases

and confirmed it was 140 which is higher than the minimum requirement.
So, wouldn't it it work?

A: OPENJSON is a table-valued function, and it must appear in the a valid location for a table expression.
EG
select openjson('{}')

fails with

Msg 195, Level 15, State 10, Line 29 'openjson' is not a recognized
  built-in function name.

But
select * from openjson('{}')

works.

A: Ideally, it should work if the compatibility level is 130 or above.
https://blogs.msdn.microsoft.com/azuresqldbsupport/2018/03/24/lesson-learned-34-does-azure-sql-database-support-openjson/

A: Three steps may help you:
1.Check your SQL Server version(Starting with 2016).
2.Check your Azure SQL database ompatibility level is 130 or higher.
3.Check your Azure SQL Database version.
Run select @@version to see if it is the V12 server.
If you see some lower version (e.g. 11.xxx) you probably have database on old architecture where JSON is not supported. You need to update your Azure SQL Database to the latest V12 version.
Reference:OPENJSON does not work in SQL Server?
Hope this helps.


text:
Q: A name for a mathematical structure of geometric type I am looking for (maybe existing) name for a mathematical structure $(X,\leqslant)$ consisting of a set $X$ and a transitive relation ${\leqslant}\subseteq X^2\times X^2$ such that $xx\leqslant yz\leqslant zy$ and $(xy\leqslant zz\;\Rightarrow\; x=y)$ for every $x,y,z\in X$. Here for elements $x,y\in X$ I denote by $xy$ the ordered pair $(x,y)$.
There are at least three important examples of such mathematical structure:

*

*a metric space $(X,d)$ in which $xy\leqslant uv$ is defined as $d(x,y)\le d(u,v)$;

*an ordered group $(X,+,\le)$ in which $xy\leqslant uv$ is defined as $|x-y|\le |u-v|$;

*the Euclidean or hyperbolic plane in which $xy\leqslant ab$ means that $xy$ is congruent to $ac$ for some $c\in[a,b]$.

Question. What would be a good name for such a structure $(X,\leqslant)$?

I thought about protometric spaces but this name is already occupied for something different.
Maybe to call it a compass space? Because the standard compass can be used for comparing distances (this is exactly what this mathematical structure describes). What do you think? Google shows nothing mathematical for the search ``compass space''.

A: After a long search, I have finally found an existing geometric tool that does exactly what is required: it compares distances without expressing them in real numbers. This measuring instrument is called a divider. So, the corresponding mathematical structure $(X,\leqslant)$ should be called a divider space.
Dividers and compasses are similar geometric tools (by their design) but serve to different purposes. A compass is used for drawing circles with a given center and a given point on the circle. In ruler-and-compass constructions, a compass cannot be used for transferring distances. The latter function is reserved for dividers, which by their construction cannot draw circles (because dividers have two sharp needles at the ends of both legs).
Nothing else but a divider is used in the famous masonic symbol:

I have got interested in dividers studying the Tarski axioms of Euclidean geometry. In contrast to the standard Euclid axioms that formalize the straightedge-and-compass geometric constructions, the Tarski axioms (without the Continuity Axiom) formalize straightedge-and-divider geometric constructions, which are more restrictive compared to the standard straightedge-and-compass constructions. For example, using only a straightedge and a divider it is possible to construct a right triangle with two given catheta but it is impossible to construct a right triangle by a cathetus and hypotenuse.
The Hilbert axioms system also differs from the standard Euclid axiom system because it actually formalizes the use of a straightedge, a divider, and a protractor (but not a compass). But a protractor adds nothing new comparing to a straightedge and a divider, which can copy angles. So, constructible distances in Tarski's and Hilbert's Geometry are the same: they form a Pithagorean field. In contrast, the straightedge-and-compass geometric constructions produce a Euclidean field (which is closed under taking square roots). To produce such a field one should add to Tarski (or Hilbert) axioms the Segment-Circle Axiom postulating the existence of a point of the intersection of a circle and a segment with endpoints at different sides of the circle.


text:
Q: OutputCollector null pointer exception hadoop I am trying to implement in memory sorting,i.e. soring based on the no. of counts. I am facing the below problem, null pinter exception in output.collect in the close method of the Reduce class. Pls help!
Is my coding logic correct? I am keeping in memory the tokens from different instances of reduce method. Please help me! I wanted a sorted output of based on the TCounts.
package com.a;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

public class Map1 extends MapReduceBase implements Mapper<LongWritable, Text, Text,
Text >{
    public void map(LongWritable key, Text value, OutputCollector<Text, Text> output,
            Reporter reporter) throws IOException {

        StringTokenizer tokenizer = new StringTokenizer(value.toString());

        String tk = tokenizer.nextToken();
        String id = tokenizer.nextToken();
        String name = tokenizer.nextToken();

        StringTokenizer tkz = new StringTokenizer(name, ",");

        ArrayList<String> al = new ArrayList<String>();

        while(tkz.hasMoreTokens())
        {
            name = tkz.nextToken();
            al.add(name);
        }

        for(int i = 0; i<al.size(); i++)
        {
            output.collect(new Text(t+" "+al.get(i)), new Text("1"));
            System.out.println("out key:----->"+t+" "+al.get(i));
        }

    }

}

public class Reduce1 extends MapReduceBase implements Reducer<Text, Text, Text, Text>{
    //  @SuppressWarnings("unchecked")

    ArrayList<TCount> al = new ArrayList<TCount>();
    String key_str = null;
    private OutputCollector<Text, Text> output;

    public void reduce (Text key, Iterator<Text> values, OutputCollector<Text,
            Text> output, Reporter reporter) throws IOException {

        int sum = 0;

        while(values.hasNext())
        {
            String val = values.next().toString();
            sum = sum+Integer.parseInt(val);;

        }

        String str_val = String.valueOf(sum);
        key_str = key.toString();
        //output.collect(key, new Text(str_val));
        TCount tc = new TCount(key.toString(), sum);
        al.add(tc);

    }

    private Text t = new Text();
    private Text txt_key = new Text();

    public void close() throws IOException {
        Collections.sort(al);

        for(int i = 0; i<al.size(); i++)
        {

            String tkn = al.get(i).getT();
            System.out.println("token:-------------------> "+tkn);

            System.out.println("output: "+output);
            txt_key = new Text(t);
            txt = new Text(String.valueOf(al.get(i).getCount()));
            output.collect(txt_key, t);

        }
    }
}

A: In class Reduce1, you're declaring the output object:
private OutputCollector<Text, Text> output;

without initializing it -> so it's null at this time.
Also in the method reduce() you pass a parameter of the same type (OutputCollector<Text, Text> output) -> so in this method, I guess you wanna say:
this.output=output;
// if the object is null, initialize it if you wanna use it

The thing is you'll get a null pointer exception as long as your object is not initialized (instantiated).


text:
Q: How to declare a PHP variable and pass it into AJAX url? When i call /comment.php it returns data that i've requested. where post_id is fixed.
/comment.php
 "ajax":
{
 "url": "http://localhost/fb-callback.php?post_id=12345_67890",
   "type" : "GET",
"dataSrc":  function (response) {
                // console.log(response);
                            if(response.whaterver == 0){
                               //DO YOUR THING HERE
                            }
                            //return back the response
                            return response;
                        },

Instead of fixed id (12345_67890), i wanna declare a php variable there,
something like this ::-
<?php
$uid = $_GET['uid'];
?>

 "ajax":
{
 "url": "http://localhost/fb-callback.php?post_id="+"&uid",
"type" : "GET",
 ................

so that when i'll call url /comment.php?uid=12345_67890** it'll return results. But it seems it doesn't work that way.
HOW CAN I DO THAT Or is there other way to make this call ?
Here is the Full code ::: https://pastebin.com/iy3htv63

A: you can echo it on the ajax url. try this
 <?php
  $uid = $_GET['uid'];
?>

 "ajax":
{
 "url": "http://localhost/fb-callback.php?post_id=<?php echo $uid; ?>",
 "type" : "GET",
 ................

A: Try This
<?php
$uid = $_GET['uid'];
?>
var uid = <?php echo $uid; ?>;
 "ajax":
{
 "url": "http://localhost/fb-callback.php?post_id="+uid,
"type" : "GET",
 ................


text:
Q: Android MapView Class Not Found When trying to run the mapview in the emulator or on the device, the activity crashes.  I feel this may be due to an import issue with the required libraries.  The error will show a class not found exception.  Please let me know if you need more information.  I have also been following this tutorial: https://blog-emildesign.rhcloud.com/?p=435
Activity:
package com.klinetel.countydentistfinder;

import com.google.android.gms.maps.*;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class ClinicMapActivity extends FragmentActivity
{
    MapView m;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clinic_map);

    }

}

Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.klinetel.countydentistfinder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="com.klinetel.countydentistfinder.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <permission
        android:name="com.klinetel.countydentistfinder.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name="com.klinetel.countydentistfinder.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.klinetel.countydentistfinder.ClinicListingActivity"
            android:label="@string/title_activity_clinic_listing"
            android:parentActivityName="com.klinetel.countydentistfinder.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.klinetel.countydentistfinder.MainActivity" />
        </activity>
        <activity
            android:name="com.klinetel.countydentistfinder.ClinicMapActivity"
            android:label="@string/title_activity_clinic_map"
            android:parentActivityName="com.klinetel.countydentistfinder.ClinicListingActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.klinetel.countydentistfinder.MainActivity" />
        </activity>
        <uses-library android:name="com.google.android.maps"></uses-library>
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value=""/>
    </application>

</manifest>

Logcat:

A: You should not add it as a external jar file.
You should reference the library project in your android map project.
http://developer.android.com/google/play-services/setup.html
Copy the google-play services_lib library project to your workspace (folder where your android map project is). The library project can be found under the following path.
     <android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib library project .

Import the library project to your eclipse
Click File > Import, select Android > Existing Android Code into Workspace, and browse the     workspace  import the library project. You can check if it is library project. Right click on the library project. Goto properties. Click Android on the left panel. You will see Is Library checked.
Right click on your android project.  Goto properties. Choose Android on the left panel. Click on Add and browse the library project. Select the same. Click ok and apply

Also make sure you have enabled google maps for android in the google api console


text:
Q: Strange behaviour with void pointers I want to create a function which gets a void pointer. This pointer points to an arbitrary user data. This is not relevant now. Which is more important a descriptor, which describe this user data. It is under this data. I want to get it's address, there are two different solution:
struct data_desc {
     size_t size;
     data_type_t type;
     /* And so on... */
};

/* Operate on the descriptor */
void operate_on_data(void *ptr)
{
    struct data_desc *desc;
    /* Now I want to get the desc /*

    /* This is the first approach, simply fails */
    desc = ((struct data_desc *)ptr) - sizeof(struct data_desc);
    /* This is the second, it works...*/
    desc = (struct data_desc *)ptr;
    desc--;
    /* Do something with desc */
}

As you can see I use two diffrent approach to get the descriptor's address. I thought the first is more natural, but it's just not works. I used more parentheses to avoid the precedence problems.
I know that these methods are not safe. The first does not work, why? What is the reason behind this behavior?
Thanks in advance!

A: The problem is pointer arithmetic.  When you take a pointer and subtract 1, you are really subtracting (1*sizeof(struct)).  The first equation with the "-sizeof", you are really subtracting (sizeof(struct) * sizeof(struct)) bytes from the pointer.  Make sense?

A: When you define data_desc as a pointer to a struct data_desc, the compiler knows to add or subtract sizeof(struct data_desc) when you increment or decrement the pointer by one.  In other words, it translates "one" into "one structure."
It's common to write code like this:
struct data_desc *desc = (struct data_desc *) ptr;

Then you can manipulate it like this:
size_t sz0 = desc->size;  // size of 0th element
size_t sz1 = desc[1].size;  // size of 1st element
size_t sz2 = (desc + 2)->size; // size of 2nd element (slightly awkward)
desc++;  // Increment to next structure

Back to your original code:  you could write desc = ((struct data_desc *)ptr) - 1;, but most programmers would prefer to initialize desc and then use it directly.

A: desc = ((struct data_desc *)ptr) - sizeof(struct data_desc);

You've typecast ptr to a struct data_desc *. Now, all arithmetic that the compiler does on this pointer is in chunks the size of the type it points to.
So, if you subtract sizeof(struct data_desc) (let's say struct  data_desc is 8 bytes in size), ptr will point to a location that can fit 8 struct data_desc in between itself and ptr.
Assuming each loc below can hold one struct data_desc
-------------------------------------------------------------
|     |     |     |     |     |     |     |     |     |     |
| loc | loc | loc | loc | loc | loc | loc | loc | loc | ptr |
|  9  |  8  |  7  |  6  |  5  |  4  |  3  |  2  |  1  |     |
-------------------------------------------------------------
      ^                                               ^
      |                                               |
     desc                                            ptr
     location                                        location
     after
     subtraction


text:
Q: Uploading to a remote server using PHP/CURL Using PHP/CURL, how to upload a file to a remote server wherein the user must be logged in first?
thanks

A: FYI CURL can pass authentication credentials along like this:
curl --user USER:PASSWORD -s http://localhost:4848/monitoring/domain/server/transaction-service

But it depends on what the server is expecting.
EDIT:
Here's how to send POST data:
    curl --data "birthyear=1905&press=%20OK%20"         http://www.example.com/when.cgi

Please ask if you have any questions.


text:
Q: How can I deploy web app on Tomcat from running app I would like to develop updater app. Lets say I've got:
- Running Tomcat
- Running Updater App on the Tomcat
- Running old version of the app on the same Tomcat

I would like to
- Stop old app
- Undeploy old app
- Deploy new version of app (lets assume that I've got new app war file somewere in Updater app resourcess.
Is it possible to do such remote deployment on Tomcat from another app at all?

A: To deploy a project to your Tomcat Server from another app you need to:
Add a library into your project "catalina-ant.jar" from the folder: {TOMCAT_PATH}\lib
And in your project to deploy a war file you need to only do:

org.apache.catalina.ant.DeployTask task = new org.apache.catalina.ant.DeployTask();
task.setUrl("http://localhost:8084/manager");
task.setUsername("managerLogin");
task.setPassword("managerPassword");
task.setPath("/UrlToYourDeploadingProject");
task.setWar(new File("c:/Project.war").getAbsolutePath());
task.execute();

Thanks to this solution I'm able to develop project that can update automatically my apps.

A: Yes. There's a set of tools (well, a .jar) released with Tomcat that's usually used by ant but that can be used by anyone willing to call the code. There are tasks for starting and stopping applications, deploying, undeploying, listing applications and so forth; essentially it's an API that wraps the functionality of the manager servlet.
One moment while I try to dig up the name or a link for you...
Here's Apache's information on this stuff: http://tomcat.apache.org/tomcat-5.5-doc/manager-howto.html#Executing Manager Commands With Ant
... and here's a user, elsewhere, describing in detail how he uses these tasks: http://raibledesigns.com/wiki/Wiki.jsp?page=TomcatAntTasks
You may object that you're not ant. That's true, but there's nothing magic about ant, it's just calling code inside the jar. That code can be called from anywhere else that follows the API.
Here's a tutorial on writing ant tasks: http://ant.apache.org/manual/tutorial-writing-tasks.html
Not quite the same, but it should give you an idea of how the API works.
I see no reason why you shouldn't be able to call this API from within a servlet if you want to.
Alternatively, you could run the manager servlet in your Tomcat and simply access the manager application like a Web service: Use your browser or WireShark to snoop on the traffic between your browser and Tomcat when you deploy an app, and then duplicate that to remote control manager. Me, I think using the tools jar is simpler.

A: If you use a "project lifecycle" tool, this undeploy/deploy can be automatized in the development cycle.
Saying that, I think about Maven2 and his "maven-deploy" plugin :

*

*mvn compile : java compilation

*mvn package : creation of the war file (for a webbapp project)

*mvn deploy : stop, undeploy the old application, deploy and start the new version !

After, you can couple this automatization with a continous integration server (like Hudson).


text:
Q: Android Java Annotation in Flutter In Android: Java I can use the annotations like @NotNull or @NonNull.
I wonder if there is a way to use them in flutter (the annotations like ones I've mentioned)

A: Dart has null-aware operators, that can be used like this:
x = y ?? z; //will assign y to x, but if y is null, then z will be assigned instead
x ??=y; //if x is null will assign y to it
x?.foo(); //this way you can call a method on an object only if object (x) is not null

Also please check this out (about null-safety in Dart): https://dart.dev/null-safety


text:
Q: Is there any simulation software that can be used for simulation circuits of wireless power transfer? I am searching for a simulation software that also shows the interaction between electromagnetic waves in a wireless power transfer setup.

A: The best and famous softwares are Advanced Design System (ADS) and ANSYS HFSS and  COMSOL Multiphysics[RF Module]

A: Try COMSOL multiphysics. It can do good electromagnetic simulations. You should provide more details. Is it for energy harvesting?

A: I think Maxwell software from Ansys can do that perfectly.


text:
Q: How to aggregate a dataframe by week? Consider the following example
library(tidyverse)
library(lubridate)

time <- seq(from =ymd("2014-02-24"),to= ymd("2014-03-20"), by="days")
set.seed(123)
values <- sample(seq(from = 20, to = 50, by = 5), size = length(time), replace = TRUE)
df2 <- data_frame(time, values)
df2 <- df2 %>% mutate(day_of_week = wday(time, label = TRUE))

Source: local data frame [25 x 3]

         time values day_of_week
       <date>  <dbl>      <fctr>
1  2014-02-24     30         Mon
2  2014-02-25     45        Tues
3  2014-02-26     30         Wed
4  2014-02-27     50       Thurs
5  2014-02-28     50         Fri
6  2014-03-01     20         Sat
7  2014-03-02     35         Sun
8  2014-03-03     50         Mon
9  2014-03-04     35        Tues
10 2014-03-05     35         Wed

I would like to aggregate this dataframe by week.
That is, suppose I define a week as starting on Monday morning and ending on Sunday evening, which we will call a Monday to Monday cycle. (importantly, I want to be able to choose other conventions, such as Friday to Friday for instance).
Then, I would simply like to count the mean of values for each week.
For instance, in the example above, one would compute the average of values between Monday February 24th to Sunday March 2nd, and so on.
How can I do that?

A: In the tidyverse,
df2 %>% group_by(week = week(time)) %>% summarise(value = mean(values))

## # A tibble: 5 × 2
##    week    value
##   <dbl>    <dbl>
## 1     8 37.50000
## 2     9 38.57143
## 3    10 38.57143
## 4    11 36.42857
## 5    12 45.00000

Or use isoweek instead:
df2 %>% group_by(week = isoweek(time)) %>% summarise(value = mean(values))

## # A tibble: 4 × 2
##    week    value
##   <int>    <dbl>
## 1     9 37.14286
## 2    10 40.71429
## 3    11 35.00000
## 4    12 42.50000

Or cut.Date:
df2 %>% group_by(week = cut(time, "week")) %>% summarise(value = mean(values))

## # A tibble: 4 × 2
##         week    value
##       <fctr>    <dbl>
## 1 2014-02-24 37.14286
## 2 2014-03-03 40.71429
## 3 2014-03-10 35.00000
## 4 2014-03-17 42.50000

which you can tell to start on Sunday, if you prefer:
df2 %>% group_by(week = cut(time, "week", start.on.monday = FALSE)) %>%
    summarise(value = mean(values))

## # A tibble: 4 × 2
##         week    value
##       <fctr>    <dbl>
## 1 2014-02-23 37.50000
## 2 2014-03-02 40.00000
## 3 2014-03-09 33.57143
## 4 2014-03-16 44.00000

If you want to shift to, say, Tuesday start, add one to your dates:
df2 %>% group_by(week = cut(time + 1, "week")) %>% summarise(value = mean(values))

## # A tibble: 4 × 2
##         week    value
##       <fctr>    <dbl>
## 1 2014-02-24 37.50000
## 2 2014-03-03 40.00000
## 3 2014-03-10 33.57143
## 4 2014-03-17 44.00000

Labels will be off, though. If using cut, consider the implications of its include.lowest and right parameters, documented at ?cut.

A: aggregate(df2$values,by=list(week(df2$time)),mean)

  Group.1        x
1       8 30.00000
2       9 40.00000
3      10 36.42857
4      11 37.85714
5      12 43.33333

This uses the week function of lubridate and gives the week number of the week in the year.
To control which day of the week is the starting day just refer to this thread on that topic:
Changing lubridate function to start on Monday rather than Sunday
The solution from that thread by nograpes suggests that if you want a custom version of the week() function using an arbitrary day of the week as the beginning of the week that you just construct it from base R like this:

start.of.week <- function(date)
  date - (setNames(c(6,0:5),0:6) [strftime(date,'%w')])

end.of.week <- function(date)
  date + (setNames(c(0,6:1),0:6) [strftime(date,'%w')])

start.of.week(as.Date(c('2014-01-05','2014-10-02','2014-09-22','2014-09-27')))
# "2013-12-30" "2014-09-29" "2014-09-22" "2014-09-22"
end.of.week(as.Date(c('2014-01-05','2014-10-02','2014-09-22','2014-09-27')))
# "2014-01-05" "2014-10-05" "2014-09-28" "2014-09-28"

In the future lubridate will have this option for an arbitrary start day for weeks, but Hadley hasn't got around to adding it yet (https://github.com/hadley/lubridate/issues/257).

A: why not straight up use floor_date and an integer to adjust the start date of the week?
library(lubridate)
time <- seq(from =ymd("2014-02-24"),to= ymd("2014-03-20"), by="days")

set.seed(123)

values <- sample(seq(from = 20, to = 50, by = 5), size = length(time), replace = TRUE)
df2 <- data_frame(time, values)
df2 <- df2 %>% mutate(day_of_week = weekdays(time))

# week wednesday to tuesday
df2 %>% group_by(Week = floor_date(time-3, unit="week")) %>%
  summarize(WeeklyAveDist=mean(values), mean(values), min_date = min(time), max_date = max(time)) %>% mutate(weekdays(min_date), weekdays(max_date)))

        Week WeeklyAveDist mean.values.   min_date   max_date
1 2014-02-16      37.50000     37.50000 2014-02-24 2014-02-25
2 2014-02-23      38.57143     38.57143 2014-02-26 2014-03-04
3 2014-03-02      38.57143     38.57143 2014-03-05 2014-03-11
4 2014-03-09      36.42857     36.42857 2014-03-12 2014-03-18
5 2014-03-16      45.00000     45.00000 2014-03-19 2014-03-20
  weekdays.min_date. weekdays.max_date.
1             Monday            Tuesday
2          Wednesday            Tuesday
3          Wednesday            Tuesday
4          Wednesday            Tuesday
5          Wednesday           Thursday

# Week Thursday to Wednesday
df2 %>% group_by(Week = floor_date(time-4, unit="week")) %>%
  summarize(WeeklyAveDist=mean(values), mean(values), min_date = min(time), max_date = max(time)) %>% mutate(weekdays(min_date), weekdays(max_date)))

        Week WeeklyAveDist mean.values.   min_date   max_date
1 2014-02-16      35.00000     35.00000 2014-02-24 2014-02-26
2 2014-02-23      39.28571     39.28571 2014-02-27 2014-03-05
3 2014-03-02      37.14286     37.14286 2014-03-06 2014-03-12
4 2014-03-09      40.00000     40.00000 2014-03-13 2014-03-19
5 2014-03-16      40.00000     40.00000 2014-03-20 2014-03-20
  weekdays.min_date. weekdays.max_date.
1             Monday          Wednesday
2           Thursday          Wednesday
3           Thursday          Wednesday
4           Thursday          Wednesday
5           Thursday           Thursday

A: Just this once, after some research, I actually think I came up with a better solution that

*

*gives the correct aggregation

*gives the correct labels

Example below for weeks starting on a thursday. The weeks will be labeled by their first day a given cycle.
library(tidyverse)
library(lubridate)
options(tibble.print_min = 30)

time <- seq(from =ymd("2014-02-24"),to= ymd("2014-03-20"), by="days")
set.seed(123)
values <- sample(seq(from = 20, to = 50, by = 5), size = length(time), replace = TRUE)
df2 <- data_frame(time, values)

df2 <- df2 %>% mutate(day_of_week_label = wday(time, label = TRUE),
                      day_of_week = wday(time, label = FALSE))

df2 <- df2 %>% mutate(thursday_cycle = time - ((as.integer(day_of_week) - 5) %% 7),
                      tmp_1 = (as.integer(day_of_week) - 5),
                      tmp_2 = ((as.integer(day_of_week) - 5) %% 7))

which gives
> df2
# A tibble: 25 × 7
         time values day_of_week_label day_of_week thursday_cycle tmp_1 tmp_2
       <date>  <dbl>             <ord>       <dbl>         <date> <dbl> <dbl>
1  2014-02-24     30               Mon           2     2014-02-20    -3     4
2  2014-02-25     45              Tues           3     2014-02-20    -2     5
3  2014-02-26     30               Wed           4     2014-02-20    -1     6
4  2014-02-27     50             Thurs           5     2014-02-27     0     0
5  2014-02-28     50               Fri           6     2014-02-27     1     1
6  2014-03-01     20               Sat           7     2014-02-27     2     2
7  2014-03-02     35               Sun           1     2014-02-27    -4     3
8  2014-03-03     50               Mon           2     2014-02-27    -3     4
9  2014-03-04     35              Tues           3     2014-02-27    -2     5
10 2014-03-05     35               Wed           4     2014-02-27    -1     6
11 2014-03-06     50             Thurs           5     2014-03-06     0     0
12 2014-03-07     35               Fri           6     2014-03-06     1     1
13 2014-03-08     40               Sat           7     2014-03-06     2     2
14 2014-03-09     40               Sun           1     2014-03-06    -4     3
15 2014-03-10     20               Mon           2     2014-03-06    -3     4
16 2014-03-11     50              Tues           3     2014-03-06    -2     5
17 2014-03-12     25               Wed           4     2014-03-06    -1     6
18 2014-03-13     20             Thurs           5     2014-03-13     0     0
19 2014-03-14     30               Fri           6     2014-03-13     1     1
20 2014-03-15     50               Sat           7     2014-03-13     2     2
21 2014-03-16     50               Sun           1     2014-03-13    -4     3
22 2014-03-17     40               Mon           2     2014-03-13    -3     4
23 2014-03-18     40              Tues           3     2014-03-13    -2     5
24 2014-03-19     50               Wed           4     2014-03-13    -1     6
25 2014-03-20     40             Thurs           5     2014-03-20     0     0


text:
Q: How to add links to sidebar in Sphinx I would like to add links to the sidebar of my pages in Sphinx. How do I go about doing this. I have around 4 pages and I want them to be accessible from each others pages without using the search feature.
Similar to this:
https://pythonhosted.org/an_example_pypi_project/sphinx.html#table-of-contents
with the previous and next topic.


text:
Q: Shifting problem with mapfish? I'm using OpenLayers 2.13 with GeoExt and mapfish print module for GeoServer.
I've a map composed of a WMS layer and a vector layer. On my web browser everything is fine but when I print this map into a PDF file with mapfish print, layers are shifted and I can't figure out why. Any ideas?
How the map is rendered by OpenLayers/GeoExt

How the map is rendered in PDF file generated by Mapfish print

Part of my code :
Map creation part:
map = new OpenLayers.Map("map", options);
var layer_dpt = new OpenLayers.Layer.WMS("dpt", "linkToGeoserver",
    {
        layers:'base_layer'
    },
    {
        singleTile: 'true'
    }
);
map.addLayer(layer_dpt);
layer_comm = new OpenLayers.Layer.Vector( 'communes',{
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: 'GeoServer WFS URL',
format: new OpenLayers.Format.GeoJSON()
})
});
map.addLayer(layer_comm);

Printing part:
var printProvider = new GeoExt.data.PrintProvider({
    method: "POST", // "POST" recommended for production use
    capabilities: printCapabilities // from the info.json script in the html
});
printProvider.setDpi(printProvider.dpis.getAt(2));
// Our print page. Tells the PrintProvider about the scale and center of
// our page.
printPage = new GeoExt.data.PrintPage({
    printProvider: printProvider,
    customParams: {
        mapTitle: "",
        comment: ""
    }
});
mapPanel = new GeoExt.MapPanel({
    region: "center",
    map: map,
    center: [map.getCenter().lon, map.getCenter().lat],
    zoom: map.zoom
});
new Ext.Panel({
    renderTo: "map",
    layout: "border",
    width: 1200,
    height: 950,
    items: [mapPanel],
    bbar: ["->", {
        text: "Print",
        id: "imprimer",
        handler: function() {
            // convenient way to fit the print page to the visible map area
            var opt = {"mode":"closest"};
            printPage.fit(mapPanel, opt);
            // print the page, optionally including the legend
            printProvider.print(mapPanel, printPage, false);
        }
    }]
});


text:
Q: Generating jquery 'rules' from business model to UI in asp.net mvc I've had a good look around and am certain that there's no matching question on SO, so here goes.
Has anyone created a 'helper' method on their model that generates jquery (or plain javascript) rules validation dynamically, based on the criteria/rules that are contained within the object and taken from a repository (i.e. DB).
What i'm thinking of is a discrete set of partial views (and associated models) that have rules at the business logic 'level' and rather than (or in combination with) validating the rule(s) at postback, translating the same rules into tightly focussed jquery methods that work identically at client (js) and server (c#) levels. I can see benefits here re performance. Also, the rules definitions could be created in a single place (in c#) and  the jquery generated off of that, thus allowing single edits to update both code streams.
I appreciate that there would be limitations imposed by language specific constraints but the general principle could be quite interesting if used appropriately. I'm also aware that testibility could be an issue when using two different language structures and hoping to achieve similar test outcomes - but those aside...
any thoughts or experiences of similar out there?
edit - this article goes some way towards what I was thinking of:
https://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/
and also:
https://devermind.wordpress.com/2009/06/21/asp-net-mvc-tip-3-how-to-cover-all-your-client-side-form-validation-needs-without-writing-any-javascript-part1/

A: It depends on what you mean by "rules".  If you mean basic validation, that already exists with the DataAnnotations attributes.
These attributes, when applied properly, can combine with Html.ValidateMessageFor helper methods to automatically validate input before the form is posted back.

A: Codebetter.com has a good tutorial with a MVC validation solution that builds the jQuery validation
http://codebetter.com/blogs/karlseguin/archive/2009/04/26/validation-part-1-getting-started.aspx

A: Have a look at this article, ASP.NET MVC 2 Custom Validation, by Phil Haack. In it he describes how to add client side validation for custom validation attributes.
HTHs,
Charles


text:
Q: Defining windows to find multiple slopes I need to define several windows for an experimental plot for which slopes can be found. For example, x runs from 0 to 400. I want to find the derivative of each 50x (i.e. 0 to 50, 50 to 100 & so on), and then average all derivatives (8 derivatives in this example). Thanks for any helps!

A: Assuming you have a vector y of measurements and want to compute the derivative by taking the difference between entry 1 and 50, 51 and 100, and so on, you could do the following:
% generate a signal
x=1:400;
y = x.^2;
nSamples = length(y);

% define number of segments and window size
N = 8;
Winsize = ceil(nSamples/N);

% preallocate the vector of slopes and compute the slopes
slopes = zeros(1,N);
for ii=1:N
    slopes(ii) = (y(min(nSamples,Winsize*ii))-y(1+Winsize*(ii-1)))/(x(min(nSamples,Winsize*ii))-x(1+Winsize*(ii-1)));
end

% take the average slope value
Averageslope = mean(slopes);

However, since you are using matlab anyway you could also just take the average derivative of the vector, which should yield a much more accurate average when dealing with noisy data:
% generate a signal
x=1:400;
y = x.^2;
slope = mean(diff(y)/diff(x));


text:
Q: Minimize a borderless form by Win + M windows shortcut The standard Win + M keyboard shortcut minimizes open windows, but it does not minimize a borderless form.
I'm thinking of capturing key events of Win + M in KeyDown event but no luck, since it does not capture both but only captures the first key.
I can't programmatically minimize it using a keyboard shortcut
Any idea on how to minimize my for form by keyboard shortcut? or can I capture Win + M to trigger minimize function?
I'm using borderless form. To reproduce the problem, create a Form and set its BorderStyle to None and run the application. When you press Win + M, all the windows minimize, but my borderless form stays normal.

A: As an option you can enable system menu (having minimize window style) for your borderless form, then while it doesn't show the control box, but the minimize command will work as expected.
Add the following piece of code to your Form and then Win + M will work as expected:
private const int WS_SYSMENU = 0x80000;
private const int WS_MINIMIZEBOX = 0x20000;
protected override CreateParams CreateParams
{
    get
    {
        CreateParams p = base.CreateParams;
        p.Style = WS_SYSMENU | WS_MINIMIZEBOX;
        return p;
    }
}

A: As a totally different option you can register a low level keyboard hook using SetWindowsHookEx and check if you received the Win + M, then minimize the window and let the key goes through other windows.
Add the following piece of code to your Form and then Win + M will work as expected:
private const int WH_KEYBOARD_LL = 13;
[StructLayout(LayoutKind.Sequential)]
private struct KBDLLHOOKSTRUCT
{
    public Keys vkCode;
    public int scanCode;
    public int flags;
    public int time;
    public IntPtr dwExtraInfo;
}
private delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(
    int idHook, HookProc lpfn, IntPtr hmod, uint dwThreadId);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(
    IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern short GetKeyState(int keyCode);
private const int KEY_PRESSED = 0x8000;
private static bool IsKeyDown(Keys key)
{
    return Convert.ToBoolean(GetKeyState((int)key) & KEY_PRESSED);
}

private IntPtr ptrHook;
private HookProc hookProc;
private IntPtr CaptureKeys(int code, IntPtr wParam, IntPtr lParam)
{
    if (code >= 0)
    {
        KBDLLHOOKSTRUCT objKeyInfo =
            (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(
                lParam, typeof(KBDLLHOOKSTRUCT));
        if (objKeyInfo.vkCode == (Keys.M) &&
            (IsKeyDown(Keys.LWin) || IsKeyDown(Keys.RWin)))
        {
            this.WindowState = FormWindowState.Minimized;
            return (IntPtr)0;
        }
    }
    return CallNextHookEx(ptrHook, code, wParam, lParam);
}
bool HasAltModifier(int flags)
{
    return (flags & 0x20) == 0x20;
}
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    var module = Process.GetCurrentProcess().MainModule;
    hookProc = new HookProc(CaptureKeys);
    ptrHook = SetWindowsHookEx(
        WH_KEYBOARD_LL, hookProc, GetModuleHandle(module.ModuleName), 0);
}


text:
Q: Как отсортировать данные для обучения нейросети Я начал изучать нейросети на python3 и пытаюсь написать простую нейронку для распознавание цифр. Данные для обучения скачал с THE MNIST DATABASE.
Доставать случайную цифру я могу так:
from mnist import MNIST
import random

mndata = MNIST('samples')
images, labels = mndata.load_training()

index = random.randrange(0, len(images))
print(mndata.display(images[index]))

Но так я получаю случайную цифру. Можно ли как-то получать конкретную цифру?


text:
Q: Dynamic requires with webpack and Angular My goal is to have dynamic require without having all the dependencies at the same level bundled, since I may have 50 brands at some point.
My structure would be this one:
-src/app
-theming
--default
--brand_1

Here is an example Angular component:
import { Component } from '@angular/core';

const brand = 'brand_1';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [`../../theming/${brand}/style.scss`]
})
export class AppComponent {
  title = 'app';
}

Problem is require creates a map with all the siblings folders and get their content.
`webpack:///C:/Users/JeanB/work_projects/playground/angular-advanced-branding/theming ^\.\/.*\/style\.scss$`
…
var map = {
  "./brand_1/style.scss": "../../../../../theming/brand_1/style.scss",
  "./default/style.scss": "../../../../../theming/default/style.scss"
};

As you can see, my variable is interpreted as a wildcard, as expected from the webpack documentation.
Would you know how to prevent this from happening?
I see two way out, one is to go with systemJS, which supports dynamic require better.
The other one is more experimental, with the context option for require in webpack.
Any help is appreciated!
-- Update
After a day of research, I came to the fact that Angular does not support interpolated urlStyles values.
Webpack is doing what it should with what webpack gives to it, which is require('blabla' + variable + '.scss').
SystemJs does not have the same behavior, but it's out of scope for now. I'll update the ticket when I have a solution.


text:
Q: ionic 3 QR Scanner is not working for PWA I want to use a QR Code Scanner in my ionic PWA which is deployed in ionic native app and calling via inappbrowser inside ionic native app.
While Using QR Scanner Plugin i'm getting below error.

A: Some ionic native plugins don't support browser platform, so you need to check the plugins that you are using if it supports browser platform. Looking on the qr scanner plugin documentation, they indicated that they are supporting browser platform.
You can try to run the code below so you need to specify which platform to run.
ionic cordova run browser

if the plugin doesn't work, try checking for other plugins that supports browser platform or search for an HTML5 version, for example the plugin below:

https://github.com/code-kotis/qr-code-scanner