Creating api tokens for third parties

Question: I'm working on an application where third parties are interested in integrating with us. I would like to create a token for each user and was wondering what is the most efficient and common way in django? I tried to find one, and found this which looks promising:
https://github.com/jpulgarin/django-tokenapi
Obviously out of the box it wont work, but I can implement it similarly. The above project basically uses the sha hashing algorithm. Is it safe to use this or  MD5 for api tokens? Any help is appreciated!
Answer: When you're choosing API keys, the two factors you're looking for are

Infeasable to guess. This mean that your key must appear random and that it is too long to brute force
Is Unique. Means that no two users can accidentally get the same API key. you can enforce this with database uniqueness constraints.

Remember, If you're only using 1 key, you MUST enable SSL on all of your api endpoints. Having keys stolen in transit is bad, M'kay?
Now, for implementation, if you're using your own custom views to serve your API, then https://github.com/jpulgarin/django-tokenapi should work well for you.
If, however you're using TasyPie or similar, you may want to use their built-in authorization code, including api-key management.
http://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html#apikeyauthentication
http://django-rest-framework.org/api-guide/authentication.html#tokenauthentication
Answer: I've always used the API key provided with TastyPie http://django-tastypie.readthedocs.org/en/latest/authentication.html#apikeyauthentication.
From models.py:
<code>    def generate_key(self):
        # Get a random UUID.
        new_uuid = uuid.uuid4()
        # Hmac that beast.
        return hmac.new(str(new_uuid), digestmod=sha1).hexdigest()
</code>

Creating api tokens for third parties


Ionic 3 sqlite export and import database

Question: I have created an app with ionic 3. I have used sqlite for database. I want to export database to a folder (outside of my app) and want to see all my back up database file in a list. Then I will choose any backup file and import to my database with file chooser.
Please help me.
Thanks in advance.
Answer: You can simply create a text file and store JSON encoded data inside it and later decode the data to store it back in the database.
Use Ionic Native File plugin for reading, creating and writing a file: https://ionicframework.com/docs/native/file/

Create an empty directory in external storage.
For taking a backup, Create a new text file and write your database table schema and rows in JSON format.
To list previous backups, request native file plugin to return all files inside your previously created folder.
To import a backup, first export current instance of database( Just for saving latest data). Then you can decode the JSON data inside your backup file and make insert queries for each row.
Comment: Thanks for your nice explanation.
Comment: I did it perfectly. Thanks again
Comment: Great. Please mark it as an answer so that other's can also follow


No water after reopening main water valve

Question: I closed the main water valve for simple repairs. After reopening it there's barely any water doesn't even register in the meter. The valve doesn't feel broken but I can't think of what could be wrong.
The solution:
Our main shutoff valve is a small gate valve. We had the city show up and shutoff the water to the house while the plumber replaced the main valve. Apparently it was a bad valve since everything is in working order now.
Comment: What type of valve is it (eg, globe, ball)? What did you repair -- or more specifically, do any taps between your repair and the main valve work?
Comment: Where is this thing located?
We have looked every where and cant find anything like a valve. We are now at day #3 with no water. Its a holiday weekend and im at my wits end.
Comment: Find where the water enters your house.  Typically in cold climates with basements, it will come through the basement wall;  main valve, meter, house valve.
In warmer areas, this may be on the outside of the house.  Find your water meter.  There will be valves around it.
Answer: I'm going to assume it's a typical gate valve, and also since you said main water valve I'll assume it's the main shutoff just before the meter.
With these assumptions in mind, I'm going to say you will have to call your local municipality. The water company does not allow (or like) home owners to tamper with anything near (and defiantly not before) the water meter.
In fact, in lots of areas the municipality actually owns the pipe (and any fixtures) before the water meter. So this is not likely a DIY job.
When you call to have them come fix the valve, ask them to replace the broken gate valve with a ball valve.
If I have assumed incorrectly and the valve is on your side of the water meter, you can try to repair it yourself (see this question for how to do it) or you could just replace the broken valve.
If you are going to fix the valve yourself (it's on your side of the meter) and there is no other shut off before this valve, you will have to make a call to the municipality to have the water shut off to the building.
If you do the work yourself, you may have to get a permit and/or have your work inspected by a licensed plumber.
Comment: +1 on the ball valve. Most of the valves in houses where you have to screw them on/off are globe valves, which are cheap but wear out relatively quickly and can get clogged up. Ball valves are only a couple dollars more, but last pretty much forever, and you can easily replace the handle if it breaks (which is about the only part that typically breaks) without plumbing.
Comment: @Gregmac: I assumed it was a gate valve, because they commonly break after being closed when they have not been used for long periods of time.


How to fetch the correct url with Aurelia + .Net Core + IIS web application

Question: I have an Aurelia app running under Asp MVC Core 1.0.  The app uses HttpClient to call controller actions, which return json data.  The Home controller contains all the actions, and I configure the HttpClient like so:
http.configure(config => {
        config
          .useStandardConfiguration()
          .withBaseUrl('Home/');
});

When running the application in Visual Studio, everything works.  It's hosted on localhost:55475, and when I call this.http.fetch('GetData'), it makes a request to localhost:55475/Home/GetData.
The problem comes when I deploy to IIS.  The application is deployed as a web application under the default web site, so the root url is server.org/MyApp.  The application starts up fine, but when I make the call this.http.fetch('GetData'), it requests from server.org/Home/GetData instead of server.org/MyApp/Home/GetData, which obviously results in a 404.
Why is my fetch request ignoring MyApp?  I thought not having a leading slash on my .withBaseUrl would make the url relative, but apparently not?
Comment: Just nudging this as I get the same issue. I'm currently investigating how I might pass System.baseURL into the module so that I can pre-pend it for the call to withBaseUrl. However, I just don't get why the App is not using the directory it was loaded from as the base from which to work.
Comment: That's essentially what I did.  I put `@Html.Hidden("rootUrl", Url.Content("~"))` in my view.  I then loaded that value into a a shared module : `this.rootUrl = $('#rootUrl').val();`.  Then I appended `rootUrl` to all my api calls.  Not terribly elegant, but it works.
Answer: The solution I found was down to the URL I put into the browser address bar... in your case, does it start to work if you browse to server.org/MyApp/ rather than to server.org/MyApp (note the extra slash)? That worked for me.
So the overall fix I needed to put in place was to have a base element at the top of the page hosting Aurelia that set the base URL with a trailing slash e.g.
<base href="/MyApp/" />
Which I added using ASP.Net Core with this line in my index.cshtml file:
<base href="@this.Url.Content("~")/" />
That or you could redirect your users to the full URL using a 302 response.


Are the specific actual rules of the Rank Meter known?

Question: Regarding the Rank Meter in Ranked in Splatoon 2,

Here's the problem:

Say you have one or two cracks. In fact, sometimes when you lose a match, it does not give another crack.
Indeed sometimes when you are are on three cracks and you lose, it does not demote/pushback...you seem to get one more free chance.

(Note, I mean in normal games with no disconnects. Of course, when there's a disconnect you are not penalized.)

Moreover, when you win the amount of movement to the right seems to vary.  Sometimes a little, sometimes a lot.
It does not seem to relate to your personal performance in the game (whether number of kills, coverage, time in control etc).

Does anyone know what the actual exact rules are for
(1)  When or if you get a crack
(2)  How much it moves when you win
It genuinely seems somewhat random.
I checked the printed handbook and it has no information.
Answer: From the Splatoon Wiki

The rank meter is represented internally as a number between 0 and 100. The numbers that track filling of the rank meter and those that track cracks are two separate systems; winning matches adds points to the number system that fills the rank meter, while losing adds points to a different number system that contributes to cracks on the meter.
A full rank meter is represented by the "fill" number reaching 100, which causes the player to rank up. The rank meter breaks when the "crack" number reaches 100. Every 25 points is equivalent to one crack on the meter.
How the player gains points that affect these numbers depends on the probability of winning a match in Ranked, as determined by the game. The number of "fill" points gained for winning a match that the game determined was a likely victory for the player's team will be lower than that gained for one with a lower probability. Conversely, losing a match that the game determines the player had a high chance to win will add a high number of points to the "crack" number compared to one where the player was less likely to win.

(emphasis mine)
So what the wiki seems to be saying is that the cracks merely serve as a visual indicator for the second number, much like the progress bar. I was unable to find values, but it probably has something to do with the difference between the ranks of each team and not just random chance.
To answer your questions:
(1) You get a crack for every 25 points in the "crack" number
(2) It moves an amount determined by how likely you were to win the game.
Comment: Ahh !   The secret seems to be *"depends on the probability of winning a match in Ranked, as determined by the game"*.   Ah hah!
Comment: sent a bounty..


Reference request for a notation stating absolute error

Question: My Question: Let $\Delta(a_n)$ be defined by $$(a_n)\in \Delta(a_n)\iff \forall n\in\mathbb N: |\epsilon_n| \le |a_n|$$
I guess it is very likely that this notation is already used in mathematical literature. Can you provide a reference for it, please?
Reason for my question: The big O notation $O(a_n)$ has two equivalent definitions (for strictly positive sequences $(a_n)$):

$(\epsilon_n) \in O(a_n) \iff \exists C_\forall > 0\,\forall n\in \mathbb N: |\epsilon_n| \le C_\forall |a_n|$
$(\epsilon_n) \in O(a_n) \iff \exists C_\infty > 0\,\forall n\in \mathbb N: \limsup_{n\to\infty} \frac{|\epsilon_n|}{|a_n|} \le C_\infty$

Thus one can state the convergence speed with the big O notation but not an estimate for the error (because $C_\forall$ and $C_\infty$ are not known). To state $C_\infty$ I want to use the big Psi notation. For $C_\forall$ I want to use $\Delta(\cdot)$ because $$(\epsilon_n)\in\Delta(C_\forall a_n) \iff \forall n\in\mathbb N: |\epsilon_n| \le C_\forall |a_n|$$ Now I am interested wether this notation is already used.
Comment: Those are not equivalent, since $a_n$ could be $0$ for infinitely many $n.$
Comment: I forgot to state that $(a_n)$ shall be a strictly positive sequence... I added it. Thanks!
Answer: Something like this is in common use in real analysis, where for two functions $f,g$ we have
$$
f \leq g \iff f(x) \leq g(x) \text{ for all } x,
$$
and it is common to see things like $|f| \leq |g|$ to mean that $|f(x)| \leq |g(x)|$ for all $x$.
This extends naturally to sequences:
$$
|\epsilon| \leq |a| \iff |\epsilon_n| \leq |a_n| \text{ for all } n.
$$
Answer: Donald Knuth refers to it in "Teach Calculus with Big O" as the A notation:

I would begin my ideal calculus course by introducing a simpler "A notation", which means "absolutely at most". For example, A(2) stands for a quantity whose absolute value is less than or equal to 2.

Source: Donald Knuth (June–July 1998). "Teach Calculus with Big O". Notices of the American Mathematical Society 45 (6): page 687.


Have Jenkins Fail Fast When Node Is Offline

Question: I have a MultiJob Project (made with the Jenkins Multijob plugin), with a series of MultiJob Phases. Let's say one of these jobs is called SubJob01. The jobs that are built are each configured with the "Restrict where this project can be run" option to be tied to one node. SubJob01 is tied to Slave01.
I would like it if these jobs would fail fast when the node is offline, instead of saying "(pending—slave01 is offline)". Specifically, I want there to be a record of the build attempt in SubJob01, with the build being marked as failed. This way, I can configure my MultiJob project to handle the situation as I'd like, instead of using the Jenkins build timeout plugin to abort the whole thing.
Does anyone know of a way to fail-fast a build if all nodes are offline? I could intersperse the MultiJob project with system Groovy scripts to check whether the desired nodes are offline, but that seems like it'd be reinventing, in the wrong place, what should already be a feature.
Comment: I don't know of existing functionality that will do this, but could you just add a shell executable step that tries to telnet to the Slave's port (22)?
Answer: I ended up creating this solution which has worked well. The first build step of SubJob01 is an Execute system Groovy script, and this is the script:
<code>import java.util.regex.Matcher
import java.util.regex.Pattern

int exitcode = 0
println("Looking for Offline Slaves:");
for (slave in hudson.model.Hudson.instance.slaves) {
 if (slave.getComputer().isOffline().toString() == "true"){
 println('  * Slave ' + slave.name + " is offline!");
   if (slave.name == "Slave01") {
     println('    !!!! This is Slave01 !!!!');
     exitcode++;
   } // if slave.name
  } // if slave offline
} // for slave in slaves

println("\n\n");
println "Slave01 is offline: " + hudson.model.Hudson.instance.getNode("Slave01").getComputer().isOffline().toString();
println("\n\n");

if (exitcode > 0){
 println("The Slave01 slave is offline - we can not possibly continue....");
 println("Please contact IT to resolve the slave down issue before retrying the build.");
 return 1;
} // if

println("\n\n");
</code>
Answer: The jenkins pipeline statement 'beforeAgent true' can be used in evaluating the when condition previous to entering the agent.
<code>    stage('Windows') {
      when {
        beforeAgent true
        expression { return ("${TARGET_NODES}".contains("windows")) }
      }
      agent { label 'win10' }
      steps {
        cleanWs()
        ...
      }
</code>
Ref:

https://www.jenkins.io/doc/book/pipeline/syntax/
https://www.jenkins.io/blog/2018/04/09/whats-in-declarative/


SDL bmp image background

Question: As you can see below there is bmp image but its background color is white:

How can i change it to be for example black (without editing the bmp image itself)?
Here I have code to show bmp image on window:
#include <iostream>
#include "SDL.h"

using namespace std;

int main(int argc, char *args[])
{
    SDL_Window *window = nullptr;
    SDL_Renderer *renderer = nullptr;
    SDL_Surface *surface = nullptr;
    SDL_Texture *texture = nullptr;
    SDL_Event event;

    SDL_Rect positionRect;
    SDL_Rect dimensionRect;

    positionRect.x = 0;
    positionRect.y = 0;
    positionRect.w = 100;
    positionRect.h = 100;

    dimensionRect.x = 0;
    dimensionRect.y = 0;
    dimensionRect.w = 300;
    dimensionRect.h = 300;

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
        return 1;
    }

    if (SDL_CreateWindowAndRenderer(500, 500, SDL_WINDOW_OPENGL, &window, &renderer)) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
        return 1;
    }

    surface = SDL_LoadBMP("sample.bmp");
    if (!surface) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create surface from image: %s", SDL_GetError());
        return 1;
    }

    texture = SDL_CreateTextureFromSurface(renderer, surface);
    if (!texture) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture from surface: %s", SDL_GetError());
        return 1;
    }

    SDL_FreeSurface(surface);
    surface = nullptr;

    while (1) {
        SDL_PollEvent(&event);
        if (event.type == SDL_QUIT) {
            break;
        }
        //SDL_SetRenderDrawColor(renderer, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
        SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, texture, &positionRect, &dimensionRect);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyTexture(texture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}

Comment: You could set a color key, sdl will make this color transparent: http://lazyfoo.net/SDL_tutorials/lesson05/index.php
Comment: I guess, changing the image is actually the most simple way to achieve this. But if it is really necessary to do it in your appl. then, please, have a look into **[`SDL_Surface`](https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlsurface.html)**. You could access the `pixels` data and replace white pixels by black pixels. AFAIK, there is no background color in a BMP. Every pixel has any color. "Background" color does only exist in your perceptance...
Comment: This isn't totally trivial. You _can_ modify the `SDL_Surface` returned by `SDL_LoadBmp`, but I don't think you can naively convert white to black (look at the colour of the figure's eyes). You coudl write a flood fill function, but modifying the image is probably easiest. You may also find that simply dropping it onto a black background results in it not looking as good; it was drawn with a deliberate dark border, after all!
Comment: @Lanting You can put that as an answer.
Answer: You should add these 2 lines,
Uint32 colorkey = SDL_MapRGB(surface->format, 255, 255, 255);
SDL_SetColorKey(surface, SDL_TRUE, colorkey);

before this line in your code
texture = SDL_CreateTextureFromSurface(renderer, surface);

SDL bmp image background


How do I display print_r on different lines?

Question: When I run the following code:

echo $_POST['zipcode'];

print_r($lookup->query($_POST['zipcode']));

?>

the results are concatenated on one line like so: 10952Array.
How can I get it to display on separate lines, like so:
08701
Array

Answer: You might need to add a linebreak:
echo $_POST['zipcode'] . '
';

If you wish to add breaks between print_r() statements:
print_r($latitude);
echo '
';
print_r($longitude);

Comment: And when it's two print_r statements how do I add the linebreak?
    print_r($latitude);
    print_r($longitude);
Comment: You can add an extra echo '' in between the print_r() statements. See edit.
Answer: to break line with print_r:
echo "
";
    print_r($lookup->query($_POST['zipcode']));
echo "
";

The  element will format it with any pre-existing formatting, so \n will turn into a new line, returned lines (when you press return/enter) will also turn into new lines.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
Comment: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre is a really useful read.
Answer: If this is what your browser displays:
Array ( [locus] => MK611812 [version] => MK611812.1 [id] => 1588040742 )

And this is what you want:
Array
(
    [locus] => MK611812
    [version] => MK611812.1
    [id] => 1588040742
)

the easy solution is to add the the
 format to your code that prints the array:
echo "
";
print_r($final);
echo "
";

Answer: Old question, but I generally include the following function with all of my PHP:
The problem occurs because line breaks are not normally shown in HTML output. The trick is to wrap the output inside a pre element:
function printr($data) {
    echo sprintf('
%s
',print_r($data,true));
}

print_r(…, true) returns the output without (yet) displaying it. From here it is inserted into the string using the printf function.
Comment: Lovely solution. Thank you.
Comment: Here I contribute with some classic black and green console styling. Enclose the `` tag with `` tag, and add the following rule to your CSS: `pre { padding: 1em; background-color: #000000; color: #08FF08; }`
Answer: Just echo these : echo $_POST['zipcode']."
";


How to see the values of elements of a structure in Visual Studio 2008 during debugging?

Question: For example,
structure S{
int a;
int *b;
}s;

//now when I try to check the values stored...
s->a = ?
s->b[0] = ?
s->b[1] = ?

.. and so on
How do I "add watch" or use any other technique to check the values? Please let me know. Thanks.
Comment: What is the question? You don't know how to show the Watch window, or you don't know how to edit things in the Watch window?
Answer: It sounds like you have a value of type S* that you want to inspect in the debugger.  The easiest way to do this is simply type the expression which produces the value into the watch window.  So for example if you have a local named pValue simply

Open the Watch Window
Type 'pValue' into one of the rows
Expand to see the contents

The tricky part is seeing all of the values in S::b as it will be displayed as a single pointer vs. an array.  In order to see the value as an array you just need to tell the debugger how many elements there are.  For example if there were 5 elements you could type the following into the watch window
pValue->b,5

Expanding that will show you the first 5 int values in pValue->b


Let's get critical: Sep 2014 Site Self-Evaluation

Question: We all love Linguistics Stack Exchange, but there is a whole world of people out there who need answers to their questions and don't even know that this site exists. When they arrive from Google, what will their first impression be? Let's try to look at this site through the eyes of someone who's never seen it before, and see how we stack up against the rest of the 'Net.
The Site Self-Evaluation review queue is open and populated with 10 questions that were asked and answered in the last quarter.
Run a few Google searches to see how easy they are to find and compare the answers we have with the information available on other sites.
Rating the questions is only a part of the puzzle, though. Do you see a pattern of questions that should have been closed but are not? Questions or answers that could use an edit? Anything that's going really well? Post an answer below to share your thoughts and discuss these questions and the site's health with your fellow users!
Comment: Definitely lots of open questions that should've been closed. This is very common here - votes expire before they get enough.
Comment: I wouldn't be so sure we all love it, @Community♦. I view it as an impediment, for the most part. Though not as much so as English Language & Usage SE. The fact that fewer than 10 users out of [How Many?](http://meta.linguistics.stackexchange.com/users) bothered to answer that questionnaire might perhaps give a clue.
Answer: Final Results

What is the difference between assertive and non-assertive words?

Net Score: 4 (Excellent: 5, Satisfactory: 1, Needs Improvement: 1)

Georgian minimal pairs with p' t' k'

Net Score: 4 (Excellent: 4, Satisfactory: 2, Needs Improvement: 0)

Possible methods of input for languages with a lot of diacritic characters

Net Score: 3 (Excellent: 3, Satisfactory: 4, Needs Improvement: 0)

Why is it possible to identify a language without hearing the words?

Net Score: 2 (Excellent: 2, Satisfactory: 4, Needs Improvement: 0)

Any difference between natural and programming languages?

Net Score: 1 (Excellent: 2, Satisfactory: 1, Needs Improvement: 1)

Why are these Sanskrit words in the nominative case

Net Score: 0 (Excellent: 1, Satisfactory: 4, Needs Improvement: 1)

A multilingual home, a pro or a con?

Net Score: -1 (Excellent: 2, Satisfactory: 1, Needs Improvement: 3)

Is Language infinite?

Net Score: -1 (Excellent: 2, Satisfactory: 0, Needs Improvement: 3)

How can I detect Formants programatically

Net Score: -1 (Excellent: 1, Satisfactory: 3, Needs Improvement: 2)

Where on the Internet can I find sound files so that I can hear the alveo-palatal consonants?

Net Score: -1 (Excellent: 0, Satisfactory: 4, Needs Improvement: 1)


Maximum time a docker containers can be used without respinning?

Question: I have this distributed Jenkins controller/agent configuration that runs java test cases.
Once the vapp is up with controller and 3 agent configuration, the vapp is used for more than 2 months to run the test cases.
At a time nearly 500 testcases are ran which takes 1 hr to complete the execution and there are n number of vapps like this and depending on availability vapp is picked to execute the test cases .
After using this vapp for more than a month, I see the linux kernel is actually killing the master container due to Out of Memory and this is not common to all the vapps but only in a few vapps.
All the cache and memory managements are done and eventhough the containers are getting killed.
My question is like is it recommended to use the vapp for more than a month continuously?
I asked to respin the vapps which means respin the containers after a month.
What is the best possible solution to this?
Answer: It seems some of your containerized applications suffer from memory leaks. Operationally your behaviour looks good already: The container gets killed and restarted if it hits configured memory limits. You could also limit the lifetime of the container as you are questioning anyway, and the real answer is in the amount of resources you are willing to spend. Would it hurt to spin up a new container for every one hour test?
If this is not good enough, you'd probably have to investigate with the developer of the application to find and remove the memory leak.


Using classes instead of anonymous type in join C# WPF Linq

Question: I need to change from using an anonymous type in my JOIN statement to using classes instead. My coding:
using (DataClassesDataContext DC = new DataClassesDataContext())
{
   var Join = (from a in DC.tblEmployeeLoginDetails
               join b in DC.tblProjects
               on a.LoginID equals b.ProjectID
               join c in DC.tblClientLoginDetails
               on b.ProjectID equals c.ClientLoginID
               where c.ClientLoginID != null
               select new
               {
                  b.ProjectID,
                  b.ProjectName,
                  b.ProjectStatus,
                  a.EmployeeName,
                  a.EmployeeSurname,
                  c.ClientName,
                }).ToList();

    dgViewProjects.ItemsSource = Join;
}

My classes: PIDData & EIDData
PIDData:
public struct PDData
{
    public string _project;

    public int ProjectID { get; set; }
    public string Name { get; set; }
    public string Status { get; set; }
    public string Employee { get; set; }
}

EIDData:
    public string _sts;

    public int UserID { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public string Role { get; set; }
    public string Department { get; set; }
    public string IDNumber { get; set; }
    public string Gender { get; set; }
    public DateTime Date { get; set; }
    public string HomeAddress { get; set; }
    public string Telephone { get; set; }
    public string City { get; set; }
    public string Province { get; set; }
    public Binary SetImage { get; set; }
}

Now I am very new to c# and coding in general, so this gets a little tricky and frustrating for me. I do not know how to use my classes instead of the anonymous type in my join statement.
Using the classes will help me to more easily manage my data from a datagrid in my program. Please share any advice or let me know if there is any more information that I can give to help in answering the question, thank you!
EDIT:
Here is what the JOIN is looking like right now:
        using (DataClassesDataContext DC = new DataClassesDataContext())
        {
           List<Match> Join = (from a in DC.tblEmployeeLoginDetails
                        join b in DC.tblProjects
                        on a.LoginID equals b.ProjectID
                        join c in DC.tblClientLoginDetails
                        on b.ProjectID equals c.ClientLoginID
                        where c.ClientLoginID != null
                        select new Match
                        {
                            ProjectIDM = b.ProjectID,
                            ProjectNameM = b.ProjectName,
                            ProjectStatusM = b.ProjectStatus,

                            EmployeeNameM = a.EmployeeName,
                            EmployeeSurnameM = a.EmployeeSurname,

                            ClientNameM = c.ClientName,
                        }).ToList();

           dgViewProjects.ItemsSource = Join;
        }

Nautious, I also created the class that you suggested.
I am not getting any errors...which is very good, but there isn't data displaying in my datagridview anymore. I think it might be because of this:

dgViewProjects.ItemsSource = Join;
Comment: Woups. My Bad.. The Fields in the Match Class needs to be properties. See edit of answer
Comment: Thank you very much Nautious for your time and effort, that fixed the problem!
Answer: if you want to use  a struct witch is not a part of DataClassesDataContext you could use anonymous types, but then you can convert it to you own type
var Join = (from a in DC.tblEmployeeLoginDetails
           join b in DC.tblProjects
           on a.LoginID equals b.ProjectID
           join c in DC.tblClientLoginDetails
           on b.ProjectID equals c.ClientLoginID
           where c.ClientLoginID != null
           select new
                    {
                        ProjectID = b.ProjectID,
                         ProjectName = b.ProjectName,
                        ProjectStatus = b.ProjectStatus,

                        EmployeeName = a.EmployeeName,
                        EmployeeSurname = a.EmployeeSurname,

                        ClientName = c.ClientName,
                    }).ToList().Select(x => new PIDData
                   {
         ProjectID = b.ProjectID,
         Name = b.ProjectName,
          Status = b.ProjectStatus,
                   }).ToList() ;

Answer: First you make a class/struct that matches the data you wish to return:
public class Match
{
    public int ProjectID { get; set; }
    public string ProjectName { get; set; }
    public object ProjectStatus { get; set; }
    public string EmployeeName { get; set; }
    public string EmployeeSurname { get; set; }
    public string ClientName { get; set; }
}

Then you create and fill instances in your select new:
select new Match
{
    ProjectID = b.ProjectID,
    ProjectName = b.ProjectName,
    ProjectStatus = b.ProjectStatus,

    EmployeeName = a.EmployeeName,
    EmployeeSurname = a.EmployeeSurname,

    ClientName = c.ClientName,
}).ToList();

now, your variable Join will be of type List<Match>
Comment: Thank you for you comment! Please view the EDIT on my question. :D I need to know how I can then bind the items to my datagrid, because there is no information displaying there anymore.


How to immediately stop processing new messages when inside a message handler?

Question: I have a Rebus bus setup with a single worker and max parallelism of 1 that processes messages "sequentialy".  In case an handler fails, or for specific business reason, I'd like the bus instance to immediately stop processing messages.
I tried using the Rebus.Event package to detect the exception in the AfterMessageHandled handler and set the number of workers to 0, but it seems other messages are processed before it can actually succeed in stoping the single worker instance.
Where in the event processing pipeline could I do
bus.Advanced.Workers.SetNumberOfWorkers(0); in order to prevent further message processing?
I also tried setting the number of workers to 0 inside a catch block in the handler itself, but it doesn't seem like the right place to do it since SetNumberOfWorkers(0) waits for handlers to complete before returning and the caller is the handler...  Looks like a some kind of a deadlock to me.
Thank you
Comment: Have you also set SetMaxParallelism(1) ? "Rebus will default to 1 worker thread and a max parallelism of 5."
https://github.com/rebus-org/Rebus/wiki/Workers-and-parallelism
Comment: Good point.  Yes I did set the max parallelism to 1.  Thanks
Answer: This particular situation is a little bit of a dilemma, because – as you've correctly observed – SetNumberOfWorkers is a blocking function, which will wait until the desired number of threads has been reached.
In your case, since you're setting it to zero, it means your message handler needs to finish before the number of threads has reached zero... and then:  ☠
I'm sorry to say this, because I bet your desire to do this is because you're in a pickle somehow – but generally, I must say that wanting to process messages sequentually and in order with message queues is begging for trouble, because there are so many things that can lead to messages being reordered.
But, I think you can solve your problem by installing a transport decorator, which will bypass the real transport when toggled. If the decorator then returns null from the Receive method, it will trigger Rebus' built-in back-off strategy and start chilling (i.e. it will increase the waiting time between polling the transport).
Check this out – first, let's create a simple, thread-safe toggle:
public class MessageHandlingToggle
{
    public volatile bool ProcessMessages = true;
}

(which you'll probably want to wrap up and make pretty somehow, but this should do for now)
and then we'll register it as a singleton in the container (assuming Microsoft DI here):
services.AddSingleton(new MessageHandlingToggle());

We'll use the ProcessMessages flag to signal whether message processing should be enabled.
Now, when you configure Rebus, you decorate the transport and give the decorator access to the toggle instance in the container:
services.AddRebus((configure, provider) =>
    configure
        .Transport(t => {
            t.Use(...);

            // install transport decorator here
            t.Decorate(c => {
                var transport = c.Get<ITransport>();
                var toggle = provider.GetRequiredService<MessageHandlingToggle>();
                return new MessageHandlingToggleTransportDecorator(transport, toggle);
            })
        })
        .(...)
);

So, now you'll just need to build the decorator:
public class MessageHandlingToggleTransportDecorator : ITransport
{
    static readonly Task<TransportMessage> NoMessage = Task.FromResult<TransportMessage>(null);

    readonly ITransport _transport;
    readonly MessageHandlingToggle _toggle;

    public MessageHandlingToggleTransportDecorator(ITransport transport, MessageHandlingToggle toggle)
    {
        _transport = transport;
        _toggle = toggle;
    }

    public string Address => _transport.Address;

    public void CreateQueue(string address) => _transport.CreateQueue(address);

    public Task Send(string destinationAddress, TransportMessage message, ITransactionContext context)
        => _transport.Send(destinationAddress, message, context);

    public Task<TransportMessage> Receive(ITransactionContext context, CancellationToken cancellationToken)
        => _toggle.ProcessMessages
            ? _transport.Receive(context, cancellationToken)
            : NoMessage;
}

As you can see, it'll just return null when ProcessMessages == false. Only thing left is to decide when to resume processing messages again, pull MessageHandlingToggle from the container somehow (probably by having it injected), and then flick the bool back to true.
I hope can work for you, or at least give you some inspiration on how you can solve your problem.
Comment: Thanks for taking the time.  I no I am not in an ideal situation ;-)  I will proceed with some testing and see it this helps!
Comment: `NoMessage` cannot be set null in this case. I'm encountering error when I try to do this.
Comment: @KrunalJethva Absolutely correct. But please note that `NoMessage` is not NULL, it's `Task.FromResult(null)`, which is a `Task` object with state == Completed and the result NULL - that's a different thing
Comment: Yes you're are right, i was confused because of compilation error while declaring it


Which Wiki System supports searching by criteria?

Question: My Question is best explained using an example:
Please visit this site: https://en.wikipedia.org/wiki/Arch_linux
Say I wanted to set up a wiki with similar sites where you could search by the criteria seen on the right.
For example: There is a search inteface on that wiki with a drop-down menu called license and one called OS Family, and you would make your choice and it would then deliver all OS Sites matching your search.
I hope my question can be understood.
Which wiki software supports that? Mybe with a plugin?
Answer: You could do this with Semantic MediaWiki and SemanticFormsSelect.


Integral (Fourier transform) of Heaviside radial function in 3D

Question: I am trying to calculate the following integral:
$ \int \frac{d k_x d k_y d k_z}{(2 \pi)^3} \left[ \exp( - \frac{(k_x^2 + k_y^2 + k_z^2) \sigma^2}{2}) + \frac{1}{2} H(\sqrt{k_x^2 + k_y^2 + k_z^2} - k_0) \right] \exp{(- \text{i} (k_x, k_y, k_z) \cdot (x , y ,z))}$
where $H$ stands for the Heaviside function and $k_0$ and $\sigma$ are known constants.
While I am quite sure about the first half (it becomes another Gaussian), I don't know how to deal with the second part, the one with the Heaviside function. How can I deal with that?
Comment: Do you see how to get the answer from this: http://math.stackexchange.com/questions/489391/fourier-transform-of-the-indicator-of-the-unit-ball
Comment: I was trying to get the answer from that one, but I can't
Answer: So what you do is to realize that you can replace $(k_x,k_y,k_z)\cdot(x,y,z)$ by $\kappa r \cos(\theta)$, where $\kappa = \sqrt{k_x^2 + k_y^2 + k_z^2}$ and $r = \sqrt{x^2+y^2+z^2}$ and $\theta$ is the angle between $(k_x,k_y,k_z)$ and $(x,y,z)$.  Also, you have that the Fourier transform of the constant function is the Dirac delta function, so we can consider $1 - H(\sqrt{k_x^2 + k_y^2 + k_z^2} - k_0) = H(k_0 - \sqrt{k_x^2 + k_y^2 + k_z^2})$ instead.  Then using spherical coordinates as shown in the first picture on this website https://en.wikipedia.org/wiki/Spherical_coordinate_system, making $(k_x,k_y,k_z)$ parallel to the $z$-axis in this same picture, and replace $r$ with $\kappa$:
$$ \int \frac{d k_x d k_y d k_z}{(2 \pi)^3} H(k_0 - \sqrt{k_x^2 + k_y^2 + k_z^2}) \exp{(- \text{i} (k_x, k_y, k_z) \cdot (x , y ,z))} $$
is equal to
$$ \int_{\theta=0}^{\pi}\int_{\kappa=0}^\infty \int_{\varphi=0}^{2\pi} \frac{\kappa^2 \sin\theta \, d\kappa \, d\theta \, d\varphi}{(2\pi)^3} H(k_0-\kappa) e^{-i\kappa r \cos\theta} $$
which equals
$$ \int_{\kappa=0}^{k_0} \int_{\theta=0}^{\pi} \frac{2 \pi \kappa^2 \sin\theta \, d\kappa \, d\theta}{(2\pi)^3} e^{-i\kappa r \cos\theta} $$
Being lazy, we plug this into Wolfram Alpha: http://www.wolframalpha.com/input/?i=Integrate%5B2+Pi+k%5E2+Sin%5Bt%5D+Exp%5B-I+k+r+Cos%5Bt%5D%5D%2F%282+Pi%29%5E3%2C+%7Bk%2C+0%2C+k0%7D%2C+%7Bt%2C+0%2C+Pi%7D%5D
to get
$$ \frac{  \sin (k_0 r
   ) - k_0 r \cos (k_0 r )}{2 \pi ^2 r ^3} .$$
Comment: I follow your reasoning, the only thing I don't understand how you can get as a result a function of $\kappa$ and not $r$...maybe just a typo?
Comment: Yes, it was a typo.  Fixed it.


JavaScript Regex: When input field onChange event fires, format fields

Question: I am using react 16.8.2 new hooks API. -Just for info-
My problem only involves JS.
I have two input fields. They take only numbers as inputs. If the user enters /\D+/ (non-digits), the field is set to ''(empty). If he enters 2.3393, the number should always be rounded to two decimal places 2.34
Field1: onChange formats the number to $ 32,233,233,322.24
Field2: onChange formats the number to 99%. Decimals places are simply truncated.
The Input field should be able to handle e.nativeEvent.inputType deleteContentBackward as well. Such that if the user is at $ 2 and deletes 2, Field1 becomes empty. Similarly for Field2. 1% on deleting % becomes empty.
So far I have this:
const handleInputChange = function (e) {
     const val = e.target.value;
     const formatValue = function () {
        if (/.*\d?\.\d*/.test(val)) return val.replace(/(?<=\d?\.\d*)\..*/g, '');
        return +val.replace(/\$\s?|(,+)|%/g, '');
      };

      if (formatValue()) {
        if (fieldSuffix === 'Percentage') {
          if (e.nativeEvent.inputType === 'deleteContentBackward') return setVal(`${formatValue()}%`.replace(/^\d%$|\d(?=%)/, ''));
          return setVal(`${formatValue()}%`);
        }
        if (fieldSuffix === 'Dollars') return setVal(`$ ${formatValue()}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','));
        return setVal(formatValue());
      }
      return setVal('');
 };

return (
    <input
        value={val}
        onChange={handleInputChange}
    />
)

It does not work well for when user enters single .. $ are prepend for every . keystroke. The case that when user enters /\D+/ is not handled. % Field2 decimal place truncation case is also not handled. I can think of other cases also that are not handled.
My code is getting complicated. This approach is not elegant. Please Help.
Answer: The following code works well.
const handleInputChange = function (e) {
      const formatValue = function () {
        // Remove non-digit, except '.' and remove everything beginning from second decimal '.'
        return e.target.value.replace(/[^0-9.]|(?<=^[^.]*\.[^.]*)\..*/g, '');
      };

      if (formatValue()) {
        if (fieldSuffix === 'Percentage') {
          // Percentage decimal truncated
          const truncatedPercentage = formatValue().replace(/\..*/, '');
          if (e.nativeEvent.inputType === 'deleteContentBackward') return setVal(`${formatValue()}%`.replace(/^\d%$|(\d|\.)(?=%)/, ''));
          return setVal(`${truncatedPercentage}%`);
        }
        if (fieldSuffix === 'Dollars') {
          // Truncated to two decimal places, not rounded
          const truncatedDollar = formatValue().replace(/(?<=\.\d{2}).*/, '');
          // Format and insert ','
          return setVal(`$ ${truncatedDollar}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','));
        }
      }
      return setVal('');
};

I still feel that there is a lot of redundancy and unhandled cases in this code


How to download multiple torrent links using transmission-daemon?

Question: I am using transmission-daemon on my server with the WEB GUI.
I was wondering if instead of each time clicking add torrent then paste the magnet link, I could instead call it in the terminal (SSH) with a command with a file (like for example with wget) then it will download the torrents which links are in the file.
Comment: To download torrents or magnet links from the CLI worth mentioning [`ariac`](https://aria2.github.io/)
Answer: This will do the job.
For .torrent files:
First, you need to upload the .torrent files to a directory on your server. Then, please follow the steps below:

Open a terminal and make sure you cd to the directory containing the .torrent files.
To add a single .torrent file to transmission-daemon, please run the following command in the terminal:

transmission-remote -n 'transmission:transmission' -a torrent_file_name.torrent

To add all .torrent files in the directory to transmission-daemon, please run the following command in the terminal:

find . -maxdepth 1 -type f -name '*.torrent' -exec transmission-remote -n 'transmission:transmission' -a {} \;

For magnet URLs:

Create a file and name it magnet.links and add the magnet URLs one per line to the file. Please avoid crating any blank lines. Add the first link in the first line and then press Enter then add the second link in the second line and so on. Do not press Enter after the last line, just save the file and exit.
Open a terminal and cd to the directory that contains the magnet.links file.
Copy and paste the following code in the terminal and press Enter:

file="magnet.links"
while IFS= read -r line
do
transmission-remote -n 'transmission:transmission' -a $line
done <"$file"

Comment: How was this not accepted?  Great answer
Comment: Great answer! Been struggling to add multiple torrents via ssh on a dedicated server.


Solution to quadratically constrained binary integer program

Question: I'm trying to solve a problem for $x$ which is a vector of length $n$ with only binary elements, i.e. each $x_{i}$ is either $0$ or $1$.
There are two constraints on $x$, one quadratic and one linear:
$$
x^{T}Ax + b^{T}x = 0 \\
Ex = d$$
All of $A$, $b$, $E$, and $d$ have integer elements. $A$ is relatively sparse and not invertible, not PSD. $E$ is also sparse and has only $1$'s on some of the diagonal elements. $d$'s values are either $0$ or $1$.
I am looking for any solution satisfying the constraints, not necessarily all solutions. And, at least one solution is guaranteed to exist based on how the constraints are formulated (this is a bit out of scope but there will be a solution).
The catch is, the problem size can be very large, on the order of $n = 10^{3}$ to $n = 10^{5}$. Any suggestions for solving this problem? I have many tools at my disposal, MATLAB, cplex, numpy, scipy, etc.
Answer: You can linearize the quadratic constraint and use an integer linear programming solver.  See https://or.stackexchange.com/questions/37/how-to-linearize-the-product-of-two-binary-variables


Mounting /cow on root failed: Invalid argument overlay mount failed

Question: I am using an xps 13 9365, which was data wiped from bios by a friend who then gave it to me thinking it was dead. I tried booting with a USB (current LTS distro (18.04 or similar)) boot disk and got into the language selection / setup menu. By using the F6 option I selected noapic. In bios sata is set to raid and legacy the secure boot option is off.
But when I try to install I get kicked into a tiny font window with the following message
(initramfs) mount: Mounting /cow on root failed: Invalid argument overlay mount failed
Any ideas?
Comment: If you created the USB boot drive with Rufus and selected persistence, you will get such an error with Ubuntu 18.04 LTS. It should work if you make a new attempt, this time without selecting persistence. Please let us know if this was the problem, or if it is another problem.
Comment: First comment from @sudodus worked for me, installing elementary OS 5 from USB on huawei matebook x pro, from windows 10. I used rufus "with persistence" initially, selecting "no persistence" fixed this issue
Comment: You can also try the different settings for SATA in the BIOS, maybe AHCI is available and will work better.
Answer: Received this error in Ubuntu [Elementary OS] using Rufus 3.8 when selecting persistence. The solution was to create a live USB without persistence, per comment above.
Comment: If you still want a persistent live drive, you can try according to this link: [Persistent live drive with a partition for persistence](https://askubuntu.com/questions/1181854/how-is-it-easier-to-make-a-persistent-live-drive-with-ubuntu-19-10)
Comment: I can confirm this. While trying to try Ubuntu 18.04.4 LTS via a Live USB drive on an HP ProBook 6470b, I ran into `initramfs mount: mounting /cow on /root failed invalid argument overlay mount failed` at the boot-up of Ubuntu.  This was because I selected persistent storage (8 GB) while flashing Ubuntu using Rufus 3.9.1624.  **Reflashing without persistent storage ("0 size") solved this problem.**  The machine now boots into Ubuntu 18.04.04 LTS.  Now I'm trying to figure out how to get WiFi working but that's a different story ...


Maximum Principle for Poisson Equation

Question: For a smooth $u(x)$, $x \in \mathbb{R}^n$, satisfying:
$\Delta u = -f$ for $||x||<1$ ,    $u=g$ on $||x||=1$
I want to show that there exists a constant $C$ such that:
$$\max\{|u|:||x||\leq 1\} \leq C(\max\{|g|:||x||=1\}+\max\{|f|:||x||<1\}).$$
Comment: Do you have conditions on $f$ and $g$?
Comment: There are no conditions on f and g.  C>0 depends only on n
Comment: Can this work for an exterior domain? Like same equation, but domain is $|x|>1$.
Answer: Well, implicitly, $A = \|f\|_\infty$ and $B = \|g\|_\infty$ must exist.
Thus, let us consider
$$u_+(x) = B + A (1-|x|^2)$$
It is a simple matter to check that $\Delta(u_+ - u) \leq 0$ where $|x| < 1$ and that $u_+ - u \geq 0$ on $|x|=1$. The maximum principle tells you the rest.
You can analogously construct
$$u_-(x) = -B - A (1-|x|^2)$$
Using these as super and subsolutions for your problem, you can see that
$$|u(x)| \leq A + B$$
where $|x| \leq 1$.
Comment: Could you please explain your steps in the first few lines?
Comment: (+1) your answer is more clear and direct than mine.
Comment: @rmh52: which step is confusing? -R
Comment: The expression for u+.  Im not sure how you decided to do that
Comment: Oh. The idea is, I picked $B$ for the boundary term, and for the $A$ term I wanted a function that had 0 on the boundary, and a very negative laplacian so I could invoke the maximum principle on the difference with $u$. Since $\Delta (|x|^2) = 2n$, I basically took the standard quadratic of the right sign as a function with the right properties.
Comment: I see... I'm not familiar with the notation you've used but I assume the infinity norm is the maximum of abs value?  How do I take the laplacian of u+ to verify that the difference is non-positive?
Comment: Yeah, the infinity norm is the essential supremum of a function (in this case, for $f$, on $|x| \leq 1$, and for $g$, on $|x|=1$). The reason I picked these functions is that you can explicitly calculate the laplacian:
$\Delta u_+ = \Delta B + \Delta A(1-|x|^2) = -2An$ since $A$ and $B$ are just constants.
Comment: Got it.  Thank you for your help.
Answer: If $u$ is a smooth function, then also $f$ and $g$ are smooth. Defined the Newtonian Potential $v$ of $f$ by $$v(x)=\int_B \Gamma(x-y)f(y)dy$$
where $B$ is the unit open ball about the origin and $\Gamma$ is the fundamental sollution of the Laplace equation. Consider the solution of the auxiliary problem $$
 \left\{ \begin{array}{rl}
 -\Delta w=0 &\mbox{ in $B$} \\
  w=v-g &\mbox{ in $\partial B$}
       \end{array} \right.
$$
By unicity we conclude that $u=v-w$. Also, from the maximum principle, we have that $$\|w\|_{L^\infty(\overline{B})}\leq \|v\|_{L^\infty(B)}+\|g\|_{L^\infty(\partial B)}$$
From here, you have two things to do:
1 - Show that there exist a constan $C_1$, such that $\|v\|_{L^\infty(B)}\leq C_1\|f\|_{L^\infty(B)}$
2 - Use the representation of $u$ in terms of $v$ and $w$ to conclude.

Maximum Principle for Poisson Equation


CakePHP extending model

Question: I am using cakePHP to develop small webpage and trying to graps MVC concept.
I have controller, in which action I am retrieving post with specified ID.
$post = $this->Post->findById($id);

I need to retrieve post title, concatenated with it's id - but I don't wanna do it in controller directly.
Of course I could write underneath $post['id'].','.$post['title'], because $post is an array.
But this will be needed in many places. Can I extend model somehow to achieve method to do it?
My approach was:
class Post extends AppModel {
    public function getTitleWithId() {
        return $this->id.','.$this->title;
    }
}

But as I saw model object is not exactly last fetched object.
Maybe I just need to create PostEntity object that accepts in constructor an array returned by findById? But maybe there is better solution.
Comment: You should update your question with your actual intentions, stuff like that you want to slugify the title before concatenation is important and should be in your question! ps. please always mention your exact CakePHP version and tag your question accordingly!
Answer: Your approach is right: let all the data managing be in the model.
Although, take a look to Virtual Fields. It will do your concatenating easier:
http://book.cakephp.org/2.0/en/models/virtual-fields.html
Then you can do a find to your virtual field:
$this->Post->find('first', array(
    'conditions' => array(
        'id' => $id
    ),
    'fields' => array('yourVirtualField')
));

EDIT
Now that I've read again your question, probably you would need to do a behavior:
http://book.cakephp.org/2.0/en/models/behaviors.html
Think of that as a way to have multiple inheritance (not the same, but somewhat the idea goes along). You develop your method on it, and attach this behavior to only the models you need with:
public $actsAs = array('yourBehavior');

Comment: In that case yes, but what I didn't mention is that I would kill two birds with one stone. I will also need perform some operations on data. More specific example is that I want "slugify" title before concatenation :) Nevertheless thanks for insight on virtual fields, in case of concatenation and other pure SQL operations it will make life easier.
Comment: Please see my edit. Seems that I didn't read carefully your question, lol
Comment: you can't pass virtual field in `fields` array, check the docs http://book.cakephp.org/2.0/en/models/virtual-fields.html#limitations-of-virtualfields
Comment: Actually maybe I wrote it not very clear way. I didn't mean that I will need that method in other Models, but rather in different methods in controller :) But still that exact method might be reusable! Thanks.
Comment: @Anilkumar Actually you can, you'll only run into problems in case you are referencing the virtual fields of an _associated_ model.
Comment: I misunderstood the line, thanks for the info @ndm :)
Comment: @Eagle I'd say they are more like mixins or pseudo multiple inheritance, but definitely not interfaces ;)
Comment: @ndm well, now that you say it, it's more like multiple inheritance than interface :P I'll fix it.
Answer: In CakePHP, Model class are manager, not really instance of a Model (even if the id is stored in). You could simply pass the id to your method and return what you want:
class Post extends AppModel {
    public $name = 'Post' ;
    public function getTitleWithId($id) {
        $post = $this->read(null, $id) ;
        return $post[$this->name]['id'].','.$post[$this->name]['title'];
    }
}

Comment: I tried that approach too. So using that approach if I would really like some fancy object I could create factory method for that object in my model. If no one will come up with anything different I will mark your answer as solution.

CakePHP extending model


what's the ratio of area of triangle AEB to the area of quadrilateral AGIB?

Question:
in the figure below , $ABC$ is a right triangle in $C$  , $AI$ , $BG$ are bisectors of of angles $A$ and $B$ respectively,  what's the ratio of  area of triangle $AEB$ to the area of  quadrilateral $AGIB$ ?

I need a hint to go , can you help me ?
Thank you
Comment: Specifically for the given coordinates (I assume that $A=(9,0)$) or in the general case?
Comment: @Hagen von Eitzen  general case , i Will edit the figure
Answer: $E$ is the centre of the incircle, whose radius is $r$.
Then the area of $AEB$ is $$\frac 12cr.$$
It is well-known that  $r=\frac{ab}{a+b+c}$.
As bisectors partition in the proportion of the adjacent sides, we have $CG:GA=a:c$ and $CI:IB=b:c$, hence the area of $CGI$ is
$$ \frac12 \frac{ab}{b+c}\frac{ba}{a+c}.$$
The desired proportion is therefore
$$ \frac{AEB}{AGIB}=\frac{\frac12\frac{abc}{a+b+c}}{\frac12ab-\frac12\frac{(ab)^2}{(a+c)(b+c)}}=\frac{ab+ac+bc+c^2}{a^2+2ab+2ac+b^2+2bc+c^2}=\frac12.$$
Comment: I know it's standard, but a small note at the beginning saying that $a = BC, b = AC$ and $c = AB$ would probably improve readability. It took me a couple of seconds to figure out what the $c$ in $\frac12cr$ was.


Docker windows with hyper-v example baffles me??? Why does the alpine example not work they way I thought it would?

Question: I am hoping an expert on Docker who uses Windows gets to read this as I really do not understand this at all.
I installed Docker on my Windows 10 machine, no vmware just hyper-v, all works great until I tried to create volumes from my local machine and use them within my Linux containers, this is when my problems start.
Within docker is an example to try to see how the volumes work:

I created a directory within my Users directory and a simple file just to see something within the alpine container.

But when I run the following command I get no files within the steve/work directory?

Where on earth is afile.txt???
Sorry if I am being a bit stupid but I have created volumes on Linux machines without any problems and I just dont get where on earth my files are? How can I dev on a Windows machine and get my source code into my containers without needing to perform Dockerfile copies of all my source files into the container??
Just for further confusion (probably on my part!) but when I execute the same command and look into just the steve folder I can see the work folder as expected but I also see a folder called work#? So the work folder is there (even if I delete it???)

I am just really really confused about how to create volumes on a Windows machine using Hyper-V.
Many thanks in advance.
P.S If you have any links which actually explain differences between the Windows Hyper-V Docker and Linux Docker I would also be very very grateful as I cant find any or documents which mix information regarding Windows with just Hyper-V and VMWare.
Thanks again...
Answer: SOLVED!
After hours and hours of research and messing around with Windows Docker I have volumes sharing correctly between my Windows host machine and a Linux container. Which means I can see files within my container which exist on my local Windows machine.
My research got me to this link THE ANSWER AND TONS OF GREAT INFO ON THIS PROBLEM
The answer which works and makes total sense is by a guy called 'dennisfischer', although the forum entry is long its well worth reading to get the background of the problem and to get a handle on what is going on between Windows fs and the container.
Anyway hopefully this may save you a hell of a lot of time!
P.S Cheers to Philip who was really helpful, thanks for the messages and hopefully this will be of some use to you at some point.
Comment: Glad to hear it helped you! It took me about two full days to find that but at least that's is a working answer now!
Answer: I just went through the same exercise with a new copy of Windows 10 Enterprise running in a VMWare Fusion vm.
The first thing you must do is to open the docker settings app, available from your app tray (or whatever it's called in Windows). Then select Sharing and share the drives you want to explore with. When you click Apply, you will be prompted with a username password dialog. Enter that and an example shown there will actually work. I setup test.user and then was able to do:
run -it --rm -v C:/Users:/data alpine ls /data
One more caveat though. I was logged into with a domain login through a business account via Office 365. my domainname\username did not work. Instead I had to create a local windows user and supply that. This will cause some extra headaches with permissions no doubt, but seems to be the only option at the moment. It is possible that had I been connected in my workplace this may have worked, but since I work at home and will be speaking at a conference next week, no joy for me!
Comment: Cheers Philip can I just ask, I got what I thought was working with the alpine image but I only got my user folder showing (steve) but the files which are definitely in they're just don't show? Anyway I have moved forward with volumes instead which appear to work as i expect. But I still cannot run a Linux image and see folder with files from my Windows file system?
Comment: I saw something similar. No errors with the volume argument, but also no files showing. I had to do the sharing setup first, and supply credentials and then it worked. If I then tried to map a folder that local user I supplied did not have access to, I actually got a useful error. Had you already done the sharing setup?
Comment: Well I know this sounds a bit nooby but I think so? I used the docker task panel app by the time and set sharing at drive level C & D on my machine, and yes I was asked for credentials which must be correct (I say that based on if they are correct I get no acknowledgement but if I enter rubbish docker does actually reject and ask for the credentials again!) but I have never seen any files within a Linux container which are - v'ed from the local machine with the run command?
Comment: Just out of interest Philip but can you run up a docker container of say busybox and use the '- v local:cont mount' and see your windows files from within the running busybox Linux container?
Comment: If the credentials are incorrect then it prompts again and again. If you go back in and those drives are still checked, you should be fine. Here is the command I used to try out your busybox question ```docker run -it --rm -v C:/:/data busybox ls /data``` It did work as expected. I choose C:\ because there is unlikely to be permission issues there.  You could also do ```docker run -it --rm -v C:/:/data busybox /bin/sh``` and poke around yourself.
Comment: PS, as an example, I was able with busybox and that /bin/sh arg to use the "linux" commands to list ProgramData/Git under the C:/ I had mapped.
Comment: Ok philip firstly thanks for all your time, very much appreciated and great to communicate with someone who has this working. But I went into the docker tool app thingy by the clock bottom right and yes my drives are all showing shared and I believe they are shared and my credentials are correct. I then ran the command you used as this must work, I get the data folder but its totally empty not a single file within it. I then executed the shell to have a look myself and sure enough the data  folder is totally empty??? I have no idea why my docker just does not map files from windows into Linux?
Comment: Just out of interest you are using hyper-v and not vmware?
Comment: hyper-v yes. Just curious. If you don't remove the image, say ```docker run -it  --name bb -v C:/:/data busybox ls /data ``` so the container is still there, what do you see in the Mounts section of  ```docker inspect bb```. Mine shows this ```"Mounts": [
            {
                "Source": "/C",
                "Destination": "/data",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            } ```
Comment: "Mounts": [
    {
        "Source": "/C",
        "Destination": "/data",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],
Comment: "Mounts": [
    {
        "Source": "/C",
        "Destination": "/data",
        "Mode": "",
        "RW": true,
        "Propagation": "rprivate"
    }
],
Comment: yep! I'm out of ideas, sorry!
Comment: Thanks Philip much appreciated!


Spark 1.0.1 and HDP 2 - How to connect via ODBC?

Question: I'm trying to connect with the Simba ODBC Shark Connector to my instance of Spark 1.0.1. When Shark was a standalone project, I was able to connect to it without any problem. Right now I'm having an hard time with this new Spark release because I suppose that Shark has been integrated inside Spark but I have no idea how to talk to it, especially because I don't know on which port it is listening to.
Actually I only managed to connect successfully to Hive(that is listening on port 10000
) with the HortonWorks ODBC connector.
Does anyone could give me an hand?
Answer: For the while, only the SAP version of Spark 1.0.1 includes the ThriftServer that you need to use Thrift/JDBC/ODBC.
http://www.saphana.com/docs/DOC-4721
The next dot release of Spark--1.1--will incorporate the ThriftServer.
https://issues.apache.org/jira/browse/SPARK-2410
George
Comment: Spark 1.1 should be released really soon; according to our current [release window](https://cwiki.apache.org/confluence/display/SPARK/Wiki+Homepage), release candidates will be released and voting will start on on August 15.  The JDBC connector was actually merged yesterday (https://github.com/apache/spark/pull/1620), so you can download and build the master branch if you want to try it out now.


What is the recommended post cap or strapping for corner post under beam and rim joists?

Question: I'm trying to find the appropriate strapping to secure a beam to a post, while providing a means to attach a double rim-joist. Consider the drawings below:

In both of these drawings if I use a post cap to attach the beam to the post, the metal of the cap interferes with the joist hangers I would use on the rim joists. In the left-hand drawing I can attach half of the rim joist directly to the front of the beam while sitting it on the post, since the beam only needs 3.5" of support. But how would I attach the second half of the rim joist so that it is 'hanging' from the beam?
What is the correct method for securing the beam to the post, while allowing for the rim joist to be secured to the beam?
I need to hang the joists off the beam - I cannot set them on top. I am hoping to not have to set-back the beam; I want it centred under the corner as shown.
Answer: If you are butting a rim joist into the beam, you can frame like the first photo with the beam held back 1-1/2" and the first rim joist extending to the end of the post.
Then, in the corner of the second (inner) rim joist and the beam, attach some Simpson A35's.  1 should do, but if you have enough height you could install 2.  Each A35 can transfer nearly 600lb of gravity load into the beam.  If this truly is a rim joist, then 1,200lb of (2) A35's + the shear on the first rim should be more than enough.
Then use (6+) 3-1/2" quality construction screws (vs cheap deck screws) end screwed through the outer rim into the end of the beam to tie the rim and the beam together.
I would not recommend a Simpson ECC style column cap; these are only needed in extreme (for DIYers) load cases.
Comment: This was my original thought but how to tie post and beam together? The A35 would interfere with whatever I strap the beam with.
Comment: Would a single L bracket like this (http://www.strongtie.com/products/connectors/HL_APG.asp) work for the post/beam connection? Then the interior face of the beam is free for the joist
Comment: Yes, that would work, put one on the beam and one on the rim.  You could also use the A35s in those locations as well if you use them in tandem. If this is exterior or supporting a roof you could add an LSTA9 strap from beam to post for uplift as well.  You could also in-liue-of or in-addition-to the aforementioned ideas,  toe screw up through the post  into the beam/rim and recess the heads; maybe a couple per side or 6-8 total;  The longer the better but 4" +/- screws would probably be sufficient.
Comment: Is this for a deck?  If there is sheathing, you could also use it to tie things together.
Comment: It's for a loft in my studio - there's storage underneath and not sheathed, unfortunately.
Comment: @Steven  Well, no uplift then.  Just lateral and gravity.
Answer: Looks like a job for the (pricey) Simpson's Strong Tie ECCL

More info here:  http://www.strongtie.com/products/connectors/eccl-ccc-cct.asp
Comment: On reviewing the documentation further, there might be a combination that works for me. I'll contact the nearest simpson vendor to confirm. Still - that price!
Comment: I looked at that and the depth of the beam required is too great. Any other options? It would be perfect with the right lumber.


How do I and Can I switch between windows 7 and Ubuntu 12.04 at random?

Question:
Possible Duplicate:
Switch between Ubuntu and Windows 7

How do I and Can I switch between windows 7 and Ubuntu 12.04 at random?   I have downloaded Ubuntu and WUBI.  I am very new at this and just want to make sure I don't lose my windows OS setup.  can I just boot from a disc whenever I want to use Ubuntu?  I don't want to start the WUBI process and then not be able to get back to Windows when I want and vice versa.
Comment: will I be able to switch OSs at every time I reboot computer?
Answer: You cannot randomly switch between the OSs. It is completely deterministic. Every time you boot, you will be given a choice between Windows, and Ubuntu. If you do not do any thing the default OS (Ubuntu, in dual boot, probably Windows in WUBI) will boot after the timeout.
Hope this helps.


Ideal number of data points per 100 pixels for a chart

Question: If there are too many data points too close together in an image, it can look pretty choppy.

In this case, we are tracking number of data points over time; eg 500 per minute, 500 per minute, etc.
Are there any guidelines about how dense your datapoints can/should be in a chart?
Comment: Although I'm not sure exactly what data you're displaying and where it's being used, a useful way of packing high-density charts into small areas is to go with [Sparklines](http://en.wikipedia.org/wiki/Sparkline).
Comment: One thing to consider is that if the users care about _slope_, that will be most legible and comparable where the axes are scaled in an optimal way so that slopes are closest to 45 degrees as possible, I believe.  Can't seem to find the attribution for that - I think it's Tufte.
Comment: Jon W: The sparklines shown there don't have the same problem I'm having of super jagged peaks and valleys.
Answer: As ever, it depends, and really this question is unanswerable without knowing more.
It depends on what your users want to take away from the graph. Some may be concerned about the spikes (which would otherwise be lost if data points were too widespread), where as others may interested in an overview in which case something like the following may suit better - calculated as a rolling average, while yet again others may be interested in a flat-line average.

As a generalisation, compare for example the needs of technical, marketing and management. Tech might be interested in spikes; Marketing in variations at time of day; Management in the comparison between this time yesterday or last week.
So your data points depend entirely on what your users need to know. If your users have different needs then provide that via different sets of information - either different graphs or overlaying as appropriate (like in the example above), but always do as much work as is necessary for your users to see the takeaways without having to manually process the information. This may include providing actual numbers (max, min, average, total, comparison with other time period etc etc).
Remember - graphs are not there just for the sake of being there - filling a gap and looking pretty - they should serve the purpose of communicating required information easily to the user.
Comment: Youtibe (and google analytical tools in general) has a nice way of dealing with this; in data-over-time charts they usually let you pick whether each point is a day, week or month, giving you a nice range of granularity. By-month charts are very smooth but by-day charts show the peaks and valleys.


Issue in textarea for the string "&#"

Question: I have a textarea in my web page. When I type "Test&#" as a word and save its giving me an error "Internal server error occurred". this issue occurs only when I type "&#" together
Comment: @Mathew, yes, but it should be of the form `&#;`, so the lack of a number may prevent the server from parsing the entity correctly. However, maybe that's only the request validation routines that doesn't like one of the characters, I would suggest investigating with the `ValidateRequest` page attribute described [here](http://msdn.microsoft.com/en-us/library/vstudio/ydy4x04a%28v=vs.100%29.aspx).
Comment: What did your debugger tell you? (assuming you have it set to stop on all exceptions)
Comment: There is no way to answer without seeing the server-side code that fails. `&#` can start an HTML entity, so it might be the symptom of the problem, but the root cause lies in your code.
Comment: it will not come to the server side
Comment: When i searched the event log i found the following message "Message: A potentially dangerous Request.Form value was detected from the client (m$cm$xg$ctl38$ctl00="&#")."
Comment: The web server might be rejecting the request because it contains an incomplete (and unparseable) numeric HTML entity, then. *Edit: from your previous comment, that's exactly what's happening.*
Comment: @FrédéricHamidi I didn't understand unparseable its simply a string right
Comment: for me it is simply a string that contains &# in it can this be solved in any manner
Answer: This is "request validation" kicking in.  See https://stackoverflow.com/a/7615149/59641 for a workaround.
Note: please take care that you're always validating the input yourself to make sure it meets your business logic, and always encode it appropriately before displaying it in a page or otherwise transmitting it to the user.

Issue in textarea for the string "&#"


My /boot/efi is not pointing to the right ESP partition

Question: I have a computer with 2 storage devices.
I would like to have Windows on one and Linux on the other.
For a variety of reasons, I want them as separate as possible.
I'm using UEFI.
I installed Kubuntu on one device, during the setup, I specified it should be used for the bootloader installation.
But it turns out it has not been. Boot loader has been written to another device.
I've mounted the ESP partition from the other device, copied its content to the ESP partition of the device Kubuntu is installed on, rebooted, in the firmware boot manager, I chose to boot from it, it worked.
Now using mount, I see the /boot/efi is still pointing to the ESP partition on the other device.
I looked at /etc/fstab, it's got one line for /boot/efi, which indicates UUID=931B-CB7F . This UUID doesn't match any of the 2 ESP partition GUID, nor anything returned by blkid.
How can I have /boot/efi point to the ESP partition on the same device as KUbuntu is installed on?
fstab:
/dev/mapper/vg0-root /               ext4    errors=remount-ro 0       1
# /boot was on /dev/nvme1n1p1 during installation UUID=df5a10ea-a128-4c35-82f6-207493d101da /boot           ext4    defaults        0       2
# /boot/efi was on /dev/nvme0n1p2 during installation
#UUID=931B-CB7F  /boot/efi       vfat    umask=0077      0       1

/dev/mapper/vg0-home /home           ext4    defaults        0       2

/dev/mapper/vg0-swap none            swap    sw              0       0

lsblk -f | grep -v loop:
NAME                FSTYPE      FSVER    LABEL UUID                                   FSAVAIL FSUSE% MOUNTPOINTS
sda
nvme0n1
├─nvme0n1p1
└─nvme0n1p2         ntfs                       0E68C51168C4F88B                        877.3G     6% /media/xlp-admin/0E68C51168C4F88B
nvme1n1
├─nvme1n1p1         ext4        1.0            df5a10ea-a128-4c35-82f6-207493d101da      1.5G    13% /boot
├─nvme1n1p2         vfat        FAT32          423D-2695
└─nvme1n1p3         crypto_LUKS 2              1fc50d65-62f7-4513-bbf8-0002ae52b6b2
  └─nvme1n1p3_crypt LVM2_member LVM2 001       GNoW1G-nfU6-2yuG-MH2O-QGiC-0wmE-ONHQv8
    ├─vg0-swap      swap        1              6dfe2158-b779-47b6-83c3-cc2df4474ec0                  [SWAP]
    ├─vg0-root      ext4        1.0            b937a6a3-c62d-445a-9709-348a27a79b57     36.1G    21% /
    └─vg0-home      ext4        1.0            d86b3683-d330-4eaf-a278-d82c34a3685f    849.7G     0% /home

In the meantime, I have installed Windows on the other device. Windows decided to put its bootloader on the Linux device, and while at it, removed the Linux bootloader. I had made a copy before and restored it.
But in the process, Windows having failed to install on the other device ESP, I removed it hoping Windows would just create another on the same device.
That lead to Linux not booting anymore, so I commented it out in fstab.
Comment: UEFI File System partition, aka "EFI Partition".
Comment: Please add the output of `cat /etc/fstab` and `lsblk -f | grep -v loop` via [edit](https://askubuntu.com/posts/1439337/edit) to your question.
Comment: @David Sorry I just realized, it's not EFS but ESP. Fixed.
Comment: Seems you have destroyed the ESP on `nvme0n1`, only an unformatted empty partition is left. Now you have only the ESP on `nvme1n1` . You can still boot into your installation? If yes, then change the UUID in `/etc/fstab` to the one of `nvme1n1p2` in the `lsblk`-output. Then run `sudo mount -a` and `sudo grub-install` to make sure grub is installed to this partition. I cannot help you fix the Windows part. Of course, you can use GParted to make this empty partition `nvme0n1p1`  a valid ESP, but then you still had to install Windows bootloader there.
Comment: @mook765 Thanks, I think I understood what was disturbing me... the very short UUID... I guess since it's a FAT partition, this "UUID" is actually the partition "serial number" (32 bit integer stored in sector 0 of FAT partition). As far as I understand, Linux can happily boot without access to ESP partition (after all it's ESP that loads kernel, it's loaded prior to it), so yes I could still access. Now I can access, and I have my /boot/efi back. If you'd turn that into an answer, I'd validate it.
Answer: Seems you have somehow destroyed the ESP on nvme0n1 (your Windows drive),I see only an unformatted empty partition nvme0n1p1. Now you have only the ESP on nvme1n1( your linux drive) which is nvme1n1p2.
Since you can still boot into your installation, you just need to change the UUID in /etc/fstab to the one of nvme1n1p2 in the lsblk-output. Then run sudo mount -a and sudo grub-install to make sure grub is completely installed in this partition.
When a system update delivers a new version of grub, you need the partition mounted, otherwise the upgrade will fail.
I cannot help you with the Windows part. Of course, you can use GParted to make this empty partition nvme0n1p1 a valid ESP, but then you still had to install Windows bootloader there, but that's a Windows thing and out of scope here. This link might be helpful.


Moment js giving incorrect week

Question: Here's my javascript
dt = moment("2016-01-01");
console.log(dt.week());

This gives week as 1
but when I refer to bootstrap calendar then it shows week as 53 of last year

can someone tell which is correct moment or bootstrap calendar? Also why?
PS - datepicker I am using is ui.bootstrap.datepicker from https://angular-ui.github.io/bootstrap/
Comment: The correct answer is that it's week 53 (of 2015) http://www.epochconverter.com/weeks/2016
Comment: I think it is to do with the set locale and what is the 'first' day of the week. moment.locale('en');
console.log(moment.locale()); // should give en
Comment: @PaulThomasGC if week 53 is right answer then how to get correct week information from momentjs?
Answer: After a bit of google search I found that using isoWeek() gives correct week number in my case.

Moment js giving incorrect week


Why my jquery handler isn't catching my form when i submit?

Question: Im making an ruby web application, using JQuery & AJAX to send/rcv data. But when i press enter to submit this form nothing happens.
What should i do to make my form submit.
Im using Foundation, this is my modal with the form inside:

Enviar Paquete

    ×

        <form id="paquete-form"  class="paquete-form row" method="post">

            <%= token_tag(nil) %>
              <select class="columns" form="paquete-form"  name="agencia"required>
                <option value="">Agencia Destino</option>
            <% Agencia.find_each do |agencia| %>
              <option value="<%= agencia.id%>"><%= agencia.nombre%></option>
            <%end%>
          </select>
            <input class="columns" type="number" min="1" step="0.01" placeholder="Ancho en cm" name="ancho" required>
            <input class="columns" type="number" min="1" step="0.01" placeholder="Alto en cm" name="alto" required>
            <input class="columns" type="number" min="1" step="0.01" placeholder="Profundidad en cm" name="profundidad" required>
            <input class="columns" type="number" min="0.1" step="0.01" placeholder="Peso en Kg" name="peso" required>
            <input class="columns" type="number" min="1" step="0.01" placeholder="Valor en Bs" name="valor" required>
            <input class="columns" type="text" placeholder="Correo Electrónico del Emisor" name="origen" required>
            <input class="columns" type="text" placeholder="Correo Electrónico del Receptor" name="destino" required>
            <textarea class="columns" form="paquete-form" placeholder="Descripción" name="descripcion" required></textarea>
            <input class="columns" type="text" placeholder="El costo de envío es:" name="costo" disabled >

          <input class="hidden-submit-button" type="submit">
          Presione Enter para enviar

        </form>

When i finish to fill my form and press enter, the event should be handle by my script:
$(".paquete-form").on('submit', function(event) {
    alert ("digs");
    event.preventDefault();
    event.stopImmediatePropagation();
    var constante=0;
    var porcentaje=0;

    $.ajax({
        type: 'POST',
        url: '/enterprise',
        data: {
        'empresa_id': $("meta[name='empresa']").attr("content")
        },
        success: function(xhr) {
            constante=xhr.constante;
            porcentaje=xhr.porcentaje;

            var ancho;
            var alto;
            var profundidad;
            var peso;
            var valor;
            ancho= $("input[name='ancho']");
            alto= $("input[name='alto']");
            profundidad= $("input[name='profundidad']");
            valor= $("input[name='valor']");
            peso= $("input[name='peso']");
            if (ancho.val()>0 && alto.val()>0 && profundidad.val()>0 && peso.val()>0 && valor.val()>0){
                $("input[name='costo']").val((ancho.val()*alto.val()*profundidad.val()*peso.val()*valor.val()/constante)+(porcentaje*valor.val()/100));
            }

        },
        fail: function(xhr, textStatus, errorThrown) {
            console.log("error")
            $('#modal_notificacion .notification-content').html(xhr.responseJSON.err_mssg);
            $('#modal_notificacion').foundation('reveal','open');
        }
    });

    $.ajax({
        type: 'POST',
        url: '/create',
        data: {
        'agencia': $(this).find("select[name='agencia']").val(),
        'alto': $(this).find("input[name='alto']").val(),
        'ancho': $(this).find("input[name='ancho']").val() ,
        'profundidad': $(this).find("input[name='profundidad']").val(),
        'peso': $(this).find("input[name='peso']").val(),
        'valor': $(this).find("input[name='valor']").val(),
        'costo': $(this).find("input[name='costo']").val(),
        'emisor': $(this).find("input[name='origen']").val(),
        'receptor': $(this).find("input[name='destino']").val(),
        'descripcion': $(this).find("textarea[name='descripcion']").val()
        },
        success: function(server_data) {
            $('#modal_notificacion .notification-content').html(server_data["success_mssg"]);
            $('#modal_notificacion').foundation('reveal','open');
        },
        error: function(xhr, textStatus, errorThrown) {
            console.log("error")
            $('#modal_notificacion .notification-content').html(xhr.responseJSON.err_mssg);
            $('#modal_notificacion').foundation('reveal','open');
        }
    });
    $('#modal_notificacion .notification-content').html('');
    $(this).trigger("reset");
});

Comment: please add the HTML form you are using
Comment: @UnamataSanatarai ready.
Comment: I pasted the whole thing into JSFiddle, and it worked. Are you sure you have jQuery running?
Answer: As Unamata Sanatarai said, the problem wasnt because of those blocks of code, was given by another JQuery function


MySQL pivot table counting

Question: I've three tables:
users
------
user_id
name

subjects
--------
subject_id
name

pivot_user_subject
------------------
user_id
subject_id

I've this query to show subjects and usernames:
SELECT a.name User, c.name Subject
FROM users a, pivot_user_subject b, subjects c
WHERE a.user_id = b.user_id AND c.subject_id = b.subject_id;

and works great. but now I need to show how many subjects an user has.
Example output:
User      Subjects                      Subjects_count
Juan      Math, Biology, Spanish               3
Rosa      NULL                                 0
Rodrigo   Math                                 1

Any idea about how can I accomplish that output only with SQL queries? Thanks.
Comment: See GROUP _CONCAT, but personally I'd handle this kind of thing in application code
Answer: Try this
SELECT u.name, GROUP_CONCAT(s.name), COUNT(s.subject_id) as Subject_count
FROM users u
LEFT JOIN  pivot_user_subject us ON u.user_id = us.user_id
LEFT JOIN subjects s ON s.subject_id = us.subject_id
GROUP BY u.user_id, u.name

SQL Fiddle
Answer: If c.name is separated by , or it is just one subject or it is just null, you may try following;)
SELECT
    a.name AS User,
    c.name AS Subjects,
    IF(c.name IS NULL, 0, LENGTH(c.name) - LENGTH(REPLACE(c.name, ',', '')) + 1) AS Subjects_count
FROM users a, pivot_user_subject b, subjects c
WHERE a.user_id = b.user_id AND c.subject_id = b.subject_id;

MySQL pivot table counting


How to display Unicode with FLTK?

Question: According to the FLTK 1.3.2 documentation:

Unicode support was only recently added to FLTK and is still
  incomplete.

However, the following are supposedly implemented:

It is important to note that the initial implementation of Unicode and
  UTF-8 in FLTK involves three important areas:

provision of Unicode character tables and some simple related    functions
conversion of char* variables and function parameters from    single byte per character representation to UTF-8 variable length
  sequences
modifications to the display font interface to accept    general Unicode character or UCS code numbers instead of just ASCII    or
  Latin1 characters.

My question is, how do I actually display Unicode on my FLTK controls? I can't find any widget functions which accept Unicode. For example, this is the signature for the label function:
void Fl_Widget::label  (   const char *    text    )
Answer: From the link you posted:

FLTK will be entirely converted to Unicode using UTF-8 encoding. If a different encoding is required by the underlying operating system, FLTK will convert the string as needed.

The three bullet points you list are the areas that make up their implementation of Unicode support; That is, these are things they are doing or are planning to do.

FLTK implementers are going to provide Unicode character tables and some simple related functions
FLTK implementers are going to convert char* variables and function parameters from using SBCS to UTF-8. (That is, they are going to re-implement FLTK functions and variables to treat char* strings as UTF-8.)
FLTK implementers going to modify the display font interface to cover more than just ASCII and Latin1 characters.

My question is, how do I actually display Unicode on my FLTK controls? I can't find any widget functions which accept Unicode. For example, this is the signature for the label function:
void Fl_Widget::label ( const char * text )

There are many people that incorrectly use 'Unicode' to mean an encoding that uses 2-byte characters. The FLTK documentation you link to does not make this mistake. Understanding this, the documentation says quite clearly how you use Unicode with the above signature: You pass the Unicode data as a char* string using the UTF-8 encoding. For example if you're using a compiler that uses UTF-8 as the execution encoding:
widget.label("кошка 日本国");

Or if you have a C++11 compiler:
widget.label( u8"кошка 日本国");

Comment: Thank you. In light of your answer I've taken the time to [educate myself about Unicode](http://www.joelonsoftware.com/articles/Unicode.html).
Comment: Note that the last bits require the compiler to understand the encoding of the source file containing the string literal.
Comment: @rubenvb: yes, and more than that: for the next to last example the compiler *must support UTF-8 as its narrow execution character set*, and e.g. Visual C++ does not, and for the last example the compiler must support the C++11 `u8` literal prefix, and e.g. Visual C++ does not. In short those are **unportable** examples. Wide string literals are portable but they must be converted to UTF-8 at run time.
Comment: That said, using UTF-8 as a general convention for `char` based strings is pretty \*nix-specific, a bad choice for a portable GUI framework, so it's very understandable that @JBentley didn't grok it at first sight (I generally fail to understand, at first, things that don't make sense, because I *expect* one of more meaningful ways I know of, or else something entirely new to me).

How to display Unicode with FLTK?


Frigidaire Dryer with error E64

Question: My dryer is giving me an error code e64. It is an affinity Frigidaire dryer. They dryer heats up just fine. It cuts off after 10-20 minutes of running with this error. The "Dryer Tech Data Sheet" describes E64 as follows:

E64 - Heater Open Circuit - Heating Element or wiring defective -
  Check heater coils and connections for open circuits. Replace heater
  and or wiring and retest.

My theory is that the thermostat has gone bad and is stuck "open" and never cuts off the heating element. Eventually the unit gets hot enough for the high limit sensor to get tripped and the dryer throws the error. Does that sound plausible? What else might be going on here?
Comment: Did you Google, as their already seems to be websites that address this specific issue, e.g. [this one](http://therandomfix.blogspot.com/2013/07/frigidaire-affinity-e64-error.html).
Answer: Turns out it was the heating coil. I was able to test resistance with a multi-meter and saw that there was a broken circuit in one of the 3 legs of the heating coil. At first I crimped the broken end together, but later replaced the part.
Googling:

test dryer heating element multimeter

will yield good results.

Frigidaire Dryer with error E64


Regex - select but not

Question: I am new to regular expression and want to create two regexes for my .net application.
I have an input variable which stores an xml. Below is the xml
<code><Row>
......
</Row>
<Row {optional}>
....
</Row>
<Row {optional} header="true" {optional}>
</Row>
</code>
I want 2 regexes:
1. Regex which selects Rows with header="true"
2. Regex which selects Rows which do not have header="true"
Regex only have to consider opening tag. eg:
Answer: Regex is not the best option for processing xml in .NET
If your're using .NET 3.5 or higher, check out LINQ to xml
For an older version of the runtime see XmlDocument and XPath
Using LINQ your code would be something like this:
<code>    var document = XDocument.Load("path to your file"); // or XDocument.Parse if you have content in a string
    var elementsWithHeaders = document.Descendants("Row").Where(x =>
         x.Attribute("header")!=null && x.Attribute("header").Value == "true");
</code>
This code is not optimal, however to make it more efficient I would need to know more assumptions about the structure of your xml
If you are using C#6 you could also use null-conditional operator to simplify the predicate above
<code>    var elementsWithHeaders = document.Descendants("Row").Where(x =>
         x.Attribute("header")?.Value == "true");
</code>

Regex - select but not


How to fix "-5 No address associated with hostname error" while updating?

Question: I am getting this error frequently while updating Ubuntu 12.04 LTS. How can I fix it? Log is:
Ign http://archive.scrapy.org precise/main Translation-en
Fetched 6,620 kB in 1min 21s (81.2 kB/s)
W: Failed to fetch http://archive.scrapy.org/ubuntu/dists/precise/Release.gpg
Something wicked happened resolving 'archive.scrapy.org:http' (-5 - No address associated with hostname)

Comment: I recently encountered this issue on my Pi (running headless - no GUI easily available to configure it) - it turned out that I had mucked up editing the `/etc/netowrk/interfaces` file (based on [this](http://www.suntimebox.com/raspberry-pi-tutorial-course/week-3/day-5/)). So others encountering similar issue may want to check their network configuration.
Answer: This has been a long term problem with apt, and Ubuntu has never fixed it.   Apt doesn't seem to use the same DNS servers that the internal system does - 'ping ' returns a correct IP address.  Apt-get claims that the hostname isn't found.
"Something wicked happened resolving 'extras.ubuntu.com:http" (Which sounds, somewhat, like it's trying to resolve a .com:http domain, which isn't a valid TLD)
To modify /etc/hosts, use the following:
Ping each of the names that are failing to resolve -
        PING extras.ubuntu.com (22.214.171.124) 56(84) bytes of data.
Use your favourite editor, such as vi - 'sudo vi /etc/hosts'.
Scroll down to the end, and add a line such as the following
18.104.22.168 extras.ubuntu.com  (with the appropriate name and IP address. IP is first)

Save the file, then re-run apt-get.  Once you've run apt-get, edit /etc/hosts again, and comment out the line with a hash mark - #.   (or delete it entirely)
#18.104.22.168 extras.ubuntu.com

The reason to comment out/delete the line is that Ubuntu apparently shuffles their servers around randomly, and that might not be the correct IP the next time.
Answer: http://archive.scrapy.org/ seems like a perfectly working Ubuntu mirror, so while I'd usually ask you to provide information about what Software Sources are configured, it looks like this problem is either specific to your Ubuntu system, or was a short-lived problem with (or accessing) your DNS server. (The problem is not actually with the server at http://archive.scrapy.org/ itself, though it may have been due to a configuration problem for that server's DNS record.)
This is, of course, assuming that you have Internet access on the affected machine. If you don't, then you need to connect to the Internet before updating. It's quite normal to see errors like that if you don't have Internet access, or if your Internet connection itself is interrupted.
The problem may have gone away by itself. If not, you can try a different DNS server (18.104.22.168 and 220.127.116.11 are good public DNS servers operated by Google), and/or try a different mirror for updating Ubuntu.
Comment: it's a short-lived problem when I update with apt-get update the error goes away. Will try google dns server.
Answer: When I got this error, I put the IP address of the Ubuntu mirror in /etc/hosts.  No more error.  (When I queried the mirror in DNS there was never a problem or delay in response, so I'm not sure of the root cause of the error.)
Comment: I recommend expanding this to explain in detail how to edit `/etc/hosts` in the way you recommend.
Answer: That hostname resolves to an Amazon EC2 instance. It's possible there was some transient issue which is now solved as it resolves fine here. Does it now work for you?
Answer: I got the "No address associated with hostname" message with Centos 6.5 when I said yes to IPv6 and apparently the ISP DHCP didn't have it. It solved the problem when I commented out the line in /etc/hosts:
# ::1     localhost6.localdomain6  localhost6


insert new value to HTML list through javascript using selenium

Question: I have to insert new value to HTML list for my automation purpose. I am using selenium with     python.
My list is:
<select name="sel_audio" id="sel_audio">
    <option value="endo/audio/beep.wav" selected="selected">beep </option>
    <option value="endo/audio/dig1.wav">dig1 </option>
    <option value="endo/audio/IMAlert.wav">IMAlert </option>
    <option value="endo/audio/IMAlertDef.wav">IMAlertDef </option>
</select>

I want ot add HighPiono.wav file to list. My code is:
self.script = "document.getElementById('sel_audio').value='" + C:\music\HighPiono.wav + "';"
driver.execute_script(self.script)

This code is setting the blank value  in list without giving any error.
Please help me.
Answer: You need to use the add() method of Select object to add new option to it. Below JavaScript will add new option to select list:
var sel = document.getElementById("sel_audio");
var new_option = document.createElement("option");
new_option.text = "HighPiono";
new_option.value = "HighPiono.wav";
sel.add(option);

Comment: Thanks for your reply Surya.                                                                 I am converting this code in python to run from selenium as follows:                                                               sel = self._browser.get_current_browser().execute_script("document.getElementById('sel_audio')")                                               new_option = self._browser.get_current_browser().execute_script("document.createElement('option')")                                                   new_option.text = "HighPiono" new_option.value = "HighPiono.wav" sel.add(option)
Comment: Then I am getting following error:                                                                 (, AttributeError("'NoneType' object has no attribute 'text'",), )
Comment: Why are you modifying like this? you have to just replace "self.script" with the JS script that I have provided in your code... Hope this helps!